<commit_before>  var axios = require('axios');
  var L = require('leaflet');
  var esri = require('esri-leaflet');
  var turf = require('turf');
  var turfFC = require('turf-featurecollection');
  var turfFilter = require('turf-filter');

  var ago_URL = 'http://services1.arcgis.com/PwLrOgCfU0cYShcG/ArcGIS/rest/services'
  var geogLevels = '/RDRBP/FeatureServer/3/query?where=id<>%27%27&objectIds=&time=&resultType=none&outFields=+geography_level%2Cgeography_label&returnIdsOnly=false&returnCountOnly=false&returnDistinctValues=true&orderByFields=geography_level&groupByFieldsForStatistics=&outStatistics=&resultOffset=&resultRecordCount=&f=pgeojson&token='
  var allBasins = 'RDRBP/FeatureServer/4/query?where=type%3D%27HUC+6%27&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&resultType=none&distance=&units=esriSRUnit_Meter&outFields=id,NAME,VALUE,MAIN,SUB&returnGeometry=false&returnCentroid=false&multipatchOption=&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&returnDistinctValues=true&orderByFields=&groupByFieldsForStatistics=&outStatistics=&resultOffset=&resultRecordCount=&returnZ=false&returnM=false&quantizationParameters=&f=pgeojson&token='
  var actualBasins = '/RDRBP/FeatureServer/0/query?where=id%3C%3E%27%27&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&resultType=none&distance=&units=esriSRUnit_Meter&outFields=id,NAME,VALUE,MAIN,SUB&returnGeometry=false&returnCentroid=false&multipatchOption=&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&returnDistinctValues=true&orderByFields=&groupByFieldsForStatistics=&outStatistics=&resultOffset=&resultRecordCount=&returnZ=false&returnM=false&quantizationParameters=&f=pgeojson&token='
  var actualCatalogingUnits = '/RDRBP/FeatureServer/1/query?where=id%3C%3E%27%27&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&resultType=none&distance=&units=esriSRUnit_Meter&outFields=id,NAME,VALUE,MAIN,SUB&returnGeometry=false&returnCentroid=false&multipatchOption=&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&returnDistinctValues=true&orderByFields=&groupByFieldsForStatistics=&outStatistics=&resultOffset=&resultRecordCount=&returnZ=false&returnM=false&quantizationParameters=&f=pgeojson&token='
  var actualHUCS = '/RDRBP/FeatureServer/2/query?where=id%3C%3E%27%27&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&resultType=none&distance=&units=esriSRUnit_Meter&outFields=id,NAME,VALUE,MAIN,SUB&returnGeometry=false&returnCentroid=false&multipatchOption=&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&returnDistinctValues=true&orderByFields=&groupByFieldsForStatistics=&outStatistics=&resultOffset=&resultRecordCount=&returnZ=false&returnM=false&quantizationParameters=&f=pgeojson&token='

  //set base URL for axios
  axios.defaults.baseURL = ago_URL;

  //create menu list
  var menuLists = [];

//get the next level of geog for a geography level to use in ago api
//  example this gets all the hucs for a Cataloging unit
function getNextLevel(geogLevel){
  switch (geogLevel) {
    case 'River Basins':
      return 1;
      break;
    case 'Cataloging Units':
      return 3;
      break;
    case 'HUC12':
      return 3;
      break;
    default:
      return 3;
    }
}
//get chart data by huc id
function get_AllChartDataLowerLevel_byID(hucid,geogLevel){
   var id = hucid;
   var level = getNextLevel(geogLevel);

   if(geogLevel === 'HUC12'){
     id = hucid.substring(0,8);
   }
   var query_URL = '/RDRBP/FeatureServer/3/query?where='+
                   'ID+like+%27' + id + '%25%27+and+geography_level%3D'+ level +
                   '&objectIds='+
                   '&time='+
                   '&resultType=none'+
                   '&outFields=chart_level%2C+chart_label%2C+chart_value%2C+chart_description%2C+chart_type%2C+chart_level_label'+
                   '&returnIdsOnly=false'+
                   '&returnCountOnly=false'+
                   '&returnDistinctValues=true'+
                   '&orderByFields=chart_level'+
                   '&groupByFieldsForStatistics='+
                   '&outStatistics='+
                   '&resultOffset='+
                   '&resultRecordCount='+
                   '&f=pgeojson&token=';

//  console.log(query_URL);
  return axios.get(query_URL);

}

//get chart data by huc id
function testit(hucid){

   var query_URL = '/RDRBP/FeatureServer/3/query?where' +
                    '=id%3D%27' + hucid + '%27' +
                    '&objectIds='+
                    '&time='+
                    '&resultType=none'+
                    '&outFields=chart_id%2C+chart_matchid%2Cchart_type%2Cchart_level%2Cchart_description%2Cchart_value'+
                    '&returnIdsOnly=false'+
                    '&returnCountOnly=false'+
                    '&returnDistinctValues=true'+
                    '&orderByFields=chart_level%2Cchart_matchid'+
                    '&groupByFieldsForStatistics='+
                    '&outStatistics='+
                    '&resultOffset='+
                    '&resultRecordCount='+
                    '&f=pgeojson&token=';

  const request = axios.get(query_URL);
  console.log(request);

  return {
    type: TEST,
    payload: request
  };

}

  //get chart data by huc id
  function get_ChartData_byID(hucid){

     var query_URL = '/RDRBP/FeatureServer/3/query?where' +
                      '=id%3D%27' + hucid + '%27' +
                      '&objectIds='+
                      '&time='+
                      '&resultType=none'+
                      '&outFields=chart_id%2C+chart_matchid%2Cchart_type%2Cchart_level%2Cchart_description%2Cchart_value'+
                      '&returnIdsOnly=false'+
                      '&returnCountOnly=false'+
                      '&returnDistinctValues=true'+
                      '&orderByFields=chart_level%2Cchart_matchid'+
                      '&groupByFieldsForStatistics='+
                      '&outStatistics='+
                      '&resultOffset='+
                      '&resultRecordCount='+
                      '&f=pgeojson&token=';

    return axios.get(query_URL);

  }

  //get chart data by huc id
  function get_ChartData_byID(hucid){

     var query_URL = '/RDRBP/FeatureServer/3/query?where' +
                      '=id%3D%27' + hucid + '%27' +
                      '&objectIds='+
                      '&time='+
                      '&resultType=none'+
                      '&outFields=chart_id%2C+chart_matchid%2Cchart_type%2Cchart_level%2Cchart_description%2Cchart_value'+
                      '&returnIdsOnly=false'+
                      '&returnCountOnly=false'+
                      '&returnDistinctValues=true'+
                      '&orderByFields=chart_level%2Cchart_matchid'+
                      '&groupByFieldsForStatistics='+
                      '&outStatistics='+
                      '&resultOffset='+
                      '&resultRecordCount='+
                      '&f=pgeojson&token=';

    return axios.get(query_URL);

  }
  //retrieves geography levels from AGO api
  function get_AGOGeographyLevels(){
    return axios.get(geogLevels);
  }

  //retrieves the list basins currently available frm AGO api
  function get_AGOBasins(){
    return axios.get(actualBasins);
  }

  //retrieves the list Cataloging Units currently available frm AGO api
  function get_AGOCatalogingUnits(){
    return axios.get(actualCatalogingUnits);
  }

  //retrieves the list Cataloging Units currently available frm AGO api
  function get_AGOHUCS(){
    return axios.get(actualHUCS);
  }

  //retrieve a list of all the River Basins in NC from AGO api
  function get_AGOBasinsALL(){
    return axios.get(allBasins);
  }

  //get an array of IDs from the JSON data.
  function get_IDs(featureCollection){

    //creaet emputy array to store the ids
    var  filterValues = [];

    //create a copy of features of obect.
    var fc = featureCollection.data.features

    //map the GeoJSON obect and build a list of the ids.
    fc.map(function(feature){
      filterValues.push(feature.properties.id);
    })

    return filterValues;
  }

  function set_NameList(name){
      return {
        name,
        lists:[]
      }
  }

  //builds a menu list
  function set_MenuList (name, menuList, geoJSON){
    var ml = [];
    var nameList = set_NameList(name);

    ml.push( nameList );

    //map the menu list
    ml.map(function(menu){
      //check if name matches the passed name
      if(menu.name === name){
        //map geojson features and add the properties (attributes) to the list
        //  this will populate the menu items
        geoJSON.features.map(function(features) {
           menu.lists.push(features.properties)
         })
      }
    })

    //return new menu list
    return ml[0]
  }

  //merges two json data lists
  //   nested would not do {...list1, ...list2}
  function mergeList(list1,list2){
    var merged = [];

    //if already an array just create a new array
    if (Array.isArray(list1)){
      merged = list1
    } else{
      merged.push(list1);
    }

    //merged.push(l1);
    merged.push(list2);

    return merged
  }
  //builds the data structure for Basin Menu List
  function get_MenuLists(filterValues){

    //get the complete list of basins and filter it by the ids of basins avaiable for viewer
    return  get_AGOBasins()
      .then(function(geoJSON){

        //get the menu list based on filtered features
        var ml = set_MenuList( 'River Basins', menuLists, geoJSON.data)

        //return the JSON list
        return ml;
      })
        .then(function(RBList){
          return get_AGOCatalogingUnits()
            .then(function(geoJSON){

              //get the menu list based on filtered features
              var ml = set_MenuList( 'Cataloging Units', menuLists, geoJSON.data)

              //merge lists
              var merged = mergeList(RBList,ml)

              return merged;
            })
        })
        .then(function(CUList){
          return get_AGOHUCS()
            .then(function(geoJSON){

              //get the menu list based on filtered features
              var ml = set_MenuList( 'HUC12', menuLists,  geoJSON.data)

              //merge lists
              var merged = mergeList(CUList,ml)

              //return the JSON list
              return merged;
            })
        })
  }

  var AGOHelpers = {
    get_AllChartDataLowerLevel_byID: function(id,level){
      return get_AllChartDataLowerLevel_byID(id,level)
      .then(function(result) {
         return result.data
      });
    },
    get_ChartData_byID: function(val){
      return get_ChartData_byID(val)
      .then(function(result) {
         return result.data
      });
    },
    //get available basins
    get_Basins: function(){
      return get_AGOBasins()
      .then(function(result) {
         return result.data
      });
    },
    //get available Cataloging Units
    get_CatalogingUnits: function(){
      return get_AGOCatalogingUnits()
      .then(function(result) {
         return result.data
      });
    },
    //get available Cataloging Units
    get_ActualHUCS: function(){
      return get_AGOHUCS()
      .then(function(result) {
         return result.data
      });
    },
    //get ALl basins
    get_BasinsAll: function(){
      return get_AGOBasinsALL()
      .then(function(result) {
         return result.data
      });
    },
    get_MenuList: function(){
      return get_MenuLists()
        .then(function(result) {
           return result
        });
      // return get_AGOBasins()
      // .then(get_IDs)
      //   .then(function(data){
      //     return  get_MenuLists(data);
      //   })
    },
    get_GeographyLevels: function(){
      return get_AGOGeographyLevels()
       .then(function(result) {
          return result.data
       });
     },
     get_filteredIDs: function(){
       return get_AGOBasins()
       .then(get_IDs)
         .then(function(data){
           return data;
         })
     }
  };

  module.exports = AGOHelpers;
