<commit_before>// arcs and tooltips
// dc-js.github.io/dc.js

var w = 980,
    h = 600;

var projection = d3.geo.albersUsa()
                 .scale(w);

var hoverBgColor = '#E98333';
var defaultBgColor = '#cccccc';
var clickBgColor = '#D96531';

var path = d3.geo.path()
    .projection(projection);

var svg = d3.select("body").insert("svg:svg", "h2")
    .attr("width", w)
    .attr("height", h);

var centroidPositions = [];

var states = svg.append("svg:g")
    .attr("id", "states");

var circles = svg.append("svg:g")
    .attr("id", "circles");

var arcs = svg.append('g')
           .attr('class', 'arcs');

// var arcGroup = arcs.selectAll('.great-arc-group')
//                 .data(data.arcs).enter()
//                 .append('g')
//                 .classed('great-arc-group', true);

var arcData;

var cells = svg.append("svg:g")
    .attr("id", "cells");

var display = svg.append("text")
                .attr("x", 130)
                .attr("y", h-60)
                .attr("class", "legend")
                .style("fill", "black")
                .text("Select a state");

var chosenStateFrom = "";
var chosenStateTo = "";
var passengersDisplay;
var fareDisplay;
var centroidsHash = {};

// sample date (please insert later) = [startDate, endDate] CROSS FILTER INPUT **********
var dateArr = [new Date(2010, 0, 1), new Date(2015, 10, 30)];

///// Utility Functions

function searchHash(key1, key2, hash) {
  var keyToFind = key1 + key2;
  return hash[keyToFind];
}

function getKeyByValue(obj,value) {
  for( var prop in obj ) {
        if( obj.hasOwnProperty( prop ) ) {
             if( obj[ prop ] === value )
                 return prop;
        }
    }
}

function updateText(svg,text) {
  svg.text(text);
}

function currentColor(svg) {
  return rgb2hex(d3.select(svg).style("fill"));
}

function clickedEle(svg) {
  return d3.select(svg).attr("clicked") === "true" ;
}

function arrToHash(arr) {
  var objHash = {};
  for (i=0;i<arr.length;i++) {
    var hashKey = arr[i][0] + arr[i][1];
    objHash[hashKey] = arr[i][2];
  }
  return objHash;
}

function rgb2hex(rgb){
 rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
 return (rgb && rgb.length === 4) ? "#" +
  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}

// Date.daysBetween = function( date1, date2 ) {
//   //Get 1 day in milliseconds
//   var one_day=1000*60*60*24;

//   // Convert both dates to milliseconds
//   var date1_ms = date1.getTime();
//   var date2_ms = date2.getTime();

//   // Calculate the difference in milliseconds
//   var difference_ms = date2_ms - date1_ms;

//   // Convert back to days and return
//   return Math.round(difference_ms/one_day);
// }

Date.quartersBetweenInDays = function( date1, date2 ) {
  if (date2 > date1) {
    var dateInYears = [ date1.getFullYear(), date2.getFullYear() ];
    var dateInQuarters = [ Math.floor((date1.getMonth())/3)+1, Math.floor((date2.getMonth())/3)+1 ];
    // console.log(dateInQuarters);
    var yearsDiff = dateInYears[1] - dateInYears[0];
    if (yearsDiff === 0) {
      return ( Math.abs(dateInQuarters[0] - dateInQuarters[1]) + 1 ) * 91;
    } else {
      return (yearsDiff-1)*365 + (Math.abs(dateInQuarters[0]-5) + dateInQuarters[1])*91;
    }
  } else {
    throw date1 + " has to be less than " + date2;
  }
}

// DO I NEED TO CHANGE THE WAY I SUM? CURRENTLY I JUST ADD ALL TOGETHER. SHOULD I DIVIDE & MULTIPLY BY TOTAL DAYS?
function statesSumArrByTime(array, prop, dateStart, dateEnd) {
  var sum = parseFloat(array[0][prop]);
  var arr = [];
  var statesParsed = [array[0]['State-from'], array[0]['State-to']];
  var daysBetween = Date.quartersBetweenInDays(dateStart, dateEnd);

  // array has to be sorted by states-from, states-to
  for (i=1; i<array.length; i++) {
    var currentDate = new Date(array[i]['Year'], array[i]['Month'], array[i]['Day']);
    if ((dateStart <= currentDate) && (dateEnd >= currentDate )) {
      var statesCurrent = [array[i]['State-from'], array[i]['State-to']];

      if (statesCurrent.toString() !== statesParsed.toString()) {
        var currentStateArr = statesParsed.slice(0);
        currentStateArr.push(sum);
        arr.push(currentStateArr);
        statesParsed = statesCurrent;
        sum = parseFloat(array[i][prop]);
      } else {
        sum += parseFloat(array[i][prop]);
      }
    }
  }
  return arr;
  // should return [[state-from, state-to, sum],[],...]
}

function statesAvgArrByTime(array, prop, dateStart, dateEnd) {
  var sumArr = [parseFloat(array[0][prop])];
  var arr = [];
  var statesParsed = [array[0]['State-from'], array[0]['State-to']];

  // array has to be sorted by states-from, states-to

  for (i=1; i<array.length; i++) {
    var currentDate = new Date(array[i]['Year'], array[i]['Month'], array[i]['Day']);
    if ((dateStart <= currentDate) && (dateEnd >= currentDate )) {
      var statesCurrent = [array[i]['State-from'], array[i]['State-to']];

      if (statesCurrent.toString() !== statesParsed.toString()) {
        var currentStateArr = statesParsed.slice(0);
        var sumArrLength = sumArr.length;
        var avg = sumArr.reduce(function(a,b) {
                        return a + b;
                      }, 0) / sumArrLength;
        currentStateArr.push(avg);
        arr.push(currentStateArr);
        statesParsed = statesCurrent;
        sumArr = [parseFloat(array[i][prop])];
      } else {
        sumArr.push(parseFloat(array[i][prop]));
      }
    }
  }
  return arr;
  // should return [[state-from, state-to, avg],[],...]
}

function getLinksLatLng(arr,fromState) {
  // input fromState code, eg. "CA"
  var links = [];
  var linksLatLng = [];
  console.log(arr);
  for (i=0; i<arr.length; i++) {
    if (arr[i][0] === fromState) {
      links.push([arr[i][0], arr[i][1]]);
    }
  }
  // d3.json("data/us-states-centroids.json", function(centroids) {
  //   console.log(centroids);
  // });
  for (j=0; j<links.length; j++) {
    var sourceTargetArr = [];
    var sourceCoord = centroidsHash[links[i][0]];
    var targetCoord = centroidsHash[links[i][1]];
    sourceTargetArr.push(sourceCoord[0],sourceCoord[1],targetCoord[0],targetCoord[1]);
    linksLatLng.push(sourceTargetArr);
  }
  console.log(links);
  return linksLatLng;
}

d3.json("data/us-states.json", function(collection) {
  var passengersHash;
  var fareHash;
  d3.csv("data/passengers-summarized.csv", function(data) {

    // var radius = d3.scale.sqrt()
    //             .domain([0,]

    //needs input from crossfilter
    var passengersArr = statesSumArrByTime(data, 'Passengers', dateArr[0], dateArr[1]);
    arcData = getLinksLatLng(passengersArr, chosenStateFrom);
    console.log(arcData);
    passengersHash = arrToHash(passengersArr);
    // console.log(passengersHash);
  });

  d3.csv("data/fare-summarized.csv", function(data) {

    // var radius = d3.scale.sqrt()
    //             .domain([0,]

    //needs input from crossfilter
    var fareArr = statesAvgArrByTime(data, 'Avg. Fare', dateArr[0], dateArr[1]);
    // console.log(fareArr);
    fareHash = arrToHash(fareArr);
  });

  states.selectAll("path")
    .data(collection.features)
    .enter()
    .append("svg:path")
    .attr("d", path)
    .attr("clicked", "false")
    .on("mouseover", function(d) {
      if (!clickedEle(this)) {
        d3.select(this)
        .style("fill", hoverBgColor);
      }

      if (chosenStateFrom) {
        chosenStateTo = getKeyByValue(statesHash, d.properties.name);
        var currentAvgFare = searchHash(chosenStateFrom, chosenStateTo, fareHash);
        var currentSumPassengers = searchHash(chosenStateFrom, chosenStateTo, passengersHash);
        fareDisplay = currentAvgFare ? "$" + Math.round(parseFloat(currentAvgFare)*100)/100 : "-";
        passengersDisplay = currentSumPassengers ? Math.round(parseFloat(currentSumPassengers)): "-";
        updateText(display, "From " + chosenStateFrom + ' to ' + chosenStateTo + ", Avg Fare: "
                  + fareDisplay + ", Total Passengers: " + passengersDisplay);
      }
    })

    .on("mouseout", function(d) {
      if (!clickedEle(this)) {
        d3.select(this)
        .style("fill", defaultBgColor);
      };
      if (chosenStateFrom) {
        chosenStateTo = getKeyByValue(statesHash, d.properties.name);
        updateText(display, "From " + chosenStateFrom + ' to ' + chosenStateTo + ", Avg Fare: "
                  + fareDisplay + ", Total Passengers: " + passengersDisplay);
      }
    })

    .on("click", function(d) {
      // reset all fills
      states.selectAll("path")
        .attr("clicked", "false")
        .style("fill", defaultBgColor);

      // set click status and fill
      d3.select(this)
        .attr("clicked", "true")
        .style("fill", clickBgColor);

      chosenStateFrom = getKeyByValue(statesHash, d.properties.name);
      var currentAvgFare = searchHash(chosenStateFrom, chosenStateTo, fareHash);
      var currentSumPassengers = searchHash(chosenStateFrom, chosenStateTo, passengersHash);
      fareDisplay = currentAvgFare ? "$" + Math.round(parseFloat(currentAvgFare)*100)/100 : "-";
      passengersDisplay = currentSumPassengers ? Math.round(parseFloat(currentSumPassengers)): "-";
      updateText(display, "From " + chosenStateFrom + ' to ' + chosenStateTo + ", Avg Fare: "
                  + fareDisplay + ", Total Passengers: " + passengersDisplay);
    });
});

d3.json("data/us-states-centroids.json", function(json) {

  var centroids = json.features.filter(function(centroid) {
    // console.log(centroid);
    var stateName = centroid.properties.name;
    var stateCode = getKeyByValue(statesHash,stateName);
    var stateCoordinates = centroid.geometry.coordinates;
    var location = [+centroid.geometry.coordinates[0], +centroid.geometry.coordinates[1]];
    var projectedLocation = projection(location);
    if (projectedLocation !== null) {
      centroidPositions.push(projectedLocation);
    }
    centroidsHash[stateCode] = stateCoordinates;
  });

  circles.selectAll("circle")
    .data(json.features)
    .enter()
    .append("circle")
    .attr("r",2)
    .attr("cx", function(d, i) {
      // return centroidPositions[i][0];
      var location = projection([json.features[i].geometry.coordinates[0],json.features[i].geometry.coordinates[1]]);
      if (location !== null) {
        return location[0];
      }
    })
    .attr("cy", function(d, i) {
      var location = projection([json.features[i].geometry.coordinates[0],json.features[i].geometry.coordinates[1]]);
      if (location !== null) {
        return location[1];
      }
    });
});

