<commit_before>(function($) {

  var sid = '';

  var responseHandler = function(successFn) {
    return function(data, textStatus, xhr) {
      var location = xhr.getResponseHeader('X-RStudio-Redirect');
      var sessionid = xhr.getResponseHeader('X-RStudio-Session');
      sid = sessionid;
      if(location) {
        window.replacePage(location, true, true);
      } else {
        successFn(data, textStatus, xhr);
      }
    };
  };

  bootAsyncLoader = function(){
    //extra login with ajax request is needed
    if(urlParam('viewer_pane') === '1' && window.alreadyChecked !== true){
      window.alreadyChecked=true;
      console.log('*********************** AJAX MODE ***********************');

      $.ajaxSetup({
        beforeSend: function (xhr)
        {
           xhr.setRequestHeader("X-RStudio-Session", sid);
           xhr.setRequestHeader("X-RStudio-Ajax",'true');
        }
      });
      //execute an ajax post request to login, this request must give back a 200 status code, otherwise it gets cancelled and the ajax doesn't keep the
      //cookie
      stayLoggedIn = function(creds){
        return $.ajax({
            type: 'POST',
            url: '/rstudio_login',
            data: creds,
            contentType:"application/x-www-form-urlencoded",
            xhrFields: {
              withCredentials: true
            },
            crossDomain:true
        });
      };
      if(urlParam('username')!==null){
        var creds = "username="+decodeURIComponent(urlParam('username'))+
          "&password=" + decodeURIComponent(urlParam("password"));
        stayLoggedIn(creds);
      }

      // Intercept all link clicks
      asyncClickHandler = function(e) {
        e.preventDefault();
        // Grab the url from the anchor tag
        var url = $(this).attr('href');
        return window.replacePage(url,true,true);
      };

      //rerender the body of the ajax retrieved url
      var rerenderBody = function(html,rebind, url){
        $('body').attr("url", url);
        $('#content').html(html);
        window.boot();
        if(rebind){
          classifyLinks();
          window.bindGlobalClickHandler();
        }
        window.bindButtonAndForms();
        window.searchHandler(jQuery);
        window.launchFullSearch();
        bindHistoryNavigation();
        window.scrollTo(0,0);
        $('.search--results').hide();
        packageVersionControl();
      };

      /************************************************************************************************************************************************
      rebinding and executing trough ajax requests
      ************************************************************************************************************************************************/

      window.bindGlobalClickHandler = function(){        //unbinding seems to fail a lot in the Rstudio browser?!->be sure not to bind twice
        $('a:not(.js-external)').each(function(){
          if(typeof($(this).attr('href')) != "undefined" &&
              $(this).attr('href').indexOf('/modalLogin')<0 &&
              $(this).attr('href').indexOf('#close-modal')<0
            ) {
            $(this).unbind('click').bind('click', asyncClickHandler);
          }
        });
      };

      bindSearchPaneClickHandler=function(){
        $('.search--results').find('a:not(.js-external)').unbind('click').bind('click',asyncClickHandler);
      };

      window.bindButtonAndForms= function(){
        $('#js-examples').unbind('click').bind('click',runExamples);
        $('#js-install').unbind('click').bind('click',installpackage);
        $('#js-hideviewer').unbind('click').bind('click',hideViewer);
        $('#js-makedefault').unbind('click').bind('click',setDefault);

        $( "form" ).each(function(){
          $(this).unbind('submit').bind('submit',function(event) {
            event.preventDefault();
            var action = $(this).attr('action');
            var type = $(this).attr('method') || 'post';

            var dataToWrite = $(this).serialize();

            window.pushHistory(action + "?"+dataToWrite);

            dataToWrite = dataToWrite+
              '&rstudio_layout=1'+
              '&viewer_pane=1'+
              '&RS_SHARED_SECRET=' + urlParam("RS_SHARED_SECRET")+
              "&Rstudio_port=" + urlParam("Rstudio_port");

            window.pushHistory(action + "?"+dataToWrite);

            $.ajax({
              type: type,
              url: action,
              headers: {
                Accept : "text/html; charset=utf-8",
                "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
              },
              data: dataToWrite,
              contentType:"application/x-www-form-urlencoded",
              xhrFields: {
                withCredentials: true
              },
              crossDomain:true
            }).then(responseHandler(function(html, textData, xhr) {
                //normal handling
                var url = type === 'GET' ? action + '?' + dataToWrite : action;
                if(action.indexOf("/login")>-1){
                  window.logInForRstudio(dataToWrite).then(function(){
                    rerenderBody(html,true, url);
                  });
                }
                else{
                  rerenderBody(html,true, url);
                }
              })
            );
          });
        });
      };
      window.logInForRstudio = function(loginData){
        return _rStudioRequest('/rpc/execute_r_code','execute_r_code',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),
          ["write('"+ loginData +"', file = paste0(find.package('Rdocumentation'),'/config/creds.txt')) \n Rdocumentation::login()"])
        .then(function(){
          console.log("Stored creds in RStudio");
          return stayLoggedIn(loginData);
        });
      };

      // Helper function to grab new HTML
      // and replace the content
      window.replacePage = function(url,rebind,addToHistory) {
        if(url.indexOf('#')>=0){
          url = url.substring(url.indexOf('#'),url.length);
          document.getElementById(url).scrollIntoView();
        }
        else{
          url = url.replace("../","");
          if(url.charAt(0)!="/"){
            url="/"+url;
          }
          var base = $('base').attr('href');
          if(url.indexOf('?')>-1){
            url = url + '&rstudio_layout=1&viewer_pane=1&RS_SHARED_SECRET=' + urlParam("RS_SHARED_SECRET")+"&Rstudio_port=" + urlParam("Rstudio_port");
          }
          else{
            url=url+'?rstudio_layout=1&viewer_pane=1&RS_SHARED_SECRET=' + urlParam("RS_SHARED_SECRET")+"&Rstudio_port=" + urlParam("Rstudio_port");
          }
          return $.ajax({
            url : base +url,
            type: 'GET',
            dataType:"html",
            Accept:"text/html",
            cache: false,
            xhrFields: {
              withCredentials: true
            },
            crossDomain:true,
            success: responseHandler(function(data, textStatus, xhr) {
              if(addToHistory){
                window.pushHistory(url);
              }
              rerenderBody(data,rebind, url);
            })
          })
          .fail(function(error) {console.log(error.responseJSON); });
        }

      };

      /************************************************************************************************************************************************
      button press functions (running examples, installing packages);
      ************************************************************************************************************************************************/
      runExamples=function(e){
        e.preventDefault();
        var package = $(".packageData").data("package-name");
        var version = $(".packageData").data("latest-version");
        checkPackageVersion(package,version).then(function(installed){
          if(installed===0|| installed==-1){
            var examples= $('.topic').find('.topic--title').filter(function(i,el){
              return $(this).text()=="Examples";
            }).parent().find('.R').text();
            _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["require("+package+")\n"+examples]);
          }
        });
        return false;
      };

      setDefault=function(e){
        e.preventDefault();
        _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["Rdocumentation::makeDefault()"]);
        return false;
      };
      hideViewer=function(e){
        e.preventDefault();
        _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["Rdocumentation::hideViewer()"]);
        return false;
      };
      /************************************************************************************************************************************************
      checking installation of package and package version
      ************************************************************************************************************************************************/
      checkPackageVersion=function(package,version){
        return _rStudioRequest('/rpc/execute_r_code','execute_r_code',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["check_package('"+package+"','"+version+"')"])
        .then(function(result){
            return parseInt(result.result);
        });
      };

      packageVersionControl=function(){
        var packageName = $(".packageData").data("package-name");
        var version = $(".packageData").data("latest-version");
        if(packageName){
          checkPackageVersion(packageName,version).then(function(installed){
            if(installed==1){
              $('.versionCheck').html('<button type="button" id="js-install" class="btn btn-large pull-right btn-primary js-external">Install</button>');
              $('.visible-installed').hide();
            }
            else if(installed==-1){
              $('.versionCheck').html('<button type="button" id="js-install" class="btn btn-large pull-right btn-primary js-external">Update</button>');
            }
            else{
              $('.versionCheck').html('You have the latest version');
            }
            $('#js-install').unbind('click',installpackage);
            $('#js-install').bind('click',installpackage);
          });
        }
      };

      installpackage=function(e){
        e.preventDefault();
        var packageName = $(".packageData").data("package-name");
        var packageSource= $(".packageData").data("type-id");
        _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),
                  ["install_package('"+packageName+"',"+packageSource+")"]);
        return false;
      };

      window.setTab=function(e,ui){
        $('ul.tabs').find('a').each(function(){
          $(this.hash).hide();
        });
        var link = ui.tab[0].innerHTML;
        link = link.substring(link.indexOf('#'),link.indexOf('" class'));
        $(link).show();
        e.preventDefault();
      };

      classifyLinks=function(){
        var base = $('base').attr('href');
        $('a:not(.js-external)').map(function(){
          var link =$(this).attr("href");
          if(typeof(link) != "undefined" && link.indexOf(base)<=-1 && (link.indexOf("www")===0  || link.indexOf("http://")===0 || link.indexOf("https://") === 0)){
            $(this).addClass("js-external");
          }
        });
      };

      window.executePackageCode=function(package,code){
        if(!package){
          package = $(".packageData").data("package-name");
        }
        _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["require("+package+")\n"+code]);
      };
      //check the packageversion
      packageVersionControl();
      classifyLinks();
      window.bindGlobalClickHandler();
      window.bindButtonAndForms();
      window.scrollTo(0,0);
    }
  };

  _rStudioRequest=function(url,method,shared_secret,port,params){
    var data={};
    data.method = method;
    //data.params = [$('.R').text()];
    data.params = params;
    data.clientId = '33e600bb-c1b1-46bf-b562-ab5cba070b0e';
    data.clientVersion = "";

    return $.ajax({
      url: 'http://127.0.0.1:'+port+url,
      headers:
      {
          'Accept':'application/json',
          'Content-Type':'application/json',
          'X-Shared-Secret':shared_secret
      },
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(data),
      processData: false,
      crossDomain:true,
      xhrFields: {
        withCredentials: true
      }
    });
  };
})($jq);
<commit_msg>solved problem with the search (#182)<commit_after>(function($) {

  var sid = '';

  var responseHandler = function(successFn) {
    return function(data, textStatus, xhr) {
      var location = xhr.getResponseHeader('X-RStudio-Redirect');
      var sessionid = xhr.getResponseHeader('X-RStudio-Session');
      sid = sessionid;
      if(location) {
        window.replacePage(location, true, true);
      } else {
        successFn(data, textStatus, xhr);
      }
    };
  };

  bootAsyncLoader = function(){
    //extra login with ajax request is needed
    if(urlParam('viewer_pane') === '1' && window.alreadyChecked !== true){
      window.alreadyChecked=true;
      console.log('*********************** AJAX MODE ***********************');

      $.ajaxSetup({
        beforeSend: function (xhr)
        {
           xhr.setRequestHeader("X-RStudio-Session", sid);
           xhr.setRequestHeader("X-RStudio-Ajax",'true');
        }
      });
      //execute an ajax post request to login, this request must give back a 200 status code, otherwise it gets cancelled and the ajax doesn't keep the
      //cookie
      stayLoggedIn = function(creds){
        return $.ajax({
            type: 'POST',
            url: '/rstudio_login',
            data: creds,
            contentType:"application/x-www-form-urlencoded",
            xhrFields: {
              withCredentials: true
            },
            crossDomain:true
        });
      };
      if(urlParam('username')!==null){
        var creds = "username="+decodeURIComponent(urlParam('username'))+
          "&password=" + decodeURIComponent(urlParam("password"));
        stayLoggedIn(creds);
      }

      // Intercept all link clicks
      asyncClickHandler = function(e) {
        e.preventDefault();
        // Grab the url from the anchor tag
        var url = $(this).attr('href');
        return window.replacePage(url,true,true);
      };

      //rerender the body of the ajax retrieved url
      var rerenderBody = function(html,rebind, url){
        $('body').attr("url", url);
        $('#content').html(html);
        window.boot();
        if(rebind){
          classifyLinks();
          window.bindGlobalClickHandler();
        }
        window.bindButtonAndForms();
        window.searchHandler(jQuery);
        window.launchFullSearch();
        bindHistoryNavigation();
        window.scrollTo(0,0);
        $('.search--results').hide();
        packageVersionControl();
      };

      /************************************************************************************************************************************************
      rebinding and executing trough ajax requests
      ************************************************************************************************************************************************/

      window.bindGlobalClickHandler = function(){        //unbinding seems to fail a lot in the Rstudio browser?!->be sure not to bind twice
        $('a:not(.js-external)').each(function(){
          if(typeof($(this).attr('href')) != "undefined" &&
              $(this).attr('href').indexOf('/modalLogin')<0 &&
              $(this).attr('href').indexOf('#close-modal')<0
            ) {
            $(this).unbind('click').bind('click', asyncClickHandler);
          }
        });
      };

      bindSearchPaneClickHandler=function(){
        $('.search--results').find('a:not(.js-external)').unbind('click').bind('click',asyncClickHandler);
      };

      window.bindButtonAndForms= function(){
        $('#js-examples').unbind('click').bind('click',runExamples);
        $('#js-install').unbind('click').bind('click',installpackage);
        $('#js-hideviewer').unbind('click').bind('click',hideViewer);
        $('#js-makedefault').unbind('click').bind('click',setDefault);

        $( "form" ).each(function(){
          $(this).unbind('submit').bind('submit',function(event) {
            event.preventDefault();
            var action = $(this).attr('action');
            var type = $(this).attr('method') || 'post';

            var dataToWrite = $(this).serialize();

            dataToWrite = dataToWrite+
              '&viewer_pane=1'+
              '&RS_SHARED_SECRET=' + urlParam("RS_SHARED_SECRET")+
              "&Rstudio_port=" + urlParam("Rstudio_port");

            window.pushHistory(action + "?"+dataToWrite);

            $.ajax({
              type: type,
              url: action,
              headers: {
                Accept : "text/html; charset=utf-8",
                "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
              },
              data: dataToWrite,
              contentType:"application/x-www-form-urlencoded",
              xhrFields: {
                withCredentials: true
              },
              crossDomain:true
            }).then(responseHandler(function(html, textData, xhr) {
                //normal handling
                var url = action + '?' + dataToWrite;
                if(action.indexOf("/login")>-1){
                  window.logInForRstudio(dataToWrite).then(function(){
                    rerenderBody(html,true, url);
                  });
                }
                else{
                  rerenderBody(html,true, url);
                }
              })
            );
          });
        });
      };
      window.logInForRstudio = function(loginData){
        return _rStudioRequest('/rpc/execute_r_code','execute_r_code',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),
          ["write('"+ loginData +"', file = paste0(find.package('Rdocumentation'),'/config/creds.txt')) \n Rdocumentation::login()"])
        .then(function(){
          console.log("Stored creds in RStudio");
          return stayLoggedIn(loginData);
        });
      };

      // Helper function to grab new HTML
      // and replace the content
      window.replacePage = function(url,rebind,addToHistory) {
        if(url.indexOf('#')>=0){
          url = url.substring(url.indexOf('#'),url.length);
          document.getElementById(url).scrollIntoView();
        }
        else{
          url = url.replace("../","");
          if(url.charAt(0)!="/"){
            url="/"+url;
          }
          var base = $('base').attr('href');
          if(url.indexOf('?')>-1){
            url = url + '&viewer_pane=1&RS_SHARED_SECRET=' + urlParam("RS_SHARED_SECRET")+"&Rstudio_port=" + urlParam("Rstudio_port");
          }
          else{
            url=url+'?viewer_pane=1&RS_SHARED_SECRET=' + urlParam("RS_SHARED_SECRET")+"&Rstudio_port=" + urlParam("Rstudio_port");
          }
          return $.ajax({
            url : base +url,
            type: 'GET',
            dataType:"html",
            Accept:"text/html",
            cache: false,
            xhrFields: {
              withCredentials: true
            },
            crossDomain:true,
            success: responseHandler(function(data, textStatus, xhr) {
              if(addToHistory){
                window.pushHistory(url);
              }
              rerenderBody(data,rebind, url);
            })
          })
          .fail(function(error) {console.log(error.responseJSON); });
        }

      };

      /************************************************************************************************************************************************
      button press functions (running examples, installing packages);
      ************************************************************************************************************************************************/
      runExamples=function(e){
        e.preventDefault();
        var package = $(".packageData").data("package-name");
        var version = $(".packageData").data("latest-version");
        checkPackageVersion(package,version).then(function(installed){
          if(installed===0|| installed==-1){
            var examples= $('.topic').find('.topic--title').filter(function(i,el){
              return $(this).text()=="Examples";
            }).parent().find('.R').text();
            _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["require("+package+")\n"+examples]);
          }
        });
        return false;
      };

      setDefault=function(e){
        e.preventDefault();
        _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["Rdocumentation::makeDefault()"]);
        return false;
      };
      hideViewer=function(e){
        e.preventDefault();
        _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["Rdocumentation::hideViewer()"]);
        return false;
      };
      /************************************************************************************************************************************************
      checking installation of package and package version
      ************************************************************************************************************************************************/
      checkPackageVersion=function(package,version){
        return _rStudioRequest('/rpc/execute_r_code','execute_r_code',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["check_package('"+package+"','"+version+"')"])
        .then(function(result){
            return parseInt(result.result);
        });
      };

      packageVersionControl=function(){
        var packageName = $(".packageData").data("package-name");
        var version = $(".packageData").data("latest-version");
        if(packageName){
          checkPackageVersion(packageName,version).then(function(installed){
            if(installed==1){
              $('.versionCheck').html('<button type="button" id="js-install" class="btn btn-large pull-right btn-primary js-external">Install</button>');
              $('.visible-installed').hide();
            }
            else if(installed==-1){
              $('.versionCheck').html('<button type="button" id="js-install" class="btn btn-large pull-right btn-primary js-external">Update</button>');
            }
            else{
              $('.versionCheck').html('You have the latest version');
            }
            $('#js-install').unbind('click',installpackage);
            $('#js-install').bind('click',installpackage);
          });
        }
      };

      installpackage=function(e){
        e.preventDefault();
        var packageName = $(".packageData").data("package-name");
        var packageSource= $(".packageData").data("type-id");
        _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),
                  ["install_package('"+packageName+"',"+packageSource+")"]);
        return false;
      };

      window.setTab=function(e,ui){
        $('ul.tabs').find('a').each(function(){
          $(this.hash).hide();
        });
        var link = ui.tab[0].innerHTML;
        link = link.substring(link.indexOf('#'),link.indexOf('" class'));
        $(link).show();
        e.preventDefault();
      };

      classifyLinks=function(){
        var base = $('base').attr('href');
        $('a:not(.js-external)').map(function(){
          var link =$(this).attr("href");
          if(typeof(link) != "undefined" && link.indexOf(base)<=-1 && (link.indexOf("www")===0  || link.indexOf("http://")===0 || link.indexOf("https://") === 0)){
            $(this).addClass("js-external");
          }
        });
      };

      window.executePackageCode=function(package,code){
        if(!package){
          package = $(".packageData").data("package-name");
        }
        _rStudioRequest('/rpc/console_input','console_input',urlParam("RS_SHARED_SECRET"),urlParam("Rstudio_port"),["require("+package+")\n"+code]);
      };
      //check the packageversion
      packageVersionControl();
      classifyLinks();
      window.bindGlobalClickHandler();
      window.bindButtonAndForms();
      window.scrollTo(0,0);
    }
  };

  _rStudioRequest=function(url,method,shared_secret,port,params){
    var data={};
    data.method = method;
    //data.params = [$('.R').text()];
    data.params = params;
    data.clientId = '33e600bb-c1b1-46bf-b562-ab5cba070b0e';
    data.clientVersion = "";

    return $.ajax({
      url: 'http://127.0.0.1:'+port+url,
      headers:
      {
          'Accept':'application/json',
          'Content-Type':'application/json',
          'X-Shared-Secret':shared_secret
      },
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(data),
      processData: false,
      crossDomain:true,
      xhrFields: {
        withCredentials: true
      }
    });
  };
})($jq);
<|endoftext|>