<commit_msg>updates queries to properly bring in all attributes<commit_after>  var axios = require('axios');
  var L = require('leaflet');
  var esri = require('esri-leaflet');
  var turf = require('turf');
  var turfFC = require('turf-featurecollection');
  var turfFilter = require('turf-filter');

  var ago_URL = 'http://services1.arcgis.com/PwLrOgCfU0cYShcG/ArcGIS/rest/services'
  var geogLevels = '/RDRBP/FeatureServer/3/query?where=id<>%27%27&objectIds=&time=&resultType=none&outFields=+geography_level%2Cgeography_label&returnIdsOnly=false&returnCountOnly=false&returnDistinctValues=true&orderByFields=geography_level&groupByFieldsForStatistics=&outStatistics=&resultOffset=&resultRecordCount=&f=pgeojson&token='
  var allBasins = 'RDRBP/FeatureServer/4/query?where=type%3D%27HUC+6%27&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&resultType=none&distance=&units=esriSRUnit_Meter&outFields=id,NAME,VALUE,MAIN,SUB&returnGeometry=false&returnCentroid=false&multipatchOption=&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&returnDistinctValues=true&orderByFields=&groupByFieldsForStatistics=&outStatistics=&resultOffset=&resultRecordCount=&returnZ=false&returnM=false&quantizationParameters=&f=pgeojson&token='
  var actualBasins = '/RDRBP/FeatureServer/0/query?where=id%3C%3E%27%27&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&resultType=none&distance=&units=esriSRUnit_Meter&outFields=id,NAME,VALUE,MAIN,SUB&returnGeometry=false&returnCentroid=false&multipatchOption=&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&returnDistinctValues=true&orderByFields=&groupByFieldsForStatistics=&outStatistics=&resultOffset=&resultRecordCount=&returnZ=false&returnM=false&quantizationParameters=&f=pgeojson&token='
  var actualCatalogingUnits = '/RDRBP/FeatureServer/1/query?where=id%3C%3E%27%27&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&resultType=none&distance=&units=esriSRUnit_Meter&outFields=id,NAME,VALUE,MAIN,SUB&returnGeometry=false&returnCentroid=false&multipatchOption=&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&returnDistinctValues=true&orderByFields=&groupByFieldsForStatistics=&outStatistics=&resultOffset=&resultRecordCount=&returnZ=false&returnM=false&quantizationParameters=&f=pgeojson&token='
  var actualHUCS = '/RDRBP/FeatureServer/2/query?where=id%3C%3E%27%27&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&resultType=none&distance=&units=esriSRUnit_Meter&outFields=id,NAME,VALUE,MAIN,SUB&returnGeometry=false&returnCentroid=false&multipatchOption=&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&returnDistinctValues=true&orderByFields=&groupByFieldsForStatistics=&outStatistics=&resultOffset=&resultRecordCount=&returnZ=false&returnM=false&quantizationParameters=&f=pgeojson&token='

  //set base URL for axios
  axios.defaults.baseURL = ago_URL;

  //create menu list
  var menuLists = [];

//get the next level of geog for a geography level to use in ago api
//  example this gets all the hucs for a Cataloging unit
function getNextLevel(geogLevel){
  switch (geogLevel) {
    case 'River Basins':
      return 1;
      break;
    case 'Cataloging Units':
      return 3;
      break;
    case 'HUC12':
      return 3;
      break;
    default:
      return 3;
    }
}
//get chart data by huc id
function get_AllChartDataLowerLevel_byID(hucid,geogLevel){
   var id = hucid;
   var level = getNextLevel(geogLevel);

   if(geogLevel === 'HUC12'){
     id = hucid.substring(0,8);
   }
   var query_URL = '/RDRBP/FeatureServer/3/query?where='+
//                   'ID+like+%27' + id + '%25%27+and+geography_level%3D'+ level +
                   'ID+like+%27' + id + '%25%27' +
                   '&objectIds='+
                   '&time='+
                   '&resultType=none'+
                   '&outFields=OBJECT_ID%2CID%2Cgeography_match_id%2Cchart_id%2Cchart_matchid%2Cgeography_level%2Cchart_level%2C+chart_label%2C+chart_value%2C+chart_description%2C+chart_type%2C+chart_level_label'+
                   '&returnIdsOnly=false'+
                   '&returnCountOnly=false'+
                   '&returnDistinctValues=true'+
                   '&orderByFields=chart_level'+
                   '&groupByFieldsForStatistics='+
                   '&outStatistics='+
                   '&resultOffset='+
                   '&resultRecordCount='+
                   '&f=pgeojson&token=';

//  console.log(query_URL);
  return axios.get(query_URL);

}

//get chart data by huc id
function testit(hucid){

   var query_URL = '/RDRBP/FeatureServer/3/query?where' +
                    '=id%3D%27' + hucid + '%27' +
                    '&objectIds='+
                    '&time='+
                    '&resultType=none'+
                    '&outFields=chart_id%2C+chart_matchid%2Cchart_type%2Cchart_level%2Cchart_description%2Cchart_value'+
                    '&returnIdsOnly=false'+
                    '&returnCountOnly=false'+
                    '&returnDistinctValues=true'+
                    '&orderByFields=chart_level%2Cchart_matchid'+
                    '&groupByFieldsForStatistics='+
                    '&outStatistics='+
                    '&resultOffset='+
                    '&resultRecordCount='+
                    '&f=pgeojson&token=';

  const request = axios.get(query_URL);
  console.log(request);

  return {
    type: TEST,
    payload: request
  };

}

  //get chart data by huc id
  function get_ChartData_byID(hucid){

     var query_URL = '/RDRBP/FeatureServer/3/query?where' +
                      '=id%3D%27' + hucid + '%27' +
                      '&objectIds='+
                      '&time='+
                      '&resultType=none'+
                      '&outFields=OBJECT_ID%2CID%2Cgeography_match_id%2Cgeography_level%2Cchart_id%2C+chart_matchid%2Cchart_type%2Cchart_level%2Cchart_level_label%2Cchart_description%2Cchart_value'+
                      '&returnIdsOnly=false'+
                      '&returnCountOnly=false'+
                      '&returnDistinctValues=true'+
                      '&orderByFields=chart_level%2Cchart_matchid'+
                      '&groupByFieldsForStatistics='+
                      '&outStatistics='+
                      '&resultOffset='+
                      '&resultRecordCount='+
                      '&f=pgeojson&token=';

    return axios.get(query_URL);

  }

  //get chart data by huc id
  function get_ChartData_byID(hucid){

     var query_URL = '/RDRBP/FeatureServer/3/query?where' +
                      '=id%3D%27' + hucid + '%27' +
                      '&objectIds='+
                      '&time='+
                      '&resultType=none'+
                      '&outFields=OBJECTID%2Cchart_id%2C+chart_matchid%2Cchart_type%2Cchart_level%2Cchart_description%2Cchart_value'+
                      '&returnIdsOnly=false'+
                      '&returnCountOnly=false'+
                      '&returnDistinctValues=true'+
                      '&orderByFields=chart_level%2Cchart_matchid'+
                      '&groupByFieldsForStatistics='+
                      '&outStatistics='+
                      '&resultOffset='+
                      '&resultRecordCount='+
                      '&f=pgeojson&token=';

    return axios.get(query_URL);

  }
  //retrieves geography levels from AGO api
  function get_AGOGeographyLevels(){
    return axios.get(geogLevels);
  }

  //retrieves the list basins currently available frm AGO api
  function get_AGOBasins(){
    return axios.get(actualBasins);
  }

  //retrieves the list Cataloging Units currently available frm AGO api
  function get_AGOCatalogingUnits(){
    return axios.get(actualCatalogingUnits);
  }

  //retrieves the list Cataloging Units currently available frm AGO api
  function get_AGOHUCS(){
    return axios.get(actualHUCS);
  }

  //retrieve a list of all the River Basins in NC from AGO api
  function get_AGOBasinsALL(){
    return axios.get(allBasins);
  }

  //get an array of IDs from the JSON data.
  function get_IDs(featureCollection){

    //creaet emputy array to store the ids
    var  filterValues = [];

    //create a copy of features of obect.
    var fc = featureCollection.data.features

    //map the GeoJSON obect and build a list of the ids.
    fc.map(function(feature){
      filterValues.push(feature.properties.id);
    })

    return filterValues;
  }

  function set_NameList(name){
      return {
        name,
        lists:[]
      }
  }

  //builds a menu list
  function set_MenuList (name, menuList, geoJSON){
    var ml = [];
    var nameList = set_NameList(name);

    ml.push( nameList );

    //map the menu list
    ml.map(function(menu){
      //check if name matches the passed name
      if(menu.name === name){
        //map geojson features and add the properties (attributes) to the list
        //  this will populate the menu items
        geoJSON.features.map(function(features) {
           menu.lists.push(features.properties)
         })
      }
    })

    //return new menu list
    return ml[0]
  }

  //merges two json data lists
  //   nested would not do {...list1, ...list2}
  function mergeList(list1,list2){
    var merged = [];

    //if already an array just create a new array
    if (Array.isArray(list1)){
      merged = list1
    } else{
      merged.push(list1);
    }

    //merged.push(l1);
    merged.push(list2);

    return merged
  }
  //builds the data structure for Basin Menu List
  function get_MenuLists(filterValues){

    //get the complete list of basins and filter it by the ids of basins avaiable for viewer
    return  get_AGOBasins()
      .then(function(geoJSON){

        //get the menu list based on filtered features
        var ml = set_MenuList( 'River Basins', menuLists, geoJSON.data)

        //return the JSON list
        return ml;
      })
        .then(function(RBList){
          return get_AGOCatalogingUnits()
            .then(function(geoJSON){

              //get the menu list based on filtered features
              var ml = set_MenuList( 'Cataloging Units', menuLists, geoJSON.data)

              //merge lists
              var merged = mergeList(RBList,ml)

              return merged;
            })
        })
        .then(function(CUList){
          return get_AGOHUCS()
            .then(function(geoJSON){

              //get the menu list based on filtered features
              var ml = set_MenuList( 'HUC12', menuLists,  geoJSON.data)

              //merge lists
              var merged = mergeList(CUList,ml)

              //return the JSON list
              return merged;
            })
        })
  }

  var AGOHelpers = {
    get_AllChartDataLowerLevel_byID: function(id,level){
      return get_AllChartDataLowerLevel_byID(id,level)
      .then(function(result) {
         return result.data
      });
    },
    get_ChartData_byID: function(val){
      return get_ChartData_byID(val)
      .then(function(result) {
         return result.data
      });
    },
    //get available basins
    get_Basins: function(){
      return get_AGOBasins()
      .then(function(result) {
         return result.data
      });
    },
    //get available Cataloging Units
    get_CatalogingUnits: function(){
      return get_AGOCatalogingUnits()
      .then(function(result) {
         return result.data
      });
    },
    //get available Cataloging Units
    get_ActualHUCS: function(){
      return get_AGOHUCS()
      .then(function(result) {
         return result.data
      });
    },
    //get ALl basins
    get_BasinsAll: function(){
      return get_AGOBasinsALL()
      .then(function(result) {
         return result.data
      });
    },
    get_MenuList: function(){
      return get_MenuLists()
        .then(function(result) {
           return result
        });
      // return get_AGOBasins()
      // .then(get_IDs)
      //   .then(function(data){
      //     return  get_MenuLists(data);
      //   })
    },
    get_GeographyLevels: function(){
      return get_AGOGeographyLevels()
       .then(function(result) {
          return result.data
       });
     },
     get_filteredIDs: function(){
       return get_AGOBasins()
       .then(get_IDs)
         .then(function(data){
           return data;
         })
     }
  };

  module.exports = AGOHelpers;
