<commit_before>// dependencies: module.js, search.js, display.js, resizable.js, navbar.js

// initialization
$(document).ready(function() {

  init_load();
  init_panes();
  init_searchpane();
  init_search();
  init_globals();
  init_favorites();
  init_feedback();
  init_display();
  init_evals();
  init_logout();
  init_about();

})

// loads course from url
var init_load = function () {
  // Parse and display search parameters, if any exist
  parseSearchParameters()

  // Parse course from the URL to determine which course (if any) to display on pageload
  var pathnameMatch = /^\/course\/(\d+)$/.exec(window.location.pathname)
  if (pathnameMatch !== null && pathnameMatch.length === 2) {
    // Load the course
    displayCourseDetails(pathnameMatch[1])
  }
}

// Handle displaying a course after pushing the back/forward button in the browser
window.onpopstate = function (event) {
  if (event.state.courseID) {
    displayCourseDetails(event.state.courseID)
  }
  parseSearchParameters()
}

// Parse the URL to check for whether the app should be showing a course and displaying any search terms
var parseSearchParameters = function () {
  // Parse search terms
  var unparsedParameters = window.location.search.replace('?', '').split('&')
  var parameters = {}
  for (var parametersIndex in unparsedParameters) {
    var keyValue = unparsedParameters[parametersIndex].split('=')
    if (keyValue.length === 2) {
      parameters[keyValue[0]] = decodeURIComponent(keyValue[1])
    }
  }
  if (parameters.hasOwnProperty('search')) {
    $('#searchbox').val(parameters.search)
  }
  if (parameters.hasOwnProperty('semester')) {
    $('#semester').data('query', parameters.semester).val(parameters.semester)
  }
  if (parameters.hasOwnProperty('sort')) {
    $('#sort').val(parameters.sort)
  }
  if (parameters !== {}) {
    searchForCourses()
  }
}

// to initialize draggability
var init_panes = function() {
  $('#search-pane').resizable({
    handleSelector: "#search-resizer",
    resizeHeight: false
  })

  $('#info-pane').resizable({
    handleSelector: "#info-resizer",
    resizeHeight: false,
    resizeWidthFrom: 'left'
  })
}

// to initalize search pane section collapsing
var init_searchpane = function() {
  $('#favorite-courses').css('max-height', '30%')

    // toggle display of favorite things
  var toggleFavDisplay = function() {
    var isVisible = $('#favorite-courses').css('display') !== 'none'

    var icon = $('#fav-display-toggle')
    icon.removeClass(isVisible ? 'fa-minus' : 'fa-plus')
    icon.addClass(isVisible ? 'fa-plus' : 'fa-minus')
    $('#favorite-courses').slideToggle()
  }
  $('#fav-display-toggle').click(toggleFavDisplay)

  // toggle display of search result things
  var toggleSearchDisplay = function() {
    var isVisible = $('#search-results').css('display') !== 'none'

    var icon = $('#search-display-toggle')
    icon.removeClass(isVisible ? 'fa-minus' : 'fa-plus')
    icon.addClass(isVisible ? 'fa-plus' : 'fa-minus')
    $('#favorite-courses').animate({'max-height': (isVisible ? '100%' : '30%')})

    $('#search-results').slideToggle()
  }
  $('#search-display-toggle').click(toggleSearchDisplay)
}

// to initialize searching function
var init_search = function() {
  // Every time a key is pressed inside the #searchbox, call the searchForCourses function
  $('#searchbox').on('input', searchForCourses)
  $('#semester, #sort').change(searchForCourses)

  // load the semesters for the dropdown
  $('#semester').children(":not([disabled])").remove()
  $.get('/api/semesters', function (semesters) {
    for (var semesterIndex in semesters) {
      var thisSemester = semesters[semesterIndex]
      var option = $(document.createElement('option')).attr('value', thisSemester._id).text(thisSemester.name)
      $('#semester').append(option)
    }
    if ($('#semester').data('query')) {
      $('#semester').children('[value=' + $('#semester').data('query') +']').attr('selected', true)
    } else {
      $('#semester').children().eq(1).attr('selected', true)
    }
  })
}

// to initialize global data
var init_globals = function() {
  // Saving the user's netid so it is globally available
  document.netid = $("#netid").text()

  // construct local favorites list
  document.favorites = []
  $.get('/api/user/favorites', function(courses) {
    for (var course in courses) {
      document.favorites.push(courses[course]["_id"])
    }
  })
}

// to initialize favorites list
var init_favorites = function() {
  // call api to get favorites and display
  $.get('/api/user/favorites', function(courses) {

    $('#favorite-header').css('display', (courses === undefined || courses.length === 0) ? 'none' : '')

    $('#favs').html('');
    $('#favorite-title').html('');

    $('#favorite-title').append(courses.length + ' Favorite Course' + (courses.length !== 1 ? 's' : ''))
    for (var courseIndex in courses) {
      var thisCourse = courses[courseIndex];

      // append favorite into favs pane
      $('#favs').append(newDOMResult(thisCourse, {"semester": 1, "tags": 1}));
    }
  })
}

// to initialize feedback mechanism
var init_feedback = function() {
  // submission
  $('#feedback-form').one('submit', function() {
    var submitURL = ''
    submitURL += 'https://docs.google.com/a/princeton.edu/forms/d/e/1FAIpQLSdX3VTSbVfwOOtwMxhWiryQFrlBNuJDUTlp-lUmsV-S0xFM_g/formResponse?'
    submitURL += 'entry.1257302391=' + document.netid
    submitURL += '&entry.680057223=' + encodeURIComponent($('#feedback-text').val())

    $(this)[0].action = submitURL
    $('#feedback-submit').text('Thank You!')
    $('#feedback-submit').addClass('disabled')
    $('#feedback-text').attr('disabled', true)
    setTimeout(toggleFeedback, 1000)
  })

  $('#feedback-toggle').click(function() {return toggleNavbar('feedback')})
}

// to initialize display toggling
var init_display = function() {
  $('#disp-instructors-toggle'  ).click(function() {section_toggle('disp', 'instructors')})
  $('#disp-description-toggle'  ).click(function() {section_toggle('disp', 'description')})
  $('#disp-assignments-toggle'  ).click(function() {section_toggle('disp', 'assignments')})
  $('#disp-grading-toggle'      ).click(function() {section_toggle('disp', 'grading')})
  $('#disp-prerequisites-toggle').click(function() {section_toggle('disp', 'prerequisites')})
  $('#disp-equivalent-toggle'   ).click(function() {section_toggle('disp', 'equivalent')})
  $('#disp-other-toggle'        ).click(function() {section_toggle('disp', 'other')})
  $('#disp-classes-toggle'      ).click(function() {section_toggle('disp', 'classes')})
}

// to initialize evals toggling
var init_evals = function() {
  $('#evals-semesters-toggle').click(function() {section_toggle('evals', 'semesters')})
  $('#evals-numeric-toggle').click(function() {section_toggle('evals', 'numeric')})
  $('#evals-comments-toggle').click(function() {section_toggle('evals', 'comments')})
}

// to intialize logout button
var init_logout = function() {
  $('#menu-bar').mouseleave(function() {
    var isNetidInvisible = $('#netid').css('display') === 'none'
    if (isNetidInvisible) $('#netid, #logout').animate({width: 'toggle'})
  })

  $('#netid').click(function() {
    var isLogoutVisible = $('#logout').css('display') !== 'none'
    if (!isLogoutVisible) $('#netid, #logout').animate({width: 'toggle'})
  })
}

// to initialize about display
var init_about = function() {
  $('#about-toggle').click(function() {return toggleNavbar('about')})
  $('#about-popup-close').click(function() {return toggleNavbar('about')})
}

// toggles display / eval sections
var section_toggle = function(pane, section) {
  var body = $('#' + pane + '-' + section + '-body')
  var icon = $('#' + pane + '-' + section + '-toggle')
  var isVisible = (body.css('display') !== 'none')

  icon.removeClass(isVisible ? 'fa-minus' : 'fa-plus')
  icon.addClass(isVisible ? 'fa-plus' : 'fa-minus')
  body.slideToggle();
}
<commit_msg>Reducing the number of requests for favourites<commit_after>// dependencies: module.js, search.js, display.js, resizable.js, navbar.js

// initialization
$(document).ready(function() {

  init_load();
  init_panes();
  init_searchpane();
  init_search();
  init_globals();
  init_favorites();
  init_feedback();
  init_display();
  init_evals();
  init_logout();
  init_about();

})

// loads course from url
var init_load = function () {
  // Parse and display search parameters, if any exist
  parseSearchParameters()

  // Parse course from the URL to determine which course (if any) to display on pageload
  var pathnameMatch = /^\/course\/(\d+)$/.exec(window.location.pathname)
  if (pathnameMatch !== null && pathnameMatch.length === 2) {
    // Load the course
    displayCourseDetails(pathnameMatch[1])
  }
}

// Handle displaying a course after pushing the back/forward button in the browser
window.onpopstate = function (event) {
  if (event.state.courseID) {
    displayCourseDetails(event.state.courseID)
  }
  parseSearchParameters()
}

// Parse the URL to check for whether the app should be showing a course and displaying any search terms
var parseSearchParameters = function () {
  // Parse search terms
  var unparsedParameters = window.location.search.replace('?', '').split('&')
  var parameters = {}
  for (var parametersIndex in unparsedParameters) {
    var keyValue = unparsedParameters[parametersIndex].split('=')
    if (keyValue.length === 2) {
      parameters[keyValue[0]] = decodeURIComponent(keyValue[1])
    }
  }
  if (parameters.hasOwnProperty('search')) {
    $('#searchbox').val(parameters.search)
  }
  if (parameters.hasOwnProperty('semester')) {
    $('#semester').data('query', parameters.semester).val(parameters.semester)
  }
  if (parameters.hasOwnProperty('sort')) {
    $('#sort').val(parameters.sort)
  }
  if (parameters !== {}) {
    searchForCourses()
  }
}

// to initialize draggability
var init_panes = function() {
  $('#search-pane').resizable({
    handleSelector: "#search-resizer",
    resizeHeight: false
  })

  $('#info-pane').resizable({
    handleSelector: "#info-resizer",
    resizeHeight: false,
    resizeWidthFrom: 'left'
  })
}

// to initalize search pane section collapsing
var init_searchpane = function() {
  $('#favorite-courses').css('max-height', '30%')

    // toggle display of favorite things
  var toggleFavDisplay = function() {
    var isVisible = $('#favorite-courses').css('display') !== 'none'

    var icon = $('#fav-display-toggle')
    icon.removeClass(isVisible ? 'fa-minus' : 'fa-plus')
    icon.addClass(isVisible ? 'fa-plus' : 'fa-minus')
    $('#favorite-courses').slideToggle()
  }
  $('#fav-display-toggle').click(toggleFavDisplay)

  // toggle display of search result things
  var toggleSearchDisplay = function() {
    var isVisible = $('#search-results').css('display') !== 'none'

    var icon = $('#search-display-toggle')
    icon.removeClass(isVisible ? 'fa-minus' : 'fa-plus')
    icon.addClass(isVisible ? 'fa-plus' : 'fa-minus')
    $('#favorite-courses').animate({'max-height': (isVisible ? '100%' : '30%')})

    $('#search-results').slideToggle()
  }
  $('#search-display-toggle').click(toggleSearchDisplay)
}