<commit_before>import _ from 'lodash/fp'
import {push} from './array'

export let isTraversable = x => _.isArray(x) || _.isPlainObject(x)
export let traverse = x =>
  isTraversable(x) && !_.isEmpty(x) && _.values(x)

export let walk = (next = traverse) => (
  pre,
  post = _.noop,
  parents = []
) => tree =>
  pre(tree, parents) ||
  _.find(
    walk(next)(pre, post, [tree, ...parents]),
    next(tree) || []
  ) ||
  post(tree, parents)

export let reduceTree = (next = traverse) =>
  _.curry((f, result, tree) => {
    walk(next)((...x) => {
      result = f(result, ...x)
    })(tree)
    return result
  })

export let treeToArrayBy = (next = traverse) =>
  _.curry((fn, tree) =>
    reduceTree(next)((r, x) => push(fn(x), r), [], tree)
  )
export let treeToArray = (next = traverse) => treeToArrayBy(next)(x => x)

export let leaves = (next = traverse) =>
  _.flow(treeToArray(next), _.reject(next))

export let tree = (next = traverse) => ({
  walk: walk(next),
  reduce: reduceTree(next),
  toArrayBy: treeToArrayBy(next),
  toArray: treeToArray(next),
  leaves: leaves(next)
})
<commit_msg>pass parents to traversal<commit_after>import _ from 'lodash/fp'
import {push} from './array'