<|endoftext|>


<commit_before>'use strict'

import React from 'react'
import EventListItem from '../../components/event-list-item'
import Pagination from '../../components/pagination/index'

const Page = () => (

Próximos Eventos

    {Array.apply(null, { length: 5 }).map((event, index) => (
      <EventListItem key={index} />
    ))}
      <Pagination />

)

export default Page
<commit_msg>Improve page, adding events<commit_after>'use strict'

import React from 'react'
import EventListItem from '../../components/event-list-item'
import Pagination from '../../components/pagination/index'

const events = [{
  title: 'Conferência CSS Brasil',
  image: 'http://www.conferenciacssbrasil.com.br/build/img/css-brasil.png',
  innerLink: 'inner.html',
  link: 'http://www.conferenciacssbrasil.com.br/',
  date: {
    day: 20,
    month: 'Maio',
    year: 2016
  },
  price: 'R$ 120,00',
  location: 'Maksound Plaza, São Paulo - SP',
  locationUrl: 'https://www.google.com.br/maps?q=maksoud+plaza&um=1&ie=UTF-8&sa=X&ved=0ahUKEwinuq_pm4rMAhXKkZAKHfMfBgoQ_AUICCgC',
  shortDescription: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corrupti vero assumenda aliquid voluptatibus quos vitae ratione aut maiores quo odio.'
}]

const Page = () => (

Próximos Eventos

      {events.map((props, index) => (
        <EventListItem key={index} {...props} />
      ))}
      <Pagination />

)

export default Page
<|endoftext|>


<commit_before>// 数据流的入口
var SnapkiteStreamClient = require('snapkite-stream-client');
var TweetActionCreators = require('../actions/tweetactioncreators');

function initailizeStreamOfTweets() {
	SnapkiteStreamClient.initializeStream(TweetActionCreators.handleAction);
}

exports.initailizeStreamOfTweets = initailizeStreamOfTweets;<commit_msg>修正了在webapiutils中的方法用错了<commit_after>// 数据流的入口
var SnapkiteStreamClient = require('snapkite-stream-client');
var TweetActionCreators = require('../actions/tweetactioncreators');

function initailizeStreamOfTweets() {
	SnapkiteStreamClient.initializeStream(TweetActionCreators.receiveTweet);
}

exports.initailizeStreamOfTweets = initailizeStreamOfTweets;<|endoftext|>


<commit_before>(function () {
  var ns = $.namespace('pskl.service');

  ns.CurrentColorsService = function (piskelController) {
    this.piskelController = piskelController;
    this.currentColors = [];
    this.cachedFrameProcessor = new pskl.model.frame.CachedFrameProcessor();
    this.cachedFrameProcessor.setFrameProcessor(this.getFrameColors_.bind(this));

    this.colorSorter = new pskl.service.color.ColorSorter();

    this.framesColorsCache_ = {};
  };

  ns.CurrentColorsService.prototype.init = function () {
    $.subscribe(Events.PISKEL_RESET, this.onPiskelUpdated_.bind(this));
    $.subscribe(Events.TOOL_RELEASED, this.onPiskelUpdated_.bind(this));

    // this.updateTimer = window.setInterval(this.updateCurrentColors_.bind(this));
  };

  ns.CurrentColorsService.prototype.getCurrentColors = function () {
    return this.currentColors;
  };

  ns.CurrentColorsService.prototype.getFrameColors_ = function (frame) {
    var frameColors = {};
    frame.forEachPixel(function (color, x, y) {
      var hexColor = this.toHexColor_(color);
      frameColors[hexColor] = true;
    }.bind(this));
    return frameColors;
  };

  ns.CurrentColorsService.prototype.onPiskelUpdated_ = function (evt) {
    var layers = this.piskelController.getLayers();
    var frames = layers.map(function (l) {return l.getFrames();}).reduce(function (p, n) {return p.concat(n);});
    var colors = {};

    frames.forEach(function (f) {
      var frameColors = this.cachedFrameProcessor.get(f);
      Object.keys(frameColors).slice(0, Constants.MAX_CURRENT_COLORS_DISPLAYED).forEach(function (color) {
        colors[color] = true;
      });
    }.bind(this));

    // Remove transparent color from used colors
    delete colors[Constants.TRANSPARENT_COLOR];

    // limit the array to the max colors to display
    var colorsArray = Object.keys(colors).slice(0, Constants.MAX_CURRENT_COLORS_DISPLAYED);
    this.currentColors = this.colorSorter.sort(colorsArray);
    console.log(this.currentColors);

    // TODO : only fire if there was a change
    $.publish(Events.CURRENT_COLORS_UPDATED);
  };

  ns.CurrentColorsService.prototype.toHexColor_ = function (color) {
    if (color === Constants.TRANSPARENT_COLOR) {
      return color;
    } else {
      color = color.replace(/\s/g, '');
      var hexRe = (/^#([a-f0-9]{3}){1,2}$/i);
      var rgbRe = (/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/i);
      if (hexRe.test(color)) {
        return color.toUpperCase();
      } else if (rgbRe.test(color)) {
        var exec = rgbRe.exec(color);
        return pskl.utils.rgbToHex(exec[1] * 1, exec[2] * 1, exec[3] * 1);
      } else {
        console.error('Could not convert color to hex : ', color);
      }
    }
  };
})();<commit_msg>sort colors on image import for palette<commit_after>(function () {
  var ns = $.namespace('pskl.service');

  ns.CurrentColorsService = function (piskelController) {
    this.piskelController = piskelController;
    this.currentColors = [];
    this.cachedFrameProcessor = new pskl.model.frame.CachedFrameProcessor();
    this.cachedFrameProcessor.setFrameProcessor(this.getFrameColors_.bind(this));

    this.colorSorter = new pskl.service.color.ColorSorter();
    this.paletteService = pskl.app.paletteService;

    this.framesColorsCache_ = {};
  };

  ns.CurrentColorsService.prototype.init = function () {
    $.subscribe(Events.PISKEL_RESET, this.onPiskelUpdated_.bind(this));
    $.subscribe(Events.TOOL_RELEASED, this.onPiskelUpdated_.bind(this));
    $.subscribe(Events.USER_SETTINGS_CHANGED, $.proxy(this.onUserSettingsChange_, this));
  };

  ns.CurrentColorsService.prototype.isCurrentColorsPaletteSelected_ = function () {
    var paletteId = pskl.UserSettings.get(pskl.UserSettings.SELECTED_PALETTE);
    var palette = this.paletteService.getPaletteById(paletteId);

    return palette.id === Constants.CURRENT_COLORS_PALETTE_ID;
  };

  ns.CurrentColorsService.prototype.onUserSettingsChange_ = function (evt, name, value) {
    if (name == pskl.UserSettings.SELECTED_PALETTE) {
      if (this.isCurrentColorsPaletteSelected_()) {
        this.updateCurrentColors_();
      }
    }
  };

  ns.CurrentColorsService.prototype.getCurrentColors = function () {
    return this.currentColors;
  };

  ns.CurrentColorsService.prototype.onPiskelUpdated_ = function (evt) {
    if (this.isCurrentColorsPaletteSelected_()) {
      this.updateCurrentColors_();
    }
  };

  ns.CurrentColorsService.prototype.updateCurrentColors_ = function () {
    var layers = this.piskelController.getLayers();
    var frames = layers.map(function (l) {return l.getFrames();}).reduce(function (p, n) {return p.concat(n);});
    var colors = {};

    frames.forEach(function (f) {
      var frameColors = this.cachedFrameProcessor.get(f);
      Object.keys(frameColors).slice(0, Constants.MAX_CURRENT_COLORS_DISPLAYED).forEach(function (color) {
        colors[color] = true;
      });
    }.bind(this));

    // Remove transparent color from used colors
    delete colors[Constants.TRANSPARENT_COLOR];

    // limit the array to the max colors to display
    var colorsArray = Object.keys(colors).slice(0, Constants.MAX_CURRENT_COLORS_DISPLAYED);
    this.currentColors = this.colorSorter.sort(colorsArray);

    // TODO : only fire if there was a change
    $.publish(Events.CURRENT_COLORS_UPDATED);
  };

  ns.CurrentColorsService.prototype.getFrameColors_ = function (frame) {
    var frameColors = {};
    frame.forEachPixel(function (color, x, y) {
      var hexColor = this.toHexColor_(color);
      frameColors[hexColor] = true;
    }.bind(this));
    return frameColors;
  };

  ns.CurrentColorsService.prototype.toHexColor_ = function (color) {
    if (color === Constants.TRANSPARENT_COLOR) {
      return color;
    } else {
      color = color.replace(/\s/g, '');
      var hexRe = (/^#([a-f0-9]{3}){1,2}$/i);
      var rgbRe = (/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/i);
      if (hexRe.test(color)) {
        return color.toUpperCase();
      } else if (rgbRe.test(color)) {
        var exec = rgbRe.exec(color);
        return pskl.utils.rgbToHex(exec[1] * 1, exec[2] * 1, exec[3] * 1);
      } else {
        console.error('Could not convert color to hex : ', color);
      }
    }
  };
})();<|endoftext|>


<commit_before>'use strict';

angular.module('classBrowserUHApp.class', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/class', {
        templateUrl: 'views/class/class.html',
        controller: 'ClassCtrl'
    });
}]).
controller('ClassCtrl', ['$scope', '$http', function ($scope, $http) {

        $scope.rowCollection = [];

        $scope.departments = {
            availableOptions: [
                {departmentAbbreviation: "abc", departmentFullName: "d"},
                {departmentAbbreviation: "q23w", departmentFullName: "Mathematics"},
                {departmentAbbreviation: "q23w", departmentFullName: "Life and Physical Sciences"},
                {departmentAbbreviation: "q23w", departmentFullName: "Language, Philosophy & Culture"},
                {departmentAbbreviation: "q23w", departmentFullName: "Creative Arts"},
                {departmentAbbreviation: "q23w", departmentFullName: "American History"},
                {departmentAbbreviation: "q23w", departmentFullName: "Government/Political Science"},
                {departmentAbbreviation: "q23w", departmentFullName: "Social & Behavioral Sciences"},
                {departmentAbbreviation: "q23w", departmentFullName: "Mathematics/Reasoning"},
                {departmentAbbreviation: "q23w", departmentFullName: "Writing in the Disciplines"}
            ]
        };

        $scope.creditHours = {
            availableOptions: [
                {creditHours: 1},
                {creditHours: 1.5},
                {creditHours: 2},
                {creditHours: 3},
                {creditHours: 4},
                {creditHours: 5},
                {creditHours: 6},
                {creditHours: 7},
                {creditHours: 8},
                {creditHours: 9},
                {creditHours: 10}
            ]
        };

        $scope.coreCategories = {
            availableOptions: [
                {categoryNumber: 1, categoryName: "Communication"},
                {categoryNumber: 2, categoryName : "Mathematics"},
                {categoryNumber: 3, categoryName : "Life and Physical Sciences"},
                {categoryNumber: 4, categoryName : "Language, Philosophy & Culture"},
                {categoryNumber: 5, categoryName : "Creative Arts"},
                {categoryNumber: 6, categoryName : "American History"},
                {categoryNumber: 7, categoryName : "Government/Political Science"},
                {categoryNumber: 8, categoryName : "Social & Behavioral Sciences"},
                {categoryNumber: 9, categoryName : "Mathematics/Reasoning"},
                {categoryNumber: 10, categoryName : "Writing in the Disciplines"}
            ]
        };

        $scope.populateClasses = function(){

            var apiUrl = $scope.apiUrl + '/information?';

            // http://localhost:8080/api/information?department=aas&credit_hours=2
            // department - A String that represents the department class(es) belong to.
            // credit-hours - An integer that represents the number of credit hours a class fulfills.
            // core - A String representing the core categories of a class.

            // console.log("User selected department: " + $scope.department);
            // console.log("User selected credit-hours: " + $scope.creditHours);
            // console.log("User selected core: " + $scope.core);
            console.log("Populating Classes...");

            $http
                .get(apiUrl)
                .success(function (data) {
                    $scope.rowCollection = data.result;
                    $scope.showDiv = true;
                    console.log(data);
                })
                .error(function (data) {
                    alert("Unable to retrieve the data.");
                });
        };
    }]);<commit_msg>Removed unused variables and comments.<commit_after>'use strict';