// d3.csv("flights-airport.csv", function(flights) {
//   var linksByOrigin = {},
//       countByAirport = {},
//       locationByAirport = {},
//       positions = [];
//
//   var arc = d3.geo.greatArc()
//       .source(function(d) { return locationByAirport[d.source]; })
//       .target(function(d) { return locationByAirport[d.target]; });
//
//   flights.forEach(function(flight) {
//     var origin = flight.origin,
//         destination = flight.destination,
//         links = linksByOrigin[origin] || (linksByOrigin[origin] = []);
//     links.push({source: origin, target: destination});
//     countByAirport[origin] = (countByAirport[origin] || 0) + 1;
//     countByAirport[destination] = (countByAirport[destination] || 0) + 1;
//   });
//
//   d3.csv("airports.csv", function(airports) {
//
//     // Only consider airports with at least one flight.
//     airports = airports.filter(function(airport) {
//       if (countByAirport[airport.iata]) {
//         var location = [+airport.longitude, +airport.latitude];
//         locationByAirport[airport.iata] = location;
//         positions.push(projection(location));
//         return true;
//       }
//     });
//
//
//     var g = cells.selectAll("g")
//         .data(airports)
//       .enter().append("svg:g");
//
//     g.append("svg:path")
//         .attr("class", "cell")
//         .attr("d", function(d, i) { return "M" + polygons[i].join("L") + "Z"; })
//         .on("mouseover", function(d, i) { d3.select("h2 span").text(d.name); });
//
//     g.selectAll("path.arc")
//         .data(function(d) { return linksByOrigin[d.iata] || []; })
//       .enter().append("svg:path")
//         .attr("class", "arc")
//         .attr("d", function(d) { return path(arc(d)); });
//
//     circles.selectAll("circle")
//         .data(airports)
//       .enter().append("svg:circle")
//         .attr("cx", function(d, i) { return positions[i][0]; })
//         .attr("cy", function(d, i) { return positions[i][1]; })
//         .attr("r", function(d, i) { return Math.sqrt(countByAirport[d.iata]); })
//         .sort(function(a, b) { return countByAirport[b.iata] - countByAirport[a.iata]; });
//   });
// });
<commit_msg>arc lat lng function created<commit_after>// arcs and tooltips
// dc-js.github.io/dc.js

var w = 980,
    h = 600;

var projection = d3.geo.albersUsa()
                 .scale(w);

var hoverBgColor = '#E98333';
var defaultBgColor = '#cccccc';
var clickBgColor = '#D96531';

var path = d3.geo.path()
    .projection(projection);

var svg = d3.select("#map").insert("svg:svg", "h2")
    .attr("width", w)
    .attr("height", h);

var centroidPositions = [];

var states = svg.append("svg:g")
    .attr("id", "states");

var circles = svg.append("svg:g")
    .attr("id", "circles");

var arcs = svg.append('g')
           .attr('class', 'arcs');

// var arcGroup = arcs.selectAll('.great-arc-group')
//                 .data(data.arcs).enter()
//                 .append('g')
//                 .classed('great-arc-group', true);

var arcData;

var cells = svg.append("svg:g")
    .attr("id", "cells");

var display = svg.append("text")
                .attr("x", 130)
                .attr("y", h-60)
                .attr("class", "legend")
                .style("fill", "black")
                .text("Select a state");

var chosenStateFrom = "";
var chosenStateTo = "";
var passengersDisplay;
var fareDisplay;
var centroidsHash = {};

// sample date (please insert later) = [startDate, endDate] CROSS FILTER INPUT **********
var dateArr = [new Date(2010, 0, 1), new Date(2015, 10, 30)];

///// Utility Functions

function searchHash(key1, key2, hash) {
  var keyToFind = key1 + key2;
  return hash[keyToFind];
}

function getKeyByValue(obj,value) {
  for( var prop in obj ) {
        if( obj.hasOwnProperty( prop ) ) {
             if( obj[ prop ] === value )
                 return prop;
        }
    }
}

function updateText(svg,text) {
  svg.text(text);
}

function currentColor(svg) {
  return rgb2hex(d3.select(svg).style("fill"));
}

function clickedEle(svg) {
  return d3.select(svg).attr("clicked") === "true" ;
}

function arrToHash(arr) {
  var objHash = {};
  for (i=0;i<arr.length;i++) {
    var hashKey = arr[i][0] + arr[i][1];
    objHash[hashKey] = arr[i][2];
  }
  return objHash;
}

function rgb2hex(rgb){
 rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
 return (rgb && rgb.length === 4) ? "#" +
  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}

// Date.daysBetween = function( date1, date2 ) {
//   //Get 1 day in milliseconds
//   var one_day=1000*60*60*24;

//   // Convert both dates to milliseconds
//   var date1_ms = date1.getTime();
//   var date2_ms = date2.getTime();

//   // Calculate the difference in milliseconds
//   var difference_ms = date2_ms - date1_ms;

//   // Convert back to days and return
//   return Math.round(difference_ms/one_day);
// }

Date.quartersBetweenInDays = function( date1, date2 ) {
  if (date2 > date1) {
    var dateInYears = [ date1.getFullYear(), date2.getFullYear() ];
    var dateInQuarters = [ Math.floor((date1.getMonth())/3)+1, Math.floor((date2.getMonth())/3)+1 ];
    // console.log(dateInQuarters);
    var yearsDiff = dateInYears[1] - dateInYears[0];
    if (yearsDiff === 0) {
      return ( Math.abs(dateInQuarters[0] - dateInQuarters[1]) + 1 ) * 91;
    } else {
      return (yearsDiff-1)*365 + (Math.abs(dateInQuarters[0]-5) + dateInQuarters[1])*91;
    }
  } else {
    throw date1 + " has to be less than " + date2;
  }
}

// DO I NEED TO CHANGE THE WAY I SUM? CURRENTLY I JUST ADD ALL TOGETHER. SHOULD I DIVIDE & MULTIPLY BY TOTAL DAYS?
function statesSumArrByTime(array, prop, dateStart, dateEnd) {
  var sum = parseFloat(array[0][prop]);
  var arr = [];
  var statesParsed = [array[0]['State-from'], array[0]['State-to']];
  var daysBetween = Date.quartersBetweenInDays(dateStart, dateEnd);

  // array has to be sorted by states-from, states-to
  for (i=1; i<array.length; i++) {
    var currentDate = new Date(array[i]['Year'], array[i]['Month'], array[i]['Day']);
    if ((dateStart <= currentDate) && (dateEnd >= currentDate )) {
      var statesCurrent = [array[i]['State-from'], array[i]['State-to']];

      if (statesCurrent.toString() !== statesParsed.toString()) {
        var currentStateArr = statesParsed.slice(0);
        currentStateArr.push(sum);
        arr.push(currentStateArr);
        statesParsed = statesCurrent;
        sum = parseFloat(array[i][prop]);
      } else {
        sum += parseFloat(array[i][prop]);
      }
    }
  }
  return arr;
  // should return [[state-from, state-to, sum],[],...]
}

function statesAvgArrByTime(array, prop, dateStart, dateEnd) {
  var sumArr = [parseFloat(array[0][prop])];
  var arr = [];
  var statesParsed = [array[0]['State-from'], array[0]['State-to']];

  // array has to be sorted by states-from, states-to

  for (i=1; i<array.length; i++) {
    var currentDate = new Date(array[i]['Year'], array[i]['Month'], array[i]['Day']);
    if ((dateStart <= currentDate) && (dateEnd >= currentDate )) {
      var statesCurrent = [array[i]['State-from'], array[i]['State-to']];

      if (statesCurrent.toString() !== statesParsed.toString()) {
        var currentStateArr = statesParsed.slice(0);
        var sumArrLength = sumArr.length;
        var avg = sumArr.reduce(function(a,b) {
                        return a + b;
                      }, 0) / sumArrLength;
        currentStateArr.push(avg);
        arr.push(currentStateArr);
        statesParsed = statesCurrent;
        sumArr = [parseFloat(array[i][prop])];
      } else {
        sumArr.push(parseFloat(array[i][prop]));
      }
    }
  }
  return arr;
  // should return [[state-from, state-to, avg],[],...]
}

function getLinksLatLng(arr,fromState) {
  // input fromState code, eg. "CA"
  var links = [];
  var linksLatLng = [];
  for (i=0; i<arr.length; i++) {
    if (arr[i][0] === fromState) {
      links.push([arr[i][0], arr[i][1]]);
    }
  }
  // d3.json("data/us-states-centroids.json", function(centroids) {
  //   console.log(centroids);
  // });

  for (j=0; j<links.length; j++) {
    var sourceTargetArr = [];
    var sourceCoord = centroidsHash[links[j][0]];
    var targetCoord = centroidsHash[links[j][1]];
    sourceTargetArr.push(sourceCoord[0],sourceCoord[1],targetCoord[0],targetCoord[1]);
    linksLatLng.push(sourceTargetArr);
  }
  return linksLatLng;
}

d3.json("data/us-states.json", function(collection) {
  var passengersHash;
  var fareHash;
  var passengersArr;
  d3.csv("data/passengers-summarized.csv", function(data) {

    // var radius = d3.scale.sqrt()
    //             .domain([0,]

    //needs input from crossfilter
    passengersArr = statesSumArrByTime(data, 'Passengers', dateArr[0], dateArr[1]);
    passengersHash = arrToHash(passengersArr);
    // console.log(passengersHash);
  });

  d3.csv("data/fare-summarized.csv", function(data) {

    // var radius = d3.scale.sqrt()
    //             .domain([0,]

    //needs input from crossfilter
    var fareArr = statesAvgArrByTime(data, 'Avg. Fare', dateArr[0], dateArr[1]);
    // console.log(fareArr);
    fareHash = arrToHash(fareArr);
  });

  states.selectAll("path")
    .data(collection.features)
    .enter()
    .append("svg:path")
    .attr("d", path)
    .attr("clicked", "false")
    .on("mouseover", function(d) {
      if (!clickedEle(this)) {
        d3.select(this)
        .style("fill", hoverBgColor);
      }

      if (chosenStateFrom) {
        chosenStateTo = getKeyByValue(statesHash, d.properties.name);
        var currentAvgFare = searchHash(chosenStateFrom, chosenStateTo, fareHash);
        var currentSumPassengers = searchHash(chosenStateFrom, chosenStateTo, passengersHash);
        fareDisplay = currentAvgFare ? "$" + Math.round(parseFloat(currentAvgFare)*100)/100 : "-";
        passengersDisplay = currentSumPassengers ? Math.round(parseFloat(currentSumPassengers)): "-";
        updateText(display, "From " + chosenStateFrom + ' to ' + chosenStateTo + ", Avg Fare: "
                  + fareDisplay + ", Total Passengers: " + passengersDisplay);
      }
    })

    .on("mouseout", function(d) {
      if (!clickedEle(this)) {
        d3.select(this)
        .style("fill", defaultBgColor);
      };
      if (chosenStateFrom) {
        chosenStateTo = getKeyByValue(statesHash, d.properties.name);
        updateText(display, "From " + chosenStateFrom + ' to ' + chosenStateTo + ", Avg Fare: "
                  + fareDisplay + ", Total Passengers: " + passengersDisplay);
      }
    })

    .on("click", function(d) {
      // reset all fills
      states.selectAll("path")
        .attr("clicked", "false")
        .style("fill", defaultBgColor);

      // set click status and fill
      d3.select(this)
        .attr("clicked", "true")
        .style("fill", clickBgColor);

      chosenStateFrom = getKeyByValue(statesHash, d.properties.name);
      var currentAvgFare = searchHash(chosenStateFrom, chosenStateTo, fareHash);
      var currentSumPassengers = searchHash(chosenStateFrom, chosenStateTo, passengersHash);
      fareDisplay = currentAvgFare ? "$" + Math.round(parseFloat(currentAvgFare)*100)/100 : "-";
      passengersDisplay = currentSumPassengers ? Math.round(parseFloat(currentSumPassengers)): "-";
      arcData = getLinksLatLng(passengersArr, chosenStateFrom);
      console.log(arcData);
      updateText(display, "From " + chosenStateFrom + ' to ' + chosenStateTo + ", Avg Fare: "
                  + fareDisplay + ", Total Passengers: " + passengersDisplay);
    });
});

d3.json("data/us-states-centroids.json", function(json) {

  var centroids = json.features.filter(function(centroid) {
    // console.log(centroid);
    var stateName = centroid.properties.name;
    var stateCode = getKeyByValue(statesHash,stateName);
    var stateCoordinates = centroid.geometry.coordinates;
    var location = [+centroid.geometry.coordinates[0], +centroid.geometry.coordinates[1]];
    var projectedLocation = projection(location);
    if (projectedLocation !== null) {
      centroidPositions.push(projectedLocation);
    }
    centroidsHash[stateCode] = stateCoordinates;
  });

  circles.selectAll("circle")
    .data(json.features)
    .enter()
    .append("circle")
    .attr("r",2)
    .attr("cx", function(d, i) {
      // return centroidPositions[i][0];
      var location = projection([json.features[i].geometry.coordinates[0],json.features[i].geometry.coordinates[1]]);
      if (location !== null) {
        return location[0];
      }
    })
    .attr("cy", function(d, i) {
      var location = projection([json.features[i].geometry.coordinates[0],json.features[i].geometry.coordinates[1]]);
      if (location !== null) {
        return location[1];
      }
    });
});