export let isTraversable = x => _.isArray(x) || _.isPlainObject(x)
export let traverse = x =>
  isTraversable(x) && !_.isEmpty(x) && _.values(x)

export let walk = (next = traverse) => (
  pre,
  post = _.noop,
  parents = []
) => tree =>
  pre(tree, parents) ||
  _.find(
    walk(next)(pre, post, [tree, ...parents]),
    next(tree, parents) || []
  ) ||
  post(tree, parents)

export let reduceTree = (next = traverse) =>
  _.curry((f, result, tree) => {
    walk(next)((...x) => {
      result = f(result, ...x)
    })(tree)
    return result
  })

export let treeToArrayBy = (next = traverse) =>
  _.curry((fn, tree) =>
    reduceTree(next)((r, x) => push(fn(x), r), [], tree)
  )
export let treeToArray = (next = traverse) => treeToArrayBy(next)(x => x)

export let leaves = (next = traverse) =>
  _.flow(treeToArray(next), _.reject(next))

export let tree = (next = traverse) => ({
  walk: walk(next),
  reduce: reduceTree(next),
  toArrayBy: treeToArrayBy(next),
  toArray: treeToArray(next),
  leaves: leaves(next)
})
<|endoftext|>


<commit_before>/**
 * Baobab Type Checking
 * =====================
 *
 * Helpers functions used throughout the library to perform some type
 * tests at runtime.
 *
 */
import {Monkey} from './monkey';

const type = {};

/**
 * Helpers
 * --------
 */

/**
 * Checking whether the given variable is of any of the given types.
 *
 * @todo   Optimize this function by dropping `some`.
 *
 * @param  {mixed} target  - Variable to test.
 * @param  {array} allowed - Array of allowed types.
 * @return {boolean}
 */
function anyOf(target, allowed) {
  return allowed.some(t => type[t](target));
}

/**
 * Simple types
 * -------------
 */

/**
 * Checking whether the given variable is an array.
 *
 * @param  {mixed} target - Variable to test.
 * @return {boolean}
 */
type.array = function(target) {
  return Array.isArray(target);
};

/**
 * Checking whether the given variable is an object.
 *
 * @param  {mixed} target - Variable to test.
 * @return {boolean}
 */
type.object = function(target) {
  return target &&
         typeof target === 'object' &&
         !Array.isArray(target) &&
         !(target instanceof Date) &&
         !(target instanceof RegExp) &&
         (typeof Map === 'function' && !(target instanceof Map)) &&
         (typeof Set === 'function' && !(target instanceof Set));
};

/**
 * Checking whether the given variable is a string.
 *
 * @param  {mixed} target - Variable to test.
 * @return {boolean}
 */
type.string = function(target) {
  return typeof target === 'string';
};

/**
 * Checking whether the given variable is a number.
 *
 * @param  {mixed} target - Variable to test.
 * @return {boolean}
 */
type.number = function(target) {
  return typeof target === 'number';
};

/**
 * Checking whether the given variable is a function.
 *
 * @param  {mixed} target - Variable to test.
 * @return {boolean}
 */
type.function = function(target) {
  return typeof target === 'function';
};

/**
 * Checking whether the given variable is a JavaScript primitive.
 *
 * @param  {mixed} target - Variable to test.
 * @return {boolean}
 */
type.primitive = function(target) {
  return target !== Object(target);
};

/**
 * Complex types
 * --------------
 */

/**
 * Checking whether the given variable is a valid splicer.
 *
 * @param  {mixed} target    - Variable to test.
 * @param  {array} [allowed] - Optional valid types in path.
 * @return {boolean}
 */
type.splicer = function(target) {
  if (!type.array(target) || target.length < 2)
    return false;

  return anyOf(target[0], ['number', 'function', 'object']) &&
         type.number(target[1]);
};

/**
 * Checking whether the given variable is a valid cursor path.
 *
 * @param  {mixed} target    - Variable to test.
 * @param  {array} [allowed] - Optional valid types in path.
 * @return {boolean}
 */

// Order is important for performance reasons
const ALLOWED_FOR_PATH = ['string', 'number', 'function', 'object'];

type.path = function(target) {
  if (!target && target !== 0 && target !== '')
    return false;

  return [].concat(target).every(step => anyOf(step, ALLOWED_FOR_PATH));
};

/**
 * Checking whether the given path is a dynamic one.
 *
 * @param  {mixed} path - The path to test.
 * @return {boolean}
 */
type.dynamicPath = function(path) {
  return path.some(step => type.function(step) || type.object(step));
};

/**
 * Retrieve any monkey subpath in the given path or null if the path never comes
 * across computed data.
 *
 * @param  {mixed} data - The data to test.
 * @param  {array} path - The path to test.
 * @return {boolean}
 */