// to initialize searching function
var init_search = function() {
  // Every time a key is pressed inside the #searchbox, call the searchForCourses function
  $('#searchbox').on('input', searchForCourses)
  $('#semester, #sort').change(searchForCourses)

  // load the semesters for the dropdown
  $('#semester').children(":not([disabled])").remove()
  $.get('/api/semesters', function (semesters) {
    for (var semesterIndex in semesters) {
      var thisSemester = semesters[semesterIndex]
      var option = $(document.createElement('option')).attr('value', thisSemester._id).text(thisSemester.name)
      $('#semester').append(option)
    }
    if ($('#semester').data('query')) {
      $('#semester').children('[value=' + $('#semester').data('query') +']').attr('selected', true)
    } else {
      $('#semester').children().eq(1).attr('selected', true)
    }
  })
}

// to initialize global data
var init_globals = function() {
  // Saving the user's netid so it is globally available
  document.netid = $("#netid").text()
}

// to initialize favorites list
var init_favorites = function() {
  // call api to get favorites and display
  document.favorites = []
  $.get('/api/user/favorites', function(courses) {

    $('#favorite-header').css('display', (courses === undefined || courses.length === 0) ? 'none' : '')

    $('#favs').html('');
    $('#favorite-title').html('');

    $('#favorite-title').append(courses.length + ' Favorite Course' + (courses.length !== 1 ? 's' : ''))
    for (var courseIndex in courses) {
      var thisCourse = courses[courseIndex];

      // Saving this user's favorite courses to the global scope
      document.favorites.push(thisCourse._id)

      // append favorite into favs pane
      $('#favs').append(newDOMResult(thisCourse, {"semester": 1, "tags": 1}));
    }
  })
}

// to initialize feedback mechanism
var init_feedback = function() {
  // submission
  $('#feedback-form').one('submit', function() {
    var submitURL = ''
    submitURL += 'https://docs.google.com/a/princeton.edu/forms/d/e/1FAIpQLSdX3VTSbVfwOOtwMxhWiryQFrlBNuJDUTlp-lUmsV-S0xFM_g/formResponse?'
    submitURL += 'entry.1257302391=' + document.netid
    submitURL += '&entry.680057223=' + encodeURIComponent($('#feedback-text').val())

    $(this)[0].action = submitURL
    $('#feedback-submit').text('Thank You!')
    $('#feedback-submit').addClass('disabled')
    $('#feedback-text').attr('disabled', true)
    setTimeout(toggleFeedback, 1000)
  })

  $('#feedback-toggle').click(function() {return toggleNavbar('feedback')})
}

// to initialize display toggling
var init_display = function() {
  $('#disp-instructors-toggle'  ).click(function() {section_toggle('disp', 'instructors')})
  $('#disp-description-toggle'  ).click(function() {section_toggle('disp', 'description')})
  $('#disp-assignments-toggle'  ).click(function() {section_toggle('disp', 'assignments')})
  $('#disp-grading-toggle'      ).click(function() {section_toggle('disp', 'grading')})
  $('#disp-prerequisites-toggle').click(function() {section_toggle('disp', 'prerequisites')})
  $('#disp-equivalent-toggle'   ).click(function() {section_toggle('disp', 'equivalent')})
  $('#disp-other-toggle'        ).click(function() {section_toggle('disp', 'other')})
  $('#disp-classes-toggle'      ).click(function() {section_toggle('disp', 'classes')})
}

// to initialize evals toggling
var init_evals = function() {
  $('#evals-semesters-toggle').click(function() {section_toggle('evals', 'semesters')})
  $('#evals-numeric-toggle').click(function() {section_toggle('evals', 'numeric')})
  $('#evals-comments-toggle').click(function() {section_toggle('evals', 'comments')})
}

// to intialize logout button
var init_logout = function() {
  $('#menu-bar').mouseleave(function() {
    var isNetidInvisible = $('#netid').css('display') === 'none'
    if (isNetidInvisible) $('#netid, #logout').animate({width: 'toggle'})
  })

  $('#netid').click(function() {
    var isLogoutVisible = $('#logout').css('display') !== 'none'
    if (!isLogoutVisible) $('#netid, #logout').animate({width: 'toggle'})
  })
}

// to initialize about display
var init_about = function() {
  $('#about-toggle').click(function() {return toggleNavbar('about')})
  $('#about-popup-close').click(function() {return toggleNavbar('about')})
}

// toggles display / eval sections
var section_toggle = function(pane, section) {
  var body = $('#' + pane + '-' + section + '-body')
  var icon = $('#' + pane + '-' + section + '-toggle')
  var isVisible = (body.css('display') !== 'none')

  icon.removeClass(isVisible ? 'fa-minus' : 'fa-plus')
  icon.addClass(isVisible ? 'fa-plus' : 'fa-minus')
  body.slideToggle();
}
<|endoftext|>


<commit_before>import {Microservices} from '../configs/microservices';
import rp from 'request-promise';
const log = require('../configs/log').log;

export default {
    name: 'lticonsumer',
    // At least one of the CRUD methods is Required
    /*
        For now hardcoded slide template - powerpoint basic slide
    */
    create: (req, resource, params, body, config, callback) => {
        //console.log("service/lticonsumer.js/resource="+resource);

        req.reqId = req.reqId ? req.reqId : -1;
        log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'create', Method: req.method});
        //console.log('params='+params);
        //console.log("params.ltiURL="+params.ltiURL);
        let ltiURL = params.ltiURL;
        let ltiKey = params.ltiKey;
        let ltiHeight = params.ltiHeight;
        let ltiWidth = params.ltiWidth;

        // LTI paramters
        let args = params.params? params.params : params;

        let url = require('url');
        let http = require('http');
        let https = require('https');
        let request = require('request');
        let querystring = require('querystring');
        let btoa = require('btoa');
        let oauth = require('oauth-sign');
        let fs = require('fs');

        let parseURL = url.parse(ltiURL, true);
        let hostname = parseURL.hostname;
        let port = parseURL.port;
        let pathname = parseURL.pathname;

        //console.log('hostname='+hostname);
        //console.log('path='+pathname);
        //console.log('port='+port);

        if(resource === 'lticonsumer'){
            /*********connect to LTI Provider*************/
            let post_data = querystring.stringify(args);
            //console.log('lticonsumer.js.args='+JSON.stringify(args));
            let request_options = {
                hostname:  hostname,
                path: pathname,
                port: port,
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            };

            let body = '';
            let req = http.request(request_options, (res) => {
                console.log('STATUS: ' + res.statusCode);
                console.log('HEADERS: ' + JSON.stringify(res.headers));
                let json = JSON.stringify(res.headers);
                //console.log('res.headers.location: ' + res.headers.location);
                res.setEncoding('utf8');
                res.on('data', (chunk) => {
                    //console.log('BODY: ' + chunk);
                    body += chunk;
                }).on('end', () => {
                //console.log("body="+body);
                //console.log("res.headers.location="+res.headers.location);
                    let ltiResponse;
                    if(res.headers.location!=null){
                        ltiResponse = {
                            ltiResponseURL: res.headers.location,
                            ltiResponseHTML: ' ',
                            ltiURL : params.ltiURL,
                            ltiKey : params.ltiKey,
                            ltiWidth: params.ltiWidth,
                            ltiHeight : params.ltiHeight
                       };
                    }
                    else {
                        ltiResponse = {
                            ltiResponseURL: '',
                            ltiResponseHTML: body,
                            ltiURL : params.ltiURL,
                            ltiKey : params.ltiKey,
                            ltiWidth: params.ltiWidth,
                            ltiHeight : params.ltiHeight
                       };
                    }
                    callback(null, ltiResponse);

                }); //end on
            });

            console.log('Setting req error callback');
            req.on('error', (err) => {
                console.log('problem with request: ' + err.message);
                callback(err);
            });

            // write data to request body
            req.write(post_data);
            console.log('Written to request.');
            req.end();
            console.log('Request ended.');
        }//end if(resource=== 'lti')
    }
};
<commit_msg>lsticonsumer.js<commit_after>import {Microservices} from '../configs/microservices';
import rp from 'request-promise';
const log = require('../configs/log').log;

export default {
    name: 'lticonsumer',
    // At least one of the CRUD methods is Required
    /*
        For now hardcoded slide template - powerpoint basic slide
    */
    create: (req, resource, params, body, config, callback) => {
        //console.log("service/lticonsumer.js/resource="+resource);

        req.reqId = req.reqId ? req.reqId : -1;
        log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'create', Method: req.method});
        //console.log('params='+params);
        //console.log("params.ltiURL="+params.ltiURL);
        let ltiURL = params.ltiURL;
        let ltiKey = params.ltiKey;
        let ltiHeight = params.ltiHeight;
        let ltiWidth = params.ltiWidth;

        // LTI paramters
        let args = params.params? params.params : params;

        let url = require('url');
        let http = require('http');
        let https = require('https');
        let request = require('request');
        let querystring = require('querystring');
        let btoa = require('btoa');
        let oauth = require('oauth-sign');
        let fs = require('fs');

        let parseURL = url.parse(ltiURL, true);
        let hostname = parseURL.hostname;
        let port = parseURL.port;
        let pathname = parseURL.pathname;

        //console.log('hostname='+hostname);
        //console.log('path='+pathname);
        //console.log('port='+port);

        if(resource === 'lticonsumer'){
            /*********connect to LTI Provider*************/
            let post_data = querystring.stringify(args);
            //console.log('lticonsumer.js.args='+JSON.stringify(args));
            let request_options = {
                hostname:  hostname,
                path: pathname,
                port: port,
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            };

            let body = '';
            let req = http.request(request_options, (res) => {
                console.log('STATUS: ' + res.statusCode);
                console.log('HEADERS: ' + JSON.stringify(res.headers));
                let json = JSON.stringify(res.headers);
                //console.log('res.headers.location: ' + res.headers.location);
                res.setEncoding('utf8');
                res.on('data', (chunk) => {
                    //console.log('BODY: ' + chunk);
                    body += chunk;
                }).on('end', () => {
                //console.log("body="+body);
                //console.log("res.headers.location="+res.headers.location);
                    let ltiResponse;
                    if(res.headers.location!=null){
                        ltiResponse = {
                            ltiResponseURL: res.headers.location,
                            ltiResponseHTML: ' ',
                            ltiURL : params.ltiURL,
                            ltiKey : params.ltiKey,
                            ltiWidth: params.ltiWidth,
                            ltiHeight : params.ltiHeight
                        };
                    }
                    else {
                        ltiResponse = {
                            ltiResponseURL: '',
                            ltiResponseHTML: body,
                            ltiURL : params.ltiURL,
                            ltiKey : params.ltiKey,
                            ltiWidth: params.ltiWidth,
                            ltiHeight : params.ltiHeight
                        };
                    }
                    callback(null, ltiResponse);

                }); //end on
            });

            console.log('Setting req error callback');
            req.on('error', (err) => {
                console.log('problem with request: ' + err.message);
                callback(err);
            });

            // write data to request body
            req.write(post_data);
            console.log('Written to request.');
            req.end();
            console.log('Request ended.');
        }//end if(resource=== 'lti')
    }
};
<|endoftext|>


<commit_before>var yargs = require('yargs');
var fs    = require('fs');
var http  = require('http');
var debug = require('debug')('word-counter:index');
var client_parse = require('./lib/client_parse.js');

var argv = yargs
    .option('c', {
      alias: 'client',
      type: 'array'
    })
    .option('s', {
      alias: 'search',
      type: 'string'
    })
    .option('f', {
      alias: 'file',
      type: 'string'
    })
    .argv;