angular.module('classBrowserUHApp.class', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/class', {
        templateUrl: 'views/class/class.html',
        controller: 'ClassCtrl'
    });
}]).
controller('ClassCtrl', ['$scope', '$http', function ($scope, $http) {
        $scope.rowCollection = [];
        var url = $scope.apiUrl + '/department';

        $scope.departments = {
            availableOptions: []
        };

        $http.get(url)
            .success(function(data) {
                console.log("Retrieved " + data.numberOfRows + " departments.");
                console.log(data);
                $scope.departments.availableOptions = data.result;
            })
            .error(function(data) {
                alert("Unable to retrieve the data.");
            });

        $scope.creditHours = {
            availableOptions: [
                {creditHours: 1},
                {creditHours: 1.5},
                {creditHours: 2},
                {creditHours: 3},
                {creditHours: 4},
                {creditHours: 5},
                {creditHours: 6},
                {creditHours: 7},
                {creditHours: 8},
                {creditHours: 9},
                {creditHours: 10}
            ]
        };

        $scope.coreCategories = {
            availableOptions: [
                {categoryNumber: 1, categoryName: "Communication"},
                {categoryNumber: 2, categoryName : "Mathematics"},
                {categoryNumber: 3, categoryName : "Life and Physical Sciences"},
                {categoryNumber: 4, categoryName : "Language, Philosophy & Culture"},
                {categoryNumber: 5, categoryName : "Creative Arts"},
                {categoryNumber: 6, categoryName : "American History"},
                {categoryNumber: 7, categoryName : "Government/Political Science"},
                {categoryNumber: 8, categoryName : "Social & Behavioral Sciences"},
                {categoryNumber: 9, categoryName : "Mathematics/Reasoning"},
                {categoryNumber: 10, categoryName : "Writing in the Disciplines"}
            ]
        };

        $scope.populateClasses = function(){

            var apiUrl = $scope.apiUrl + '/information?';
            $scope.poop = "wefhuefrhiurefhiu";

            // http://localhost:8080/api/information?department=aas&credit_hours=2
            // department - A String that represents the department class(es) belong to.
            // credit-hours - An integer that represents the number of credit hours a class fulfills.
            // core - A String representing the core categories of a class.

            // console.log("User selected department: " + $scope.department);
            // console.log("User selected credit-hours: " + $scope.creditHours);
            // console.log("User selected core: " + $scope.core);
            console.log("Populating Classes...");
            console.log($scope.departmentModel);
            console.log($scope.creditHourModel);
            console.log($scope.coreModel);

            // $http
            //     .get(apiUrl)
            //     .success(function (data) {
            //         $scope.rowCollection = data.result;
            //         $scope.showDiv = true;
            //         console.log(data);
            //     })
            //     .error(function (data) {
            //         alert("Unable to retrieve the data.");
            //     });
        };
    }]);<|endoftext|>


<commit_before>/**
 * @flow
 */

const dataDecoders = {
  pcm8: (buffer, offset, output, channels, samples) => {
    let input = new Uint8Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let data = input[pos++] - 128;
        output[ch][i] = data < 0 ? data / 128 : data / 127;
      }
    }
  },
  pcm16: (buffer, offset, output, channels, samples) => {
    let input = new Int16Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let data = input[pos++];
        output[ch][i] = data < 0 ? data / 32768 : data / 32767;
      }
    }
  },
  pcm24: (buffer, offset, output, channels, samples) => {
    let input = new Uint8Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let x0 = input[pos++];
        let x1 = input[pos++];
        let x2 = input[pos++];
        let xx = (x0 + (x1 << 8) + (x2 << 16));
        let data = xx > 0x800000 ? xx - 0x1000000 : xx;
        output[ch][i] = data < 0 ? data / 8388608 : data / 8388607;
      }
    }
  },
  pcm32: (buffer, offset, output, channels, samples) => {
    let input = new Int32Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let data = input[pos++];
        output[ch][i] = data < 0 ? data / 2147483648 : data / 2147483647;
      }
    }
  },
  pcm32f: (buffer, offset, output, channels, samples) => {
    let input = new Float32Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        output[ch][i] = input[pos++];
      }
    }
  },
  pcm64f: (buffer, offset, output, channels, samples) => {
    let input = new Float64Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        output[ch][i] = input[pos++];
      }
    }
  },
};

const dataEncoders = {
  pcm8: (buffer, offset, input, channels, samples) => {
    let output = new Uint8Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let v = Math.max(-1, Math.min(input[ch][i], 1));
        v = ((v * 0.5 + 0.5) * 255) | 0;
        output[pos++] = v;
      }
    }
  },
  pcm16: (buffer, offset, input, channels, samples) => {
    let output = new Int16Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let v = Math.max(-1, Math.min(input[ch][i], 1));
        v = ((v < 0) ? v * 32768 : v * 32767) | 0;
        output[pos++] = v;
      }
    }
  },
  pcm24: (buffer, offset, input, channels, samples) => {
    let output = new Uint8Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let v = Math.max(-1, Math.min(input[ch][i], 1));
        v = ((v < 0) ? 0x1000000 + v * 8388608 : v * 8388607) | 0;
        output[pos++] = (v >> 0) & 0xff;
        output[pos++] = (v >> 8) & 0xff;
        output[pos++] = (v >> 16) & 0xff;
      }
    }
  },
  pcm32: (buffer, offset, input, channels, samples) => {
    let output = new Int32Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let v = Math.max(-1, Math.min(input[ch][i], 1));
        v = ((v < 0) ? v * 2147483648 : v * 2147483647) | 0;
        output[pos++] = v;
      }
    }
  },
  pcm32f: (buffer, offset, input, channels, samples) => {
    let output = new Float32Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let v = Math.max(-1, Math.min(input[ch][i], 1));
        output[pos++] = v;
      }
    }
  },
  pcm64f: (buffer, offset, input, channels, samples) => {
    let output = new Float64Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let v = Math.max(-1, Math.min(input[ch][i], 1));
        output[pos++] = v;
      }
    }
  },
};

function lookup(table, bitDepth, floatingPoint) {
  let name = 'pcm' + bitDepth + (floatingPoint ? 'f' : '');
  let fn = table[name];
  if (!fn) {
    throw new TypeError('Unsupported data format: ' + name);
  }
  return fn;
}

function decodeHeader(v, pos, end) {
  function u8() {
    let x = v.getUint8(pos);
    pos++;
    return x;
  }

  function u16() {
    let x = v.getUint16(pos, true);
    pos += 2;
    return x;
  }

  function u32() {
    let x = v.getUint32(pos, true);
    pos += 4;
    return x;
  }

  function string(len) {
    let str = '';
    for (let i = 0; i < len; ++i) {
      str += String.fromCharCode(u8());
    }
    return str;
  }

  if (string(4) !== 'RIFF') {
    throw new TypeError('Invalid WAV file');
  }
  u32();
  if (string(4) !== 'WAVE') {
    throw new TypeError('Invalid WAV file');
  }

  let fmt;

  while (pos < end) {
    let type = string(4);
    let size = u32();
    let next = pos + size;
    switch (type) {
    case 'fmt ': {
      let formatId = u16();
      if (formatId !== 0x0001 && formatId !== 0x0003) {
        throw new TypeError('Unsupported format in WAV file: ' + formatId.toString(16));
      }
      fmt = {
        format: 'lpcm',
        floatingPoint: formatId === 0x0003,
        channels: u16(),
        sampleRate: u32(),
        byteRate: u32(),
        blockSize: u16(),
        bitDepth: u16(),
      };
      break;
    }
    case 'data': {
      if (!fmt) {
        throw new TypeError('Missing "fmt " chunk.');
      }
      return {
        fmt,
        pos,
        samples: size / fmt.blockSize,
      };
    }
    case 'FLLR':
    case 'LIST':
      break; // Ignore
    default:
      throw new TypeError(`Invalid sub chunk type ${type}`);
    }
    pos = next;
  }
  return null;
}