type.monkeyPath = function(data, path) {
  let subpath = [],
      c = data,
      i,
      l;

  for (i = 0, l = path.length; i < l; i++) {
    subpath.push(path[i]);

    if (typeof c !== 'object')
      return null;

    c = c[path[i]];

    if (c instanceof Monkey)
      return subpath;
  }

  return null;
};

/**
 * Check if the given object property is a lazy getter used by a monkey.
 *
 * @param  {mixed}   o           - The target object.
 * @param  {string}  propertyKey - The property to test.
 * @return {boolean}
 */
type.lazyGetter = function(o, propertyKey) {
  const descriptor = Object.getOwnPropertyDescriptor(o, propertyKey);

  return descriptor &&
         descriptor.get &&
         descriptor.get.isLazyGetter === true;
};

/**
 * Returns the type of the given monkey definition or `null` if invalid.
 *
 * @param  {mixed} definition - The definition to check.
 * @return {string|null}
 */
type.monkeyDefinition = function(definition) {

  if (type.object(definition)) {
    if (!type.function(definition.get) ||
        (definition.cursors &&
         (!type.object(definition.cursors) ||
          !(Object.keys(definition.cursors).every(k => type.path(definition.cursors[k]))))))
      return null;
    else
      return 'object';
  }
  else if (type.array(definition)) {
    if (!type.function(definition[definition.length - 1]) ||
        !definition.slice(0, -1).every(p => type.path(p)))
      return null;
    else
      return 'array';
  }

  return null;
};

/**
 * Checking whether the given watcher definition is valid.
 *
 * @param  {mixed}   definition - The definition to check.
 * @return {boolean}
 */
type.watcherMapping = function(definition) {
  return type.object(definition) &&
         Object.keys(definition).every(k => type.path(definition[k]));
};

/**
 * Checking whether the given string is a valid operation type.
 *
 * @param  {mixed} string - The string to test.
 * @return {boolean}
 */

// Ordered by likeliness
const VALID_OPERATIONS = [
  'set',
  'apply',
  'push',
  'unshift',
  'concat',
  'deepMerge',
  'merge',
  'splice',
  'unset'
];

type.operationType = function(string) {
  return typeof string === 'string' && !!~VALID_OPERATIONS.indexOf(string);
};

export default type;
<commit_msg>Extend the object test<commit_after>/**
 * Baobab Type Checking
 * =====================
 *
 * Helpers functions used throughout the library to perform some type
 * tests at runtime.
 *
 */
import {Monkey} from './monkey';

const type = {};

/**
 * Helpers
 * --------
 */

/**
 * Checking whether the given variable is of any of the given types.
 *
 * @todo   Optimize this function by dropping `some`.
 *
 * @param  {mixed} target  - Variable to test.
 * @param  {array} allowed - Array of allowed types.
 * @return {boolean}
 */
function anyOf(target, allowed) {
  return allowed.some(t => type[t](target));
}

/**
 * Simple types
 * -------------
 */

/**
 * Checking whether the given variable is an array.
 *
 * @param  {mixed} target - Variable to test.
 * @return {boolean}
 */
type.array = function(target) {
  return Array.isArray(target);
};

/**
 * Checking whether the given variable is an object.
 *
 * @param  {mixed} target - Variable to test.
 * @return {boolean}
 */
type.object = function(target) {
  return target &&
         typeof target === 'object' &&
         !Array.isArray(target) &&
         !(target instanceof Date) &&
         !(target instanceof RegExp) &&
         !(typeof Map === 'function' && target instanceof Map) &&
         !(typeof Set === 'function' && target instanceof Set);
};

/**
 * Checking whether the given variable is a string.
 *
 * @param  {mixed} target - Variable to test.
 * @return {boolean}
 */
type.string = function(target) {
  return typeof target === 'string';
};

/**
 * Checking whether the given variable is a number.
 *
 * @param  {mixed} target - Variable to test.
 * @return {boolean}
 */
type.number = function(target) {
  return typeof target === 'number';
};

/**
 * Checking whether the given variable is a function.
 *
 * @param  {mixed} target - Variable to test.
 * @return {boolean}
 */
type.function = function(target) {
  return typeof target === 'function';
};

/**
 * Checking whether the given variable is a JavaScript primitive.
 *
 * @param  {mixed} target - Variable to test.
 * @return {boolean}
 */
type.primitive = function(target) {
  return target !== Object(target);
};

/**
 * Complex types
 * --------------
 */

/**
 * Checking whether the given variable is a valid splicer.
 *
 * @param  {mixed} target    - Variable to test.
 * @param  {array} [allowed] - Optional valid types in path.
 * @return {boolean}
 */
type.splicer = function(target) {
  if (!type.array(target) || target.length < 2)
    return false;

  return anyOf(target[0], ['number', 'function', 'object']) &&
         type.number(target[1]);
};

/**
 * Checking whether the given variable is a valid cursor path.
 *
 * @param  {mixed} target    - Variable to test.
 * @param  {array} [allowed] - Optional valid types in path.
 * @return {boolean}
 */

// Order is important for performance reasons
const ALLOWED_FOR_PATH = ['string', 'number', 'function', 'object'];

type.path = function(target) {
  if (!target && target !== 0 && target !== '')
    return false;

  return [].concat(target).every(step => anyOf(step, ALLOWED_FOR_PATH));
};

/**
 * Checking whether the given path is a dynamic one.
 *
 * @param  {mixed} path - The path to test.
 * @return {boolean}
 */
type.dynamicPath = function(path) {
  return path.some(step => type.function(step) || type.object(step));
};

/**
 * Retrieve any monkey subpath in the given path or null if the path never comes
 * across computed data.
 *
 * @param  {mixed} data - The data to test.
 * @param  {array} path - The path to test.
 * @return {boolean}
 */
type.monkeyPath = function(data, path) {
  let subpath = [],
      c = data,
      i,
      l;

  for (i = 0, l = path.length; i < l; i++) {
    subpath.push(path[i]);

    if (typeof c !== 'object')
      return null;

    c = c[path[i]];

    if (c instanceof Monkey)
      return subpath;
  }

  return null;
};

/**
 * Check if the given object property is a lazy getter used by a monkey.
 *
 * @param  {mixed}   o           - The target object.
 * @param  {string}  propertyKey - The property to test.
 * @return {boolean}
 */
type.lazyGetter = function(o, propertyKey) {
  const descriptor = Object.getOwnPropertyDescriptor(o, propertyKey);

  return descriptor &&
         descriptor.get &&
         descriptor.get.isLazyGetter === true;
};

/**
 * Returns the type of the given monkey definition or `null` if invalid.
 *
 * @param  {mixed} definition - The definition to check.
 * @return {string|null}
 */
type.monkeyDefinition = function(definition) {

  if (type.object(definition)) {
    if (!type.function(definition.get) ||
        (definition.cursors &&
         (!type.object(definition.cursors) ||
          !(Object.keys(definition.cursors).every(k => type.path(definition.cursors[k]))))))
      return null;
    else
      return 'object';
  }
  else if (type.array(definition)) {
    if (!type.function(definition[definition.length - 1]) ||
        !definition.slice(0, -1).every(p => type.path(p)))
      return null;
    else
      return 'array';
  }

  return null;
};

/**
 * Checking whether the given watcher definition is valid.
 *
 * @param  {mixed}   definition - The definition to check.
 * @return {boolean}
 */
type.watcherMapping = function(definition) {
  return type.object(definition) &&
         Object.keys(definition).every(k => type.path(definition[k]));
};

/**
 * Checking whether the given string is a valid operation type.
 *
 * @param  {mixed} string - The string to test.
 * @return {boolean}
 */

// Ordered by likeliness
const VALID_OPERATIONS = [
  'set',
  'apply',
  'push',
  'unshift',
  'concat',
  'deepMerge',
  'merge',
  'splice',
  'unset'
];

type.operationType = function(string) {
  return typeof string === 'string' && !!~VALID_OPERATIONS.indexOf(string);
};

export default type;
<|endoftext|>


<commit_before>const winston = require('winston');

const flatten = (arr) => arr.reduce((a, b) => (
  Array.isArray(b) ? a.concat(flatten(b))
    : a.concat(b)
), []);

const logger = new winston.Logger({
  transports: [
    new winston.transports.Console({
      handleExceptions: true,
      json: true,
      stringify: true,
    }),
  ],
});

module.exports = { flatten, logger };
<commit_msg>Set log level from environment var<commit_after>const winston = require('winston');

const flatten = (arr) => arr.reduce((a, b) => (
  Array.isArray(b) ? a.concat(flatten(b))
    : a.concat(b)
), []);

winston.level = process.env.LOG_LEVEL || 'info';