var
  clients = argv.client,
  search = argv.search,
  filename = argv.file,
  fileArray = [],
  client_count = 0,
  ocurrences = 0,
  options = {
    host: 'localhost',
    port: 5050,
    method: 'POST',
    path: '/',
    headers: {
      'Content-Type': 'application/json'
    }
  },
  request = null;

// Lê o arquivo
fs.readFile(filename, 'utf8', function(err, data) {
  if (err) throw err;
  // Separa o arquivo em pedaços e guarda no array `fileArray`
  fileArray = data.match(/([^\s]+\s\s*){1,200}/g);

  mountOptions();
});

// Monta as opções de cada client para enviar
function mountOptions() {
  for (var i = 0; i < clients.length; i++) {
    var client = clients[i];
    var postData = getPostData();

    if (postData) {
      sendRequest(client, postData);
    } else {
      debug('End of file reached');
    }
  }
};

function getPostData() {
  var content = fileArray.pop();
  if(content != null) {
    return JSON.stringify({
      'content': content,
      'search': search
    });
  } else {
    return false;
  }
};

// Envia para o cliente um pedaço do texto e a palavra a ser buscada (Start dos requests)
function sendRequest(client, postData) {
  var options = client_parse(client);
  var request = http.request(options, process_client.bind(null, client));
  do_request();

  request.on('error', function(e) {
    debug('Error processing request: ' + e.message);
  });

  request.write(postData);
  request.end();
};

function process_client(client, res) {
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    var chunk = JSON.parse(chunk);
    debug('Client "%s" responded with %o', client, chunk);
    var searchReturned = chunk.search;
    var ocurrencesReturned = chunk.ocurrences;
    var postData = getPostData();

    ocurrences += ocurrencesReturned;
    process_response();

    if (postData) {
      sendRequest(client, postData);
    }
  });
};

function do_request() {
  client_count++;
}

function process_response() {
  client_count--;
  if (client_count === 0) {
    // console.log('end of requests');
    console.log('Found %d ocurrences of "%s" on file %s.', ocurrences, search, filename);
  }
}
<commit_msg>resume request write and end just to end<commit_after>var yargs = require('yargs');
var fs    = require('fs');
var http  = require('http');
var debug = require('debug')('word-counter:index');
var client_parse = require('./lib/client_parse.js');

var argv = yargs
    .option('c', {
      alias: 'client',
      type: 'array'
    })
    .option('s', {
      alias: 'search',
      type: 'string'
    })
    .option('f', {
      alias: 'file',
      type: 'string'
    })
    .argv;

var
  clients = argv.client,
  search = argv.search,
  filename = argv.file,
  fileArray = [],
  client_count = 0,
  ocurrences = 0,
  options = {
    host: 'localhost',
    port: 5050,
    method: 'POST',
    path: '/',
    headers: {
      'Content-Type': 'application/json'
    }
  },
  request = null;

// Lê o arquivo
fs.readFile(filename, 'utf8', function(err, data) {
  if (err) throw err;
  // Separa o arquivo em pedaços e guarda no array `fileArray`
  fileArray = data.match(/([^\s]+\s\s*){1,200}/g);

  mountOptions();
});

// Monta as opções de cada client para enviar
function mountOptions() {
  for (var i = 0; i < clients.length; i++) {
    var client = clients[i];
    var postData = getPostData();

    if (postData) {
      sendRequest(client, postData);
    } else {
      debug('End of file reached');
    }
  }
};

function getPostData() {
  var content = fileArray.pop();
  if(content != null) {
    return JSON.stringify({
      'content': content,
      'search': search
    });
  } else {
    return false;
  }
};

// Envia para o cliente um pedaço do texto e a palavra a ser buscada (Start dos requests)
function sendRequest(client, postData) {
  var options = client_parse(client);
  var request = http.request(options, process_client.bind(null, client));
  do_request();

  request.on('error', function(e) {
    debug('Error processing request: ' + e.message);
  });

  request.end(postData);
};

function process_client(client, res) {
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    var chunk = JSON.parse(chunk);
    debug('Client "%s" responded with %o', client, chunk);
    var searchReturned = chunk.search;
    var ocurrencesReturned = chunk.ocurrences;
    var postData = getPostData();

    ocurrences += ocurrencesReturned;
    process_response();

    if (postData) {
      sendRequest(client, postData);
    }
  });
};

function do_request() {
  client_count++;
}

function process_response() {
  client_count--;
  if (client_count === 0) {
    // console.log('end of requests');
    console.log('Found %d ocurrences of "%s" on file %s.', ocurrences, search, filename);
  }
}
<|endoftext|>