type DecodeReturnType = {
  sampleRate: number;
  channels: number;
  bitDepth: number;
  channelData: Array<Float32Array>;
};

function decode(buffer: ArrayBuffer | $TypedArray): DecodeReturnType {
  let pos = 0, end = 0;
  if (buffer instanceof ArrayBuffer) {
    // If we are handed a straight up array buffer, start at offset 0 and use
    // the full length of the buffer.
    pos = 0;
    end = buffer.byteLength;
  } else {
    // If we are handed a typed array or a buffer, then we have to consider the
    // offset and length into the underlying array buffer.
    pos = buffer.byteOffset;
    end = buffer.length;
    buffer = buffer.buffer;
  }

  let v = new DataView(buffer);
  let result = decodeHeader(v, pos, end);
  if (!result) {
    throw new Error(`Failed to decode`);
  }

  let fmt = result.fmt;
  let samples = result.samples;
  pos = result.pos;

  let channelData = [];
  for (let ch = 0; ch < fmt.channels; ++ch) {
    channelData[ch] = new Float32Array(samples);
  }
  let decodeData = lookup(dataDecoders, fmt.bitDepth, fmt.floatingPoint);
  decodeData(buffer, pos, channelData, fmt.channels, samples);

  return {
    sampleRate: fmt.sampleRate,
    channels: fmt.channels,
    bitDepth: fmt.bitDepth,
    channelData,
  };
}

type DecodeRawReturnType = {
  sampleRate: number;
  channels: number;
  bitDepth: number;
  channelData: Buffer;
};

function decodeRaw(buffer: ArrayBuffer | $TypedArray): DecodeRawReturnType {
  let pos = 0, end = 0;
  if (buffer instanceof ArrayBuffer) {
    // If we are handed a straight up array buffer, start at offset 0 and use
    // the full length of the buffer.
    pos = 0;
    end = buffer.byteLength;
  } else {
    // If we are handed a typed array or a buffer, then we have to consider the
    // offset and length into the underlying array buffer.
    pos = buffer.byteOffset;
    end = buffer.length;
    buffer = buffer.buffer;
  }

  let v = new DataView(buffer);
  let result = decodeHeader(v, pos, end);
  if (!result) {
    throw new Error(`Failed to decode`);
  }

  let fmt = result.fmt;
  pos = result.pos;

  return {
    sampleRate: fmt.sampleRate,
    channels: fmt.channels,
    bitDepth: fmt.bitDepth,
    channelData: Buffer.from(buffer, pos),
  };
}

function encodeHeader(
  v,
  floatingPoint,
  channels,
  sampleRate,
  bitDepth,
  size
) {
  let pos = 0;

  function u8(x) {
    v.setUint8(pos++, x);
  }

  function u16(x) {
    v.setUint16(pos, x, true);
    pos += 2;
  }

  function u32(x) {
    v.setUint32(pos, x, true);
    pos += 4;
  }

  function string(s) {
    for (let i = 0; i < s.length; ++i) {
      u8(s.charCodeAt(i));
    }
  }

  // write header
  string('RIFF');
  u32(size - 8);
  string('WAVE');

  // write 'fmt ' chunk
  string('fmt ');
  u32(16);
  u16(floatingPoint ? 0x0003 : 0x0001);
  u16(channels);
  u32(sampleRate);
  u32(sampleRate * channels * (bitDepth >> 3));
  u16(channels * (bitDepth >> 3));
  u16(bitDepth);

  // write 'data' chunk
  string('data');
  u32(size - 44);

  return pos;
}

type EncodeOptionsType = {
  sampleRate: number;
  float?: boolean;
  channels?: number;
  bitDepth: number;
};

function encode(
  channelData: Array<Float32Array>,
  opts: EncodeOptionsType
): Buffer {
  let sampleRate = opts.sampleRate || 16000;
  let floatingPoint = !!opts.float;
  let bitDepth = floatingPoint ? 32 : ((opts.bitDepth | 0) || 16);
  let channels = channelData.length;
  let samples = channelData[0].length;
  let encodeData = lookup(dataEncoders, bitDepth, floatingPoint);

  if (channels < 1 || channels > 3) {
    throw new Error(`Atleast 1 channel needs to be specified`);
  }

  let buffer = new ArrayBuffer(44 + (samples * channels * (bitDepth >> 3)));
  let v = new DataView(buffer);

  let pos = encodeHeader(v,
    floatingPoint,
    channels,
    sampleRate,
    bitDepth,
    buffer.byteLength
  );

  encodeData(buffer, pos, channelData, channels, samples);
  return Buffer.from(buffer);
}

function encodeRaw(channelData: Buffer, opts: EncodeOptionsType): Buffer {
  let sampleRate = opts.sampleRate || 16000;
  let floatingPoint = !!opts.float;
  let bitDepth = floatingPoint ? 32 : ((opts.bitDepth | 0) || 16);
  let channels = opts.channels || 1;

  if (channels < 1 || channels > 3) {
    throw new Error(`Atleast 1 channel needs to be specified`);
  }

  let header = new ArrayBuffer(44);
  let v = new DataView(header);

  encodeHeader(v,
    floatingPoint,
    channels,
    sampleRate,
    bitDepth,
    channelData.length + 44
  );

  return Buffer.concat([Buffer.from(header), channelData]);
}

module.exports = {
  decode: decode,
  decodeRaw: decodeRaw,
  encode: encode,
  encodeRaw: encodeRaw,
};
<commit_msg>node-wav to return if the wav file encoding if float or not<commit_after>/**
 * @flow
 */

const dataDecoders = {
  pcm8: (buffer, offset, output, channels, samples) => {
    let input = new Uint8Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let data = input[pos++] - 128;
        output[ch][i] = data < 0 ? data / 128 : data / 127;
      }
    }
  },
  pcm16: (buffer, offset, output, channels, samples) => {
    let input = new Int16Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let data = input[pos++];
        output[ch][i] = data < 0 ? data / 32768 : data / 32767;
      }
    }
  },
  pcm24: (buffer, offset, output, channels, samples) => {
    let input = new Uint8Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let x0 = input[pos++];
        let x1 = input[pos++];
        let x2 = input[pos++];
        let xx = (x0 + (x1 << 8) + (x2 << 16));
        let data = xx > 0x800000 ? xx - 0x1000000 : xx;
        output[ch][i] = data < 0 ? data / 8388608 : data / 8388607;
      }
    }
  },
  pcm32: (buffer, offset, output, channels, samples) => {
    let input = new Int32Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let data = input[pos++];
        output[ch][i] = data < 0 ? data / 2147483648 : data / 2147483647;
      }
    }
  },
  pcm32f: (buffer, offset, output, channels, samples) => {
    let input = new Float32Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        output[ch][i] = input[pos++];
      }
    }
  },
  pcm64f: (buffer, offset, output, channels, samples) => {
    let input = new Float64Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        output[ch][i] = input[pos++];
      }
    }
  },
};

const dataEncoders = {
  pcm8: (buffer, offset, input, channels, samples) => {
    let output = new Uint8Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let v = Math.max(-1, Math.min(input[ch][i], 1));
        v = ((v * 0.5 + 0.5) * 255) | 0;
        output[pos++] = v;
      }
    }
  },
  pcm16: (buffer, offset, input, channels, samples) => {
    let output = new Int16Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let v = Math.max(-1, Math.min(input[ch][i], 1));
        v = ((v < 0) ? v * 32768 : v * 32767) | 0;
        output[pos++] = v;
      }
    }
  },
  pcm24: (buffer, offset, input, channels, samples) => {
    let output = new Uint8Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let v = Math.max(-1, Math.min(input[ch][i], 1));
        v = ((v < 0) ? 0x1000000 + v * 8388608 : v * 8388607) | 0;
        output[pos++] = (v >> 0) & 0xff;
        output[pos++] = (v >> 8) & 0xff;
        output[pos++] = (v >> 16) & 0xff;
      }
    }
  },
  pcm32: (buffer, offset, input, channels, samples) => {
    let output = new Int32Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let v = Math.max(-1, Math.min(input[ch][i], 1));
        v = ((v < 0) ? v * 2147483648 : v * 2147483647) | 0;
        output[pos++] = v;
      }
    }
  },
  pcm32f: (buffer, offset, input, channels, samples) => {
    let output = new Float32Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let v = Math.max(-1, Math.min(input[ch][i], 1));
        output[pos++] = v;
      }
    }
  },
  pcm64f: (buffer, offset, input, channels, samples) => {
    let output = new Float64Array(buffer, offset);
    let pos = 0;
    for (let i = 0; i < samples; ++i) {
      for (let ch = 0; ch < channels; ++ch) {
        let v = Math.max(-1, Math.min(input[ch][i], 1));
        output[pos++] = v;
      }
    }
  },
};

function lookup(table, bitDepth, floatingPoint) {
  let name = 'pcm' + bitDepth + (floatingPoint ? 'f' : '');
  let fn = table[name];
  if (!fn) {
    throw new TypeError('Unsupported data format: ' + name);
  }
  return fn;
}

function decodeHeader(v, pos, end) {
  function u8() {
    let x = v.getUint8(pos);
    pos++;
    return x;
  }

  function u16() {
    let x = v.getUint16(pos, true);
    pos += 2;
    return x;
  }

  function u32() {
    let x = v.getUint32(pos, true);
    pos += 4;
    return x;
  }

  function string(len) {
    let str = '';
    for (let i = 0; i < len; ++i) {
      str += String.fromCharCode(u8());
    }
    return str;
  }

  if (string(4) !== 'RIFF') {
    throw new TypeError('Invalid WAV file');
  }
  u32();
  if (string(4) !== 'WAVE') {
    throw new TypeError('Invalid WAV file');
  }

  let fmt;

  while (pos < end) {
    let type = string(4);
    let size = u32();
    let next = pos + size;
    switch (type) {
    case 'fmt ': {
      let formatId = u16();
      if (formatId !== 0x0001 && formatId !== 0x0003) {
        throw new TypeError('Unsupported format in WAV file: ' + formatId.toString(16));
      }
      fmt = {
        format: 'lpcm',
        floatingPoint: formatId === 0x0003,
        channels: u16(),
        sampleRate: u32(),
        byteRate: u32(),
        blockSize: u16(),
        bitDepth: u16(),
      };
      break;
    }
    case 'data': {
      if (!fmt) {
        throw new TypeError('Missing "fmt " chunk.');
      }
      return {
        fmt,
        pos,
        samples: size / fmt.blockSize,
      };
    }
    case 'FLLR':
    case 'LIST':
      break; // Ignore
    default:
      throw new TypeError(`Invalid sub chunk type ${type}`);
    }
    pos = next;
  }
  return null;
}

type DecodeReturnType = {
  sampleRate: number;
  channels: number;
  bitDepth: number;
  channelData: Array<Float32Array>;
  float: boolean;
};