const logger = new winston.Logger({
  transports: [
    new winston.transports.Console({
      handleExceptions: true,
      json: true,
      stringify: true,
    }),
  ],
});

module.exports = { flatten, logger };
<|endoftext|>


<commit_before>'use strict'
var warn = require('./warn') // @[/development]

var iterator = exports.iterator = typeof Symbol === 'function' && Symbol.iterator || undefined

exports.INTERNAL = function () {}

// Returns an array or throws. The returned object may or may not be a safe
// copy. The only safe operations are to synchronously loop through the object.
// After control is given back to the caller, the object must not be used.
// The returned array COULD be a subclass of Array.
exports.asArray = function $UUID(iterable) {
	if (Array.isArray(iterable)) {
		return iterable
	}
	if (iterator && iterable != null && typeof iterable[iterator] === 'function') {
		var arr = []
		var it = iterable[iterator]()
		var item
		while (!(item = it.next()).done) {
			arr.push(item.value)
		}
		return arr
	}
	throw new TypeError('Expected argument to be an iterable object.')
}

// Returns whether the given catch predicate shoulf catch the exception reason.
exports.catchesError = function (predicate, reason) {
	if (predicate === Error || (predicate && predicate.prototype instanceof Error)) {
		return reason instanceof predicate
	}
	if (typeof predicate === 'function') {
		return !!predicate(reason)
	}
	if (predicate && typeof predicate === 'object') {
		var keys = Object.keys(predicate)
		for (var i=0, len=keys.length; i<len; i++) {
			var key = keys[i]
			if (reason[key] != predicate[key]) {
				return false
			}
		}
		if (len > 0) {
			return true
		}
	}
	warn('The predicate passed to .catch() is invalid, and will be ignored.') // @[/development]
	return false
}

// @[browser]
// A safe, cross-browser log function.
exports.console = {
	log: function () {
		if (typeof console === 'object' && console) {
			Function.prototype.apply.call(console.log, console, arguments)
		}
	},
	// @[development]
	warn: function () {
		if (typeof console === 'object' && console) {
			Function.prototype.apply.call(console.warn, console, arguments)
		}
	},
	// @[/]
	error: function () {
		if (typeof console === 'object' && console) {
			Function.prototype.apply.call(console.error, console, arguments)
		}
	}
}
// @[/]
<commit_msg>fixed util.js<commit_after>'use strict'
var iterator = exports.iterator = typeof Symbol === 'function' && Symbol.iterator || undefined

exports.INTERNAL = function () {}

// Returns an array or throws. The returned object may or may not be a safe
// copy. The only safe operations are to synchronously loop through the object.
// After control is given back to the caller, the object must not be used.
// The returned array COULD be a subclass of Array.
exports.asArray = function $UUID(iterable) {
	if (Array.isArray(iterable)) {
		return iterable
	}
	if (iterator && iterable != null && typeof iterable[iterator] === 'function') {
		var arr = []
		var it = iterable[iterator]()
		var item
		while (!(item = it.next()).done) {
			arr.push(item.value)
		}
		return arr
	}
	throw new TypeError('Expected argument to be an iterable object.')
}

// Returns whether the given catch predicate shoulf catch the exception reason.
exports.catchesError = function (predicate, reason) {
	if (predicate === Error || (predicate && predicate.prototype instanceof Error)) {
		return reason instanceof predicate
	}
	if (typeof predicate === 'function') {
		return !!predicate(reason)
	}
	if (predicate && typeof predicate === 'object') {
		var keys = Object.keys(predicate)
		for (var i=0, len=keys.length; i<len; i++) {
			var key = keys[i]
			if (reason[key] != predicate[key]) {
				return false
			}
		}
		if (len > 0) {
			return true
		}
	}
	warn('The predicate passed to .catch() is invalid, and will be ignored.') // @[/development]
	return false
}

// @[browser]
// A safe, cross-browser log function.
exports.console = {
	log: function () {
		if (typeof console === 'object' && console) {
			Function.prototype.apply.call(console.log, console, arguments)
		}
	},
	// @[development]
	warn: function () {
		if (typeof console === 'object' && console) {
			Function.prototype.apply.call(console.warn, console, arguments)
		}
	},
	// @[/]
	error: function () {
		if (typeof console === 'object' && console) {
			Function.prototype.apply.call(console.error, console, arguments)
		}
	}
}
// @[/]

// @[development]
// This must be at the bottom of the page so that warn.js doesn't load an
// uninitialized util.js.
var warn = require('./warn')
// @[/]
<|endoftext|>


<commit_before>'use strict';
var E = module.exports;

E.load_script = function(url, onload, attrs){
    var script = document.createElement('script');
    script.src = url;
    script.onload = onload;
    if (attrs)
        Object.assign(script, attrs);
    if (document.getElementsByTagName('head').length)
        document.getElementsByTagName('head')[0].appendChild(script);
    else if (document.getElementsByTagName('body').length)
        document.getElementsByTagName('body')[0].appendChild(script);
    else if (document.head)
        document.head.appendChild(script);
};

E.current_script = function(){
    var script;
    if (script = document.currentScript)
        return script;
    if (script = document.querySelector(
        'script[src*="//player.h-cdn.com/player/hola_player"'))
    {
        return script;
    }
    // assumes wasn't loaded async
    var scripts = document.getElementsByTagName('script');
    return scripts[scripts.length-1];
};

var id_counter = 0;
var rand = Math.floor(Math.random()*10000)+'';
E.unique_id = function(prefix){
    return (prefix ? prefix+'_' : '')+rand+'_'+(++id_counter);
};

E.scaled_number = function(num){
    if (num===undefined)
        return '';
    if (!num)
        return '0';
    var k = 1024;
    var sizes = ['', 'K', 'M', 'G', 'T', 'P'];
    var i = Math.floor(Math.log(num)/Math.log(k));
    num /= Math.pow(k, i);
    if (num<0.001)
        return '0';
    if (num>=k-1)
        num = Math.trunc(num);
    var str = num.toFixed(num<1 ? 3 : num<10 ? 2 : num<100 ? 1 : 0);
    return str.replace(/\.0*$/, '')+sizes[i];
};
<commit_msg>corrected url<commit_after>'use strict';
var E = module.exports;

E.load_script = function(url, onload, attrs){
    var script = document.createElement('script');
    script.src = url;
    script.onload = onload;
    if (attrs)
        Object.assign(script, attrs);
    if (document.getElementsByTagName('head').length)
        document.getElementsByTagName('head')[0].appendChild(script);
    else if (document.getElementsByTagName('body').length)
        document.getElementsByTagName('body')[0].appendChild(script);
    else if (document.head)
        document.head.appendChild(script);
};

E.current_script = function(){
    var script;
    if (script = document.currentScript)
        return script;
    if (script = document.querySelector(
        'script[src*="//player.h-cdn.com/player/"'))
    {
        return script;
    }
    // assumes wasn't loaded async
    var scripts = document.getElementsByTagName('script');
    return scripts[scripts.length-1];
};

var id_counter = 0;
var rand = Math.floor(Math.random()*10000)+'';
E.unique_id = function(prefix){
    return (prefix ? prefix+'_' : '')+rand+'_'+(++id_counter);
};

E.scaled_number = function(num){
    if (num===undefined)
        return '';
    if (!num)
        return '0';
    var k = 1024;
    var sizes = ['', 'K', 'M', 'G', 'T', 'P'];
    var i = Math.floor(Math.log(num)/Math.log(k));
    num /= Math.pow(k, i);
    if (num<0.001)
        return '0';
    if (num>=k-1)
        num = Math.trunc(num);
    var str = num.toFixed(num<1 ? 3 : num<10 ? 2 : num<100 ? 1 : 0);
    return str.replace(/\.0*$/, '')+sizes[i];
};
<|endoftext|>