<commit_before>(function(Application, Window) {

  /**
   * Main Window
   */
  var ApplicationFileManagerWindow = function(app) {
    Window.apply(this, ['ApplicationFileManagerWindow', {width: 650, height: 420}, app]);

    this.title      = "File Manager";
    fileView   = null;
    sideView   = null;

    this._title = this.title;
    this._properties.allow_drop = true;
    this._icon = 'apps/file-manager.png';
  };

  ApplicationFileManagerWindow.prototype = Object.create(Window.prototype);

  ApplicationFileManagerWindow.prototype.init = function() {
    var self  = this;
    var app   = this._appRef;
    var root  = Window.prototype.init.apply(this, arguments);

    var fileView   = this._addGUIElement(new OSjs.GUI.FileView('FileManagerFileView', '/', {dnd: true, summary: true}), root);
    var sideView   = this._addGUIElement(new OSjs.GUI.ListView('FileManagerSideView', {dnd: false, singleClick: true}), root);
    var statusBar  = this._addGUIElement(new OSjs.GUI.StatusBar('FileManagerStatusBar'), root);
    var menuBar    = this._addGUIElement(new OSjs.GUI.MenuBar('FileManagerMenuBar'), root);

    fileView.onItemDropped = function(ev, el, item) {
      // TODO
      console.warn("Not implemented yet!");
      return false;
    };
    fileView.onFilesDropped = function(ev, el, files) {
      return self.onDropUpload(ev, el, files);
    };
    fileView.onFinished = function(dir, numItems, totalBytes) {
      statusBar.setText("Showing " + numItems + " item(s), " + totalBytes + " byte(s)");
      self._toggleLoading(false);
      try {
        self._appRef.go(dir, self);
      } catch ( e ) {
        console.warn("ApplicationFileManagerWindow->onFinished()", e);
      }
    };
    fileView.onRefresh = function() {
      statusBar.setText("Refreshing...");
      self._toggleLoading(true);
    };
    fileView.onActivated = function(name, type, mime) {
      if ( name ) {
        if ( type === 'file' ) {
          app.open(name, mime);
        } else {
          statusBar.setText("Loading...");
        }
      }
    };
    fileView.onError = function(error) {
      self._toggleLoading(false);
      OSjs.API.error("File Manager error", "An error occured while handling your request", error);
    };

    menuBar.addItem("File", [
      {title: 'Create directory', onClick: function() {
        var fileView = self._getGUIElement('FileManagerFileView');
        var cur = fileView.getPath();
        app._createDialog('Input', ["Create a new directory in " + cur + "", '', function(btn, value) {
          self._focus();
          if ( btn !== 'ok' || !value ) return;

          app.mkdir((cur + '/' + value), function() {
            if ( fileView ) {
              fileView.refresh();
              self._focus();
            }
          });
        }], self);
      }},
      {title: 'Upload', onClick: function() {
        var fileView = self._getGUIElement('FileManagerFileView');
        app._createDialog('FileUpload', [fileView.getPath(), null, function(btn, filename, mime, size) {
          self._focus();
          if ( btn != 'ok' && btn != 'complete' ) return;
          if ( fileView ) {
            fileView.refresh(function() {
              fileView.setSelected(filename, 'filename');
              self._focus();
            });
          }
        }], self);
      }},
      {title: 'Close', onClick: function() {
        self._close();
      }}
    ]);
    menuBar.addItem("Edit", [
      {name: 'Rename', title: 'Rename', onClick: function() {
        var fileView = self._getGUIElement('FileManagerFileView');
        var cur = fileView.getSelected();
        if ( !cur ) return;
        var fname = OSjs.Utils.filename(cur.path);
        app._createDialog('Input', ["Rename " + fname + "", fname, function(btn, value) {
          self._focus();
          if ( btn !== 'ok' || !value ) return;
          var newpath = OSjs.Utils.dirname(cur.path) + '/' + value;

          app.move(cur.path, newpath, function() {
            if ( fileView ) {
              fileView.refresh();
              self._focus();
            }
          });
        }], self);
      }},
      {name: 'Delete', title: 'Delete', onClick: function() {
        self._focus();

        var fileView = self._getGUIElement('FileManagerFileView');
        var cur = fileView.getSelected();
        if ( !cur ) return;
        var fname = OSjs.Utils.filename(cur.path);

        app._createDialog('Confirm', ["Delete " + fname + " ?", function(btn) {
          self._focus();
          if ( btn !== 'ok' ) return;
          app.unlink(cur.path, function() {
            if ( fileView ) {
              fileView.refresh();
            }
          });
        }]);
      }}
    ]);
    menuBar.addItem("View", [
      {title: 'Refresh', onClick: function() {
        var fileView = self._getGUIElement('FileManagerFileView');
        fileView.refresh();
        self._focus();
      }}
    ]);
    menuBar.onMenuOpen = function(menu) {
      var fileView = self._getGUIElement('FileManagerFileView');
      var sel = fileView.getSelected();
      var el1 = menu.getRoot().getElementsByClassName("MenuItem_Rename")[0];
      var el2 = menu.getRoot().getElementsByClassName("MenuItem_Delete")[0];
      var cur = sel ? sel.filename != '..' : false;
      if ( el1 ) {
        if ( cur ) {
          el1.className = el1.className.replace(/\s?Disabled/, '');
        } else {
          el1.className += ' Disabled';
        }
      }
      if ( el2 ) {
        if ( cur ) {
          el2.className = el2.className.replace(/\s?Disabled/, '');
        } else {
          el2.className += ' Disabled';
        }
      }
    };

    var _getFileIcon = function(r) {
      return OSjs.API.getThemeResource(r, 'icon');
    };

    sideView.setColumns([
      {key: 'image', title: '', type: 'image', domProperties: {width: "16"}},
      {key: 'filename', title: 'Filename'},
      {key: 'mime', title: 'Mime', visible: false},
      {key: 'size', title: 'Size', visible: false},
      {key: 'path', title: 'Path', visible: false, domProperties: {width: "70"}},
      {key: 'type', title: 'Type', visible: false, domProperties: {width: "50"}}
     ]);
    sideView.setRows([
      {image: _getFileIcon('places/folder_home.png'), filename: 'Home', mime: null, size: 0, type: 'link', path: OSjs.API.getDefaultPath('/')},
      {image: _getFileIcon('places/folder.png'), filename: 'Temp', mime: null, size: 0, type: 'link', path: '/tmp'},
      {image: _getFileIcon('devices/drive-harddisk.png'), filename: 'Filesystem', mime: null, size: 0, type: 'link', path: '/'}
    ]);
    sideView.onActivate = function(ev, listView, t) {
      if ( t ) {
        var path = t.getAttribute('data-path');
        var type = t.getAttribute('data-type');
        if ( path ) {
          if ( type === 'file' ) {
            app.open(path, t.getAttribute('data-mime'));
          } else {
            var fileView = self._getGUIElement('FileManagerFileView');
            fileView.chdir(path);
          }
        }
      }
    };

    sideView.render();
  };

  ApplicationFileManagerWindow.prototype.destroy = function() {
    Window.prototype.destroy.apply(this, arguments);
  };

  ApplicationFileManagerWindow.prototype._onKeyEvent = function(ev) {
    Window.prototype._onKeyEvent.apply(this, arguments);
    var fileView = this._getGUIElement('FileManagerFileView');
    if ( fileView ) {
      fileView.onKeyPress(ev);
    }
  };

  ApplicationFileManagerWindow.prototype._onDndEvent = function(ev, type, item, args) {
    Window.prototype._onDndEvent.apply(this, arguments);
    if ( type === 'filesDrop' && item ) {
      return this.onDropUpload(ev, null, item);
    }
    return true;
  };

  ApplicationFileManagerWindow.prototype.onDropUpload = function(ev, el, files) {
    var self = this;
    if ( files && files.length ) {
      var app = this._appRef;
      var fileView = this._getGUIElement('FileManagerFileView');
      var dest = fileView.getPath();

      for ( var i = 0; i < files.length; i++ ) {
        app._createDialog('FileUpload', [dest, files[i], function(btn, filename, mime, size) {
          if ( btn != 'ok' && btn != 'complete' ) return;
          var fileView = self._getGUIElement('FileManagerFileView');
          if ( fileView ) {
            fileView.refresh(function() {
              fileView.setSelected(filename, 'filename');
              self._focus();
            });
          }
        }], this);
      }
    }
    return false;
  };

  /**
   * Application
   */
  var ApplicationFileManager = function(args, metadata) {
    Application.apply(this, ['ApplicationFileManager', args, metadata]);
  };

  ApplicationFileManager.prototype = Object.create(Application.prototype);

  ApplicationFileManager.prototype.destroy = function() {
    return Application.prototype.destroy.apply(this, []);
  };

  ApplicationFileManager.prototype.init = function(core, session) {
    Application.prototype.init.apply(this, arguments);

    this._addWindow(new ApplicationFileManagerWindow(this));

    var path = this._getArgument('path') || OSjs.API.getDefaultPath('/');
    var w = this._getWindow('ApplicationFileManagerWindow');
    w._getGUIElement('FileManagerFileView').chdir(path);
    this.go(path, w);
  };

  ApplicationFileManager.prototype._onMessage = function(obj, msg, args) {
    Application.prototype._onMessage.apply(this, arguments);

    if ( msg == 'destroyWindow' && obj._name === 'ApplicationFileManagerWindow' ) {
      this.destroy();
    }
  };

  ApplicationFileManager.prototype.open = function(filename, mime) {
    OSjs.API.open(filename, mime);
  };

  ApplicationFileManager.prototype.go = function(dir, w) {
    this._setArgument('path', dir);
    w._setTitle(w.title + ' - ' + (dir || '/'));
  };

  ApplicationFileManager.prototype._action = function(name, args, callback) {
    callback = callback || function() {};

    var _onError = function(error) {
      // FIXME
      OSjs.API.error("File Manager error", "An error occured while handling your request", error);

      callback(false);
    };

    OSjs.API.call('fs', {'method': name, 'arguments': args}, function(res) {
      if ( !res || (typeof res.result === 'undefined') || res.error ) {
        _onError(res.error || 'Fatal error');
      } else {
        callback(res.result);
      }
    }, function(error) {
      _onError(error);
    });
  };

  ApplicationFileManager.prototype.move = function(src, dest, callback) {
    return this._action('move', [src, dest], callback);
  };

  ApplicationFileManager.prototype.unlink = function(name, callback) {
    return this._action('delete', [name], callback);
  };

  ApplicationFileManager.prototype.mkdir = function(name, callback) {
    return this._action('mkdir', [name], callback);
  };

  //
  // EXPORTS
  //
  OSjs.Applications = OSjs.Applications || {};
  OSjs.Applications.ApplicationFileManager = ApplicationFileManager;

})(OSjs.Core.Application, OSjs.Core.Window);
<commit_msg>Bugfix: FileManager after refactor<commit_after>(function(Application, Window) {

  /**
   * Main Window
   */
  var ApplicationFileManagerWindow = function(app) {
    Window.apply(this, ['ApplicationFileManagerWindow', {width: 650, height: 420}, app]);

    this.title      = "File Manager";
    fileView   = null;
    sideView   = null;

    this._title = this.title;
    this._properties.allow_drop = true;
    this._icon = 'apps/file-manager.png';
  };

  ApplicationFileManagerWindow.prototype = Object.create(Window.prototype);

  ApplicationFileManagerWindow.prototype.init = function() {
    var self  = this;
    var app   = this._appRef;
    var root  = Window.prototype.init.apply(this, arguments);

    var fileView   = this._addGUIElement(new OSjs.GUI.FileView('FileManagerFileView', '/', {dnd: true, summary: true}), root);
    var sideView   = this._addGUIElement(new OSjs.GUI.ListView('FileManagerSideView', {dnd: false, singleClick: true}), root);
    var statusBar  = this._addGUIElement(new OSjs.GUI.StatusBar('FileManagerStatusBar'), root);
    var menuBar    = this._addGUIElement(new OSjs.GUI.MenuBar('FileManagerMenuBar'), root);

    fileView.onItemDropped = function(ev, el, item) {
      // TODO
      console.warn("Not implemented yet!");
      return false;
    };
    fileView.onFilesDropped = function(ev, el, files) {
      return self.onDropUpload(ev, el, files);
    };
    fileView.onFinished = function(dir, numItems, totalBytes) {
      statusBar.setText("Showing " + numItems + " item(s), " + totalBytes + " byte(s)");
      self._toggleLoading(false);
      try {
        self._appRef.go(dir, self);
      } catch ( e ) {
        console.warn("ApplicationFileManagerWindow->onFinished()", e);
      }
    };
    fileView.onRefresh = function() {
      statusBar.setText("Refreshing...");
      self._toggleLoading(true);
    };
    fileView.onActivated = function(name, type, mime) {
      if ( name ) {
        if ( type === 'file' ) {
          app.open(name, mime);
        } else {
          statusBar.setText("Loading...");
        }
      }
    };
    fileView.onError = function(error) {
      self._toggleLoading(false);
      OSjs.API.error("File Manager error", "An error occured while handling your request", error);
    };

    menuBar.addItem("File", [
      {title: 'Create directory', onClick: function() {
        var fileView = self._getGUIElement('FileManagerFileView');
        var cur = fileView.getPath();
        app._createDialog('Input', ["Create a new directory in " + cur + "", '', function(btn, value) {
          self._focus();
          if ( btn !== 'ok' || !value ) return;

          app.mkdir((cur + '/' + value), function() {
            if ( fileView ) {
              fileView.refresh();
              self._focus();
            }
          });
        }], self);
      }},
      {title: 'Upload', onClick: function() {
        var fileView = self._getGUIElement('FileManagerFileView');
        app._createDialog('FileUpload', [fileView.getPath(), null, function(btn, filename, mime, size) {
          self._focus();
          if ( btn != 'ok' && btn != 'complete' ) return;
          if ( fileView ) {
            fileView.refresh(function() {
              fileView.setSelected(filename, 'filename');
              self._focus();
            });
          }
        }], self);
      }},
      {title: 'Close', onClick: function() {
        self._close();
      }}
    ]);
    menuBar.addItem("Edit", [
      {name: 'Rename', title: 'Rename', onClick: function() {
        var fileView = self._getGUIElement('FileManagerFileView');
        var cur = fileView.getSelected();
        if ( !cur ) return;
        var fname = OSjs.Utils.filename(cur.path);
        app._createDialog('Input', ["Rename " + fname + "", fname, function(btn, value) {
          self._focus();
          if ( btn !== 'ok' || !value ) return;
          var newpath = OSjs.Utils.dirname(cur.path) + '/' + value;

          app.move(cur.path, newpath, function() {
            if ( fileView ) {
              fileView.refresh();
              self._focus();
            }
          });
        }], self);
      }},
      {name: 'Delete', title: 'Delete', onClick: function() {
        self._focus();

        var fileView = self._getGUIElement('FileManagerFileView');
        var cur = fileView.getSelected();
        if ( !cur ) return;
        var fname = OSjs.Utils.filename(cur.path);

        app._createDialog('Confirm', ["Delete " + fname + " ?", function(btn) {
          self._focus();
          if ( btn !== 'ok' ) return;
          app.unlink(cur.path, function() {
            if ( fileView ) {
              fileView.refresh();
            }
          });
        }]);
      }}
    ]);
    menuBar.addItem("View", [
      {title: 'Refresh', onClick: function() {
        var fileView = self._getGUIElement('FileManagerFileView');
        fileView.refresh();
        self._focus();
      }}
    ]);
    menuBar.onMenuOpen = function(menu) {
      var fileView = self._getGUIElement('FileManagerFileView');
      var sel = fileView.getSelected();
      var el1 = menu.getRoot().getElementsByClassName("MenuItem_Rename")[0];
      var el2 = menu.getRoot().getElementsByClassName("MenuItem_Delete")[0];
      var cur = sel ? sel.filename != '..' : false;
      if ( el1 ) {
        if ( cur ) {
          el1.className = el1.className.replace(/\s?Disabled/, '');
        } else {
          el1.className += ' Disabled';
        }
      }
      if ( el2 ) {
        if ( cur ) {
          el2.className = el2.className.replace(/\s?Disabled/, '');
        } else {
          el2.className += ' Disabled';
        }
      }
    };

    var _getFileIcon = function(r) {
      return OSjs.API.getThemeResource(r, 'icon');
    };

    sideView.setColumns([
      {key: 'image', title: '', type: 'image', domProperties: {width: "16"}},
      {key: 'filename', title: 'Filename'},
      {key: 'mime', title: 'Mime', visible: false},
      {key: 'size', title: 'Size', visible: false},
      {key: 'path', title: 'Path', visible: false, domProperties: {width: "70"}},
      {key: 'type', title: 'Type', visible: false, domProperties: {width: "50"}}
     ]);
    sideView.setRows([
      {image: _getFileIcon('places/folder_home.png'), filename: 'Home', mime: null, size: 0, type: 'link', path: OSjs.API.getDefaultPath('/')},
      {image: _getFileIcon('places/folder.png'), filename: 'Temp', mime: null, size: 0, type: 'link', path: '/tmp'},
      {image: _getFileIcon('devices/drive-harddisk.png'), filename: 'Filesystem', mime: null, size: 0, type: 'link', path: '/'}
    ]);
    sideView.onActivate = function(ev, el, item) {
      if ( el && item && item.path ) {
        if ( item.type === 'file' ) {
          app.open(item.path, item.mime);
        } else {
          var fileView = self._getGUIElement('FileManagerFileView');
          if ( fileView ) {
            fileView.chdir(item.path);
          }
        }
      }
    };

    sideView.render();
  };

  ApplicationFileManagerWindow.prototype.destroy = function() {
    Window.prototype.destroy.apply(this, arguments);
  };

  ApplicationFileManagerWindow.prototype._onKeyEvent = function(ev) {
    Window.prototype._onKeyEvent.apply(this, arguments);
    var fileView = this._getGUIElement('FileManagerFileView');
    if ( fileView ) {
      fileView.onKeyPress(ev);
    }
  };

  ApplicationFileManagerWindow.prototype._onDndEvent = function(ev, type, item, args) {
    Window.prototype._onDndEvent.apply(this, arguments);
    if ( type === 'filesDrop' && item ) {
      return this.onDropUpload(ev, null, item);
    }
    return true;
  };

  ApplicationFileManagerWindow.prototype.onDropUpload = function(ev, el, files) {
    var self = this;
    if ( files && files.length ) {
      var app = this._appRef;
      var fileView = this._getGUIElement('FileManagerFileView');
      var dest = fileView.getPath();

      for ( var i = 0; i < files.length; i++ ) {
        app._createDialog('FileUpload', [dest, files[i], function(btn, filename, mime, size) {
          if ( btn != 'ok' && btn != 'complete' ) return;
          var fileView = self._getGUIElement('FileManagerFileView');
          if ( fileView ) {
            fileView.refresh(function() {
              fileView.setSelected(filename, 'filename');
              self._focus();
            });
          }
        }], this);
      }
    }
    return false;
  };

  /**
   * Application
   */
  var ApplicationFileManager = function(args, metadata) {
    Application.apply(this, ['ApplicationFileManager', args, metadata]);
  };

  ApplicationFileManager.prototype = Object.create(Application.prototype);

  ApplicationFileManager.prototype.destroy = function() {
    return Application.prototype.destroy.apply(this, []);
  };

  ApplicationFileManager.prototype.init = function(core, session) {
    Application.prototype.init.apply(this, arguments);

    this._addWindow(new ApplicationFileManagerWindow(this));

    var path = this._getArgument('path') || OSjs.API.getDefaultPath('/');
    var w = this._getWindow('ApplicationFileManagerWindow');
    w._getGUIElement('FileManagerFileView').chdir(path);
    this.go(path, w);
  };

  ApplicationFileManager.prototype._onMessage = function(obj, msg, args) {
    Application.prototype._onMessage.apply(this, arguments);

    if ( msg == 'destroyWindow' && obj._name === 'ApplicationFileManagerWindow' ) {
      this.destroy();
    }
  };

  ApplicationFileManager.prototype.open = function(filename, mime) {
    OSjs.API.open(filename, mime);
  };

  ApplicationFileManager.prototype.go = function(dir, w) {
    this._setArgument('path', dir);
    w._setTitle(w.title + ' - ' + (dir || '/'));
  };

  ApplicationFileManager.prototype._action = function(name, args, callback) {
    callback = callback || function() {};

    var _onError = function(error) {
      // FIXME
      OSjs.API.error("File Manager error", "An error occured while handling your request", error);

      callback(false);
    };

    OSjs.API.call('fs', {'method': name, 'arguments': args}, function(res) {
      if ( !res || (typeof res.result === 'undefined') || res.error ) {
        _onError(res.error || 'Fatal error');
      } else {
        callback(res.result);
      }
    }, function(error) {
      _onError(error);
    });
  };

  ApplicationFileManager.prototype.move = function(src, dest, callback) {
    return this._action('move', [src, dest], callback);
  };

  ApplicationFileManager.prototype.unlink = function(name, callback) {
    return this._action('delete', [name], callback);
  };

  ApplicationFileManager.prototype.mkdir = function(name, callback) {
    return this._action('mkdir', [name], callback);
  };

  //
  // EXPORTS
  //
  OSjs.Applications = OSjs.Applications || {};
  OSjs.Applications.ApplicationFileManager = ApplicationFileManager;

})(OSjs.Core.Application, OSjs.Core.Window);
<|endoftext|>