// d3.csv("flights-airport.csv", function(flights) {
//   var linksByOrigin = {},
//       countByAirport = {},
//       locationByAirport = {},
//       positions = [];
//
//   var arc = d3.geo.greatArc()
//       .source(function(d) { return locationByAirport[d.source]; })
//       .target(function(d) { return locationByAirport[d.target]; });
//
//   flights.forEach(function(flight) {
//     var origin = flight.origin,
//         destination = flight.destination,
//         links = linksByOrigin[origin] || (linksByOrigin[origin] = []);
//     links.push({source: origin, target: destination});
//     countByAirport[origin] = (countByAirport[origin] || 0) + 1;
//     countByAirport[destination] = (countByAirport[destination] || 0) + 1;
//   });
//
//   d3.csv("airports.csv", function(airports) {
//
//     // Only consider airports with at least one flight.
//     airports = airports.filter(function(airport) {
//       if (countByAirport[airport.iata]) {
//         var location = [+airport.longitude, +airport.latitude];
//         locationByAirport[airport.iata] = location;
//         positions.push(projection(location));
//         return true;
//       }
//     });
//
//
//     var g = cells.selectAll("g")
//         .data(airports)
//       .enter().append("svg:g");
//
//     g.append("svg:path")
//         .attr("class", "cell")
//         .attr("d", function(d, i) { return "M" + polygons[i].join("L") + "Z"; })
//         .on("mouseover", function(d, i) { d3.select("h2 span").text(d.name); });
//
//     g.selectAll("path.arc")
//         .data(function(d) { return linksByOrigin[d.iata] || []; })
//       .enter().append("svg:path")
//         .attr("class", "arc")
//         .attr("d", function(d) { return path(arc(d)); });
//
//     circles.selectAll("circle")
//         .data(airports)
//       .enter().append("svg:circle")
//         .attr("cx", function(d, i) { return positions[i][0]; })
//         .attr("cy", function(d, i) { return positions[i][1]; })
//         .attr("r", function(d, i) { return Math.sqrt(countByAirport[d.iata]); })
//         .sort(function(a, b) { return countByAirport[b.iata] - countByAirport[a.iata]; });
//   });
// });
<|endoftext|>


<commit_before>define(['angular',
  'lodash',
  'require',
  'app/core/config',
],
function (angular, _, require, config) {
  'use strict';

  var module = angular.module('grafana.controllers');

  module.controller('ShareModalCtrl', function($scope, $rootScope, $location, $timeout, timeSrv, $element, templateSrv, linkSrv) {

    $scope.options = { forCurrent: true, includeTemplateVars: true, theme: 'current' };
    $scope.editor = { index: $scope.tabIndex || 0};

    $scope.init = function() {
      $scope.modeSharePanel = $scope.panel ? true : false;

      $scope.tabs = [{title: 'Link', src: 'shareLink.html'}];

      if ($scope.modeSharePanel) {
        $scope.modalTitle = 'Share Panel';
        $scope.tabs.push({title: 'Embed', src: 'shareEmbed.html'});
      } else {
        $scope.modalTitle = 'Share Dashboard';
      }

      if (!$scope.dashboard.meta.isSnapshot) {
        $scope.tabs.push({title: 'Snapshot sharing', src: 'shareSnapshot.html'});
      }

      $scope.buildUrl();
    };

    $scope.buildUrl = function() {
      var baseUrl = $location.absUrl();
      var queryStart = baseUrl.indexOf('?');

      if (queryStart !== -1) {
        baseUrl = baseUrl.substring(0, queryStart);
      }

      var params = angular.copy($location.search());

      var range = timeSrv.timeRange();
      params.from = range.from.valueOf();
      params.to = range.to.valueOf();

      if ($scope.options.includeTemplateVars) {
        templateSrv.fillVariableValuesForUrl(params);
      }

      if (!$scope.options.forCurrent) {
        delete params.from;
        delete params.to;
      }

      if ($scope.options.theme !== 'current') {
        params.theme = $scope.options.theme;
      }

      if ($scope.modeSharePanel) {
        params.panelId = $scope.panel.id;
        params.fullscreen = true;
      } else {
        delete params.panelId;
        delete params.fullscreen;
      }

      $scope.shareUrl = linkSrv.addParamsToUrl(baseUrl, params);

      var soloUrl = $scope.shareUrl;
      soloUrl = soloUrl.replace('/dashboard/', '/dashboard-solo/');
      soloUrl = soloUrl.replace("&fullscreen", "");

      $scope.iframeHtml = '';

      $scope.imageUrl = soloUrl.replace('/dashboard-solo/', '/render/dashboard-solo/');
      $scope.imageUrl += '&width=1000';
      $scope.imageUrl += '&height=500';
    };

  });

  module.directive('clipboardButton',function() {
    return function(scope, elem) {
      require(['vendor/zero_clipboard'], function(ZeroClipboard) {
        ZeroClipboard.config({
          swfPath: config.appSubUrl + '/public/vendor/zero_clipboard.swf'
        });
        new ZeroClipboard(elem[0]);
      });
    };
  });

});
<commit_msg>fix(share modal): fixed link in share modal when sub app url is /dashboard/, fixes #5109<commit_after>define(['angular',
  'lodash',
  'require',
  'app/core/config',
],
function (angular, _, require, config) {
  'use strict';

  var module = angular.module('grafana.controllers');

  module.controller('ShareModalCtrl', function($scope, $rootScope, $location, $timeout, timeSrv, $element, templateSrv, linkSrv) {

    $scope.options = { forCurrent: true, includeTemplateVars: true, theme: 'current' };
    $scope.editor = { index: $scope.tabIndex || 0};

    $scope.init = function() {
      $scope.modeSharePanel = $scope.panel ? true : false;

      $scope.tabs = [{title: 'Link', src: 'shareLink.html'}];

      if ($scope.modeSharePanel) {
        $scope.modalTitle = 'Share Panel';
        $scope.tabs.push({title: 'Embed', src: 'shareEmbed.html'});
      } else {
        $scope.modalTitle = 'Share Dashboard';
      }

      if (!$scope.dashboard.meta.isSnapshot) {
        $scope.tabs.push({title: 'Snapshot sharing', src: 'shareSnapshot.html'});
      }

      $scope.buildUrl();
    };

    $scope.buildUrl = function() {
      var baseUrl = $location.absUrl();
      var queryStart = baseUrl.indexOf('?');

      if (queryStart !== -1) {
        baseUrl = baseUrl.substring(0, queryStart);
      }

      var params = angular.copy($location.search());

      var range = timeSrv.timeRange();
      params.from = range.from.valueOf();
      params.to = range.to.valueOf();

      if ($scope.options.includeTemplateVars) {
        templateSrv.fillVariableValuesForUrl(params);
      }

      if (!$scope.options.forCurrent) {
        delete params.from;
        delete params.to;
      }

      if ($scope.options.theme !== 'current') {
        params.theme = $scope.options.theme;
      }

      if ($scope.modeSharePanel) {
        params.panelId = $scope.panel.id;
        params.fullscreen = true;
      } else {
        delete params.panelId;
        delete params.fullscreen;
      }

      $scope.shareUrl = linkSrv.addParamsToUrl(baseUrl, params);

      var soloUrl = $scope.shareUrl;
      soloUrl = soloUrl.replace(config.appSubUrl + '/dashboard/', config.appSubUrl + '/dashboard-solo/');
      soloUrl = soloUrl.replace("&fullscreen", "");

      $scope.iframeHtml = '';

      $scope.imageUrl = soloUrl.replace('/dashboard-solo/', '/render/dashboard-solo/');
      $scope.imageUrl += '&width=1000';
      $scope.imageUrl += '&height=500';
    };

  });

  module.directive('clipboardButton',function() {
    return function(scope, elem) {
      require(['vendor/zero_clipboard'], function(ZeroClipboard) {
        ZeroClipboard.config({
          swfPath: config.appSubUrl + '/public/vendor/zero_clipboard.swf'
        });
        new ZeroClipboard(elem[0]);
      });
    };
  });

});
<|endoftext|>


<commit_before>var flag = 0;