<commit_before>/**
 * @author : gherardo varando (gherardo.varando@gmail.com)
 *
 * @license: GPL v3
 *     This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

const fs = require('fs');
const {
    app
} = require('electron').remote;
const os = require('os');

exports.parseTimeInterval = function(s) {
    if (s < 1000) {
        return `${s.toPrecision(3)} milliseconds`;
    } else if (s < 60000) {
        return `${(s/1000).toPrecision(2)} seconds`;
    } else if (s < 3600000) {
        return `${(s/60000).toPrecision(2)} minutes`;
    } else if (s < 86400000) {
        return `${(s/3600000).toPrecision(2)} hours`;
    } else {
        return `${(s/86400000).toPrecision(3)} days`;
    }
}

exports.div = function(className, text) {
    if (document) {
        let t = document.createElement('DIV');
        if (x) {
            t.innerHTML = x;
        }
        if (className) {
            t.className = className;
        }
        return t;
    }
}

exports.setProgress = function(val) {
    require('electron').remote.getCurrentWindow().setProgressBar(val / 100);
}

exports.stringify = function(object) {
    if (object) {
        return (JSON.stringify(object).replace(/\u007D/g, '').replace(/\u007B/g, '').replace(/\u0022/g, ''));
    }
    return null;
}

exports.isNode = function() {
    if (typeof module !== 'undefined' && module.exports) {
        return true;
    } else {
        return false;
    }
}

exports.isElectron = function() {
    if (process.versions.electron) {
        return true;
    } else {
        return false;
    }
}

exports.sum = function(v) {
    let sum = v.reduce((a, b) => {
        if (isNaN(b)) return a;
        return a + b;
    }, 0);
    return sum;
}

exports.mean = function(v) {
    let n = v.reduce((a, b) => {
        if (isNaN(b)) return a;
        return a + 1;
    }, 0);
    let sum = exports.sum(v);
    return (sum / n);
}

exports.clone = function(obj) {
    return Object.assign({}, obj);
    //return JSON.parse(JSON.stringify(obj));
}

exports.notifyOS = function(text) {
    var notif = new window.Notification(`${app.getName()}`, {
        body: text
    });
}

exports.readJSON = function(filename, callback, error) {
    fs.readFile(filename, 'utf-8', function(err, data) {
        if (err) {
            error(err);
            return;
        }
        var obj = JSON.parse(data);
        callback(obj);
    });
}

exports.readJSONsync = function(filename, error) {
    let data;
    try {
        data = fs.readFileSync(filename, 'utf-8');
        return JSON.parse(data);
    } catch (err) {
        if (error) {
            error(err);
        }
        return null;
    }
}

exports.empty = function(parent, child) {
    if (parent) {
        if (child) {
            parent.removeChild(child);
            this.empty(parent, parent.firstChild);
        }
    }
}

exports.isIcon = function(icon) {
    if (icon) {
        if (icon.className) {
            if (icon.className.includes('fa') | icon.className.includes('icon')) return true;
        }
    }
    return false;
}

exports.icon = function(icon) {
    if (this.isIcon(icon)) return icon;
    if (typeof icon === 'string') {
        let ic;
        if (icon.includes('fa')) {
            ic = document.createElement('I');
            ic.className = icon;
        } else if (icon.includes('icon')) {
            ic = document.createElement('SPAN');
            ic.className = icon;
        } else {
            ic = document.createElement('SPAN');
        }
        return ic;
    } else {
        return document.createElement('DIV');
    }

}

// exports.setOne(obj, x, l) {
//     if (typeof obj[x] === 'undefined') {
//         for (let i in l) {
//             if (typeof obj[l[i]] != 'undefined') {
//                 obj[x] = obj[l[i]];
//                 break;
//             }
//         }
//
//     }
//     for (let i in l) {
//         delete obj[l[i]];
//     }
// }

//move this to appropriate util where used
// /**
//  * Layer utilities.
//  */
// exports.layers = {
//
//     /**
//      * Creates a JSON configuration file for a layer (pixels layer or points layer).
//      *
//      * @static
//      * @param {string} sourcePath - Path with source files to create JSON configuration.
//      * @param {string} destinationPath - Path where JSON configuration file will be saved.
//      * @param {Util.Layers.Mode} mode - JSON configuration mode (folder / single image / image list).
//      * @param {string} layerType - Layer type, points (objects) or pixels (holes).
//      * @param {function(string)} next - Callback for returning JSON Configuration file path.
//      */
//     createJSONConfiguration = function(sourcePath, destinationPath, mode, layerType, next) {
//         let template;
//
//         let dimPromise = new Promise((resolveDim, rejectDim) => {
//             if (mode === Util.Layers.Mode.FOLDER) {
//                 fs.readdir(sourcePath, (err, files) => {
//                     let aImage;
//                     let allStatsPromises = [];
//                     let xValues = [];
//                     let yValues = [];
//
//                     files.forEach(file => {
//                         let statPromise = new Promise((resolveStat) => {
//                             fs.stat(path.join(sourcePath, file), (err, stats) => {
//                                 if (stats.isFile()) {
//                                     let xRegex = /_X[0-9]+/g;
//                                     let yRegex = /_Y[0-9]+/g;
//
//                                     let xString = xRegex.exec(file);
//                                     let yString = yRegex.exec(file);
//
//                                     if (xString == null || yString == null) {
//                                         resolveStat();
//                                     } else {
//                                         let xNumRegex = /[0-9]+/g;
//                                         let yNumRegex = /[0-9]+/g;
//                                         let x = xNumRegex.exec(xString);
//                                         let y = yNumRegex.exec(yString);
//                                         xValues.push(x);
//                                         yValues.push(y);
//                                         if (aImage == null) aImage = file;
//                                         if (template == null) {
//                                             let xSplit = file.split(xString);
//                                             let tempTemplate = `${xSplit[0]}_X{x}${xSplit[1]}`;
//                                             let ySplit = tempTemplate.split(yString);
//                                             template = `${ySplit[0]}_Y{y}${ySplit[1]}`;
//                                         }
//                                         resolveStat();
//                                     }
//                                 } else {
//                                     resolveStat();
//                                 }
//                             });
//                         });
//                         allStatsPromises.push(statPromise);
//                     });
//
//                     Promise.all(allStatsPromises).then(() => {
//                         let xMin = Math.min(...xValues);
//                         let xMax = Math.max(...xValues);
//                         let yMin = Math.min(...yValues);
//                         let yMax = Math.max(...yValues);
//                         let xTiles = xMax - xMin + 1;
//                         let yTiles = yMax - yMin + 1;
//                         Util.Image.getSize(path.join(sourcePath, aImage), (err, width, height) => {
//                             if (!err) {
//                                 let tileSize = Math.max(width, height);
//                                 let size = Math.max(width * xTiles, height * yTiles);
//                                 resolveDim([tileSize, size]);
//                             } else {
//                                 rejectDim(err);
//                             }
//                         });
//                     });
//                 });
//             } else if (mode === Util.Layers.Mode.SINGLE_IMAGE) {
//                 Util.Image.getSize(sourcePath, (err, width, height) => {
//                     if (!err) {
//                         let tileSize = Math.max(width, height);
//                         let size = tileSize;
//                         resolveDim([tileSize, size]);
//                     } else {
//                         rejectDim(err);
//                     }
//                 });
//             } else if (mode === Util.Layers.Mode.IMAGE_LIST) {
//                 resolveDim([256, 256]); // temporary solution (bad sizes).
//             }
//         });
//
//         dimPromise.then((size) => {
//             let filename;
//             if (template != null) {
//                 filename = template;
//             } else {
//                 filename = path.basename(sourcePath);
//             }
//
//             let jsonConfig = {};
//
//             switch (layerType) {
//                 case `points`:
//                     jsonConfig = {
//                         name: `centroid_${filename}`,
//                         author: os.userInfo().username,
//                         type: `pointsLayer`,
//                         tileSize: size[0],
//                         size: size[1],
//                         pointsUrlTemplate: `points_${filename.replace(/ /g, "_")}.csv`
//                     }
//                     break;
//
//                 case `pixels`:
//                     jsonConfig = {
//                         name: `holes_${filename}`,
//                         author: os.userInfo().username,
//                         type: `pixelsLayer`,
//                         role: 'holes',
//                         tileSize: size[0],
//                         size: size[1],
//                         norm: size[2] || 1,
//                         pixelsUrlTemplate: `holes_${filename.replace(/ /g, "_")}.txt`
//                     }
//                     break;
//             }
//
//             next(jsonConfig);
//         });
//     }
//
// }
//
// /**
//  * JSON Configuration creation modes.
//  */
// exports.layers.Mode = {
//     SINGLE_IMAGE: 0,
//     FOLDER: 1,
//     IMAGE_LIST: 2
// }
//
// /**
//  * Image utilities.
//  */
// exports.image =  {
//
//     /**
//      * Calculates slice number of an image.
//      *
//      * @static
//      * @param {string} imagePath - Source image path.
//      * @returns {number} Number of slices.
//      */
//     getTotalSlices: function(imagePath) {
//         if (imagePath.endsWith(".tif") || imagePath.endsWith(".tiff")) {
//             let data = fs.readFileSync(imagePath);
//             let tiffImage = new Tiff({
//                 buffer: data
//             });
//             return tiffImage.countDirectory();
//         } else {
//             // Only tiff images have more than one slice.
//             return 1;
//         }
//     },
//
//     /**
//      * Calculates size (width and height) of an image.
//      *
//      * @static
//      * @param {string} imagePath - Source image path.
//      * @param {function(string, number, number)} next - Callback for returning image dimensions (or error).
//      */
//     getSize: function(imagePath, next) {
//         if (imagePath.endsWith(".tif") || imagePath.endsWith(".tiff")) {
//             fs.readFile(imagePath, (err, data) => {
//                 if (!err) {
//                     try {
//                         let tiffImage = new Tiff({
//                             buffer: data
//                         });
//                         tiffImage.setDirectory(0);
//                         next(null, tiffImage.toCanvas().width, tiffImage.toCanvas().height);
//                     } catch (err) {
//                         next(null, 256, 256); // default
//                     }
//                 } else {
//                     next(err);
//                 }
//             });
//         } else {
//             let dim = sizeOf(imagePath);
//             next(null, dim.width, dim.height);
//         }
//     }
//
// }
<commit_msg>fix err<commit_after>/**
 * @author : gherardo varando (gherardo.varando@gmail.com)
 *
 * @license: GPL v3
 *     This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

const fs = require('fs');
const {
    app
} = require('electron').remote;
const os = require('os');

exports.parseTimeInterval = function(s) {
    if (s < 1000) {
        return `${s.toPrecision(3)} milliseconds`;
    } else if (s < 60000) {
        return `${(s/1000).toPrecision(2)} seconds`;
    } else if (s < 3600000) {
        return `${(s/60000).toPrecision(2)} minutes`;
    } else if (s < 86400000) {
        return `${(s/3600000).toPrecision(2)} hours`;
    } else {
        return `${(s/86400000).toPrecision(3)} days`;
    }
}

exports.div = function(className, text) {
    if (document) {
        let t = document.createElement('DIV');
        if (text) {
            t.innerHTML = text;
        }
        if (className) {
            t.className = className;
        }
        return t;
    }
}

exports.setProgress = function(val) {
    require('electron').remote.getCurrentWindow().setProgressBar(val / 100);
}

exports.stringify = function(object) {
    if (object) {
        return (JSON.stringify(object).replace(/\u007D/g, '').replace(/\u007B/g, '').replace(/\u0022/g, ''));
    }
    return null;
}

exports.isNode = function() {
    if (typeof module !== 'undefined' && module.exports) {
        return true;
    } else {
        return false;
    }
}

exports.isElectron = function() {
    if (process.versions.electron) {
        return true;
    } else {
        return false;
    }
}

exports.sum = function(v) {
    let sum = v.reduce((a, b) => {
        if (isNaN(b)) return a;
        return a + b;
    }, 0);
    return sum;
}

exports.mean = function(v) {
    let n = v.reduce((a, b) => {
        if (isNaN(b)) return a;
        return a + 1;
    }, 0);
    let sum = exports.sum(v);
    return (sum / n);
}

exports.clone = function(obj) {
    return Object.assign({}, obj);
    //return JSON.parse(JSON.stringify(obj));
}

exports.notifyOS = function(text) {
    var notif = new window.Notification(`${app.getName()}`, {
        body: text
    });
}

exports.readJSON = function(filename, callback, error) {
    fs.readFile(filename, 'utf-8', function(err, data) {
        if (err) {
            error(err);
            return;
        }
        var obj = JSON.parse(data);
        callback(obj);
    });
}

exports.readJSONsync = function(filename, error) {
    let data;
    try {
        data = fs.readFileSync(filename, 'utf-8');
        return JSON.parse(data);
    } catch (err) {
        if (error) {
            error(err);
        }
        return null;
    }
}

exports.empty = function(parent, child) {
    if (parent) {
        if (child) {
            parent.removeChild(child);
            this.empty(parent, parent.firstChild);
        }
    }
}

exports.isIcon = function(icon) {
    if (icon) {
        if (icon.className) {
            if (icon.className.includes('fa') | icon.className.includes('icon')) return true;
        }
    }
    return false;
}

exports.icon = function(icon) {
    if (this.isIcon(icon)) return icon;
    if (typeof icon === 'string') {
        let ic;
        if (icon.includes('fa')) {
            ic = document.createElement('I');
            ic.className = icon;
        } else if (icon.includes('icon')) {
            ic = document.createElement('SPAN');
            ic.className = icon;
        } else {
            ic = document.createElement('SPAN');
        }
        return ic;
    } else {
        return document.createElement('DIV');
    }

}

// exports.setOne(obj, x, l) {
//     if (typeof obj[x] === 'undefined') {
//         for (let i in l) {
//             if (typeof obj[l[i]] != 'undefined') {
//                 obj[x] = obj[l[i]];
//                 break;
//             }
//         }
//
//     }
//     for (let i in l) {
//         delete obj[l[i]];
//     }
// }

//move this to appropriate util where used
// /**
//  * Layer utilities.
//  */
// exports.layers = {
//
//     /**
//      * Creates a JSON configuration file for a layer (pixels layer or points layer).
//      *
//      * @static
//      * @param {string} sourcePath - Path with source files to create JSON configuration.
//      * @param {string} destinationPath - Path where JSON configuration file will be saved.
//      * @param {Util.Layers.Mode} mode - JSON configuration mode (folder / single image / image list).
//      * @param {string} layerType - Layer type, points (objects) or pixels (holes).
//      * @param {function(string)} next - Callback for returning JSON Configuration file path.
//      */
//     createJSONConfiguration = function(sourcePath, destinationPath, mode, layerType, next) {
//         let template;
//
//         let dimPromise = new Promise((resolveDim, rejectDim) => {
//             if (mode === Util.Layers.Mode.FOLDER) {
//                 fs.readdir(sourcePath, (err, files) => {
//                     let aImage;
//                     let allStatsPromises = [];
//                     let xValues = [];
//                     let yValues = [];
//
//                     files.forEach(file => {
//                         let statPromise = new Promise((resolveStat) => {
//                             fs.stat(path.join(sourcePath, file), (err, stats) => {
//                                 if (stats.isFile()) {
//                                     let xRegex = /_X[0-9]+/g;
//                                     let yRegex = /_Y[0-9]+/g;
//
//                                     let xString = xRegex.exec(file);
//                                     let yString = yRegex.exec(file);
//
//                                     if (xString == null || yString == null) {
//                                         resolveStat();
//                                     } else {
//                                         let xNumRegex = /[0-9]+/g;
//                                         let yNumRegex = /[0-9]+/g;
//                                         let x = xNumRegex.exec(xString);
//                                         let y = yNumRegex.exec(yString);
//                                         xValues.push(x);
//                                         yValues.push(y);
//                                         if (aImage == null) aImage = file;
//                                         if (template == null) {
//                                             let xSplit = file.split(xString);
//                                             let tempTemplate = `${xSplit[0]}_X{x}${xSplit[1]}`;
//                                             let ySplit = tempTemplate.split(yString);
//                                             template = `${ySplit[0]}_Y{y}${ySplit[1]}`;
//                                         }
//                                         resolveStat();
//                                     }
//                                 } else {
//                                     resolveStat();
//                                 }
//                             });
//                         });
//                         allStatsPromises.push(statPromise);
//                     });
//
//                     Promise.all(allStatsPromises).then(() => {
//                         let xMin = Math.min(...xValues);
//                         let xMax = Math.max(...xValues);
//                         let yMin = Math.min(...yValues);
//                         let yMax = Math.max(...yValues);
//                         let xTiles = xMax - xMin + 1;
//                         let yTiles = yMax - yMin + 1;
//                         Util.Image.getSize(path.join(sourcePath, aImage), (err, width, height) => {
//                             if (!err) {
//                                 let tileSize = Math.max(width, height);
//                                 let size = Math.max(width * xTiles, height * yTiles);
//                                 resolveDim([tileSize, size]);
//                             } else {
//                                 rejectDim(err);
//                             }
//                         });
//                     });
//                 });
//             } else if (mode === Util.Layers.Mode.SINGLE_IMAGE) {
//                 Util.Image.getSize(sourcePath, (err, width, height) => {
//                     if (!err) {
//                         let tileSize = Math.max(width, height);
//                         let size = tileSize;
//                         resolveDim([tileSize, size]);
//                     } else {
//                         rejectDim(err);
//                     }
//                 });
//             } else if (mode === Util.Layers.Mode.IMAGE_LIST) {
//                 resolveDim([256, 256]); // temporary solution (bad sizes).
//             }
//         });
//
//         dimPromise.then((size) => {
//             let filename;
//             if (template != null) {
//                 filename = template;
//             } else {
//                 filename = path.basename(sourcePath);
//             }
//
//             let jsonConfig = {};
//
//             switch (layerType) {
//                 case `points`:
//                     jsonConfig = {
//                         name: `centroid_${filename}`,
//                         author: os.userInfo().username,
//                         type: `pointsLayer`,
//                         tileSize: size[0],
//                         size: size[1],
//                         pointsUrlTemplate: `points_${filename.replace(/ /g, "_")}.csv`
//                     }
//                     break;
//
//                 case `pixels`:
//                     jsonConfig = {
//                         name: `holes_${filename}`,
//                         author: os.userInfo().username,
//                         type: `pixelsLayer`,
//                         role: 'holes',
//                         tileSize: size[0],
//                         size: size[1],
//                         norm: size[2] || 1,
//                         pixelsUrlTemplate: `holes_${filename.replace(/ /g, "_")}.txt`
//                     }
//                     break;
//             }
//
//             next(jsonConfig);
//         });
//     }
//
// }
//
// /**
//  * JSON Configuration creation modes.
//  */
// exports.layers.Mode = {
//     SINGLE_IMAGE: 0,
//     FOLDER: 1,
//     IMAGE_LIST: 2
// }
//
// /**
//  * Image utilities.
//  */
// exports.image =  {
//
//     /**
//      * Calculates slice number of an image.
//      *
//      * @static
//      * @param {string} imagePath - Source image path.
//      * @returns {number} Number of slices.
//      */
//     getTotalSlices: function(imagePath) {
//         if (imagePath.endsWith(".tif") || imagePath.endsWith(".tiff")) {
//             let data = fs.readFileSync(imagePath);
//             let tiffImage = new Tiff({
//                 buffer: data
//             });
//             return tiffImage.countDirectory();
//         } else {
//             // Only tiff images have more than one slice.
//             return 1;
//         }
//     },
//
//     /**
//      * Calculates size (width and height) of an image.
//      *
//      * @static
//      * @param {string} imagePath - Source image path.
//      * @param {function(string, number, number)} next - Callback for returning image dimensions (or error).
//      */
//     getSize: function(imagePath, next) {
//         if (imagePath.endsWith(".tif") || imagePath.endsWith(".tiff")) {
//             fs.readFile(imagePath, (err, data) => {
//                 if (!err) {
//                     try {
//                         let tiffImage = new Tiff({
//                             buffer: data
//                         });
//                         tiffImage.setDirectory(0);
//                         next(null, tiffImage.toCanvas().width, tiffImage.toCanvas().height);
//                     } catch (err) {
//                         next(null, 256, 256); // default
//                     }
//                 } else {
//                     next(err);
//                 }
//             });
//         } else {
//             let dim = sizeOf(imagePath);
//             next(null, dim.width, dim.height);
//         }
//     }
//
// }
<|endoftext|>