<commit_before>function allPermutations(choices, sequenceLength) {
  if (!(sequenceLength > 0)) {
    return [];
  }

  var permutations = choices.slice();

  while (permutations.length != Math.pow(choices.length, sequenceLength)) {
    permutations = choices.reduce(function (resultList, currentReplacement) {
      return resultList.concat(permutations.map(function (currentStem) {
        return currentReplacement + currentStem;
      }));
    }, []);
  }

  return permutations;
}

module.exports = {
  allPermutations: allPermutations
};<commit_msg>Pull function out of loop.<commit_after>function allPermutations(choices, sequenceLength) {
  if (!(sequenceLength > 0)) {
    return [];
  }

  var i;
  var permutations = choices.slice();

  function permute(resultList, currentReplacement) {
    return resultList.concat(permutations.map(function (currentStem) {
      return currentReplacement + currentStem;
    }));
  }

  for (i = 1; i < sequenceLength; ++i) {
    permutations = choices.reduce(permute, []);
  }

  return permutations;
}

module.exports = {
  allPermutations: allPermutations
};<|endoftext|>


<commit_before>/*!
 * OS.js - JavaScript Operating System
 *
 * Copyright (c) 2011-2013, Anders Evenrud <andersevenrud@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @licence Simplified BSD License
 */
(function(Application, Window, GUI, Dialogs) {

  function formatTime(secs) {
    var hr  = Math.floor(secs / 3600);
    var min = Math.floor((secs - (hr * 3600))/60);
    var sec = Math.floor(secs - (hr * 3600) -  (min * 60));

    if (min < 10){
      min = "0" + min;
    }
    if (sec < 10){
      sec  = "0" + sec;
    }

    return min + ':' + sec;
  }

  /////////////////////////////////////////////////////////////////////////////
  // WINDOWS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Main Window
   */
  var ApplicationMusicPlayerWindow = function(app) {
    Window.apply(this, ['ApplicationMusicPlayerWindow', {width: 322, height: 225}, app]);

    this.title            = "Music Player";
    this.$buttons         = {};
    this.$labels          = {};
    this.$audio           = null;
    this.currentFilename  = '';
    this.seeking          = false;

    // Set window properties here
    this._title = this.title;
    this._icon  = "status/audio-volume-high.png";

    this._properties.allow_drop     = true;
    this._properties.allow_resize   = false;
    this._properties.allow_maximize = false;
  };

  ApplicationMusicPlayerWindow.prototype = Object.create(Window.prototype);

  ApplicationMusicPlayerWindow.prototype.init = function(wmRef, app) {
    var root = Window.prototype.init.apply(this, arguments);
    var self = this;

    var _createButton = function(img, onclick) {
      var b = document.createElement('button');
      var i = document.createElement('img');
      i.alt = '';
      i.src = OSjs.API.getThemeResource('actions/' + img + '.png', 'icon', '32x32');
      b.onclick = onclick;
      b.disabled = "disabled";
      b.appendChild(i);

      self.$buttons[img.split('_')[1]] = b;

      return b;
    };

    var menuBar = this._addGUIElement(new OSjs.GUI.MenuBar('ApplicationTextpadMenuBar'), root);
    menuBar.addItem("File", [
      {title: 'Open', name: 'Open', onClick: function() {
        app._createDialog('File', [{type: 'open', mimes: ['^audio']}, function(btn, fname, fmime) {
          if ( btn !== 'ok' ) return;
          app.play(fname, fmime);
        }], self);
      }},
      {title: 'Close', name: 'Close', onClick: function() {
        self._close();
      }}
    ]);

    var container = document.createElement('div');
    container.className = 'Container';

    // Audio
    this.$audio = document.createElement('audio');
    this.$audio.style.display = 'none';
    this.$audio.style.position = 'absolute';
    this.$audio.style.top = '-10000px';
    this.$audio.style.left = '-10000px';

    // Info
    var info = document.createElement('div');
    info.className = 'Info';

    var lblArtist = document.createElement('div');
    var spanArtist = document.createElement('span');
    var infoArtist = document.createElement('span');
    spanArtist.className = 'Label';
    spanArtist.innerHTML = 'Artist';
    infoArtist.innerHTML = '-';
    lblArtist.appendChild(spanArtist);
    lblArtist.appendChild(infoArtist);
    info.appendChild(lblArtist);
    this.$labels.Artist = infoArtist;

    var lblAlbum = document.createElement('div');
    var spanAlbum = document.createElement('span');
    var infoAlbum = document.createElement('span');
    spanAlbum.className = 'Label';
    spanAlbum.innerHTML = 'Album';
    infoAlbum.innerHTML = '-';
    lblAlbum.appendChild(spanAlbum);
    lblAlbum.appendChild(infoAlbum);
    info.appendChild(lblAlbum);
    this.$labels.Album = infoAlbum;

    var lblTrack = document.createElement('div');
    var spanTrack = document.createElement('span');
    var infoTrack = document.createElement('span');
    spanTrack.className = 'Label';
    spanTrack.innerHTML = 'Track';
    infoTrack.innerHTML = '-';
    lblTrack.appendChild(spanTrack);
    lblTrack.appendChild(infoTrack);
    info.appendChild(lblTrack);
    this.$labels.Track = infoTrack;

    var lblTime = document.createElement('div');
    var spanTime = document.createElement('span');
    var infoTime = document.createElement('span');
    spanTime.className = 'Label';
    spanTime.innerHTML = 'Time';
    infoTime.innerHTML = '00:00 / 00:00';
    lblTime.appendChild(spanTime);
    lblTime.appendChild(infoTime);
    info.appendChild(lblTime);
    this.$labels.Time = infoTime;

    // Buttons
    var buttons = document.createElement('div');
    buttons.className = 'Buttons';

    buttons.appendChild(_createButton('player_start', function(ev) {
    }));
    buttons.appendChild(_createButton('player_rew', function(ev) {
    }));
    buttons.appendChild(_createButton('player_play', function(ev) {
      self.$audio.play();
    }));
    buttons.appendChild(_createButton('player_pause', function(ev) {
      self.$audio.pause();
    }));
    buttons.appendChild(_createButton('player_fwd', function(ev) {
    }));
    buttons.appendChild(_createButton('player_end', function(ev) {
    }));

    // Containers
    container.appendChild(info);
    var slider = this._addGUIElement(new OSjs.GUI.Slider('MusicPlayerSlider', {min:0, max:100, val:0}, function(val) {
      if ( val < 0 ) return;
      self.seek(val);
    }), container);
    container.appendChild(buttons);

    // FIXME: Remove event listeners
    this.$audio.addEventListener("loadeddata", function(ev) {
      self.updateInfo(ev, null, slider);
      app.info(self.currentFilename);
    });
    this.$audio.addEventListener("timeupdate", function(ev) {
      self.updateTime(ev, slider);
    });
    this.$audio.addEventListener("error", function(ev) {
      self.updateInfo(ev, null, slider);
    });

    root.appendChild(container);
    root.appendChild(this.$audio);
    return root;
  };

  ApplicationMusicPlayerWindow.prototype.destroy = function() {
    // Destroy custom objects etc. here

    Window.prototype.destroy.apply(this, arguments);
  };

  ApplicationMusicPlayerWindow.prototype._onDndEvent = function(ev, type, item, args) {
    Window.prototype._onDndEvent.apply(this, arguments);
    if ( type === 'itemDrop' && item ) {
      var data = item.data;
      if ( data && data.type === 'file' && data.mime ) {
        this._appRef.play(data.path, data.mime);
      }
    }
  };

  ApplicationMusicPlayerWindow.prototype.play = function(filename, mime) {
    this.currentFilename = filename;

    try {
      this.$labels.Arist.innerHTML = filename;
      this.$labels.Album.innerHTML = mime;
    } catch ( e ) {
      console.warn("Failed to set labels", e);
    }

    try {
      this.$buttons.play.removeAttribute('disabled');
      this.$buttons.pause.removeAttribute('disabled');
    } catch ( e ) {
      console.warn("Failed toggle buttons", e);
    }

    this.$audio.src         = OSjs.API.getResourceURL(filename);
    this.$audio.volume      = 1.0;

    this.$audio.play();

    this._setTitle(this.title + ' - ' + OSjs.Utils.filename(filename));

    return true;
  };

  ApplicationMusicPlayerWindow.prototype.updateInfo = function(ev, info, slider) {
    if ( this.seeking ) return;
    if ( !this.$audio ) return;
    info = info || {};
    var msg = '-';
    if ( !info.Artist && !info.Album && !info.Track ) {
      msg = "Media information query failed";
    }
    this.$labels.Artist.innerHTML = info.Artist || msg;
    this.$labels.Album.innerHTML  = info.Album  || OSjs.Utils.dirname(this.currentFilename);
    this.$labels.Track.innerHTML  = info.Track  || OSjs.Utils.filename(this.currentFilename);
    this.updateTime(ev, slider);

    if ( slider ) {
      slider.min = 0;
      slider.max = 0;
      slider.setValue(0);
    }
  };

  ApplicationMusicPlayerWindow.prototype.updateTime = function(ev, slider, error) {
    if ( this.seeking ) return;
    if ( !this.$audio ) return;
    ev = ev || window.event;

    var total   = error ? 0 : this.$audio.duration;
    var current = error ? 0 : this.$audio.currentTime;
    var unknown = false;

    if ( isNaN(current) || !isFinite(current) ) current = 0.0;
    if ( isNaN(total) || !isFinite(total) ) {
      total = current;
      unknown = true;
    }

    var ftotal   = formatTime(total);
    var fcurrent = formatTime(current);
    if ( unknown ) {
      ftotal = '-' + ftotal + ' (seek unavailable in format)';
    }
    this.$labels.Time.innerHTML = fcurrent  + " / " + ftotal;

    if ( slider ) {
      slider.max = Math.round(total);
      slider.setValue(Math.round(current));
    }
  };

  ApplicationMusicPlayerWindow.prototype.seek = function(val) {
    this.seeking = true;
    try {
      this.$audio.currentTime = val;
    } catch ( e ) {
      console.warn("Failed to seek", e, val);
    }

    this.seeking = false;
  };

  /////////////////////////////////////////////////////////////////////////////
  // APPLICATION
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Application
   */
  var ApplicationMusicPlayer = function(args, metadata) {
    if ( !OSjs.Utils.getCompability().audio ) {
      throw "Your platform does not support Audio :(";
    }
    Application.apply(this, ['ApplicationMusicPlayer', args, metadata]);
    this.__dname = 'MusicPlayer';
  };

  ApplicationMusicPlayer.prototype = Object.create(Application.prototype);

  ApplicationMusicPlayer.prototype.destroy = function() {
    return Application.prototype.destroy.apply(this, []);
  };

  ApplicationMusicPlayer.prototype.init = function(core, session) {
    Application.prototype.init.apply(this, arguments);
    var self = this;

    this._addWindow(new ApplicationMusicPlayerWindow(this));

    var path = this._getArgument('file');
    var mime = this._getArgument('mime');
    if ( path ) {
      this.play(path, mime);
    }
  };

  ApplicationMusicPlayer.prototype._onMessage = function(obj, msg, args) {
    Application.prototype._onMessage.apply(this, arguments);

    if ( msg == 'destroyWindow' && obj._name === 'ApplicationMusicPlayerWindow' ) {
      this.destroy();
    } else if ( msg == 'attention' && args ) {
      this.play(args.file, args.mime);
    }
  };

  ApplicationMusicPlayer.prototype.play = function(filename, mime) {
    mime = mime || '';
    if ( !mime.match(/^audio/) ) {
      throw "The audio type is not supported: " + mime;
    }

    var win = this._getWindow('ApplicationMusicPlayerWindow');
    if ( win ) {
      if ( win.play(filename, mime) ) {
        (function() {})();
      }
    }

    this._setArgument('file', filename);
    this._setArgument('mime', mime);
  };

  ApplicationMusicPlayer.prototype.info = function(filename) {
    var win = this._getWindow('ApplicationMusicPlayerWindow');
    if ( win ) {
      this._call('info', {filename: filename}, function(res) {
        var info = (res && res.result) ? res.result : null;
        win.updateInfo(null, info);
      });
    }
  };

  //
  // EXPORTS
  //
  OSjs.Applications = OSjs.Applications || {};
  OSjs.Applications.ApplicationMusicPlayer = ApplicationMusicPlayer;

})(OSjs.Core.Application, OSjs.Core.Window, OSjs.Core.GUI, OSjs.Core.Dialogs);
<commit_msg>MusicPlayer: Error handling<commit_after>/*!
 * OS.js - JavaScript Operating System
 *
 * Copyright (c) 2011-2013, Anders Evenrud <andersevenrud@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @licence Simplified BSD License
 */