function decode(buffer: ArrayBuffer | $TypedArray): DecodeReturnType {
  let pos = 0, end = 0;
  if (buffer instanceof ArrayBuffer) {
    // If we are handed a straight up array buffer, start at offset 0 and use
    // the full length of the buffer.
    pos = 0;
    end = buffer.byteLength;
  } else {
    // If we are handed a typed array or a buffer, then we have to consider the
    // offset and length into the underlying array buffer.
    pos = buffer.byteOffset;
    end = buffer.length;
    buffer = buffer.buffer;
  }

  let v = new DataView(buffer);
  let result = decodeHeader(v, pos, end);
  if (!result) {
    throw new Error(`Failed to decode`);
  }

  let fmt = result.fmt;
  let samples = result.samples;
  pos = result.pos;

  let channelData = [];
  for (let ch = 0; ch < fmt.channels; ++ch) {
    channelData[ch] = new Float32Array(samples);
  }
  let decodeData = lookup(dataDecoders, fmt.bitDepth, fmt.floatingPoint);
  decodeData(buffer, pos, channelData, fmt.channels, samples);

  return {
    sampleRate: fmt.sampleRate,
    channels: fmt.channels,
    bitDepth: fmt.bitDepth,
    float: fmt.floatingPoint,
    channelData,
  };
}

type DecodeRawReturnType = {
  sampleRate: number;
  channels: number;
  bitDepth: number;
  channelData: Buffer;
  float: boolean;
};

function decodeRaw(buffer: ArrayBuffer | $TypedArray): DecodeRawReturnType {
  let pos = 0, end = 0;
  if (buffer instanceof ArrayBuffer) {
    // If we are handed a straight up array buffer, start at offset 0 and use
    // the full length of the buffer.
    pos = 0;
    end = buffer.byteLength;
  } else {
    // If we are handed a typed array or a buffer, then we have to consider the
    // offset and length into the underlying array buffer.
    pos = buffer.byteOffset;
    end = buffer.length;
    buffer = buffer.buffer;
  }

  let v = new DataView(buffer);
  let result = decodeHeader(v, pos, end);
  if (!result) {
    throw new Error(`Failed to decode`);
  }

  let fmt = result.fmt;
  pos = result.pos;

  return {
    sampleRate: fmt.sampleRate,
    channels: fmt.channels,
    bitDepth: fmt.bitDepth,
    float: fmt.floatingPoint,
    channelData: Buffer.from(buffer, pos),
  };
}

function encodeHeader(
  v,
  floatingPoint,
  channels,
  sampleRate,
  bitDepth,
  size
) {
  let pos = 0;

  function u8(x) {
    v.setUint8(pos++, x);
  }

  function u16(x) {
    v.setUint16(pos, x, true);
    pos += 2;
  }

  function u32(x) {
    v.setUint32(pos, x, true);
    pos += 4;
  }

  function string(s) {
    for (let i = 0; i < s.length; ++i) {
      u8(s.charCodeAt(i));
    }
  }

  // write header
  string('RIFF');
  u32(size - 8);
  string('WAVE');

  // write 'fmt ' chunk
  string('fmt ');
  u32(16);
  u16(floatingPoint ? 0x0003 : 0x0001);
  u16(channels);
  u32(sampleRate);
  u32(sampleRate * channels * (bitDepth >> 3));
  u16(channels * (bitDepth >> 3));
  u16(bitDepth);

  // write 'data' chunk
  string('data');
  u32(size - 44);

  return pos;
}

type EncodeOptionsType = {
  sampleRate: number;
  float?: boolean;
  channels?: number;
  bitDepth: number;
};

function encode(
  channelData: Array<Float32Array>,
  opts: EncodeOptionsType
): Buffer {
  let sampleRate = opts.sampleRate || 16000;
  let floatingPoint = !!opts.float;
  let bitDepth = floatingPoint ? 32 : ((opts.bitDepth | 0) || 16);
  let channels = channelData.length;
  let samples = channelData[0].length;
  let encodeData = lookup(dataEncoders, bitDepth, floatingPoint);

  if (channels < 1 || channels > 3) {
    throw new Error(`Atleast 1 channel needs to be specified`);
  }

  let buffer = new ArrayBuffer(44 + (samples * channels * (bitDepth >> 3)));
  let v = new DataView(buffer);

  let pos = encodeHeader(v,
    floatingPoint,
    channels,
    sampleRate,
    bitDepth,
    buffer.byteLength
  );

  encodeData(buffer, pos, channelData, channels, samples);
  return Buffer.from(buffer);
}

function encodeRaw(channelData: Buffer, opts: EncodeOptionsType): Buffer {
  let sampleRate = opts.sampleRate || 16000;
  let floatingPoint = !!opts.float;
  let bitDepth = floatingPoint ? 32 : ((opts.bitDepth | 0) || 16);
  let channels = opts.channels || 1;

  if (channels < 1 || channels > 3) {
    throw new Error(`Atleast 1 channel needs to be specified`);
  }

  let header = new ArrayBuffer(44);
  let v = new DataView(header);

  encodeHeader(v,
    floatingPoint,
    channels,
    sampleRate,
    bitDepth,
    channelData.length + 44
  );

  return Buffer.concat([Buffer.from(header), channelData]);
}

module.exports = {
  decode: decode,
  decodeRaw: decodeRaw,
  encode: encode,
  encodeRaw: encodeRaw,
};
<|endoftext|>


<commit_before>var TopHackers = Ember.View.create({
  templateName: 'views/top-hackers'
});

export default TopHackers;
<commit_msg>TopHackers view should extend Ember.view not create a new one<commit_after>var TopHackers = Ember.View.extend({
  templateName: 'views/top-hackers'
});

export default TopHackers;
<|endoftext|>


<commit_before>var _ = require('lodash');
var config = require('../../core/util.js').getConfig();

var sqlite = require('./handle');
var sqliteUtil = require('./util');
var util = require('../../core/util');
var log = require('../../core/log');

var Store = function(done, pluginMeta) {
  _.bindAll(this);
  this.done = done;

  this.db = sqlite.initDB(false);
  this.db.serialize(this.upsertTables);

  this.cache = [];
  this.buffered = util.gekkoMode() === "importer";
}

Store.prototype.upsertTables = function() {
  var createQueries = [
    `
      CREATE TABLE IF NOT EXISTS
      ${sqliteUtil.table('candles')} (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        start INTEGER UNIQUE,
        open REAL NOT NULL,
        high REAL NOT NULL,
        low REAL NOT NULL,
        close REAL NOT NULL,
        vwp REAL NOT NULL,
        volume REAL NOT NULL,
        trades INTEGER NOT NULL
      );
    `,

    // TODO: create trades
    // ``

    // TODO: create advices
    // ``
  ];

  var next = _.after(_.size(createQueries), this.done);

  _.each(createQueries, function(q) {
    this.db.run(q, next);
  }, this);
}

Store.prototype.writeCandles = function() {
  if(_.isEmpty(this.cache))
    return;

  var transaction = function() {
    this.db.run("BEGIN TRANSACTION");

    var stmt = this.db.prepare(`
      INSERT OR IGNORE INTO ${sqliteUtil.table('candles')}
      VALUES (?,?,?,?,?,?,?,?,?)
    `, function(err, rows) {
        if(err) {
          log.error(err);
          return util.die('DB error at INSERT: '+ err);
        }
      });

    _.each(this.cache, candle => {
      stmt.run(
        null,
        candle.start.unix(),
        candle.open,
        candle.high,
        candle.low,
        candle.close,
        candle.vwp,
        candle.volume,
        candle.trades
      );
    });

    stmt.finalize();
    this.db.run("COMMIT");

    this.cache = [];
  }

  this.db.serialize(_.bind(transaction, this));
}

var processCandle = function(candle, done) {
  this.cache.push(candle);
  if (!this.buffered || this.cache.length > 1000)
    this.writeCandles();

  done();
};

var finalize = function(done) {
  this.writeCandles();
  this.db.close(() => { done(); });
  this.db = null;
}

if(config.candleWriter.enabled) {
  Store.prototype.processCandle = processCandle;
  Store.prototype.finalize = finalize;
}

// TODO: add storing of trades / advice?

// var processTrades = function(candles) {
//   util.die('NOT IMPLEMENTED');
// }

// var processAdvice = function(candles) {
//   util.die('NOT IMPLEMENTED');
// }

// if(config.tradeWriter.enabled)
//  Store.prototype.processTrades = processTrades;

// if(config.adviceWriter.enabled)
//   Store.prototype.processAdvice = processAdvice;

module.exports = Store;
<commit_msg>force WAL checkpoint after every write<commit_after>var _ = require('lodash');
var config = require('../../core/util.js').getConfig();

var sqlite = require('./handle');
var sqliteUtil = require('./util');
var util = require('../../core/util');
var log = require('../../core/log');

var Store = function(done, pluginMeta) {
  _.bindAll(this);
  this.done = done;

  this.db = sqlite.initDB(false);
  this.db.serialize(this.upsertTables);

  this.cache = [];
  this.buffered = util.gekkoMode() === "importer";
}

Store.prototype.upsertTables = function() {
  var createQueries = [
    `
      CREATE TABLE IF NOT EXISTS
      ${sqliteUtil.table('candles')} (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        start INTEGER UNIQUE,
        open REAL NOT NULL,
        high REAL NOT NULL,
        low REAL NOT NULL,
        close REAL NOT NULL,
        vwp REAL NOT NULL,
        volume REAL NOT NULL,
        trades INTEGER NOT NULL
      );
    `,

    // TODO: create trades
    // ``

    // TODO: create advices
    // ``
  ];

  var next = _.after(_.size(createQueries), this.done);

  _.each(createQueries, function(q) {
    this.db.run(q, next);
  }, this);
}

Store.prototype.writeCandles = function() {
  console.log(this.cache);
  if(_.isEmpty(this.cache))
    return;

  const transaction = () => {
    this.db.run("BEGIN TRANSACTION");

    var stmt = this.db.prepare(`
      INSERT OR IGNORE INTO ${sqliteUtil.table('candles')}
      VALUES (?,?,?,?,?,?,?,?,?)
    `, function(err, rows) {
        if(err) {
          log.error(err);
          return util.die('DB error at INSERT: '+ err);
        }
      });

    _.each(this.cache, candle => {
      stmt.run(
        null,
        candle.start.unix(),
        candle.open,
        candle.high,
        candle.low,
        candle.close,
        candle.vwp,
        candle.volume,
        candle.trades
      );
    });

    stmt.finalize();
    this.db.run("COMMIT");
    // TEMP: should fix https://forum.gekko.wizb.it/thread-57279-post-59194.html#pid59194
    this.db.run("pragma wal_checkpoint;");

    this.cache = [];
  }

  this.db.serialize(transaction);
}

var processCandle = function(candle, done) {
  this.cache.push(candle);
  if (!this.buffered || this.cache.length > 1000)
    this.writeCandles();

  done();
};