<commit_before>function fixWebpackFilePath(filePath) {
  const isWin = process.platform.startsWith('win');

  if (filePath.indexOf('!') !== -1) {
    filePath = filePath.split('!').pop();
  }

  if (filePath.indexOf('?') !== -1) {
    filePath = filePath.split('?')[0];
  }

  // Workaround for https://github.com/mattlewis92/karma-coverage-istanbul-reporter/issues/9
  if (isWin) {
    filePath = filePath.replace(/\\/g, '/');
  }

  return filePath;
}

function fixWebpackSourcePaths(sourceMap) {
  return Object.assign({}, sourceMap, {
    sources: sourceMap.sources.map(source => {
      source = fixWebpackFilePath(source);
      if (sourceMap.sourceRoot && source.startsWith(sourceMap.sourceRoot)) {
        source = source.replace(sourceMap.sourceRoot, '');
      }
      return source;
    })
  });
}

module.exports.fixWebpackSourcePaths = fixWebpackSourcePaths;
module.exports.fixWebpackFilePath = fixWebpackFilePath;
<commit_msg>fix: don't throw when there are no sources as part of the sourcemap<commit_after>function fixWebpackFilePath(filePath) {
  const isWin = process.platform.startsWith('win');

  if (filePath.indexOf('!') !== -1) {
    filePath = filePath.split('!').pop();
  }

  if (filePath.indexOf('?') !== -1) {
    filePath = filePath.split('?')[0];
  }

  // Workaround for https://github.com/mattlewis92/karma-coverage-istanbul-reporter/issues/9
  if (isWin) {
    filePath = filePath.replace(/\\/g, '/');
  }

  return filePath;
}