(function(Application, Window, GUI, Dialogs) {

  function formatTime(secs) {
    var hr  = Math.floor(secs / 3600);
    var min = Math.floor((secs - (hr * 3600))/60);
    var sec = Math.floor(secs - (hr * 3600) -  (min * 60));

    if (min < 10){
      min = "0" + min;
    }
    if (sec < 10){
      sec  = "0" + sec;
    }

    return min + ':' + sec;
  }

  /////////////////////////////////////////////////////////////////////////////
  // WINDOWS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Main Window
   */
  var ApplicationMusicPlayerWindow = function(app) {
    Window.apply(this, ['ApplicationMusicPlayerWindow', {width: 322, height: 225}, app]);

    this.title            = "Music Player";
    this.$buttons         = {};
    this.$labels          = {};
    this.$audio           = null;
    this.currentFilename  = '';
    this.seeking          = false;

    // Set window properties here
    this._title = this.title;
    this._icon  = "status/audio-volume-high.png";

    this._properties.allow_drop     = true;
    this._properties.allow_resize   = false;
    this._properties.allow_maximize = false;
  };

  ApplicationMusicPlayerWindow.prototype = Object.create(Window.prototype);

  ApplicationMusicPlayerWindow.prototype.init = function(wmRef, app) {
    var root = Window.prototype.init.apply(this, arguments);
    var self = this;

    var _createButton = function(img, onclick) {
      var b = document.createElement('button');
      var i = document.createElement('img');
      i.alt = '';
      i.src = OSjs.API.getThemeResource('actions/' + img + '.png', 'icon', '32x32');
      b.onclick = onclick;
      b.disabled = "disabled";
      b.appendChild(i);

      self.$buttons[img.split('_')[1]] = b;

      return b;
    };

    var menuBar = this._addGUIElement(new OSjs.GUI.MenuBar('ApplicationTextpadMenuBar'), root);
    menuBar.addItem("File", [
      {title: 'Open', name: 'Open', onClick: function() {
        app._createDialog('File', [{type: 'open', mimes: ['^audio']}, function(btn, fname, fmime) {
          if ( btn !== 'ok' ) return;
          app.play(fname, fmime);
        }], self);
      }},
      {title: 'Close', name: 'Close', onClick: function() {
        self._close();
      }}
    ]);

    var container = document.createElement('div');
    container.className = 'Container';

    // Audio
    this.$audio = document.createElement('audio');
    this.$audio.style.display = 'none';
    this.$audio.style.position = 'absolute';
    this.$audio.style.top = '-10000px';
    this.$audio.style.left = '-10000px';

    // Info
    var info = document.createElement('div');
    info.className = 'Info';

    var lblArtist = document.createElement('div');
    var spanArtist = document.createElement('span');
    var infoArtist = document.createElement('span');
    spanArtist.className = 'Label';
    spanArtist.innerHTML = 'Artist';
    infoArtist.innerHTML = '-';
    lblArtist.appendChild(spanArtist);
    lblArtist.appendChild(infoArtist);
    info.appendChild(lblArtist);
    this.$labels.Artist = infoArtist;

    var lblAlbum = document.createElement('div');
    var spanAlbum = document.createElement('span');
    var infoAlbum = document.createElement('span');
    spanAlbum.className = 'Label';
    spanAlbum.innerHTML = 'Album';
    infoAlbum.innerHTML = '-';
    lblAlbum.appendChild(spanAlbum);
    lblAlbum.appendChild(infoAlbum);
    info.appendChild(lblAlbum);
    this.$labels.Album = infoAlbum;

    var lblTrack = document.createElement('div');
    var spanTrack = document.createElement('span');
    var infoTrack = document.createElement('span');
    spanTrack.className = 'Label';
    spanTrack.innerHTML = 'Track';
    infoTrack.innerHTML = '-';
    lblTrack.appendChild(spanTrack);
    lblTrack.appendChild(infoTrack);
    info.appendChild(lblTrack);
    this.$labels.Track = infoTrack;

    var lblTime = document.createElement('div');
    var spanTime = document.createElement('span');
    var infoTime = document.createElement('span');
    spanTime.className = 'Label';
    spanTime.innerHTML = 'Time';
    infoTime.innerHTML = '00:00 / 00:00';
    lblTime.appendChild(spanTime);
    lblTime.appendChild(infoTime);
    info.appendChild(lblTime);
    this.$labels.Time = infoTime;

    // Buttons
    var buttons = document.createElement('div');
    buttons.className = 'Buttons';

    buttons.appendChild(_createButton('player_start', function(ev) {
    }));
    buttons.appendChild(_createButton('player_rew', function(ev) {
    }));
    buttons.appendChild(_createButton('player_play', function(ev) {
      self.$audio.play();
    }));
    buttons.appendChild(_createButton('player_pause', function(ev) {
      self.$audio.pause();
    }));
    buttons.appendChild(_createButton('player_fwd', function(ev) {
    }));
    buttons.appendChild(_createButton('player_end', function(ev) {
    }));

    // Containers
    container.appendChild(info);
    var slider = this._addGUIElement(new OSjs.GUI.Slider('MusicPlayerSlider', {min:0, max:100, val:0}, function(val) {
      if ( val < 0 ) return;
      self.seek(val);
    }), container);
    container.appendChild(buttons);

    // FIXME: Remove event listeners
    this.$audio.addEventListener("loadeddata", function(ev) {
      self.updateInfo(ev, null, slider);
      app.info(self.currentFilename);
    });
    this.$audio.addEventListener("timeupdate", function(ev) {
      self.updateTime(ev, slider);
    });
    this.$audio.addEventListener("error", function(ev) {
      self.updateInfo(ev, null, slider);

      var msg;
      try {
        switch ( ev.target.error.code ) {
          case ev.target.error.MEDIA_ERR_ABORTED:
            msg = 'You aborted the video playback.';
            break;
          case ev.target.error.MEDIA_ERR_NETWORK:
            msg = 'A network error caused the audio download to fail.';
            break;
          case ev.target.error.MEDIA_ERR_DECODE:
            msg = 'The audio playback was aborted due to a corruption problem or because the video used features your browser did not support.';
            break;
          case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
            msg = 'The video audio not be loaded, either because the server or network failed or because the format is not supported.';
            break;
          default:
            msg = "Unknown error";
            break;
        }
      } catch ( e ) {
        msg = "Fatal error: " + e;
      }

      self._error("Music Player error", "Failed to play file", msg);
    }, true);

    root.appendChild(container);
    root.appendChild(this.$audio);
    return root;
  };

  ApplicationMusicPlayerWindow.prototype.destroy = function() {
    // Destroy custom objects etc. here

    Window.prototype.destroy.apply(this, arguments);
  };

  ApplicationMusicPlayerWindow.prototype._onDndEvent = function(ev, type, item, args) {
    Window.prototype._onDndEvent.apply(this, arguments);
    if ( type === 'itemDrop' && item ) {
      var data = item.data;
      if ( data && data.type === 'file' && data.mime ) {
        this._appRef.play(data.path, data.mime);
      }
    }
  };

  ApplicationMusicPlayerWindow.prototype.play = function(filename, mime) {
    this.currentFilename = filename;

    try {
      this.$labels.Arist.innerHTML = filename;
      this.$labels.Album.innerHTML = mime;
    } catch ( e ) {
      console.warn("Failed to set labels", e);
    }

    try {
      this.$buttons.play.removeAttribute('disabled');
      this.$buttons.pause.removeAttribute('disabled');
    } catch ( e ) {
      console.warn("Failed toggle buttons", e);
    }

    this.$audio.src         = OSjs.API.getResourceURL(filename);
    this.$audio.volume      = 1.0;

    this.$audio.play();

    this._setTitle(this.title + ' - ' + OSjs.Utils.filename(filename));

    return true;
  };

  ApplicationMusicPlayerWindow.prototype.updateInfo = function(ev, info, slider) {
    if ( this.seeking ) return;
    if ( !this.$audio ) return;
    info = info || {};
    var msg = '-';
    if ( !info.Artist && !info.Album && !info.Track ) {
      msg = "Media information query failed";
    }
    this.$labels.Artist.innerHTML = info.Artist || msg;
    this.$labels.Album.innerHTML  = info.Album  || OSjs.Utils.dirname(this.currentFilename);
    this.$labels.Track.innerHTML  = info.Track  || OSjs.Utils.filename(this.currentFilename);
    this.updateTime(ev, slider);

    if ( slider ) {
      slider.min = 0;
      slider.max = 0;
      slider.setValue(0);
    }
  };

  ApplicationMusicPlayerWindow.prototype.updateTime = function(ev, slider, error) {
    if ( this.seeking ) return;
    if ( !this.$audio ) return;
    ev = ev || window.event;

    var total   = error ? 0 : this.$audio.duration;
    var current = error ? 0 : this.$audio.currentTime;
    var unknown = false;

    if ( isNaN(current) || !isFinite(current) ) current = 0.0;
    if ( isNaN(total) || !isFinite(total) ) {
      total = current;
      unknown = true;
    }

    var ftotal   = formatTime(total);
    var fcurrent = formatTime(current);
    if ( unknown ) {
      ftotal = '-' + ftotal + ' (seek unavailable in format)';
    }
    this.$labels.Time.innerHTML = fcurrent  + " / " + ftotal;

    if ( slider ) {
      slider.max = Math.round(total);
      slider.setValue(Math.round(current));
    }
  };

  ApplicationMusicPlayerWindow.prototype.seek = function(val) {
    this.seeking = true;
    try {
      this.$audio.currentTime = val;
    } catch ( e ) {
      console.warn("Failed to seek", e, val);
    }

    this.seeking = false;
  };

  /////////////////////////////////////////////////////////////////////////////
  // APPLICATION
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Application
   */
  var ApplicationMusicPlayer = function(args, metadata) {
    if ( !OSjs.Utils.getCompability().audio ) {
      throw "Your platform does not support Audio :(";
    }
    Application.apply(this, ['ApplicationMusicPlayer', args, metadata]);
    this.__dname = 'MusicPlayer';
  };

  ApplicationMusicPlayer.prototype = Object.create(Application.prototype);

  ApplicationMusicPlayer.prototype.destroy = function() {
    return Application.prototype.destroy.apply(this, []);
  };

  ApplicationMusicPlayer.prototype.init = function(core, session) {
    Application.prototype.init.apply(this, arguments);
    var self = this;

    this._addWindow(new ApplicationMusicPlayerWindow(this));

    var path = this._getArgument('file');
    var mime = this._getArgument('mime');
    if ( path ) {
      this.play(path, mime);
    }
  };

  ApplicationMusicPlayer.prototype._onMessage = function(obj, msg, args) {
    Application.prototype._onMessage.apply(this, arguments);

    if ( msg == 'destroyWindow' && obj._name === 'ApplicationMusicPlayerWindow' ) {
      this.destroy();
    } else if ( msg == 'attention' && args ) {
      this.play(args.file, args.mime);
    }
  };

  ApplicationMusicPlayer.prototype.play = function(filename, mime) {
    mime = mime || '';
    if ( !mime.match(/^audio/) ) {
      var msg = "The audio type is not supported: " + mime;
      this._error("Music Player error", "Failed to play file", msg);
      return;
    }

    var win = this._getWindow('ApplicationMusicPlayerWindow');
    if ( win ) {
      if ( win.play(filename, mime) ) {
        (function() {})();
      }
    }

    this._setArgument('file', filename);
    this._setArgument('mime', mime);
  };

  ApplicationMusicPlayer.prototype.info = function(filename) {
    var win = this._getWindow('ApplicationMusicPlayerWindow');
    if ( win ) {
      this._call('info', {filename: filename}, function(res) {
        var info = (res && res.result) ? res.result : null;
        win.updateInfo(null, info);
      });
    }
  };

  //
  // EXPORTS
  //
  OSjs.Applications = OSjs.Applications || {};
  OSjs.Applications.ApplicationMusicPlayer = ApplicationMusicPlayer;

})(OSjs.Core.Application, OSjs.Core.Window, OSjs.Core.GUI, OSjs.Core.Dialogs);
<|endoftext|>