var finalize = function(done) {
  this.writeCandles();
  this.db.close(() => { done(); });
  this.db = null;
}

if(config.candleWriter.enabled) {
  Store.prototype.processCandle = processCandle;
  Store.prototype.finalize = finalize;
}

// TODO: add storing of trades / advice?

// var processTrades = function(candles) {
//   util.die('NOT IMPLEMENTED');
// }

// var processAdvice = function(candles) {
//   util.die('NOT IMPLEMENTED');
// }

// if(config.tradeWriter.enabled)
//  Store.prototype.processTrades = processTrades;

// if(config.adviceWriter.enabled)
//   Store.prototype.processAdvice = processAdvice;

module.exports = Store;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.RELATIONSHIP({
  cardinality: '*:*',
  sourceModel: 'foam.nanos.auth.Group',
  targetModel: 'foam.nanos.auth.Permission',
  forwardName: 'permissions',
  inverseName: 'groups',
  junctionDAOKey: 'localGroupPermissionJunctionDAO'
});

/*
foam.RELATIONSHIP({
  cardinality: '*:*',
  sourceModel: 'foam.nanos.auth.User',
  targetModel: 'foam.nanos.auth.Group',
  forwardName: 'groups',
  inverseName: 'users',
  sourceProperty: {
    hidden: true
  },
  targetProperty: {
    hidden: true
  }
});
*/

foam.RELATIONSHIP({
  sourceModel: 'foam.nanos.theme.Theme',
  targetModel: 'foam.nanos.auth.User',
  cardinality: '1:*',
  forwardName: 'users',
  inverseName: 'personalTheme',
  sourceProperty: {
    hidden: true,
    visibility: 'HIDDEN'
  }
});
<commit_msg>Revert target dao key to non-local groupPermissionJunctionDAO<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.RELATIONSHIP({
  cardinality: '*:*',
  sourceModel: 'foam.nanos.auth.Group',
  targetModel: 'foam.nanos.auth.Permission',
  forwardName: 'permissions',
  inverseName: 'groups',
  junctionDAOKey: 'groupPermissionJunctionDAO'
});

/*
foam.RELATIONSHIP({
  cardinality: '*:*',
  sourceModel: 'foam.nanos.auth.User',
  targetModel: 'foam.nanos.auth.Group',
  forwardName: 'groups',
  inverseName: 'users',
  sourceProperty: {
    hidden: true
  },
  targetProperty: {
    hidden: true
  }
});
*/

foam.RELATIONSHIP({
  sourceModel: 'foam.nanos.theme.Theme',
  targetModel: 'foam.nanos.auth.User',
  cardinality: '1:*',
  forwardName: 'users',
  inverseName: 'personalTheme',
  sourceProperty: {
    hidden: true,
    visibility: 'HIDDEN'
  }
});
<|endoftext|>


<commit_before>'use strict';