function fixWebpackSourcePaths(sourceMap) {
  return Object.assign({}, sourceMap, {
    sources: (sourceMap.sources || []).map(source => {
      source = fixWebpackFilePath(source);
      if (sourceMap.sourceRoot && source.startsWith(sourceMap.sourceRoot)) {
        source = source.replace(sourceMap.sourceRoot, '');
      }
      return source;
    })
  });
}

module.exports.fixWebpackSourcePaths = fixWebpackSourcePaths;
module.exports.fixWebpackFilePath = fixWebpackFilePath;
<|endoftext|>


<commit_before>/** Copy own-properties from `props` onto `obj`.
 *	@returns obj
 *	@private
 */
export function extend(obj, props) {
	if (props) {
		for (let i in props) {
			if (props[i]!==undefined) {
				obj[i] = props[i];
			}
		}
	}
	return obj;
}

/** Fast clone. Note: does not filter out non-own properties.
 *	@see https://esbench.com/bench/56baa34f45df6895002e03b6
 */
export function clone(obj) {
	return extend({}, obj);
}

/** Create a caching wrapper for the given function.
 *	Note: As this method is only used for memoizing string operations, it does not safeguard against Object.prototype manipulation.
 *	@private
 */
export function memoize(fn) {
	let mem = {};
	return k => mem[k] || (mem[k] = fn(k));
}

/** Get a deep property value from the given object, expressed in dot-notation.
 *	@private
 */
export function delve(obj, key) {
	for (let p=key.split('.'), i=0; i<p.length && obj; i++) {
		obj = obj[p[i]];
	}
	return obj;
}

/** Convert an Array-like object to an Array
 *	@private
 */
export function toArray(obj, offset) {
	return [].slice.call(obj, offset);
}

/** @private is the given object a Function? */
export function isFunction(obj) {
	return 'function'===typeof obj;
}

/** @private is the given object a String? */
export function isString(obj) {
	return 'string'===typeof obj;
}

/** Check if a value is `null` or `undefined`.
 *	@private
 */
export function empty(x) {
	return x===undefined || x===null;
}

/** Check if a value is `null`, `undefined`, or explicitly `false`. */
export function falsey(value) {
	return value===false || empty(value);
}

/** Convert a hashmap of CSS classes to a space-delimited className string
 *	@private
 */
export function hashToClassName(c) {
	let str = '';
	for (let prop in c) {
		if (c[prop]) {
			if (str) str += ' ';
			str += prop;
		}
	}
	return str;
}

/** Just a memoized String.prototype.toLowerCase */
export const toLowerCase = memoize( s => s.toLowerCase() );

// For animations, rAF is vastly superior. However, it scores poorly on benchmarks :(
// export const setImmediate = typeof requestAnimationFrame==='function' ? requestAnimationFrame : setTimeout;

/** Call a function asynchronously, as soon as possible.
 *	@param {Function} callback
 */
let resolved = typeof Promise!=='undefined' && Promise.resolve();
export const setImmediate = resolved ? (f => { resolved.then(f); }) : setTimeout;
<commit_msg>Drop `memoize()`, since it's now only used for `toLowerCase()` and can be simply inlined.<commit_after>/** Copy own-properties from `props` onto `obj`.
 *	@returns obj
 *	@private
 */
export function extend(obj, props) {
	if (props) {
		for (let i in props) {
			if (props[i]!==undefined) {
				obj[i] = props[i];
			}
		}
	}
	return obj;
}

/** Fast clone. Note: does not filter out non-own properties.
 *	@see https://esbench.com/bench/56baa34f45df6895002e03b6
 */
export function clone(obj) {
	return extend({}, obj);
}

/** Get a deep property value from the given object, expressed in dot-notation.
 *	@private
 */
export function delve(obj, key) {
	for (let p=key.split('.'), i=0; i<p.length && obj; i++) {
		obj = obj[p[i]];
	}
	return obj;
}

/** Convert an Array-like object to an Array
 *	@private
 */
export function toArray(obj, offset) {
	return [].slice.call(obj, offset);
}

/** @private is the given object a Function? */
export function isFunction(obj) {
	return 'function'===typeof obj;
}

/** @private is the given object a String? */
export function isString(obj) {
	return 'string'===typeof obj;
}

/** Check if a value is `null` or `undefined`.
 *	@private
 */
export function empty(x) {
	return x===undefined || x===null;
}

/** Check if a value is `null`, `undefined`, or explicitly `false`. */
export function falsey(value) {
	return value===false || empty(value);
}

/** Convert a hashmap of CSS classes to a space-delimited className string
 *	@private
 */
export function hashToClassName(c) {
	let str = '';
	for (let prop in c) {
		if (c[prop]) {
			if (str) str += ' ';
			str += prop;
		}
	}
	return str;
}

/** Just a memoized String#toLowerCase */
let lcCache = {};
export const toLowerCase = s => lcCache[s] || (lcCache[s] = s.toLowerCase());

/** Call a function asynchronously, as soon as possible.
 *	@param {Function} callback
 */
let resolved = typeof Promise!=='undefined' && Promise.resolve();
export const setImmediate = resolved ? (f => { resolved.then(f); }) : setTimeout;
<|endoftext|>