<commit_before>var fs = require('fs');
var parse = require('parse-diff');
var argv = require('minimist')(process.argv.slice(2));

var unifiedDiff = argv._[0];
if (unifiedDiff.endsWith('.diff')) {
    readFile(argv._[0], function(warnings) {
        warnings.forEach(function(item) {
            console.log(item.content.message);
        });
    });
}

function readFile(file, callback) {
    fs.readFile(file, "utf-8", function(err, data) {
        if (err) {
            console.error(err);
            callback(undefined);
        }
        findBug(data, function(warnings) {
            callback(warnings);
        });
    });
}

function findBug(diff, callback) {

    // Store New Warnings \ Old Warnings
    var warnings = [];

    var files = parse(diff);

    files.forEach(function(file) {
        file.chunks.forEach(function(chunk) {

            // Store all deletions and additions in the original orders
            var changes = [];

            for (var i = 0; i < chunk.changes.length; i++) {

                var change = chunk.changes[i];
                if (change.type === 'del' || change.type === 'add') {
                    if (containsWarning(change) && !shouldFilterWarning(change)) {
                        changes.push(parseWarning(change));
                    }
                }
            }

            warnings = warnings.concat(filterChanges(changes));
        });
    });

    callback(warnings);
}

function parseWarning(change) {
    var decodedChange = JSON.parse(JSON.stringify(change));

    var components = change.content.split(':');
    var content = {
        message: change.content.substring(1),
        filename: components[0].substring(1),
        startLine: Number(components[1]),
        startCol: Number(components[2].split('~')[0]),
        endLine: Number(components[2].split('~')[1]),
        endCol: Number(components[3]),
        warning: components[4].substring(1)
    }
    decodedChange.content = content;

    return decodedChange;
}

function isSameChange(delChange, addChange) {
    return delChange.content.filename === addChange.content.filename && delChange.content.startLine === addChange.content.startLine && delChange.content.warning === addChange.content.warning;
}

function filterChanges(changes) {
    var filteredIndex = [];
    var filteredChanges = [];

    for (var i = 0; i < changes.length; i++) {
        if (changes[i].type === 'del' && filteredIndex.indexOf(i) === -1) {
            var del = changes[i];

            for (var j = i + 1; j < changes.length; j++) {
                if (changes[j].type === 'add' && filteredIndex.indexOf(j) === -1) {
                    var add = changes[j];

                    if (isSameChange(del, add)) {
                        filteredIndex.push(i, j);
                    }
                }
            }
        }
    }

    for (var i = 0; i < changes.length; i++) {
        if (filteredIndex.indexOf(i) === -1 && changes[i].type === 'add')
            filteredChanges.push(changes[i]);
    }

    return (filteredChanges);
}

function containsWarning(change) {
    return change.content.indexOf('[Warning]') > -1
}

function shouldFilterWarning(change) {
    var content = change.content;

    // Conditional expression [expr] is always true / false
    if (content.indexOf('Conditional expression') > -1 && content.indexOf('is always') > -1) {
        return true;
    }

    // Too many / few arguments to function
    else if (content.indexOf('Too many arguments to function') > -1 || content.indexOf('Too few arguments to function') > -1) {
        return true;
    } else {
        return false;
    }
}

module.exports = {
    readFile: readFile,
    findBug: findBug,
    parseWarning: parseWarning,
    isSameChange: isSameChange,
    filterChanges: filterChanges,
    shouldFilterWarning: shouldFilterWarning
}<commit_msg>Print the number of warnings found.<commit_after>var fs = require('fs');
var parse = require('parse-diff');
var argv = require('minimist')(process.argv.slice(2));

var unifiedDiff = argv._[0];
if (unifiedDiff.endsWith('.diff')) {
    readFile(argv._[0], function(warnings) {
        warnings.forEach(function(item) {
            console.log(item.content.message);
        });
        console.log(warnings.length + ' warning(s) found.');
    });
}

function readFile(file, callback) {
    fs.readFile(file, "utf-8", function(err, data) {
        if (err) {
            console.error(err);
            callback(undefined);
        }
        findBug(data, function(warnings) {
            callback(warnings);
        });
    });
}

function findBug(diff, callback) {

    // Store New Warnings \ Old Warnings
    var warnings = [];

    var files = parse(diff);

    files.forEach(function(file) {
        file.chunks.forEach(function(chunk) {

            // Store all deletions and additions in the original orders
            var changes = [];

            for (var i = 0; i < chunk.changes.length; i++) {

                var change = chunk.changes[i];
                if (change.type === 'del' || change.type === 'add') {
                    if (containsWarning(change) && !shouldFilterWarning(change)) {
                        changes.push(parseWarning(change));
                    }
                }
            }

            warnings = warnings.concat(filterChanges(changes));
        });
    });

    callback(warnings);
}

function parseWarning(change) {
    var decodedChange = JSON.parse(JSON.stringify(change));

    var components = change.content.split(':');
    var content = {
        message: change.content.substring(1),
        filename: components[0].substring(1),
        startLine: Number(components[1]),
        startCol: Number(components[2].split('~')[0]),
        endLine: Number(components[2].split('~')[1]),
        endCol: Number(components[3]),
        warning: components[4].substring(1)
    }
    decodedChange.content = content;

    return decodedChange;
}

function isSameChange(delChange, addChange) {
    return delChange.content.filename === addChange.content.filename && delChange.content.startLine === addChange.content.startLine && delChange.content.warning === addChange.content.warning;
}

function filterChanges(changes) {
    var filteredIndex = [];
    var filteredChanges = [];

    for (var i = 0; i < changes.length; i++) {
        if (changes[i].type === 'del' && filteredIndex.indexOf(i) === -1) {
            var del = changes[i];

            for (var j = i + 1; j < changes.length; j++) {
                if (changes[j].type === 'add' && filteredIndex.indexOf(j) === -1) {
                    var add = changes[j];

                    if (isSameChange(del, add)) {
                        filteredIndex.push(i, j);
                    }
                }
            }
        }
    }

    for (var i = 0; i < changes.length; i++) {
        if (filteredIndex.indexOf(i) === -1 && changes[i].type === 'add')
            filteredChanges.push(changes[i]);
    }

    return (filteredChanges);
}

function containsWarning(change) {
    return change.content.indexOf('[Warning]') > -1
}