function terminal(e, input) {

    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) {

        var terminalDiv = $('.terminal');
        var inputVal = $('.terminal-input').val();

        $('.console').last().remove();
        if(flag == 0) {
            terminalDiv.append('~ $ashish >> ' + inputVal);
        }
        else {
            terminalDiv.append('~/projects $ashish >> ' + inputVal);
        }
        if (inputVal == 'ls' && flag == 0) {
            terminalDiv.append('
projects   resume.pdf   game.app
');
        } else if (inputVal == 'ls' && flag == 1) {
            terminalDiv.append('
WikiSearch   Clippy   ink   Erectus
');
        } else if (inputVal == 'open resume.pdf' && flag == 0) {
            window.location.href = 'https://drive.google.com/file/d/0B3OeNoTC80mGSHlJN0xnLU9MckU/view?usp=sharing';
        } else if (inputVal == 'cd projects') {
            terminalDiv.append('

');
            flag = 1;
        } else if ((inputVal == 'cd WikiSearch' ||  inputVal == 'cd ink') && flag == 1) {
            window.location.href = 'http://github.com/thinker3197/' + inputVal.slice(3, inputVal.length);
        } else if ((inputVal == 'cd Erectus' || inputVal == 'cd Clippy') && flag == 1) {
            window.location.href = 'http://github.com/The-Turing-Machine/' + inputVal.slice(3, inputVal.length);
        } else if (inputVal == 'cd ..' && flag == 1) {
            terminalDiv.append('

');
            flag = 0;
        } else {
            terminalDiv.append('
Enter something valid!
');
        }
        if(flag == 0) {
            terminalDiv.append('
 ~ $ashish >> <input type = "text" class = "terminal-input" onKeyPress = "terminal(event, this)" autofocus>
');
        }
        else {
            terminalDiv.append('
 ~/projects $ashish >> <input type = "text" class = "terminal-input" onKeyPress = "terminal(event, this)" autofocus>
');
        }
        $(".terminal-input").focus();
    }
}

$(window).load(function(){
   $('#cover').fadeOut(300);
});

$(document).ready(function() {
    $('.fa').on('click', function() {
        if ($('.intro').hasClass('clicked')) {
            $('.intro').removeClass('clicked');
        } else {
            $('.intro').addClass('clicked');
        }
    });
});<commit_msg>Update resume<commit_after>var flag = 0;

function terminal(e, input) {

    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) {

        var terminalDiv = $('.terminal');
        var inputVal = $('.terminal-input').val();

        $('.console').last().remove();
        if(flag == 0) {
            terminalDiv.append('~ $ashish >> ' + inputVal);
        }
        else {
            terminalDiv.append('~/projects $ashish >> ' + inputVal);
        }
        if (inputVal == 'ls' && flag == 0) {
            terminalDiv.append('
projects   resume.pdf   game.app
');
        } else if (inputVal == 'ls' && flag == 1) {
            terminalDiv.append('
WikiSearch   Clippy   ink   Erectus
');
        } else if (inputVal == 'open resume.pdf' && flag == 0) {
            window.location.href = 'https://drive.google.com/file/d/0B3OeNoTC80mGV2RTUUxZWW82ZDg/view?usp=sharing';
        } else if (inputVal == 'cd projects') {
            terminalDiv.append('

');
            flag = 1;
        } else if ((inputVal == 'cd WikiSearch' ||  inputVal == 'cd ink') && flag == 1) {
            window.location.href = 'http://github.com/thinker3197/' + inputVal.slice(3, inputVal.length);
        } else if ((inputVal == 'cd Erectus' || inputVal == 'cd Clippy') && flag == 1) {
            window.location.href = 'http://github.com/The-Turing-Machine/' + inputVal.slice(3, inputVal.length);
        } else if (inputVal == 'cd ..' && flag == 1) {
            terminalDiv.append('

');
            flag = 0;
        } else {
            terminalDiv.append('
Enter something valid!
');
        }
        if(flag == 0) {
            terminalDiv.append('
 ~ $ashish >> <input type = "text" class = "terminal-input" onKeyPress = "terminal(event, this)" autofocus>
');
        }
        else {
            terminalDiv.append('
 ~/projects $ashish >> <input type = "text" class = "terminal-input" onKeyPress = "terminal(event, this)" autofocus>
');
        }
        $(".terminal-input").focus();
    }
}

$(window).load(function(){
   $('#cover').fadeOut(300);
});

$(document).ready(function() {
    $('.fa').on('click', function() {
        if ($('.intro').hasClass('clicked')) {
            $('.intro').removeClass('clicked');
        } else {
            $('.intro').addClass('clicked');
        }
    });
});<|endoftext|>


<commit_before>(function($,W,D)
{
	var JQUERY4U = {};

	JQUERY4U.UTIL =
	{
		setupFormValidation: function()
		{
			//form validation rules
			$("#register-form".validate({
				rules:{
					firstname: "required",
					lastname: "required",
					email: {
						required: true,
						email: true
					},
					password: {
						required: true,
						minlength: 5
					},
					agree: "required"
				},
				messages: {
					firstname: "Please enter your firstname",
					lastname: "Please enter your lastname",
					password: {
						required: "Please provide a password",
						minlength: "Your password must be at least 5 characters long"
					},
					email: "Please enter a valid email address",
					agree: "Please accept our policy"
				},
				submitHandler: function(form){
					form.submit();
				}
		});
	}
}

$(D).ready(function($) {
	JQUERY4U.UTIL.setupFormValidation();
});

})
(jQuery, window, document);<commit_msg>correct the jquery validation code<commit_after>(function($,W,D)
{
    var JQUERY4U = {};

    JQUERY4U.UTIL =
    {
        setupFormValidation: function()
        {
            //form validation rules
            $("#register-form").validate({
                rules: {
                    firstname: "required",
                    lastname: "required",
                    email: {
                        required: true,
                        email: true
                    },
                    password: {
                        required: true,
                        minlength: 5
                    },
                    agree: "required"
                },
                messages: {
                    firstname: "Please enter your firstname",
                    lastname: "Please enter your lastname",
                    password: {
                        required: "Please provide a password",
                        minlength: "Your password must be at least 5 characters long"
                    },
                    email: "Please enter a valid email address",
                    agree: "Please accept our policy"
                },
                submitHandler: function(form) {
                    form.submit();
                }
            });
        }
    }

    //when the dom has loaded setup form validation rules
    $(D).ready(function($) {
        JQUERY4U.UTIL.setupFormValidation();
    });

})(jQuery, window, document);<|endoftext|>


<commit_before>requirejs.config({
  baseUrl: 'bower_components',
  paths: {

    // external code

    d3:          'd3/d3.min',
    crossfilter: 'crossfilter/crossfilter.min',
    jquery:      'jquery/dist/jquery.min',
    lodash:      'lodash/dist/lodash.min',

    // local code

    baseChart: '../js/basechart',
    model:     '../js/model',
    chart:     '../js/chart'
  },
  shim: {
  }
});

define(['jquery', 'chart', 'model'], function ($, Chart, Model) {
  var chart = new Chart($('.chart'));
  var model = new Model()
    .on('data', gotData);

  function gotData(data) {
    chart.setData(data.slice(0, DAYS * HOURS));
  }
});
<commit_msg>look at 40 days<commit_after>requirejs.config({
  baseUrl: 'bower_components',
  paths: {

    // external code

    d3:          'd3/d3.min',
    crossfilter: 'crossfilter/crossfilter.min',
    jquery:      'jquery/dist/jquery.min',
    lodash:      'lodash/dist/lodash.min',

    // local code

    baseChart: '../js/basechart',
    model:     '../js/model',
    chart:     '../js/chart'
  },
  shim: {
  }
});

define(['jquery', 'chart', 'model'], function ($, Chart, Model) {
  var chart = new Chart($('.chart'));
  var model = new Model()
    .on('data', gotData);

  function gotData(data) {
    chart.setData(data.slice(0, 40 * HOURS));
  }
});
<|endoftext|>


<commit_before>'use strict';

function draw_logic(){
    core_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          canvas_buffer.fillRect(
            core_entities[entity]['x'],
            core_entities[entity]['y'],
            1,
            1
          );
      },
    });
}

function logic(){
    core_entity_create({
      'properties': {
        'speed': core_random_integer({
          'max': 3,
          'todo': 'ceil',
        }),
        'x': canvas_properties['width'],
        'y': core_random_integer({
          'max': canvas_properties['height'],
        }),
      },
    });

    core_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          core_entities[entity]['x'] -= core_entities[entity]['speed'];

          // Remove stars that reached left side of screen.
          if(core_entities[entity]['x'] < 0){
              core_entity_remove({
                'entities': [
                  entity,
                ],
              });
          }
      },
    });
}

function repo_init(){
    core_repo_init({
      'title': 'D2LoD-ArcaneSanctuary.htm',
    });
    canvas_init();
}
<commit_msg>added ids<commit_after>'use strict';

function draw_logic(){
    core_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          canvas_buffer.fillRect(
            core_entities[entity]['x'],
            core_entities[entity]['y'],
            1,
            1
          );
      },
    });
}

function logic(){
    core_entity_create({
      'id': id_count,
      'properties': {
        'speed': core_random_integer({
          'max': 3,
          'todo': 'ceil',
        }),
        'x': canvas_properties['width'],
        'y': core_random_integer({
          'max': canvas_properties['height'],
        }),
      },
    });
    id_count++;

    core_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          core_entities[entity]['x'] -= core_entities[entity]['speed'];

          // Remove stars that reached left side of screen.
          if(core_entities[entity]['x'] < 0){
              core_entity_remove({
                'entities': [
                  entity,
                ],
              });
          }
      },
    });
}

function repo_init(){
    core_repo_init({
      'globals': {
        'id_count': 0,
      },
      'title': 'D2LoD-ArcaneSanctuary.htm',
    });
    canvas_init();
}
<|endoftext|>


<commit_before>var util = require('./util')
// promise
// Promise.all 全部完成触发 then
// Promise.race 哪个先触发 reject 或者 resolve 触发then
// Promise.reject 将对象转变为 promise 对象
// Promise.resolve 将对象转变为 promise 对象
var rnoContent = /^(?:get|head)$/
var ajax = function(config){
	var type = config.type
	var useFormData = config.useFormData && util.isObject(config.data)
	var needContentType = config.contentType && !rnoContent.test(type) //文件上传无需 content-type,自动设置
	var data = config.data
	var crossdomain = getUrlHost(config.url) !== location.host
	var dataType = config.dataType || ''
	var traditional = config.traditional

	if(data){
		if(type === 'get'){
			if(util.isObject(data)){
				data = encodeData(data,traditional)
			}
			config.url = addQuery(config.url,data)
			data = null
		}else{
			// formData
			if(useFormData){
				data = makeFormData(data,traditional)
			}else{
				// add Content-Type
				data = encodeData(data,traditional)
			}
		}
	}

	if(dataType.toLowerCase() === 'jsonp'){
		var jsonpCallback = config.jsonpCallback
		if(!jsonpCallback){
			jsonpCallback = 'misakaCallback' + (config.fresh ? util.now() : '')
		}
		window[jsonpCallback] = window[jsonpCallback] || function(){
			config.success && config.success.apply(null,[].slice.call(arguments))
			setTimeout(function(){
				delete window[jsonpCallback]
			},100)
		}
		config.url = addQuery(config.url,config.jsonp + '=' + jsonpCallback)
		return getScript(config.url,null,config.error,{
			charset: config.charset
		})
	}

	var xhr = new XMLHttpRequest,upload
	xhr.open(type,config.url,config.async)
	if(crossdomain){
		if(config.crossdomain){
			xhr.withCredentials = true
		}
		delete config.headers['X-Requested-With']
	}
	if(needContentType){
		// 大小写差异，不规范需要 allow-headers
		xhr.setRequestHeader('Content-Type',config.contentType)
	}
	if(!useFormData){
		xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
	}
	if(config.headers){
		util.each(config.headers,function(header,key){
			xhr.setRequestHeader(key,header)
		})
	}
	if(config.timeout){
		xhr.timeout = config.timeout
	}
	xhr.onload = function(){
		if(this.status >= 200 && this.status < 300 || this.status === 304){
			var value = this.responseText
			if(dataType.toLowerCase() === 'json'){
				value = JSON.parse(value)
			}
			config.success && config.success(value,this)
		}else{
			config.error && config.error(e,this)
		}
	}
	xhr.ontimeout = xhr.onerror = function(e){
		config.error && config.error(e,this)
	}
	if(config._upload){
		// 是否文件上传
		upload = xhr.upload
		// upload.onload = xhr.onload.bind(upload)
		// upload.onerror = xhr.onerror.bind(upload)
		upload.onprogress = function(e){
			if(e.lengthComputable){
				config.progress && config.progress(e.loaded,e.total)
			}
		}
	}
	xhr.send(data)
}
var ajaxSetup = function(config){
	var defaultConfig = {
		type: 'get',
		// contentType: 'application/x-www-form-urlencoded; charset=UTF-8', //使用 formData,无需设定
		headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        charset: 'utf-8',
        fresh: true,
        async: true,
        timeout: null,
        crossdomain: false,
        traditional: false,
        jsonp: 'callback',
        useFormData: true
	}
	config.type = config.type || defaultConfig.type.toLowerCase()
	config = util.extend(config,defaultConfig,true)
	return ajax(config)
}
var uploadSetup = function(config){
	var defaultConfig = {
		type: 'post',
		headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        async: true,
        timeout: null,
        chunked: false, //分块上传 http://www.html5rocks.com/zh/tutorials/file/xhr2/
        crossdomain: false,
        _upload: true,
        useFormData: true
	}
	config = util.extend(config,defaultConfig,true)
	return ajax(config)
}

var getScript = function(url,onload,onerror,extra){
	if(typeof extra === 'undefined' && util.isObject(onerror)){
		extra = onerror
		onerror = null;
	}
	var s = document.createElement('script'),
		head = document.getElementsByTagName('head')[0]
	s.async = true;
	s.onload = function(){
		head.removeChild(s)
		onload && onload()
		s = null
	}
	s.onerror = function(e){
		head.removeChild(s)
		onerror && onerror(e)
		s = null
	}
	extra && util.each(extra,function(value,property){
		s[property] = extra[property]
	})
	s.src = url
	head.appendChild(s)
}

var getUrlHost = (function(){
	var a = document.createElement('a')
	return function(url){
		a.href = url
		return a.host
	}
})()
function encodeData(data,traditional){
	if(util.isString(data)){return data.replace(/\+/g,'%2B')}
	var ret = [];
	util.each(data,function(d,key){
		if(util.isArray(d) || util.isArrayLike(d)){
			var _key = traditional ? key : key + '[]'
			util.each(d,function(_d){
				if(util.isString(_d)){
					_d = encodeURIComponent(_d)
				}
				ret.push(_key + '=' + _d)
			})
		}else{
			ret.push(key + '=' + encodeURIComponent(d))
		}
	})
	return ret.join('&')
}
function makeFormData(data,traditional){
	// formdata 无需编码属性名
	// formdata 无需编码
	var formData = new FormData
	util.each(data,function(d,prop){
		if(util.isArray(d) || util.isArrayLike(d)){
			var _prop = traditional ? prop : prop + '[]'
			util.each(d,function(_d){
				// if(util.isString(_d)){
				// 	_d = encodeURIComponent(_d)
				// }
				formData.append(_prop,_d)
			})
		}else{
			formData.append(prop,(d))
		}
	})
	return formData
}
function addQuery(url,data){
	data = data.replace(/\+/g,'%2B')
	if(url.indexOf('?') !== -1){
		url += '&' + data
	}else{
		url += '?' + data
	}
	return url
}
module.exports = {
	ajax: ajaxSetup,
	getScript: getScript,
	fileUpload: uploadSetup
}
console.log('ajax加载完毕')
<commit_msg>fix promise<commit_after>var util = require('./util')

var rnoContent = /^(?:get|head)$/
var ajax = function(config){
	var type = config.type
	var useFormData = config.useFormData && util.isObject(config.data)
	var needContentType = config.contentType && !rnoContent.test(type) //文件上传无需 content-type,自动设置
	var data = config.data
	var crossdomain = getUrlHost(config.url) !== location.host
	var dataType = config.dataType || ''
	var traditional = config.traditional

	if(data){
		if(type === 'get'){
			if(util.isObject(data)){
				data = encodeData(data,traditional)
			}
			config.url = addQuery(config.url,data)
			data = null
		}else{
			// formData
			if(useFormData){
				data = makeFormData(data,traditional)
			}else{
				// add Content-Type
				data = encodeData(data,traditional)
			}
		}
	}

	if(dataType.toLowerCase() === 'jsonp'){
		var jsonpCallback = config.jsonpCallback
		if(!jsonpCallback){
			jsonpCallback = 'misakaCallback' + (config.fresh ? util.now() : '')
		}
		window[jsonpCallback] = window[jsonpCallback] || function(){
			config.success && config.success.apply(null,[].slice.call(arguments))
			setTimeout(function(){
				delete window[jsonpCallback]
			},100)
		}
		config.url = addQuery(config.url,config.jsonp + '=' + jsonpCallback)
		return getScript(config.url,null,config.error,{
			charset: config.charset
		})
	}

	var xhr = new XMLHttpRequest,upload
	xhr.open(type,config.url,config.async)
	if(crossdomain){
		if(config.crossdomain){
			xhr.withCredentials = true
		}
		delete config.headers['X-Requested-With']
	}
	if(needContentType){
		// 大小写差异，不规范需要 allow-headers
		xhr.setRequestHeader('Content-Type',config.contentType)
	}
	if(!useFormData){
		xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
	}
	if(config.headers){
		util.each(config.headers,function(header,key){
			xhr.setRequestHeader(key,header)
		})
	}
	if(config.timeout){
		xhr.timeout = config.timeout
	}
	xhr.onload = function(){
		if(this.status >= 200 && this.status < 300 || this.status === 304){
			var value = this.responseText
			if(dataType.toLowerCase() === 'json'){
				value = JSON.parse(value)
			}
			config.success && config.success(value,this)
		}else{
			config.error && config.error(e,this)
		}
	}
	xhr.ontimeout = xhr.onerror = function(e){
		config.error && config.error(e,this)
	}
	if(config._upload){
		// 是否文件上传
		upload = xhr.upload
		// upload.onload = xhr.onload.bind(upload)
		// upload.onerror = xhr.onerror.bind(upload)
		upload.onprogress = function(e){
			if(e.lengthComputable){
				config.progress && config.progress(e.loaded,e.total)
			}
		}
	}
	xhr.send(data)
}
var ajaxSetup = function(config){
	var defaultConfig = {
		type: 'get',
		// contentType: 'application/x-www-form-urlencoded; charset=UTF-8', //使用 formData,无需设定
		headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        charset: 'utf-8',
        fresh: true,
        async: true,
        timeout: null,
        crossdomain: false,
        traditional: false,
        jsonp: 'callback',
        useFormData: true
	}
	config.type = config.type || defaultConfig.type.toLowerCase()
	config = util.extend(config,defaultConfig,true)
	return ajax(config)
}
var uploadSetup = function(config){
	var defaultConfig = {
		type: 'post',
		headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        async: true,
        timeout: null,
        chunked: false, //分块上传 http://www.html5rocks.com/zh/tutorials/file/xhr2/
        crossdomain: false,
        _upload: true,
        useFormData: true
	}
	config = util.extend(config,defaultConfig,true)
	return ajax(config)
}

var getScript = function(url,onload,onerror,extra){
	if(typeof extra === 'undefined' && util.isObject(onerror)){
		extra = onerror
		onerror = null;
	}
	var s = document.createElement('script'),
		head = document.getElementsByTagName('head')[0]
	s.async = true;
	s.onload = function(){
		head.removeChild(s)
		onload && onload()
		s = null
	}
	s.onerror = function(e){
		head.removeChild(s)
		onerror && onerror(e)
		s = null
	}
	extra && util.each(extra,function(value,property){
		s[property] = extra[property]
	})
	s.src = url
	head.appendChild(s)
}

var getUrlHost = (function(){
	var a = document.createElement('a')
	return function(url){
		a.href = url
		return a.host
	}
})()
function encodeData(data,traditional){
	if(util.isString(data)){return data.replace(/\+/g,'%2B')}
	var ret = [];
	util.each(data,function(d,key){
		if(util.isArray(d) || util.isArrayLike(d)){
			var _key = traditional ? key : key + '[]'
			util.each(d,function(_d){
				if(util.isString(_d)){
					_d = encodeURIComponent(_d)
				}
				ret.push(_key + '=' + _d)
			})
		}else{
			ret.push(key + '=' + encodeURIComponent(d))
		}
	})
	return ret.join('&')
}
function makeFormData(data,traditional){
	// formdata 无需编码属性名
	// formdata 无需编码
	var formData = new FormData
	util.each(data,function(d,prop){
		if(util.isArray(d) || util.isArrayLike(d)){
			var _prop = traditional ? prop : prop + '[]'
			util.each(d,function(_d){
				// if(util.isString(_d)){
				// 	_d = encodeURIComponent(_d)
				// }
				formData.append(_prop,_d)
			})
		}else{
			formData.append(prop,(d))
		}
	})
	return formData
}
function addQuery(url,data){
	data = data.replace(/\+/g,'%2B')
	if(url.indexOf('?') !== -1){
		url += '&' + data
	}else{
		url += '?' + data
	}
	return url
}
module.exports = {
	ajax: ajaxSetup,
	getScript: getScript,
	fileUpload: uploadSetup
}
console.log('ajax加载完毕')
<|endoftext|>


<commit_before>var writeChar = function(someOutput, characterToWrite) {
    someOutput.append(characterToWrite);
}

var globalMultiplier = 1;
var delayFunction = function(INITIAL_MULTIPLIER) {
    globalMultiplier = 1/Math.pow(2,globalMultiplier);
    return Math.round(Math.random() * INITIAL_MULTIPLIER * globalMultiplier);
};
var writePrompt = function(listOfPrompts, listOfAnswers, someOutput, someContent, isAnswer) {
    if(someContent == undefined) {
        toOutput = listOfPrompts[0];
        newAnswers = listOfAnswers;
        newPrompts = listOfPrompts.slice(1);
        var promptDom = $("");
        promptDom.append("
");
        $('termcontainer').append(promptDom);
        writePrompt(newPrompts, newAnswers, promptDom, toOutput);
    } else if(someContent == "") {
        var toOutput = null;
        var newPrompts = null;
        var newAnswers = null;

        if(listOfPrompts.length < listOfAnswers.length) {
            toOutput = listOfAnswers[0];
            newAnswers = listOfAnswers.slice(1);
            newPrompts = listOfPrompts;
        } else if(listOfPrompts.length > listOfAnswers.length) {
            toOutput = listOfPrompts[0];
            newAnswers = listOfAnswers;
            newPrompts = listOfPrompts.slice(1);
        } else if(listOfPrompts.length != 0){
            toOutput = listOfPrompts[0];
            newAnswers = listOfAnswers;
            newPrompts = listOfPrompts.slice(1);
        } else {
            return;
        }

        if(isAnswer) {
            someOutput.addClass("answer")
        }
        someOutput.removeClass("active");

        var promptDom = $("");
        promptDom.append("
");
        $('.termcontainer').append(promptDom);
        writePrompt(newPrompts, newAnswers, promptDom, toOutput);
        return;

    }
    var INITIAL_MULTIPLIER = 5;
    setTimeout(function() {
        var currentChar = someContent.charAt(0);
        someOutput.addClass("active");
        writeChar(someOutput, currentChar);
        writePrompt(listOfPrompts, listOfAnswers, someOutput, someContent.substring(1));
        someOutput.removeClass("active");
    }, delayFunction(INITIAL_MULTIPLIER));
}

var cleanup = function() {
    var prompts = $('.prompts');
    var answers = $('.answers');
    prompts.remove();
    answers.remove();
}

$(document).ready(function() {
    var prompts = $('.prompts p');
    var answers = $('.answers p')
    promptContents = prompts.map(function(index) {
        var currentText = $(this).text();
        return currentText;
    });

    answerContents = answers.map(function(index) {
        var currentText = $(this).text();
        return currentText;
    });
    cleanup();

    writePrompt(promptContents, answerContents);
});<commit_msg>Modify javascript to have hue increase and make it appear faster.<commit_after>/*
The following code is taken from this stackoverflow question https://stackoverflow.com/questions/17433015/change-the-hue-of-a-rgb-color-in-javascript
*/
// Changes the RGB/HEX temporarily to a HSL-Value, modifies that value
// and changes it back to RGB/HEX.

function changeHue(rgb, degree) {
    var hsl = rgbToHSL(rgb);
    hsl.h += degree;
    if (hsl.h > 360) {
        hsl.h -= 360;
    }
    else if (hsl.h < 0) {
        hsl.h += 360;
    }
    return hslToRGB(hsl);
}

// exepcts a string and returns an object
function rgbToHSL(rgb) {
    // strip the leading # if it's there
    rgb = rgb.replace(/^\s*#|\s*$/g, '');

    // convert 3 char codes --> 6, e.g. `E0F` --> `EE00FF`
    if(rgb.length == 3){
        rgb = rgb.replace(/(.)/g, '$1$1');
    }

    var r = parseInt(rgb.substr(0, 2), 16) / 255,
        g = parseInt(rgb.substr(2, 2), 16) / 255,
        b = parseInt(rgb.substr(4, 2), 16) / 255,
        cMax = Math.max(r, g, b),
        cMin = Math.min(r, g, b),
        delta = cMax - cMin,
        l = (cMax + cMin) / 2,
        h = 0,
        s = 0;

    if (delta == 0) {
        h = 0;
    }
    else if (cMax == r) {
        h = 60 * (((g - b) / delta) % 6);
    }
    else if (cMax == g) {
        h = 60 * (((b - r) / delta) + 2);
    }
    else {
        h = 60 * (((r - g) / delta) + 4);
    }

    if (delta == 0) {
        s = 0;
    }
    else {
        s = (delta/(1-Math.abs(2*l - 1)))
    }

    return {
        h: h,
        s: s,
        l: l
    }
}

// expects an object and returns a string
function hslToRGB(hsl) {
    var h = hsl.h,
        s = hsl.s,
        l = hsl.l,
        c = (1 - Math.abs(2*l - 1)) * s,
        x = c * ( 1 - Math.abs((h / 60 ) % 2 - 1 )),
        m = l - c/ 2,
        r, g, b;

    if (h < 60) {
        r = c;
        g = x;
        b = 0;
    }
    else if (h < 120) {
        r = x;
        g = c;
        b = 0;
    }
    else if (h < 180) {
        r = 0;
        g = c;
        b = x;
    }
    else if (h < 240) {
        r = 0;
        g = x;
        b = c;
    }
    else if (h < 300) {
        r = x;
        g = 0;
        b = c;
    }
    else {
        r = c;
        g = 0;
        b = x;
    }

    r = normalize_rgb_value(r, m);
    g = normalize_rgb_value(g, m);
    b = normalize_rgb_value(b, m);

    return rgbToHex(r,g,b);
}

function normalize_rgb_value(color, m) {
    color = Math.floor((color + m) * 255);
    if (color < 0) {
        color = 0;
    }
    return color;
}

function rgbToHex(r, g, b) {
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

var writeChar = function(someOutput, characterToWrite, nextCharToWrite, finalCharacter) {
    someOutput.append(characterToWrite, nextCharToWrite, finalCharacter);
}

var globalMultiplier = 1;
var delayFunction = function(INITIAL_MULTIPLIER) {
    globalMultiplier = 1/Math.pow(2,globalMultiplier);
    return Math.round(Math.random() * INITIAL_MULTIPLIER * globalMultiplier);
};
var writePrompt = function(listOfPrompts, listOfAnswers, someOutput, someContent, colorOfText, isAnswer) {
    if(someContent == undefined) {
        toOutput = listOfPrompts[0];
        newAnswers = listOfAnswers;
        newPrompts = listOfPrompts.slice(1);
        var promptDom = $("");
        promptDom.append("
");
        promptDom.css("color", colorOfText);
        $('termcontainer').append(promptDom);
        writePrompt(newPrompts, newAnswers, promptDom, toOutput,changeHue(colorOfText, 2));
        return;
    } else if(someContent == "") {
        var toOutput = null;
        var newPrompts = null;
        var newAnswers = null;

        if(listOfPrompts.length < listOfAnswers.length) {
            toOutput = listOfAnswers[0];
            newAnswers = listOfAnswers.slice(1);
            newPrompts = listOfPrompts;
        } else if(listOfPrompts.length > listOfAnswers.length) {
            toOutput = listOfPrompts[0];
            newAnswers = listOfAnswers;
            newPrompts = listOfPrompts.slice(1);
        } else if(listOfPrompts.length != 0){
            toOutput = listOfPrompts[0];
            newAnswers = listOfAnswers;
            newPrompts = listOfPrompts.slice(1);
        } else {
            return;
        }

        if(isAnswer) {     someOutput.addClass("answer") }
        someOutput.removeClass("active");

        var promptDom = $("");
        promptDom.append("
");
        promptDom.css("color", colorOfText);
        $('.termcontainer').append(promptDom);
        writePrompt(newPrompts, newAnswers, promptDom, toOutput, changeHue(colorOfText, 2));
        return;

    }
    var INITIAL_MULTIPLIER = 5;
    setTimeout(function() {
        var currentChar = someContent.charAt(0);
        var nextChar = someContent.charAt(1);
        var finalCharacter = someContent.charAt(2);
        someOutput.addClass("active");
        writeChar(someOutput, currentChar, nextChar, finalCharacter);
        writePrompt(listOfPrompts, listOfAnswers, someOutput, someContent.substring(3), colorOfText);
        someOutput.removeClass("active");
    }, delayFunction(INITIAL_MULTIPLIER));
}

var cleanup = function() {
    var prompts = $('.prompts');
    var answers = $('.answers');
    prompts.remove();
    answers.remove();
}

$(document).ready(function() {
    var prompts = $('.prompts p');
    var answers = $('.answers p')
    promptContents = prompts.map(function(index) {
        var currentText = $(this).text();
        return currentText;
    });

    answerContents = answers.map(function(index) {
        var currentText = $(this).text();
        return currentText;
    });
    cleanup();

    writePrompt(promptContents, answerContents, undefined, undefined, "#55ff55");
});

<|endoftext|>


<commit_before>'use strict';

function draw_logic(){
    for(let object in world){
        canvas_setproperties({
          'properties': {
            'fillStyle': world[object][4],
          },
        });
        canvas_buffer.fillRect(
          world[object][0],
          world[object][1],
          world[object][2],
          world[object][3]
        );
    }
    for(let object in scenery){
        canvas_draw_path({
          'properties': {
            'fillStyle': scenery[object]['color'],
          },
          'translate': true,
          'vertices': scenery[object]['vertices'],
          'x': scenery[object]['x'],
          'y': scenery[object]['y'],
        });
    }
}

function logic(){
    // Update scenery.
    for(let object in scenery){
        scenery[object]['x'] -= core_storage_data['speed'];

        if(scenery[object]['x'] > -100
          || scenery[object]['color'] === '#be6400'){
            continue;
        }

        let new_x = canvas_properties['width'] + core_random_integer({
          'max': canvas_properties['width'],
        });
        let new_y = core_random_integer({
          'max': canvas_properties['height'],
        });

        while(new_y > -80 + canvas_properties['height-half']
          && new_y < 80 + canvas_properties['height-half']){
            new_y = core_random_integer({
              'max': canvas_properties['height'],
            });
        }

        scenery[object]['x'] = new_x;
        scenery[object]['y'] = new_y;
        scenery[object - 1]['x'] = new_x;
        scenery[object - 1]['y'] = new_y + 25;
    }
}

function repo_init(){
    core_repo_init({
      'globals': {
        'scenery': [],
        'world': [],
      },
      'storage': {
        'speed': 4,
        'trees': 6,
      },
      'storage-menu': '

<input id=speed>Speed'
        + '
<input id=trees>Trees
',
      'title': 'Trains-2D.htm',
    });
    canvas_init();

    canvas_properties['clearColor'] = '#141';
}

function resize_logic(){
    world.length = 0;
    world = [
      [0, canvas_properties['height-half'] - 40, canvas_properties['width'], 80, '#432'],
      [0, canvas_properties['height-half'] + 10, canvas_properties['width'], 4, '#444'],
      [0, canvas_properties['height-half'] - 14, canvas_properties['width'], 4, '#444'],
      [canvas_properties['width-half'] - 310, canvas_properties['height-half'] - 30, 200, 60, '#555'],
      [canvas_properties['width-half'] - 100, canvas_properties['height-half'] - 30, 200, 60, '#555'],
      [canvas_properties['width-half'] + 110, canvas_properties['height-half'] - 30, 200, 60, '#555'],
    ];
    scenery.length = 0;
    let loop_counter = core_storage_data['trees'] - 1;
    do{
        prefabs_canvas_tree_2d({
          'id': loop_counter,
          'x': -canvas_properties['width'],
        });
    }while(loop_counter--);
}
<commit_msg>removed comment<commit_after>'use strict';

function draw_logic(){
    for(let object in world){
        canvas_setproperties({
          'properties': {
            'fillStyle': world[object][4],
          },
        });
        canvas_buffer.fillRect(
          world[object][0],
          world[object][1],
          world[object][2],
          world[object][3]
        );
    }
    for(let object in scenery){
        canvas_draw_path({
          'properties': {
            'fillStyle': scenery[object]['color'],
          },
          'translate': true,
          'vertices': scenery[object]['vertices'],
          'x': scenery[object]['x'],
          'y': scenery[object]['y'],
        });
    }
}

function logic(){
    for(let object in scenery){
        scenery[object]['x'] -= core_storage_data['speed'];

        if(scenery[object]['x'] > -100
          || scenery[object]['color'] === '#be6400'){
            continue;
        }

        let new_x = canvas_properties['width'] + core_random_integer({
          'max': canvas_properties['width'],
        });
        let new_y = core_random_integer({
          'max': canvas_properties['height'],
        });

        while(new_y > -80 + canvas_properties['height-half']
          && new_y < 80 + canvas_properties['height-half']){
            new_y = core_random_integer({
              'max': canvas_properties['height'],
            });
        }

        scenery[object]['x'] = new_x;
        scenery[object]['y'] = new_y;
        scenery[object - 1]['x'] = new_x;
        scenery[object - 1]['y'] = new_y + 25;
    }
}

function repo_init(){
    core_repo_init({
      'globals': {
        'scenery': [],
        'world': [],
      },
      'storage': {
        'speed': 4,
        'trees': 6,
      },
      'storage-menu': '

<input id=speed>Speed'
        + '
<input id=trees>Trees
',
      'title': 'Trains-2D.htm',
    });
    canvas_init();

    canvas_properties['clearColor'] = '#141';
}

function resize_logic(){
    world.length = 0;
    world = [
      [0, canvas_properties['height-half'] - 40, canvas_properties['width'], 80, '#432'],
      [0, canvas_properties['height-half'] + 10, canvas_properties['width'], 4, '#444'],
      [0, canvas_properties['height-half'] - 14, canvas_properties['width'], 4, '#444'],
      [canvas_properties['width-half'] - 310, canvas_properties['height-half'] - 30, 200, 60, '#555'],
      [canvas_properties['width-half'] - 100, canvas_properties['height-half'] - 30, 200, 60, '#555'],
      [canvas_properties['width-half'] + 110, canvas_properties['height-half'] - 30, 200, 60, '#555'],
    ];
    scenery.length = 0;
    let loop_counter = core_storage_data['trees'] - 1;
    do{
        prefabs_canvas_tree_2d({
          'id': loop_counter,
          'x': -canvas_properties['width'],
        });
    }while(loop_counter--);
}
<|endoftext|>


<commit_before>(function() {

	'use strict';

	var masterfile = 'locales/nl_nl.json',
		$article = $('article'),
		htmlPattern = /<[a-z][\s\S]*>/i,
		json, currentValue,

	changeJsonValue = function ( obj, strProp, newValue ) {
		var re = /\["?([^"\]]+)"?\]/g,
			m, p;

		while ((m = re.exec(strProp)) && typeof obj[p = m[1]] === 'object')
			obj = obj[p];

		if (p)
			obj[p] = newValue;
	},

	render = function ( response ) {
		json = response;
		$article.empty().renderJSON(response);

		$('.renderjson-scalar', $article).each(function( key, el ) {
			htmlToMarkdown(key, el);
			stylise(el);
		});

		$('textarea').elastic();
	},

	stylise = function ( el ) {
		$(el).attr('class', 'col-xs-5 value')
			.prev().attr('class', 'col-xs-2 key')
			.parent().attr('class', 'row');
	},

	htmlToMarkdown = function ( i, el ) {
		var txt = el.value;

		if ( htmlPattern.test(txt) ) {
			var md = HTML2Markdown(txt);
			$article.find('[title=\''+el.title+'\']').val(md);
		}
	},

	storeCurrent = function ( ev ) {
		ev.stopPropagation();
		currentValue = ev.currentTarget.value;
	},

	checkEdit = function ( ev ) {
		if ( currentValue !== ev.currentTarget.value ){
			$(ev.currentTarget).addClass('modified').data('original', currentValue);

			previewChanges(ev.currentTarget);
		}
	},

	previewChanges = function ( el ) {
		var html = marked(el.value);

		if ( !el.$preview) {
			el.$preview = $('
').insertAfter(el);
		}

		// if el has only one p tag remove it.
		if ( html.split('
').length-1 === 1 )
			html = html.replace(/(\
|\<\/p\>)/gi, '');

		el.$preview.html(html);
	},

	upload = function ( ev ) {
		// console.log(ev.currentTarget.value);

		// loadFile(ev.currentTarget.value);
	},

	reset = function () {
		location.reload();
	},

	save = function () {
		var filename = masterfile.split('/').pop(),
			saveObj = {
				filename: filename.replace(/\.[^/.]+$/, ''),
				json: json
			}, isModified;

		$(':focus').blur();

		$('.modified').each(function(key, el) {
			var node = el.title,
				newValue = el.$preview.html();

			changeJsonValue(json, node, newValue);
			isModified = 1;
		}).removeClass('modified');

		if ( !isModified ) return;

		$.post('/save.php', saveObj, function ( response ){
			json = saveObj;
			window.open(response);
		});
	},

	uploadFile = function () {
		var file = this.files[0],
			fd = new FormData(),
			xhr;

		fd.append('uploadfile', file);

		xhr = new XMLHttpRequest();
		xhr.open('POST', 'upload.php', true);

		xhr.onload = function() {
			if (this.status == 200) {
				var response;
				try {
					response = JSON.parse(this.response);
				} catch(error) {
					console.log('response isnt json');
				}

				if ( response )
					render(response.dataObj);
			}
		};

		xhr.send(fd);
	};

	// upload initial file
	$.get(masterfile, render);

	marked.setOptions({
		renderer: new marked.Renderer(),
		gfm: false,
		breaks: true,
		sanitize: true,
		smartLists: true,
		smartypants: true
	});

	$article.on('focus', '.value', storeCurrent);
	$article.on('blur', '.value', checkEdit);

	$('#upload').on('change', upload);
	$('#reset').on('click', reset);
	$('#save').on('click', save);
	$('#uploadfile').on('change', uploadFile);

})();<commit_msg>save obj update fixed<commit_after>(function() {

	'use strict';

	var masterfile = 'locales/nl_nl.json',
		$article = $('article'),
		htmlPattern = /<[a-z][\s\S]*>/i,
		json, currentValue,

	render = function ( response ) {
		json = response;
		$article.empty().renderJSON(response);

		$('.renderjson-scalar', $article).each(function( key, el ) {
			htmlToMarkdown(key, el);
			stylise(el);
		});

		$('textarea').elastic();
	},

	stylise = function ( el ) {
		$(el).attr('class', 'col-xs-5 value')
			.prev().attr('class', 'col-xs-2 key')
			.parent().attr('class', 'row');
	},

	htmlToMarkdown = function ( i, el ) {
		var txt = el.value;

		if ( htmlPattern.test(txt) ) {
			var md = HTML2Markdown(txt);
			$article.find('[title=\''+el.title+'\']').val(md);
		}
	},

	storeCurrent = function ( ev ) {
		ev.stopPropagation();
		currentValue = ev.currentTarget.value;
	},

	checkEdit = function ( ev ) {
		if ( currentValue !== ev.currentTarget.value ){
			$(ev.currentTarget).addClass('modified').data('original', currentValue);

			previewChanges(ev.currentTarget);
		}
	},

	previewChanges = function ( el ) {
		var html = marked(el.value);

		if ( !el.$preview) {
			el.$preview = $('
').insertAfter(el);
		}

		// if el has only one p tag remove it.
		if ( html.split('
').length-1 === 1 )
			html = html.replace(/(\
|\<\/p\>)/gi, '');

		el.$preview.html(html);
	},

	uploadFile = function () {
		var file = this.files[0],
			fd = new FormData(),
			xhr;

		fd.append('uploadfile', file);

		xhr = new XMLHttpRequest();
		xhr.open('POST', 'upload.php', true);

		xhr.onload = function() {
			if (this.status == 200) {
				var response;
				try {
					response = JSON.parse(this.response);
				} catch(error) {
					console.log('response isnt json');
				}

				if ( response )
					render(response.dataObj);
			}
		};

		xhr.send(fd);
	},

	reset = function () {
		location.reload();
	},

	// update value in json object to match what changed in editor
	changeJsonValue = function ( obj, strProp, newValue ) {
		var re = /\["?([^"\]]+)"?\]/g,
			m, p;

		while ((m = re.exec(strProp)) && typeof obj[p = m[1]] === 'object')
			obj = obj[p];

		if (p)
			obj[p] = newValue;
	},

	save = function () {
		var filename = masterfile.split('/').pop(),
			saveObj = {
				filename: filename.replace(/\.[^/.]+$/, ''),
				json: json
			}, isModified;

		$(':focus').blur();

		$('.modified').each(function(key, el) {
			var node = el.title,
				newValue = el.$preview.html();

			changeJsonValue(json, node, newValue);
			isModified = 1;
		}).removeClass('modified');

		if ( !isModified ) return;

		$.post('/save.php', saveObj, function ( response ){
			json = saveObj.json;
			window.open(response);
		});
	};

	// upload initial file
	$.get(masterfile, render);

	// initialise markdown preview renderer
	marked.setOptions({
		renderer: new marked.Renderer(),
		gfm: false,
		breaks: true,
		sanitize: true,
		smartLists: true,
		smartypants: true
	});

	// set events
	$article.on('focus', '.value', storeCurrent);
	$article.on('blur', '.value', checkEdit);

	$('#uploadfile').on('change', uploadFile);
	$('#reset').on('click', reset);
	$('#save').on('click', save);

})();<|endoftext|>


<commit_before>// Global polygon mesh
var boxMesh;
// Global scene object
var scene;
// Global camera object
var camera;
// The cube has to rotate around all three axes, so we need three rotation values.
// x, y and z rotation
var xRotation = 0.0;
var yRotation = 0.0;
// Rotation speed around x and y axis
var xSpeed = 0.0;
var ySpeed = 0.0;
// Translation along the z axis
var zTranslation = 5;
// Texture and flag for current texture filter
var texturesLoaded = false;
var textureArray = [];

const imageCount = 42;
const channelCount = 7;
var channels = {
	"path":[
		"images/coloredmovie_4datasets/",
		"images/coloredmovie_4datasets/grayscale/nuclei",
		"images/coloredmovie_4datasets/grayscale/dpERK",
		"images/coloredmovie_4datasets/grayscale/twist",
		"images/coloredmovie_4datasets/grayscale/dorsal",
		"images/coloredmovie_4datasets/grayscale/ind",
		"images/coloredmovie_4datasets/grayscale/rhomboid",
	]
};

var manager = new THREE.LoadingManager();
manager.onLoad = function() {
	texturesLoaded = true;
	selectTexture(0, 0);
};

// Initialize the scene
initializeScene();

// Instead of calling 'renderScene()', we call a new function: 'animateScene()'. It will
// update the rotation values and call 'renderScene()' in a loop.
// Animate the scene
animateScene();

/**
 * Initialize the scene
 */
function initializeScene() {
	// Check whether the browser supports WebGL. If so, instantiate the hardware accelerated
	// WebGL renderer. For antialiasing, we have to enable it. The canvas renderer uses
	// antialiasing by default.
	// The approach of multiple renderers is quite nice, because your scene can also be
	// viewed in browsers, which don't support WebGL. The limitations of the canvas renderer
	// in contrast to the WebGL renderer will be explained in the tutorials, when there is a
	// difference.
	webGLAvailable = false;
	if (Detector.webgl) {
		renderer = new THREE.WebGLRenderer({antialias:true});
		webGLAvailable = true;
		// document.getElementById("overlaytext").innerHTML += "WebGL Renderer";
		// If its not supported, instantiate the canvas renderer to support all non WebGL
		// browsers
	} else {
		renderer = new THREE.CanvasRenderer();
		//document.getElementById("overlaytext").innerHTML += "Canvas Renderer";
	}

	// Set the background color
	renderer.setClearColor(0xc8c8c8);

	// Get the size of the inner window (content area) to create a full size renderer
	canvasWidth = window.innerWidth-20;
	canvasHeight = window.innerHeight-20;

	// Set the renderers size to the content areas size
	renderer.setSize(canvasWidth, canvasHeight);

	// Get the DIV element from the HTML document by its ID and append the renderers DOM
	// object to it
	document.getElementById("WebGLCanvas").appendChild(renderer.domElement);

	// Create the scene, in which all objects are stored (e. g. camera, lights,
	// geometries, ...)
	scene = new THREE.Scene();

	// Now that we have a scene, we want to look into it. Therefore we need a camera.
	// Three.js offers three camera types:
	//  - PerspectiveCamera (perspective projection)
	//  - OrthographicCamera (parallel projection)
	//  - CombinedCamera (allows to switch between perspective / parallel projection
	//    during runtime)
	// In this example we create a perspective camera. Parameters for the perspective
	// camera are ...
	// ... field of view (FOV),
	// ... aspect ratio (usually set to the quotient of canvas width to canvas height)
	// ... near and
	// ... far.
	// Near and far define the cliping planes of the view frustum. Three.js provides an
	// example (http://mrdoob.github.com/three.js/examples/
	// -> canvas_camera_orthographic2.html), which allows to play around with these
	// parameters.
	// The camera is moved 10 units towards the z axis to allow looking to the center of
	// the scene.
	// After definition, the camera has to be added to the scene.
	camera = new THREE.PerspectiveCamera(45, canvasWidth / canvasHeight, 1, 100);
	camera.position.set(0, 0, 10);
	camera.lookAt(scene.position);
	scene.add(camera);

	var boxMaterial = new THREE.MeshBasicMaterial({
		 side:THREE.DoubleSide
	});
	// Create the cube
	boxGeometry = new THREE.BoxGeometry(2.0, 2.0, 2.0);
	// Create a mesh and insert the geometry and the material. Translate the whole mesh
	// by 1.5 on the x axis and by 4 on the z axis and add the mesh to the scene.
	boxMesh = new THREE.Mesh(boxGeometry, boxMaterial);
	boxMesh.position.set(0.0, 0.0, 4.0);
	scene.add(boxMesh);

	// Load an image as texture
	var textureLoader = new THREE.TextureLoader(manager);
	for (ch = 0; ch < channelCount; ++ch) {
		for (img = 0; img < imageCount; ++img) {
			textureLoader.load(channels.path[ch].concat(img+1,".png"), function(t) {
				textureArray.push(t);
			});
		}
	}

	// // Ambient light has no direction, it illuminates every object with the same
	// // intensity. If only ambient light is used, no shading effects will occur.
	// var ambientLight = new THREE.AmbientLight(0x101010, 1.0);
	// scene.add(ambientLight);

	// // Directional light has a source and shines in all directions, like the sun.
	// // This behaviour creates shading effects.
	// directionalLight = new THREE.DirectionalLight(0xffffff, 1.0);
	// directionalLight.position.set(0.0, 0.0, 1.0);
	// scene.add(directionalLight);

	// Add a listener for 'keydown' events. By this listener, all key events will be
	// passed to the function 'onDocumentKeyDown'. There's another event type 'keypress'.
	// It will report only the visible characters like 'a', but not the function keys
	// like 'cursor up'.
	document.addEventListener("keydown", onDocumentKeyDown, false);

	// // Ambient light has no direction, it illuminates every object with the same
	// // intensity. If only ambient light is used, no shading effects will occur.
	// ambientLight = new THREE.AmbientLight(0x404040);
	// scene.add(ambientLight);

	// // Directional light has a source and shines in all directions, like the sun.
	// // This behaviour creates shading effects.

	// directionalLight = new THREE.PointLight(0xffffff);
	// directionalLight.position.set(250,250,250);
	// scene.add(directionalLight);
}

/**
 * Select current texture to display in loaded texture arrays
 */
function selectTexture(channel, image) {
	boxMesh.material.map = textureArray[channel * imageCount + image];
	document.getElementById("overlaytext").innerHTML = channels.path[channel].concat(image+1,".png");
}

/**
 * This function is called, when a key is pushed down.
 */
 function onDocumentKeyDown(event) {
	this.currentImage = this.currentImage || 0;
	this.currentChannel = this.currentChannel || 0;

	// Get the key code of the pressed key
	var keyCode = event.which;
	if (keyCode == enums.keyboard.SPACE) {	// SWITCH CHANNEL
		if (this.currentChannel < channelCount - 1) {
			++this.currentChannel;
		} else {
			this.currentChannel = 0;
		}

	} else if(keyCode == enums.keyboard.KEY_W) {	// ROTATE UP
		xSpeed -= 0.01;
	} else if(keyCode == enums.keyboard.KEY_S) {	// ROTATE DOWN
		xSpeed += 0.01;
	} else if(keyCode == enums.keyboard.KEY_A) {	// ROTATE LEFT
		ySpeed -= 0.01;
	} else if(keyCode == enums.keyboard.KEY_D) {	// ROTATE RIGHT
		ySpeed += 0.01;

	} else if(keyCode == enums.keyboard.LEFT_ARROW) {	// NEXT IMAGE
		if (this.currentImage > 0) {
			--this.currentImage;
		} else {
			this.currentImage = imageCount - 1;
		}

	} else if(keyCode == enums.keyboard.RIGHT_ARROW) {	// PREVIOUS IMAGE
		if (this.currentImage < imageCount - 1) {
			++this.currentImage;
		} else {
			this.currentImage = 0;
		}

		// Page up
	} else if(keyCode == enums.keyboard.UP_ARROW) {	// ZOOM IN
		zTranslation += 0.2;
		// Page down
	} else if(keyCode == enums.keyboard.DOWN_ARROW) {	// ZOOM OUT
		zTranslation -= 0.2;
	}
	else if(keyCode == enums.keyboard.KEY_R) {	// RESET VIEW
		xRotation = 0.0;
		yRotation = 0.0;
		xSpeed = 0.0;
		ySpeed = 0.0;
		zTranslation = 5;
 }
	selectTexture(this.currentChannel, this.currentImage);
}

/**
* Animate the scene and call rendering.
*/
function animateScene() {
	//directionalLight.position = camera.position;
	if (texturesLoaded) {
		// Increase the x, y and z rotation of the cube
	  xRotation += xSpeed;
	  yRotation += ySpeed;
	  boxMesh.rotation.set(xRotation, yRotation, 0.0);

	  // Apply the the translation along the z axis
	  boxMesh.position.z = zTranslation;
		// Map the 3D scene down to the 2D screen (render the frame)
		renderScene();
	}

	// Define the function, which is called by the browser supported timer loop. If the
	// browser tab is not visible, the animation is paused. So 'animateScene()' is called
	// in a browser controlled loop.
	requestAnimationFrame(animateScene);
}

/**
* Render the scene. Map the 3D world to the 2D screen.
*/
function renderScene() {
	renderer.render(scene, camera);
}

//   Old Script
// var scene = new THREE.Scene();
// var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
// var renderer = new THREE.WebGLRenderer();

// renderer.setSize( window.innerWidth/2, window.innerHeight/2 );
// renderer.setClearColor(0xc8c8c8);
// document.getElementById("WebGLCanvas").appendChild( renderer.domElement );

// // (width, height, depth)
// var geometry = new THREE.BoxGeometry( 5, 5, 5 );

// 		var loader = new THREE.TextureLoader();
// 		  loader.load("images/24.png", function(texture){
//  			var material = new THREE.MeshLambertMaterial({map: texture});
//  			cube= new THREE.Mesh(geometry, material);
//  			scene.add(cube);
// 		});

// //var material = new THREE.MeshLambertMaterial( { color: 0xf6546a } );
// //var cube = new THREE.Mesh( geometry, material );
// //scene.add( cube );

// // (color, intensity)
// var light = new THREE.PointLight(0xffffff, 1.2);
// // (x, y, z)
// light.position.set(0, 0, 6);
// scene.add(light);

// camera.position.z = 10;

// var render = function render() {
// 	requestAnimationFrame( render );
// 	cube.rotation.x += 0.01;
// 	cube.rotation.y += 0.01;
// 	renderer.render( scene, camera );
// }
// render();
<commit_msg>try to make the assignements to texture array synchronous by calling console in the loop<commit_after>// Global polygon mesh
var boxMesh;
// Global scene object
var scene;
// Global camera object
var camera;
// The cube has to rotate around all three axes, so we need three rotation values.
// x, y and z rotation
var xRotation = 0.0;
var yRotation = 0.0;
// Rotation speed around x and y axis
var xSpeed = 0.0;
var ySpeed = 0.0;
// Translation along the z axis
var zTranslation = 5;
// Texture and flag for current texture filter
var texturesLoaded = false;

const imageCount = 42;
const channelCount = 7;

var textureArray =  [];

var channels = {
	"path":[
		"images/coloredmovie_4datasets/",
		"images/coloredmovie_4datasets/grayscale/nuclei",
		"images/coloredmovie_4datasets/grayscale/dpERK",
		"images/coloredmovie_4datasets/grayscale/twist",
		"images/coloredmovie_4datasets/grayscale/dorsal",
		"images/coloredmovie_4datasets/grayscale/ind",
		"images/coloredmovie_4datasets/grayscale/rhomboid",
	]
};

var manager = new THREE.LoadingManager();
manager.onLoad = function() {
	texturesLoaded = true;
	selectTexture(0, 0);
};

// Initialize the scene
initializeScene();

// Instead of calling 'renderScene()', we call a new function: 'animateScene()'. It will
// update the rotation values and call 'renderScene()' in a loop.
// Animate the scene
animateScene();

/**
 * Initialize the scene
 */
function initializeScene() {
	// Check whether the browser supports WebGL. If so, instantiate the hardware accelerated
	// WebGL renderer. For antialiasing, we have to enable it. The canvas renderer uses
	// antialiasing by default.
	// The approach of multiple renderers is quite nice, because your scene can also be
	// viewed in browsers, which don't support WebGL. The limitations of the canvas renderer
	// in contrast to the WebGL renderer will be explained in the tutorials, when there is a
	// difference.
	webGLAvailable = false;
	if (Detector.webgl) {
		renderer = new THREE.WebGLRenderer({antialias:true});
		webGLAvailable = true;
		// document.getElementById("overlaytext").innerHTML += "WebGL Renderer";
		// If its not supported, instantiate the canvas renderer to support all non WebGL
		// browsers
	} else {
		renderer = new THREE.CanvasRenderer();
		//document.getElementById("overlaytext").innerHTML += "Canvas Renderer";
	}

	// Set the background color
	renderer.setClearColor(0xc8c8c8);

	// Get the size of the inner window (content area) to create a full size renderer
	canvasWidth = window.innerWidth-20;
	canvasHeight = window.innerHeight-20;

	// Set the renderers size to the content areas size
	renderer.setSize(canvasWidth, canvasHeight);

	// Get the DIV element from the HTML document by its ID and append the renderers DOM
	// object to it
	document.getElementById("WebGLCanvas").appendChild(renderer.domElement);

	// Create the scene, in which all objects are stored (e. g. camera, lights,
	// geometries, ...)
	scene = new THREE.Scene();

	// Now that we have a scene, we want to look into it. Therefore we need a camera.
	// Three.js offers three camera types:
	//  - PerspectiveCamera (perspective projection)
	//  - OrthographicCamera (parallel projection)
	//  - CombinedCamera (allows to switch between perspective / parallel projection
	//    during runtime)
	// In this example we create a perspective camera. Parameters for the perspective
	// camera are ...
	// ... field of view (FOV),
	// ... aspect ratio (usually set to the quotient of canvas width to canvas height)
	// ... near and
	// ... far.
	// Near and far define the cliping planes of the view frustum. Three.js provides an
	// example (http://mrdoob.github.com/three.js/examples/
	// -> canvas_camera_orthographic2.html), which allows to play around with these
	// parameters.
	// The camera is moved 10 units towards the z axis to allow looking to the center of
	// the scene.
	// After definition, the camera has to be added to the scene.
	camera = new THREE.PerspectiveCamera(45, canvasWidth / canvasHeight, 1, 100);
	camera.position.set(0, 0, 10);
	camera.lookAt(scene.position);
	scene.add(camera);

	var boxMaterial = new THREE.MeshBasicMaterial({
		 side:THREE.DoubleSide
	});
	// Create the cube
	boxGeometry = new THREE.BoxGeometry(2.0, 2.0, 2.0);
	// Create a mesh and insert the geometry and the material. Translate the whole mesh
	// by 1.5 on the x axis and by 4 on the z axis and add the mesh to the scene.
	boxMesh = new THREE.Mesh(boxGeometry, boxMaterial);
	boxMesh.position.set(0.0, 0.0, 4.0);
	scene.add(boxMesh);

	// Load an image as texture
	var textureLoader = new THREE.TextureLoader(manager);
	for (ch = 0; ch < channelCount; ++ch) {
		for (img = 0; img < imageCount; ++img) {
			textureLoader.load(channels.path[ch].concat(img+1,".png"), function(t) {
				console.log(ch*imageCount + img);
				textureArray.push(t); //
			});
		}
	}

	// // Ambient light has no direction, it illuminates every object with the same
	// // intensity. If only ambient light is used, no shading effects will occur.
	// var ambientLight = new THREE.AmbientLight(0x101010, 1.0);
	// scene.add(ambientLight);

	// // Directional light has a source and shines in all directions, like the sun.
	// // This behaviour creates shading effects.
	// directionalLight = new THREE.DirectionalLight(0xffffff, 1.0);
	// directionalLight.position.set(0.0, 0.0, 1.0);
	// scene.add(directionalLight);

	// Add a listener for 'keydown' events. By this listener, all key events will be
	// passed to the function 'onDocumentKeyDown'. There's another event type 'keypress'.
	// It will report only the visible characters like 'a', but not the function keys
	// like 'cursor up'.
	document.addEventListener("keydown", onDocumentKeyDown, false);

	// // Ambient light has no direction, it illuminates every object with the same
	// // intensity. If only ambient light is used, no shading effects will occur.
	// ambientLight = new THREE.AmbientLight(0x404040);
	// scene.add(ambientLight);

	// // Directional light has a source and shines in all directions, like the sun.
	// // This behaviour creates shading effects.

	// directionalLight = new THREE.PointLight(0xffffff);
	// directionalLight.position.set(250,250,250);
	// scene.add(directionalLight);
}

/**
 * Select current texture to display in loaded texture arrays
 */
function selectTexture(channel, image) {
	boxMesh.material.map = textureArray[channel * imageCount + image];
	document.getElementById("overlaytext").innerHTML = channels.path[channel].concat(image+1,".png");
}

/**
 * This function is called, when a key is pushed down.
 */
 function onDocumentKeyDown(event) {
	this.currentImage = this.currentImage || 0;
	this.currentChannel = this.currentChannel || 0;

	// Get the key code of the pressed key
	var keyCode = event.which;
	if (keyCode == enums.keyboard.SPACE) {	// SWITCH CHANNEL
		if (this.currentChannel < channelCount - 1) {
			++this.currentChannel;
		} else {
			this.currentChannel = 0;
		}

	} else if(keyCode == enums.keyboard.KEY_W) {	// ROTATE UP
		xSpeed -= 0.01;
	} else if(keyCode == enums.keyboard.KEY_S) {	// ROTATE DOWN
		xSpeed += 0.01;
	} else if(keyCode == enums.keyboard.KEY_A) {	// ROTATE LEFT
		ySpeed -= 0.01;
	} else if(keyCode == enums.keyboard.KEY_D) {	// ROTATE RIGHT
		ySpeed += 0.01;

	} else if(keyCode == enums.keyboard.LEFT_ARROW) {	// NEXT IMAGE
		if (this.currentImage > 0) {
			--this.currentImage;
		} else {
			this.currentImage = imageCount - 1;
		}

	} else if(keyCode == enums.keyboard.RIGHT_ARROW) {	// PREVIOUS IMAGE
		if (this.currentImage < imageCount - 1) {
			++this.currentImage;
		} else {
			this.currentImage = 0;
		}

		// Page up
	} else if(keyCode == enums.keyboard.UP_ARROW) {	// ZOOM IN
		zTranslation += 0.2;
		// Page down
	} else if(keyCode == enums.keyboard.DOWN_ARROW) {	// ZOOM OUT
		zTranslation -= 0.2;
	}
	else if(keyCode == enums.keyboard.KEY_R) {	// RESET VIEW
		xRotation = 0.0;
		yRotation = 0.0;
		xSpeed = 0.0;
		ySpeed = 0.0;
		zTranslation = 5;
 }
	selectTexture(this.currentChannel, this.currentImage);
}

/**
* Animate the scene and call rendering.
*/
function animateScene() {
	//directionalLight.position = camera.position;
	if (texturesLoaded) {
		// Increase the x, y and z rotation of the cube
	  xRotation += xSpeed;
	  yRotation += ySpeed;
	  boxMesh.rotation.set(xRotation, yRotation, 0.0);

	  // Apply the the translation along the z axis
	  boxMesh.position.z = zTranslation;
		// Map the 3D scene down to the 2D screen (render the frame)
		renderScene();
	}

	// Define the function, which is called by the browser supported timer loop. If the
	// browser tab is not visible, the animation is paused. So 'animateScene()' is called
	// in a browser controlled loop.
	requestAnimationFrame(animateScene);
}

/**
* Render the scene. Map the 3D world to the 2D screen.
*/
function renderScene() {
	renderer.render(scene, camera);
}

//   Old Script
// var scene = new THREE.Scene();
// var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
// var renderer = new THREE.WebGLRenderer();

// renderer.setSize( window.innerWidth/2, window.innerHeight/2 );
// renderer.setClearColor(0xc8c8c8);
// document.getElementById("WebGLCanvas").appendChild( renderer.domElement );

// // (width, height, depth)
// var geometry = new THREE.BoxGeometry( 5, 5, 5 );

// 		var loader = new THREE.TextureLoader();
// 		  loader.load("images/24.png", function(texture){
//  			var material = new THREE.MeshLambertMaterial({map: texture});
//  			cube= new THREE.Mesh(geometry, material);
//  			scene.add(cube);
// 		});

// //var material = new THREE.MeshLambertMaterial( { color: 0xf6546a } );
// //var cube = new THREE.Mesh( geometry, material );
// //scene.add( cube );

// // (color, intensity)
// var light = new THREE.PointLight(0xffffff, 1.2);
// // (x, y, z)
// light.position.set(0, 0, 6);
// scene.add(light);

// camera.position.z = 10;

// var render = function render() {
// 	requestAnimationFrame( render );
// 	cube.rotation.x += 0.01;
// 	cube.rotation.y += 0.01;
// 	renderer.render( scene, camera );
// }
// render();
<|endoftext|>