/*jshint -W083 */
(function () {
    var jasmineJUnit = {},
        glob = require("glob"),
        grunt = require('grunt'),
        path = require('path'),
        _ = require('lodash'),
        fs = require('fs'),
        XmlDocument = require('xmldoc').XmlDocument,
        xmlEntities = new (require('html-entities').XmlEntities)();

    /**
     * Merge all junit results.
     * Because the karma-junit-reporter does not use the name of the spec file for the classname, the
     * results need to be updated with the correct classname.
     *
     * #1 iterate over each location .
     * #2 iterate over each file and check if there are jasmine tests by checking for it().
     * #3 add all the jasmine tests to the array.
     * #4 replace the classname with the spec filename.
     * #5 append the tests to the result.
     * #6 write merged results to file.
     */
    jasmineJUnit.merge = function (locations, outputFile, type) {

        var CURRENT_PATH = '.',
            PREFIX = '<?xml version="1.0"?><testsuites>',
            SUFFIX = '</testsuites>',
            JASMINE_TESTCASE_REGEX = /[^\w]x?it\s?\([\'\"](.*)[\'\"]/g,
            resultContent = PREFIX,
            TYPE = type === 'itUnit' ? ' integration' : '';

        // #1
        locations.forEach(function (l) {
            var specs = [],
                cwd = (l.cwd || CURRENT_PATH) + path.sep,
                testDir = cwd + l.test,
                testDirExists = grunt.file.exists(testDir),
                reportFile,
                reportFileExists;

            if (l.reports[type]) {

                glob.sync(l.reports[type], {cwd: cwd, root: '/'}).forEach(function (file) {
                    reportFile = cwd + file;
                    reportFileExists = grunt.file.exists(reportFile);
                });

                if (l.test && testDirExists) {
                    if (l.reports[type] && reportFileExists) {

                        // #2
                        glob.sync('**/*.js', {cwd: testDir, root: '/'}).forEach(function (file) {
                            var tests = [],
                                content = grunt.file.read(testDir + path.sep + file),
                                matches = content.match(JASMINE_TESTCASE_REGEX);

                            if (matches !== null) {
                                // #3
                                for (var i = 0, len = matches.length; i < len; i++) {
                                    tests.push(xmlEntities.encode(matches[i].replace(JASMINE_TESTCASE_REGEX, '$1')).replace(/\\/g, '')); // remove escaped characters
                                }
                                specs.push({
                                    'name': path.basename(file, path.extname(file)),
                                    'tests': tests
                                });
                            }
                        });

                        // #4
                        var content = new XmlDocument(grunt.file.read(reportFile)),
                            testsuites;
                        if (content.name === 'testsuite') {
                            testsuites = [content];
                        } else {
                            testsuites = content.childrenNamed("testsuite");
                        }
                        for (var i = 0; i < testsuites.length; i++) {
                            testsuites[i].eachChild(function (testcase) {
                                if (testcase.name === 'testcase') {
                                    var name = xmlEntities.encode(testcase.attr.name);

                                    var matchingSpecs = _.pluck(_.filter(specs, function (spec) {
                                        return _.find(spec.tests, function (test) {
                                            return test === name || xmlEntities.encode(test) === name;
                                        });
                                    }), 'name');
                                    var matchingSpec = matchingSpecs[0];
                                    if (matchingSpecs.length > 1) {
                                        var m = _.find(specs, function (spec) {
                                            return spec.name === matchingSpec;
                                        });
                                        m.tests = _.without(m.tests, name);
                                    }
                                    testcase.attr.name = name;
                                    testcase.attr.classname = matchingSpec.replace(/\./g, '_');
                                }
                            });
                        }
                        // #5
                        resultContent = resultContent.concat(testsuites);
                    } else {
                        if (!reportFileExists) {
                            grunt.log.warn('The specified' + TYPE + ' jUnit report [' + reportFile + '] does not exist');
                        }
                    }
                }
            } else {
                grunt.log.warn('No' + TYPE + ' jUnit report has been specified');
            }
        });
        // #6
        grunt.file.write(outputFile, resultContent.concat(SUFFIX));
    };

    module.exports = jasmineJUnit;
})();<commit_msg>robustness / check if a matching spec has been found prior to adding test to xml results - avoid 'replace' method to fail on an undefined matchingSpec<commit_after>'use strict';

/*jshint -W083 */
(function () {
    var jasmineJUnit = {},
        glob = require("glob"),
        grunt = require('grunt'),
        path = require('path'),
        _ = require('lodash'),
        fs = require('fs'),
        XmlDocument = require('xmldoc').XmlDocument,
        xmlEntities = new (require('html-entities').XmlEntities)();

    /**
     * Merge all junit results.
     * Because the karma-junit-reporter does not use the name of the spec file for the classname, the
     * results need to be updated with the correct classname.
     *
     * #1 iterate over each location .
     * #2 iterate over each file and check if there are jasmine tests by checking for it().
     * #3 add all the jasmine tests to the array.
     * #4 replace the classname with the spec filename.
     * #5 append the tests to the result.
     * #6 write merged results to file.
     */
    jasmineJUnit.merge = function (locations, outputFile, type) {

        var CURRENT_PATH = '.',
            PREFIX = '<?xml version="1.0"?><testsuites>',
            SUFFIX = '</testsuites>',
            JASMINE_TESTCASE_REGEX = /[^\w]x?it\s?\([\'\"](.*)[\'\"]/g,
            resultContent = PREFIX,
            TYPE = type === 'itUnit' ? ' integration' : '';

        // #1
        locations.forEach(function (l) {
            var specs = [],
                cwd = (l.cwd || CURRENT_PATH) + path.sep,
                testDir = cwd + l.test,
                testDirExists = grunt.file.exists(testDir),
                reportFile,
                reportFileExists;

            if (l.reports[type]) {

                glob.sync(l.reports[type], {cwd: cwd, root: '/'}).forEach(function (file) {
                    reportFile = cwd + file;
                    reportFileExists = grunt.file.exists(reportFile);
                });

                if (l.test && testDirExists) {
                    if (l.reports[type] && reportFileExists) {

                        // #2
                        glob.sync('**/*.js', {cwd: testDir, root: '/'}).forEach(function (file) {
                            var tests = [],
                                content = grunt.file.read(testDir + path.sep + file),
                                matches = content.match(JASMINE_TESTCASE_REGEX);

                            if (matches !== null) {
                                // #3
                                for (var i = 0, len = matches.length; i < len; i++) {
                                    tests.push(xmlEntities.encode(matches[i].replace(JASMINE_TESTCASE_REGEX, '$1')).replace(/\\/g, '')); // remove escaped characters
                                }
                                specs.push({
                                    'name': path.basename(file, path.extname(file)),
                                    'tests': tests
                                });
                            }
                        });

                        // #4
                        var content = new XmlDocument(grunt.file.read(reportFile)),
                            testsuites;
                        if (content.name === 'testsuite') {
                            testsuites = [content];
                        } else {
                            testsuites = content.childrenNamed("testsuite");
                        }
                        for (var i = 0; i < testsuites.length; i++) {
                            testsuites[i].eachChild(function (testcase) {
                                if (testcase.name === 'testcase') {
                                    var name = xmlEntities.encode(testcase.attr.name);

                                    var matchingSpecs = _.pluck(_.filter(specs, function (spec) {
                                        return _.find(spec.tests, function (test) {
                                            return test === name || xmlEntities.encode(test) === name;
                                        });
                                    }), 'name');
                                    if (matchingSpecs.length === 0) {
                                        grunt.log.warn('No spec filename found for test [' + name + ']');
                                    } else {
                                        var matchingSpec = matchingSpecs[0];
                                        if (matchingSpecs.length > 1) {
                                            var m = _.find(specs, function (spec) {
                                                return spec.name === matchingSpec;
                                            });
                                            m.tests = _.without(m.tests, name);
                                        }
                                        testcase.attr.name = name;
                                        testcase.attr.classname = matchingSpec.replace(/\./g, '_');
                                    }
                                }
                            });
                        }
                        // #5
                        resultContent = resultContent.concat(testsuites);
                    } else {
                        if (!reportFileExists) {
                            grunt.log.warn('The specified' + TYPE + ' jUnit report [' + reportFile + '] does not exist');
                        }
                    }
                }
            } else {
                grunt.log.warn('No' + TYPE + ' jUnit report has been specified');
            }
        });
        // #6
        grunt.file.write(outputFile, resultContent.concat(SUFFIX));
    };

    module.exports = jasmineJUnit;
})();
<|endoftext|>


<commit_before>var notifier = new require("node-notifier");
var extend   = require("extend");
var path     = require("path");
var CFG      = require("./config.js");
var pkg      = require(path.join("..", "..", CFG.FILE.config.pkg));

module.exports = {
  defaults: {
    title: pkg.name
  },

  showNotification: function (options) {
    extend(options, this.defaults);

    if("undefined" !== typeof(process.env.REMEMBER_CI)) {
      // Running inside a CI environment, do not show notifications
      console.log("[notification]", options.message);
    } else {
      // Running inside a non-CI environment, okay to show notifications
      notifier.notify(options);
    }
  },

  appIcon: {
    sass: __dirname + "/../assets/images/sass-logo.png",
    karma: __dirname + "/../assets/images/karma-logo.png"
  }
};
<commit_msg>Use correct environment variable.<commit_after>var notifier = new require("node-notifier");
var extend   = require("extend");
var path     = require("path");
var CFG      = require("./config.js");
var pkg      = require(path.join("..", "..", CFG.FILE.config.pkg));

module.exports = {
  defaults: {
    title: pkg.name
  },

  showNotification: function (options) {
    extend(options, this.defaults);

    if("undefined" !== typeof(process.env.VOXEL_CI)) {
      // Running inside a CI environment, do not show notifications
      console.log("[notification]", options.message);
    } else {
      // Running inside a non-CI environment, okay to show notifications
      notifier.notify(options);
    }
  },

  appIcon: {
    sass: __dirname + "/../assets/images/sass-logo.png",
    karma: __dirname + "/../assets/images/karma-logo.png"
  }
};
<|endoftext|>


<commit_before>// *************************************************************************
// Copyright (c) 2014-2017, SUSE LLC
//
// 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.
//
// 3. Neither the name of SUSE LLC nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// 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 HOLDER 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.
// *************************************************************************
//
// app/sched-history-lib.js
//
"use strict";

define ([
    'jquery',
    'ajax',
    'current-user',
    'datetime',
    'lib',
    'target',
    'stack',
    'start'
], function (
    $,
    ajax,
    currentUser,
    datetime,
    lib,
    target,
    stack,
    start
) {

    var genSchedHistoryAction = function (tgt) {
            return function () {
                var nick = currentUser('obj').nick,
                    rest = {
                        "method": 'GET',
                        "path": 'schedule/history/nick/' + currentUser('obj').nick
                    },
                    // success callback
                    sc = function (st) {
                        if (st.code === 'DISPATCH_RECORDS_FOUND') {
                            console.log("Payload is", st.payload);
                            var history = st.payload.history.map(
                                function (row) {
                                    return {
                                        "nick": nick,
                                        "shid": row.shid,
                                        "sid": row.sid,
                                        "effective": datetime.readableDate(row.effective),
                                        "scode": row.scode
                                    };
                                }
                            );
                            if (tgt === 'schedHistoryDtable') {
                                stack.push(tgt, history, {
                                    "xtarget": "mainSched"
                                });
                            } else if (tgt === 'schedHistoryDrowselect') {
                                stack.push(tgt, {
                                    'pos': 0,
                                    'set': history
                                });
                            }
                        }
                    },
                    fc = function (st) {
                        lib.displayError(st.payload.message);
                        if (st.payload.code === "404") {
                            // The employee has no history records. This is not
                            // really an error condition.
                            if (tgt === 'schedHistoryDtable') {
                                stack.push(tgt, [], {
                                    "xtarget": "mainSched"
                                });
                            } else if (tgt === 'schedHistoryDrowselect') {
                                stack.push(tgt, {
                                    'pos': 0,
                                    'set': []
                                });
                            }
                        }
                    };
                ajax(rest, sc, fc);
            };
        };

    return {
        "actionSchedHistory":     genSchedHistoryAction(
                                     'schedHistoryDtable'
                                 ),
        "actionSchedHistoryEdit": genSchedHistoryAction(
                                     'schedHistoryDrowselect'
                                 ),
        "schedHistorySaveAction": function () {
            var rest = {
                    "method": 'POST',
                    "path": 'schedule/history/nick/' + currentUser('obj').nick,
                    "body": {
                        "effective": $("#pHeffective").val(),
                        "sid": $("#sDid").val(),
                        "scode": $("#sDcode").val()
                    }
                },
                // success callback
                sc = function (st) {
                    if (st.code === 'DOCHAZKA_CUD_OK') {
                        console.log("Payload is", st.payload);
                        stack.unwindToTarget("actionSchedHistory");
                    }
                },
                fc = function (st) {
                    lib.displayError(st.payload.message);
                    if (st.payload.code === '404') {
                        // go back to miniMenu listener
                        $('input[name="sel"]').val('').focus();
                    }
                };
            ajax(rest, sc, fc);
            // start.drowselectListen();
        },
        "schedHistoryDeleteAction": function () {
            var shid,
                set = lib.drowselectState.set,
                pos = lib.drowselectState.pos,
                rest = {
                    "method": 'DELETE',
                    "path": 'schedule/history/shid/'
                },
                // success callback
                sc = function (st) {
                    if (st.code === 'DOCHAZKA_CUD_OK') {
                        console.log("Payload is", st.payload);
                        stack.unwindToTarget("actionSchedHistory");
                    }
                },
                fc = function (st) {
                    lib.displayError(st.payload.message);
                    $('input[name="sel"]').val('').focus();
                };

            if (set === null || set === undefined || set.length === 0) {
                lib.displayError("Nothing to do");
                $('input[name="sel"]').val('').focus();
                // start.drowselectListen();
            }
            shid = set[pos].shid;
            console.log("Going to delete SHID " + shid);
            rest.path += shid;
            ajax(rest, sc, fc);
            // start.drowselectListen();
        },
        "schedHistoryAddRecordAction": function (obj) {
            console.log("Entering schedHistoryAddRecordAction with obj", obj);
            stack.push('schedHistoryAddRecord', {
                'nick': obj.nick
            });
        }
    };
});

<commit_msg>js: fix improperly populated nick in "Add schedule history record"<commit_after>// *************************************************************************
// Copyright (c) 2014-2017, SUSE LLC
//
// 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.
//
// 3. Neither the name of SUSE LLC nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// 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 HOLDER 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.
// *************************************************************************
//
// app/sched-history-lib.js
//
"use strict";

define ([
    'jquery',
    'ajax',
    'current-user',
    'datetime',
    'lib',
    'target',
    'stack',
    'start'
], function (
    $,
    ajax,
    currentUser,
    datetime,
    lib,
    target,
    stack,
    start
) {

    var genSchedHistoryAction = function (tgt) {
            return function () {
                var rest = {
                        "method": 'GET',
                        "path": 'schedule/history/nick/' + currentUser('obj').nick
                    },
                    // success callback
                    sc = function (st) {
                        if (st.code === 'DISPATCH_RECORDS_FOUND') {
                            console.log("Payload is", st.payload);
                            var history = st.payload.history.map(
                                function (row) {
                                    return {
                                        "shid": row.shid,
                                        "sid": row.sid,
                                        "effective": datetime.readableDate(row.effective),
                                        "scode": row.scode
                                    };
                                }
                            );
                            if (tgt === 'schedHistoryDtable') {
                                stack.push(tgt, history, {
                                    "xtarget": "mainSched"
                                });
                            } else if (tgt === 'schedHistoryDrowselect') {
                                stack.push(tgt, {
                                    'pos': 0,
                                    'set': history
                                });
                            }
                        }
                    },
                    fc = function (st) {
                        lib.displayError(st.payload.message);
                        if (st.payload.code === "404") {
                            // The employee has no history records. This is not
                            // really an error condition.
                            if (tgt === 'schedHistoryDtable') {
                                stack.push(tgt, [], {
                                    "xtarget": "mainSched"
                                });
                            } else if (tgt === 'schedHistoryDrowselect') {
                                stack.push(tgt, {
                                    'pos': 0,
                                    'set': []
                                });
                            }
                        }
                    };
                ajax(rest, sc, fc);
            };
        };

    return {
        "actionSchedHistory":     genSchedHistoryAction(
                                     'schedHistoryDtable'
                                 ),
        "actionSchedHistoryEdit": genSchedHistoryAction(
                                     'schedHistoryDrowselect'
                                 ),
        "schedHistorySaveAction": function () {
            var rest = {
                    "method": 'POST',
                    "path": 'schedule/history/nick/' + currentUser('obj').nick,
                    "body": {
                        "effective": $("#pHeffective").val(),
                        "sid": $("#sDid").val(),
                        "scode": $("#sDcode").val()
                    }
                },
                // success callback
                sc = function (st) {
                    if (st.code === 'DOCHAZKA_CUD_OK') {
                        console.log("Payload is", st.payload);
                        stack.unwindToTarget("actionSchedHistory");
                    }
                },
                fc = function (st) {
                    lib.displayError(st.payload.message);
                    if (st.payload.code === '404') {
                        // go back to miniMenu listener
                        $('input[name="sel"]').val('').focus();
                    }
                };
            ajax(rest, sc, fc);
            // start.drowselectListen();
        },
        "schedHistoryDeleteAction": function () {
            var shid,
                set = lib.drowselectState.set,
                pos = lib.drowselectState.pos,
                rest = {
                    "method": 'DELETE',
                    "path": 'schedule/history/shid/'
                },
                // success callback
                sc = function (st) {
                    if (st.code === 'DOCHAZKA_CUD_OK') {
                        console.log("Payload is", st.payload);
                        stack.unwindToTarget("actionSchedHistory");
                    }
                },
                fc = function (st) {
                    lib.displayError(st.payload.message);
                    $('input[name="sel"]').val('').focus();
                };

            if (set === null || set === undefined || set.length === 0) {
                lib.displayError("Nothing to do");
                $('input[name="sel"]').val('').focus();
                // start.drowselectListen();
            }
            shid = set[pos].shid;
            console.log("Going to delete SHID " + shid);
            rest.path += shid;
            ajax(rest, sc, fc);
            // start.drowselectListen();
        },
        "schedHistoryAddRecordAction": function (obj) {
            var cu = currentUser('obj');
            console.log("Entering schedHistoryAddRecordAction, nick is " + cu.nick);
            stack.push('schedHistoryAddRecord', {
                'nick': cu.nick
            });
        }
    };
});

<|endoftext|>