function shouldFilterWarning(change) {
    var content = change.content;

    // Conditional expression [expr] is always true / false
    if (content.indexOf('Conditional expression') > -1 && content.indexOf('is always') > -1) {
        return true;
    }

    // Too many / few arguments to function
    else if (content.indexOf('Too many arguments to function') > -1 || content.indexOf('Too few arguments to function') > -1) {
        return true;
    } else {
        return false;
    }
}

module.exports = {
    readFile: readFile,
    findBug: findBug,
    parseWarning: parseWarning,
    isSameChange: isSameChange,
    filterChanges: filterChanges,
    shouldFilterWarning: shouldFilterWarning
}<|endoftext|>


<commit_before>/*!
 * romanize <https://github.com/jonschlinkert/romanize>
 * Based on http://bit.ly/1weeOfY
 *
 * Copyright (c) 2014 Jon Schlinkert, contributors.
 * Licensed under the MIT License
 */

'use strict';

module.exports = function(num) {
  var numeral = '';
  var lookup = {
    M: 1000,
    CM: 900,
    D: 500,
    CD: 400,
    C: 100,
    XC: 90,
    L: 50,
    XL: 40,
    X: 10,
    IX: 9,
    V: 5,
    IV: 4,
    I: 1
  };

  for (var key in lookup) {
    while (num >= lookup[key]) {
      numeral += key;
      num -= lookup[key];
    }
  }
  return numeral;
};
<commit_msg>minor optimizations<commit_after>/*!
 * romanize <https://github.com/jonschlinkert/romanize>
 * Inspired by http://bit.ly/1weeOfY
 *
 * Copyright (c) 2014, 2017, Jon Schlinkert.
 * Released under the MIT License.
 */

'use strict';

var numerals = { M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90, L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1 };

module.exports = function(num) {
  var keys = Object.keys(numerals);
  var numeral = '';
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    while (num >= numerals[key]) {
      numeral += key;
      num -= numerals[key];
    }
  }
  return numeral;
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

try {
  'use strict'
  var meow = require('meow')
    , chalk = require('chalk')

  // temporary test of meow
  var cli = meow(
    '\n  Usages\n'+
    '    $ gloss2text\n'+
    '    $ gloss2text <grammarfile>\n\n'+
    '      REPL mode, any gloss typed on the command-line is parsed.\n'+
    '      /h or /help for inline help about available commands\n\n'+
    '    $ gloss2text <grammarfile> <glossfile>\n\n'+
    '      Options\n'+
    '        -o, --out\tfile to send output to (otherwise goes to command-line)\n'+
    '        -i, --interlinear\toutput both result text on one line and original gloss under\n'+
    '\n'+
    '      Examples\n'+
    '        $ gloss grammar.json gloss.txt -i\n',
    '        $ gloss grammar.yml gloss.txt -i -o glossed.txt\n',
    {
      alias: {
        o: 'output',
        i: 'interlinear'
      }
    }
  )

  if (cli.input.length==0 && Object.keys(cli.flags).length==0) {
    cli.showHelp()
  } else {
    //TODO
    if (cli.input.length!==2 && Object.keys(cli.flags).length > 0) throw Error('Cannot have options in REPL mode.')

    //console.log(cli.input)
    //console.log(cli.flags)

    var parser_builder = require(__dirname+'/lib/parser.js')
      , fs = require('fs')
      , yaml = require('js-yaml')
      , parse = /yml$/.test(cli.input[0]) ? yaml.safeLoad : JSON.parse

    if (cli.input.length==2) {
      var parser = parser_builder(parse(fs.readFileSync(cli.input[0], 'utf8')))
        , text = fs.readFileSync(cli.input[1], 'utf8')
        , lines = text.split('\n')
        , x = undefined

      lines.forEach(function(l) {
        if (/^\s*$/.test(l) || l.startsWith('>')) {
          process.stdout.write(l+'\n')
        } else if (l.startsWith('#')) {
          x = l.replace(/^#\s*/,'')
        } else {
          var p = parser(l)
          if (typeof x !== 'undefined' && p !== x) {
            process.stdout.write(chalk.red('Expect: '+x)+'\n')
            process.stdout.write(chalk.red('Actual: '+p)+'\n')
          } else {
            process.stdout.write(chalk.cyan(p)+'\n')
          }
          if (cli.flags.i) process.stdout.write(chalk.yellow(l)+'\n')
          x = undefined
        }
      })
    }
  }

//*
} catch(e) {
  process.stderr.write(chalk.magenta('ERROR:'+e.message+'\n'))
  process.exit(1)
//*/
} finally {
  process.exit(0)
}
<commit_msg>start a tool to help grammar maintenance<commit_after>#!/usr/bin/env node

try {
  'use strict'
  var meow = require('meow')
    , chalk = require('chalk')

  // temporary test of meow
  var cli = meow(
    '\n  Usages\n'+
    '    $ gloss2text\n\n'+
    '      This documentation.\n'+
    '\n'+
    '    $ gloss2text <grammarfile>\n'+
    '\n'+
    '      Options\n'+
    '        -c, --count\tcount lexicon entries\n'+
    '\n'+
    '    $ gloss2text <grammarfile> <glossfile>\n'+
    '\n'+
    '      Options\n'+
    '        -o, --out\tfile to send output to (otherwise goes to command-line)\n'+
    '        -i, --interlinear\toutput both result text on one line and original gloss under\n'+
    '\n'+
    '      Examples\n'+
    '        $ gloss grammar.json gloss.txt -i\n',
    '        $ gloss grammar.yml gloss.txt -i -o glossed.txt\n',
    {
      alias: {
        o: 'output',
        i: 'interlinear',
        c: 'count',

      }
    }
  )

  if (cli.input.length==0 && Object.keys(cli.flags).length==0) {
    cli.showHelp()
  } else {
    //console.log(cli.input)
    //console.log(cli.flags)

    var parser_builder = require(__dirname+'/lib/parser.js')
      , fs = require('fs')
      , yaml = require('js-yaml')
      , parse = /yml$/.test(cli.input[0]) ? yaml.safeLoad : JSON.parse

    if (cli.input.length==1) {
      var grammar_analyser = require(__dirname+'/lib/grammar_analyser.js')(parse(fs.readFileSync(cli.input[0], 'utf8')))
      if (cli.flags.c) {
        console.log('lexicon entries: '+grammar_analyser.count())
      }
    } else if (cli.input.length==2) {
      var parser = parser_builder(parse(fs.readFileSync(cli.input[0], 'utf8')))
        , text = fs.readFileSync(cli.input[1], 'utf8')
        , lines = text.split('\n')
        , x = undefined

      lines.forEach(function(l) {
        if (/^\s*$/.test(l) || l.startsWith('>')) {
          process.stdout.write(l+'\n')
        } else if (l.startsWith('#')) {
          x = l.replace(/^#\s*/,'')
        } else {
          var p = parser(l)
          if (typeof x !== 'undefined' && p !== x) {
            process.stdout.write(chalk.red('Expect: '+x)+'\n')
            process.stdout.write(chalk.red('Actual: '+p)+'\n')
          } else {
            process.stdout.write(chalk.cyan(p)+'\n')
          }
          if (cli.flags.i) process.stdout.write(chalk.yellow(l)+'\n')
          x = undefined
        }
      })
    }
  }

//*
} catch(e) {
  process.stderr.write(chalk.magenta('ERROR:'+e.message+'\n'))
  process.exit(1)
//*/
} finally {
  process.exit(0)
}
<|endoftext|>


<commit_before>var Object_keys = function (obj) {
    if (Object.keys) return Object.keys(obj)
    else {
        var res = [];
        for (var key in obj) res.push(key)
        return res;
    }
};

var forEach = function (xs, fn) {
    if (xs.forEach) return xs.forEach(fn)
    else for (var i = 0; i < xs.length; i++) {
        fn(xs[i], i, xs);
    }
};

var Script = exports.Script = function NodeScript (code) {
    if (!(this instanceof Script)) return new Script(code);
    this.code = code;
};

Script.prototype.runInNewContext = function (context) {
    if (!context) context = {};

    var iframe = document.createElement('iframe');
    if (!iframe.style) iframe.style = {};
    iframe.style.display = 'none';

    document.body.appendChild(iframe);

    var win = iframe.contentWindow;

    forEach(Object_keys(context), function (key) {
        win[key] = context[key];
    });

    if (!win.eval && win.execScript) {
        // win.eval() magically appears when this is called in IE:
        win.execScript('null');
    }

    var res = win.eval(this.code);

    forEach(Object_keys(win), function (key) {
        context[key] = win[key];
    });

    document.body.removeChild(iframe);

    return res;
};

Script.prototype.runInThisContext = function () {
    return eval(this.code); // maybe...
};

Script.prototype.runInContext = function (context) {
    // seems to be just runInNewContext on magical context objects which are
    // otherwise indistinguishable from objects except plain old objects
    // for the parameter segfaults node
    return this.runInNewContext(context);
};

forEach(Object_keys(Script.prototype), function (name) {
    exports[name] = Script[name] = function (code) {
        var s = Script(code);
        return s[name].apply(s, [].slice.call(arguments, 1));
    };
});

exports.createScript = function (code) {
    return exports.Script(code);
};

exports.createContext = Script.createContext = function (context) {
    // not really sure what this one does
    // seems to just make a shallow copy
    var copy = {};
    forEach(Object_keys(context), function (key) {
        copy[key] = context[key];
    });
    return copy;
};
<commit_msg>support Script.createContext() without arguments<commit_after>var Object_keys = function (obj) {
    if (Object.keys) return Object.keys(obj)
    else {
        var res = [];
        for (var key in obj) res.push(key)
        return res;
    }
};

var forEach = function (xs, fn) {
    if (xs.forEach) return xs.forEach(fn)
    else for (var i = 0; i < xs.length; i++) {
        fn(xs[i], i, xs);
    }
};

var Script = exports.Script = function NodeScript (code) {
    if (!(this instanceof Script)) return new Script(code);
    this.code = code;
};

Script.prototype.runInNewContext = function (context) {
    if (!context) context = {};

    var iframe = document.createElement('iframe');
    if (!iframe.style) iframe.style = {};
    iframe.style.display = 'none';

    document.body.appendChild(iframe);

    var win = iframe.contentWindow;

    forEach(Object_keys(context), function (key) {
        win[key] = context[key];
    });

    if (!win.eval && win.execScript) {
        // win.eval() magically appears when this is called in IE:
        win.execScript('null');
    }

    var res = win.eval(this.code);

    forEach(Object_keys(win), function (key) {
        context[key] = win[key];
    });

    document.body.removeChild(iframe);

    return res;
};

Script.prototype.runInThisContext = function () {
    return eval(this.code); // maybe...
};

Script.prototype.runInContext = function (context) {
    // seems to be just runInNewContext on magical context objects which are
    // otherwise indistinguishable from objects except plain old objects
    // for the parameter segfaults node
    return this.runInNewContext(context);
};

forEach(Object_keys(Script.prototype), function (name) {
    exports[name] = Script[name] = function (code) {
        var s = Script(code);
        return s[name].apply(s, [].slice.call(arguments, 1));
    };
});

exports.createScript = function (code) {
    return exports.Script(code);
};

exports.createContext = Script.createContext = function (context) {
    // not really sure what this one does
    // seems to just make a shallow copy
    var copy = {};
    if(typeof context === 'object') {
        forEach(Object_keys(context), function (key) {
            copy[key] = context[key];
        });
    }
    return copy;
};
<|endoftext|>