<commit_before>$(function() {
	if(window.location.protocol === "https:") {
		location.href = "http://mywebservice.info/beauty/";
	}

	var url = "http://mywebservice.info/beautyUniversity/data_out/school/university";

	$( '.swipebox' ).swipebox( {
		afterOpen: function() {
			$("div.slide > img").attr("data-caption", "This test data-caption");
			$('img.caption').captionjs({
				'class_name'      : 'captionjs', // Class name for each

				'schema'          : true,        // Use schema.org markup (i.e., itemtype, itemprop)
				'mode'            : 'stacked',   // default | stacked | animated | hide
				'debug_mode'      : true,       // Output debug info to the JS console
				'force_dimensions': true,        // Force the dimensions in case they cannot be detected (e.g., image is not yet painted to viewport)
				'is_responsive'   : true,       // Ensure the figure and image change size when in responsive layout. Requires a container to control responsiveness!
				'inherit_styles'  : false        // Have the caption.js container inherit box-model properties from the original image
			});
		}
	});

	jsonGet(url);
	$(window).on('ajaxComplete', function() {
  		setTimeout(function() {
  			$(window).lazyLoadXT();
  		}, 50);
	});

	$("#go-top").click(function(event) {
		event.preventDefault();
		$("html, body").animate({ scrollTop: 0 }, "slow");
	});

	$("#go-school-btn").click(function(event) {
		event.preventDefault();
		$("#img-contents").html("");
		if($("#fans-page-name").text() === "表特大學") {
			$("#go-school-btn").text("表特大學");
			$("#fans-page-name").text("表特輔仁");
			url = "http://mywebservice.info/beautyUniversity/data_out/school/FJU";
		}
		else {
			$("#go-school-btn").text("表特輔仁");
			$("#fans-page-name").text("表特大學");
			url = "http://mywebservice.info/beautyUniversity/data_out/school/university";
		}
		jsonGet(url);
	});

	/*
	$("#highchart-btn").click(function(event) {
		event.preventDefault();
		var str = "";
		if($("#fans-page-name").text() === "表特輔仁") {
			str = "FJU";
		}
		else {
			str = "university";
		}
		$("#img-contents").html("");
		$("#chart-container").html("");

		//using high chart

		 $('#chart-container').highcharts({
			chart: {
				plotBackgroundColor: null,
				plotBorderWidth: null,
				plotShadow: false,
				type: 'pie'
			},
			title: {
				text: 'Browser market shares January, 2015 to May, 2015'
			},
			tooltip: {
				pointFormat: '{series.name}: {point.percentage:.1f}%'
			},
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '{point.name}: {point.percentage:.1f} %',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }
                }
            }
        },
        series: [{
            name: 'Brands',
            colorByPoint: true,
            data: [{
                name: 'Microsoft Internet Explorer',
                y: 56.33
            }, {
                name: 'Chrome',
                y: 24.03,
                sliced: true,
                selected: true
            }, {
                name: 'Firefox',
                y: 10.38
            }, {
                name: 'Safari',
                y: 4.77
            }, {
                name: 'Opera',
                y: 0.91
            }, {
                name: 'Proprietary or Undetectable',
                y: 0.2
            }]
        }]
    });
	});
	*/
});

function jsonGet(url) {
	$.getJSON(url, function(data) {
		var str = "";
		var j = 0;
		if(url.indexOf("university") !== -1) {
			for (var i = data.length - 1; i >= 0; i--) {
				if(data[i]["message"] === "" || data[i]["object_id"] === "") {
					continue;
				}

				str += "";
				str += "";
				str += "";
				j++;
			}
		}
		else {
			for (var i = 0; i < data.length; i++) {
				if(data[i]["message"] === "" || data[i]["object_id"] === "") {
					continue;
				}

				str += "";
				str += "";
				str += "";
				j++;
			}
		}
		console.log(j);
		$("#img-contents").append(str);
	 });
}

function getAnalytic(url) {

}<commit_msg>add beforeopen in swipebox<commit_after>$(function() {
	if(window.location.protocol === "https:") {
		location.href = "http://mywebservice.info/beauty/";
	}

	var url = "http://mywebservice.info/beautyUniversity/data_out/school/university";

	$( '.swipebox' ).swipebox( {
		beforeopen: function() {
			$("div.slide > img").attr("data-caption", "This test data-caption");
		},
		afterOpen: function() {
			$("div.slide > img").captionjs({
				'class_name'      : 'captionjs', // Class name for each

				'schema'          : true,        // Use schema.org markup (i.e., itemtype, itemprop)
				'mode'            : 'stacked',   // default | stacked | animated | hide
				'debug_mode'      : true,       // Output debug info to the JS console
				'force_dimensions': true,        // Force the dimensions in case they cannot be detected (e.g., image is not yet painted to viewport)
				'is_responsive'   : true,       // Ensure the figure and image change size when in responsive layout. Requires a container to control responsiveness!
				'inherit_styles'  : false        // Have the caption.js container inherit box-model properties from the original image
			});
		}
	});

	jsonGet(url);
	$(window).on('ajaxComplete', function() {
  		setTimeout(function() {
  			$(window).lazyLoadXT();
  		}, 50);
	});

	$("#go-top").click(function(event) {
		event.preventDefault();
		$("html, body").animate({ scrollTop: 0 }, "slow");
	});

	$("#go-school-btn").click(function(event) {
		event.preventDefault();
		$("#img-contents").html("");
		if($("#fans-page-name").text() === "表特大學") {
			$("#go-school-btn").text("表特大學");
			$("#fans-page-name").text("表特輔仁");
			url = "http://mywebservice.info/beautyUniversity/data_out/school/FJU";
		}
		else {
			$("#go-school-btn").text("表特輔仁");
			$("#fans-page-name").text("表特大學");
			url = "http://mywebservice.info/beautyUniversity/data_out/school/university";
		}
		jsonGet(url);
	});

	/*
	$("#highchart-btn").click(function(event) {
		event.preventDefault();
		var str = "";
		if($("#fans-page-name").text() === "表特輔仁") {
			str = "FJU";
		}
		else {
			str = "university";
		}
		$("#img-contents").html("");
		$("#chart-container").html("");

		//using high chart

		 $('#chart-container').highcharts({
			chart: {
				plotBackgroundColor: null,
				plotBorderWidth: null,
				plotShadow: false,
				type: 'pie'
			},
			title: {
				text: 'Browser market shares January, 2015 to May, 2015'
			},
			tooltip: {
				pointFormat: '{series.name}: {point.percentage:.1f}%'
			},
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '{point.name}: {point.percentage:.1f} %',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }
                }
            }
        },
        series: [{
            name: 'Brands',
            colorByPoint: true,
            data: [{
                name: 'Microsoft Internet Explorer',
                y: 56.33
            }, {
                name: 'Chrome',
                y: 24.03,
                sliced: true,
                selected: true
            }, {
                name: 'Firefox',
                y: 10.38
            }, {
                name: 'Safari',
                y: 4.77
            }, {
                name: 'Opera',
                y: 0.91
            }, {
                name: 'Proprietary or Undetectable',
                y: 0.2
            }]
        }]
    });
	});
	*/
});

function jsonGet(url) {
	$.getJSON(url, function(data) {
		var str = "";
		var j = 0;
		if(url.indexOf("university") !== -1) {
			for (var i = data.length - 1; i >= 0; i--) {
				if(data[i]["message"] === "" || data[i]["object_id"] === "") {
					continue;
				}

				str += "";
				str += "";
				str += "";
				j++;
			}
		}
		else {
			for (var i = 0; i < data.length; i++) {
				if(data[i]["message"] === "" || data[i]["object_id"] === "") {
					continue;
				}

				str += "";
				str += "";
				str += "";
				j++;
			}
		}
		console.log(j);
		$("#img-contents").append(str);
	 });
}

function getAnalytic(url) {

}<|endoftext|>


<commit_before>import React from 'react';

// 7 Hour Forecast

const HourWeather = (props) => {
  const showHours = () => {
    const weatherHours = props.weather;

    const listHours =
    weatherHours.map((obj) => {
      return (

            {obj.time}

            {obj.conciseCondition}

      );
    });
    return listHours;
  };

  return (

      {showHours()}

  );
};

export default HourWeather;
<commit_msg>fix small bug<commit_after>import React from 'react';

// 7 Hour Forecast

const HourWeather = (props) => {
  const showHours = () => {
    const weatherHours = props.weather;

    const listHours =
    weatherHours.map((obj) => {
      return (

            {obj.time}

            {obj.temp}°F

            {obj.conciseCondition}

      );
    });
    return listHours;
  };

  return (

      {showHours()}

  );
};

export default HourWeather;
<|endoftext|>


<commit_before>// Copyright 2019, University of Colorado Boulder

/**
 * Links for the AboutDialog, used in phet brand and phet-io brand since they are the same for both.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Michael Kauzmann (PhET Interactive Simulations)
 * @author Chris Klusendorf (PhET Interactive Simulations)
 */
define( require => {
  'use strict';

  // modules
  const brand = require( 'BRAND/../../js/brand' );

  // strings
  const termsPrivacyAndLicensingString = require( 'string!JOIST/termsPrivacyAndLicensing' );
  const translationCreditsLinkString = require( 'string!JOIST/translation.credits.link' );
  const thirdPartyCreditsLinkString = require( 'string!JOIST/thirdParty.credits.link' );

  /**
   * @param {string} simName
   * @param {string} locale
   * @returns {Object[]}
   * @public
   */
  const getLinks = ( simName, locale ) => {
    return [
      {
        text: termsPrivacyAndLicensingString,
        url: 'http://phet.colorado.edu/en/licensing/html',
        tandemName: 'termsPrivacyAndLicensingLinkText'
      },
      {
        text: translationCreditsLinkString,
        url: 'http://phet.colorado.edu/translation-credits?simName=' + encodeURIComponent( simName ) + '&locale=' + encodeURIComponent( locale ),
        tandemName: 'translationCreditsLinkText'
      },
      {
        text: thirdPartyCreditsLinkString,
        url: 'http://phet.colorado.edu/third-party-credits?simName=' + encodeURIComponent( simName ) +
             '&locale=' + encodeURIComponent( locale ) + '#' + simName,
        tandemName: 'thirdPartyCreditsLinkText'
      }
    ];
  };

  return brand.register( 'getLinks', getLinks );
} );
<commit_msg>update copyright dates from daily grunt work<commit_after>// Copyright 2019-2020, University of Colorado Boulder

/**
 * Links for the AboutDialog, used in phet brand and phet-io brand since they are the same for both.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Michael Kauzmann (PhET Interactive Simulations)
 * @author Chris Klusendorf (PhET Interactive Simulations)
 */
define( require => {
  'use strict';

  // modules
  const brand = require( 'BRAND/../../js/brand' );

  // strings
  const termsPrivacyAndLicensingString = require( 'string!JOIST/termsPrivacyAndLicensing' );
  const translationCreditsLinkString = require( 'string!JOIST/translation.credits.link' );
  const thirdPartyCreditsLinkString = require( 'string!JOIST/thirdParty.credits.link' );

  /**
   * @param {string} simName
   * @param {string} locale
   * @returns {Object[]}
   * @public
   */
  const getLinks = ( simName, locale ) => {
    return [
      {
        text: termsPrivacyAndLicensingString,
        url: 'http://phet.colorado.edu/en/licensing/html',
        tandemName: 'termsPrivacyAndLicensingLinkText'
      },
      {
        text: translationCreditsLinkString,
        url: 'http://phet.colorado.edu/translation-credits?simName=' + encodeURIComponent( simName ) + '&locale=' + encodeURIComponent( locale ),
        tandemName: 'translationCreditsLinkText'
      },
      {
        text: thirdPartyCreditsLinkString,
        url: 'http://phet.colorado.edu/third-party-credits?simName=' + encodeURIComponent( simName ) +
             '&locale=' + encodeURIComponent( locale ) + '#' + simName,
        tandemName: 'thirdPartyCreditsLinkText'
      }
    ];
  };

  return brand.register( 'getLinks', getLinks );
} );
<|endoftext|>


<commit_before>/** Create a grid by uploading files */

import Icon from '@conveyal/woonerf/components/icon'
import React, {Component, PropTypes} from 'react'

import {File, Text} from './input'
import {Body, Heading, Panel} from './panel'
import messages from '../utils/messages'

export default class CreateGrid extends Component {
  static propTypes = {
    projectId: PropTypes.string.isRequired,
    fetch: PropTypes.func.isRequired,
    finish: PropTypes.func.isRequired
  }

  state = {
    uploading: false,
    csv: false,
    id: null
  }

  render () {
    const {uploading} = this.state

    return (
      <Panel>
        <Heading>{messages.analysis.createGrid}</Heading>
        {uploading ? <Uploading /> : this.renderForm()}
      </Panel>
    )
  }

  onSubmit = (e) => {
    e.preventDefault()
    const {fetch, finish, projectId} = this.props
    const body = new window.FormData(e.target)
    this.setState({ ...this.state, uploading: true })

    fetch({
      url: `/api/grid/${projectId}`,
      options: {
        body,
        method: 'post'
      },
      next (error, response) {
        if (error) {
          window.alert(error)
          console.error(error)
        } else {
          finish(projectId)
        }
      }
    })
  }

  setFiles = (e) => {
    const files = e.target.files
    // signal if it's a CSV file; if so, we need to show extra fields
    // if it's a shapefile, this is not needed
    const csv = files.length === 1 && files[0].name.toLowerCase().endsWith('.csv')
    this.setState({...this.state, files, csv})
  }

  renderForm () {
    const {csv, files, name, uploading} = this.state

    return
      <form onSubmit={this.onSubmit} method='post' encType='multipart/form-data'>
        <Text name='Name'
          label={messages.analysis.gridName}
          placeholder={messages.analysis.gridName}
          value={name}
          onChange={e => this.setState({...this.state, name: e.target.value})}
          />

        <File
          multiple
          label={messages.analysis.gridFiles}
          name='files'
          onChange={this.setFiles}
          value={files}
          />

        {csv && this.renderCsvFields()}

        <input
          className='btn btn-block btn-success'
          disabled={uploading || !name || !files}
          type='submit'
          value={messages.analysis.createGrid}
          />
      </form>

  }

  /** CSV files don't have standard lat and lon column names, so make the user specify them */
  renderCsvFields () {
    const { latField, lonField } = this.state
    return
      <Text name='latField'
        label={messages.analysis.latField}
        placeholder={messages.analysis.latField}
        value={latField}
        onChange={e => this.setState({...this.state, latField: e.target.value})}
        />

      <Text name='lonField'
        label={messages.analysis.lonField}
        placeholder={messages.analysis.lonField}
        value={lonField}
        onChange={e => this.setState({...this.state, lonField: e.target.value})}
        />

  }
}

function Uploading () {
  return (

      <Icon type='spinner' className='fa-spin pull-left' />
      {messages.analysis.uploading}

  )
}
<commit_msg>fix(grid): Don't set value directly for file upload.<commit_after>/** Create a grid by uploading files */

import Icon from '@conveyal/woonerf/components/icon'
import React, {Component, PropTypes} from 'react'

import {File, Text} from './input'
import {Body, Heading, Panel} from './panel'
import messages from '../utils/messages'

export default class CreateGrid extends Component {
  static propTypes = {
    projectId: PropTypes.string.isRequired,
    fetch: PropTypes.func.isRequired,
    finish: PropTypes.func.isRequired
  }

  state = {
    uploading: false,
    csv: false,
    id: null
  }

  render () {
    const {uploading} = this.state

    return (
      <Panel>
        <Heading>{messages.analysis.createGrid}</Heading>
        {uploading ? <Uploading /> : this.renderForm()}
      </Panel>
    )
  }

  onSubmit = (e) => {
    e.preventDefault()
    const {fetch, finish, projectId} = this.props
    const body = new window.FormData(e.target)
    this.setState({ ...this.state, uploading: true })

    fetch({
      url: `/api/grid/${projectId}`,
      options: {
        body,
        method: 'post'
      },
      next (error, response) {
        if (error) {
          window.alert(error)
          console.error(error)
        } else {
          finish(projectId)
        }
      }
    })
  }

  setFiles = (e) => {
    const files = e.target.files
    // signal if it's a CSV file; if so, we need to show extra fields
    // if it's a shapefile, this is not needed
    const csv = files.length === 1 && files[0].name.toLowerCase().endsWith('.csv')
    this.setState({...this.state, files, csv})
  }

  renderForm () {
    const {csv, files, name, uploading} = this.state

    return
      <form onSubmit={this.onSubmit} method='post' encType='multipart/form-data'>
        <Text name='Name'
          label={messages.analysis.gridName}
          placeholder={messages.analysis.gridName}
          value={name}
          onChange={e => this.setState({...this.state, name: e.target.value})}
          />

        <File
          multiple
          label={messages.analysis.gridFiles}
          name='files'
          onChange={this.setFiles}
          />

        {csv && this.renderCsvFields()}

        <input
          className='btn btn-block btn-success'
          disabled={uploading || !name || !files}
          type='submit'
          value={messages.analysis.createGrid}
          />
      </form>

  }

  /** CSV files don't have standard lat and lon column names, so make the user specify them */
  renderCsvFields () {
    const { latField, lonField } = this.state
    return
      <Text name='latField'
        label={messages.analysis.latField}
        placeholder={messages.analysis.latField}
        value={latField}
        onChange={e => this.setState({...this.state, latField: e.target.value})}
        />

      <Text name='lonField'
        label={messages.analysis.lonField}
        placeholder={messages.analysis.lonField}
        value={lonField}
        onChange={e => this.setState({...this.state, lonField: e.target.value})}
        />

  }
}

function Uploading () {
  return (

      <Icon type='spinner' className='fa-spin pull-left' />
      {messages.analysis.uploading}

  )
}
<|endoftext|>


<commit_before>/*

The MIT License (MIT)

Copyright (c) 2015 Yuryu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

var payout = [
	NaN, NaN, NaN, NaN, NaN, NaN,
	10000, 36, 720, 360, 80, 252, 108, 72,
	54, 180, 72, 180, 119, 36, 306, 1080, 144, 1800, 3600
];

var size = 3;
var requiredNums = 4;
var payoutMin = 6;
var payoutMax = 24;
var payoutNum = payoutMax - payoutMin + 1;

var currentScrollPosition = 0;

function createOptions(n) {
	var result = "<option value='0' selected='selected'>0</option>";
	for ( var i = 1; i <= n; i++ ) {
		result += "<option value='" + i + "'>" + i + "</option>"
	}
	return result;
}

function rowColStr(row, col) {
	return "r" + row + "c" + col;
}

function validateScratch() {
	var ints = {};
	var count = 0;
	var success = true;
	for ( var i = 0; i < size * size; i++ ) {
		var v = parseInt($("#scratch select[name='" + i + "'] option:selected").val());
		$("#scratch select[name='" + i + "']").parent()
			.removeClass("has-error").removeClass("success")
			.removeClass("danger");
		if ( v != 0 ) {
			if ( ints[v] ) {
				ints[v].forEach(function(v, i, a){
					$("#scratch select[name='" + v + "']").parent()
						.addClass("has-error").addClass("danger");
				});
				$("#scratch select[name='" + i + "']").parent()
					.addClass("has-error").addClass("danger");
				success = false;
			}
			ints[v] = [i];
			count++;
		}
	}
	if ( count > requiredNums ) {
		for ( var i in ints ) {
			if ( ints.hasOwnProperty(i) ) {
				ints[i].forEach(function(v, i, a){
					$("#scratch select[name='" + v + "']").parent()
						.addClass("has-error").addClass("danger");
				});
			}
		}
	}
	return count == requiredNums && success;
}

function createScratch(table) {
	var c = 0;
	var options = createOptions(size * size);
	for (var row = 0; row < size; row++ ) {
		var tr = $("

").appendTo(table);
		tr.append("	")
		for ( var col = 0; col < size; col++) {
			tr.append("<select name='" + c + "' class='form-control'>"
				+ options + "</select>	");
			c++;
		}
	}
	$("#scratch select").change(function() {
		if ( validateScratch() ) {
			solveScratch();
			$("#scratchform input[name='solve']").removeAttr("disabled");
		} else {
			$("#scratch .exp").removeClass("success");
			$("#scratch .exp").html(" ");
			$("#scratchform input[name='solve']").attr("disabled", "disabled");
		}
	});
}

function highlightHorizontal(row) {
	for ( var i = 0; i < size; i++ ) {
		$("#" + rowColStr(row, i)).addClass("success");
	}
}

function highlightVertical(col) {
	for ( var i = 0; i < size; i++ ) {
		$("#" + rowColStr(i, col)).addClass("success");
	}
}

function highlightDiagonal(dir) {
	for ( var i = 0 ; i < size; i++ ) {
		var col = i;
		if ( dir == 1 ) {
			col = size - i - 1;
		}
		$("#" + rowColStr(i, col)).addClass("success");
	}
}

function solveScratch() {
	parsePayout();
	var row;
	var table = [];
	for ( var i = 0; i < size * size; i++ ) {
		if ( i % size == 0 ) {
			row = [];
			table.push(row);
		}
		row.push(parseInt($("#scratch select[name='" + i + "'] option:selected").val()));
	}
	var solver = new Solver();
	var result = solver.solve(table, payout);
	var maxindex = 0;
	var maxvalue = 0;
	for ( var i = 0; i < result.length; i++ ) {
		if ( i < size ) {
			$("#er" + i).text(Math.floor(result[i]));
		} else if ( i < size * 2 ) {
			$("#ec" + (i - size)).text(Math.floor(result[i]));
		} else {
			$("#ed" + (i - size * 2)).text(Math.floor(result[i]));
		}
		if ( maxvalue < result[i] ) {
			maxindex = i;
			maxvalue = result[i];
		}
	}
	$("#scratch .exp").removeClass("success");
	if ( maxindex < size ) {
		highlightHorizontal(maxindex);
		$("#er" + maxindex).addClass("success");
	} else if ( maxindex < size * 2 ) {
		highlightVertical(maxindex - size);
		$("#ec" + (maxindex - size)).addClass("success");
	} else {
		highlightDiagonal(maxindex - size * 2);
		$("#ed" + (maxindex - size * 2)).addClass("success");
	}

}

function resetScratch() {
	$("#scratch td").removeClass("has-error").removeClass("success")
			.removeClass("danger");
	$("#scratchform input[name='solve']").attr("disabled", "disabled");
	$("#scratch select").val("0");
	$("#scratch .exp").html(" ");
	$("#scratch .exp").removeClass("success");
}

function createPayoutCells(n) {
	return "" + n + "	" +
	"<input type='text' class='form-control' id='p" + n +
	"' value='" + payout[n] + "'>	";
}

function createPayout(table) {
	for ( var i = payoutMin; i < payoutMin + Math.floor((payoutNum) / 2); i++ ) {
		table.append("
" + createPayoutCells(i) +
			createPayoutCells(i + Math.floor((payoutNum) / 2) + 1) + "
");
	}
	if ( payoutNum % 2 == 1 ) {
		var p = Math.floor(payoutNum / 2) + payoutMin;
		table.append("
" + createPayoutCells(p) + "
");
	}
}

function parsePayout() {
	for ( var i = payoutMin; i <= payoutMax; i++ ) {
		payout[i] = parseInt($("#p" + i).val());
	}
}

$(document).ready(function() {
	createScratch($("#scratch tbody"));
	createPayout($("#payout tbody"));
	var i18nopts = {
		fallbackLng: 'en',
		detectLngQS: 'lang',
		resGetPath: 'locales/__ns__-__lng__.json'
	};
	i18n.init(i18nopts, function (t) {
			$("title").text(t("title"));
			$('.i18n').i18n();
	});
	$(document).scroll(function(){
    	currentScrollPosition = $(this).scrollTop();
	});
	$("#scratch select").focus(function () {
		$(document).scrollTop(currentScrollPosition);
	});
});
<commit_msg>Allow users to preview from 2 cells<commit_after>/*

The MIT License (MIT)

Copyright (c) 2015 Yuryu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

var payout = [
	NaN, NaN, NaN, NaN, NaN, NaN,
	10000, 36, 720, 360, 80, 252, 108, 72,
	54, 180, 72, 180, 119, 36, 306, 1080, 144, 1800, 3600
];

var size = 3;
var requiredNums = 2;
var maxRevealedNums = 4;
var payoutMin = 6;
var payoutMax = 24;
var payoutNum = payoutMax - payoutMin + 1;

var currentScrollPosition = 0;

function createOptions(n) {
	var result = "<option value='0' selected='selected'>0</option>";
	for ( var i = 1; i <= n; i++ ) {
		result += "<option value='" + i + "'>" + i + "</option>"
	}
	return result;
}

function rowColStr(row, col) {
	return "r" + row + "c" + col;
}

function clearCellClass(cell) {
	cell.removeClass("has-error").removeClass("success")
		.removeClass("active").removeClass("danger");
}

function validateScratch() {
	var ints = {};
	var count = 0;
	var success = true;
	var table = [], row = [];
	for ( var i = 0; i < size * size; i++ ) {
		var v = parseInt($("#scratch select[name='" + i + "'] option:selected").val());
		row.push(v);
		if ( i % size == (size - 1) ) {
			table.push(row);
		}
		clearCellClass($("#scratch select[name='" + i + "']").parent());
		if ( v != 0 ) {
			if ( ints[v] ) {
				ints[v].forEach(function(v, i, a){
					$("#scratch select[name='" + v + "']").parent()
						.addClass("has-error").addClass("danger");
				});
				$("#scratch select[name='" + i + "']").parent()
					.addClass("has-error").addClass("danger");
				success = false;
			}
			ints[v] = [i];
			count++;
		}
	}
	if ( count > maxRevealedNums ) {
		for ( var i in ints ) {
			if ( ints.hasOwnProperty(i) ) {
				ints[i].forEach(function(v, i, a){
					$("#scratch select[name='" + v + "']").parent()
						.addClass("has-error").addClass("danger");
				});
			}
		}
		return false;
	}
	return count >= requiredNums && success;
}

function createScratch(table) {
	var c = 0;
	var options = createOptions(size * size);
	for (var row = 0; row < size; row++ ) {
		var tr = $("

").appendTo(table);
		tr.append("	")
		for ( var col = 0; col < size; col++) {
			tr.append("<select name='" + c + "' class='form-control'>"
				+ options + "</select>	");
			c++;
		}
	}
	$("#scratch select").change(function() {
		if ( validateScratch() ) {
			solveScratch();
			$("#scratchform input[name='solve']").removeAttr("disabled");
		} else {
			clearCellClass($("#scratch .exp"));
			$("#scratch .exp").html(" ");
			$("#scratchform input[name='solve']").attr("disabled", "disabled");
		}
	});
}

function highlightHorizontal(row, c) {
	for ( var i = 0; i < size; i++ ) {
		$("#" + rowColStr(row, i)).addClass(c);
	}
}

function highlightVertical(col, c) {
	for ( var i = 0; i < size; i++ ) {
		$("#" + rowColStr(i, col)).addClass(c);
	}
}

function highlightDiagonal(dir, c) {
	for ( var i = 0 ; i < size; i++ ) {
		var col = i;
		if ( dir == 1 ) {
			col = size - i - 1;
		}
		$("#" + rowColStr(i, col)).addClass(c);
	}
}

function solveScratch() {
	parsePayout();
	var row;
	var table = [];
	var revealed = 0;
	for ( var i = 0; i < size * size; i++ ) {
		if ( i % size == 0 ) {
			row = [];
			table.push(row);
		}
		var v = parseInt($("#scratch select[name='" + i + "'] option:selected").val());
		if ( v != 0 ) revealed++;
		row.push(v);
	}
	var solver = new Solver();
	var result = solver.solve(table, payout);
	var maxindex = 0;
	var maxvalue = 0;
	for ( var i = 0; i < result.length; i++ ) {
		if ( i < size ) {
			$("#er" + i).text(Math.floor(result[i]));
		} else if ( i < size * 2 ) {
			$("#ec" + (i - size)).text(Math.floor(result[i]));
		} else {
			$("#ed" + (i - size * 2)).text(Math.floor(result[i]));
		}
		if ( maxvalue < result[i] ) {
			maxindex = i;
			maxvalue = result[i];
		}
	}
	$("#scratch .exp").removeClass("success").removeClass("active");
	var highlightClass = "success";
	if ( revealed != maxRevealedNums ) highlightClass = "active";
	if ( maxindex < size ) {
		highlightHorizontal(maxindex, highlightClass);
		$("#er" + maxindex).addClass(highlightClass);
	} else if ( maxindex < size * 2 ) {
		highlightVertical(maxindex - size, highlightClass);
		$("#ec" + (maxindex - size)).addClass(highlightClass);
	} else {
		highlightDiagonal(maxindex - size * 2, highlightClass);
		$("#ed" + (maxindex - size * 2)).addClass(highlightClass);
	}

}

function resetScratch() {
	clearCellClass($("#scratch td"));
	$("#scratchform input[name='solve']").attr("disabled", "disabled");
	$("#scratch select").val("0");
	$("#scratch .exp").html(" ");
	clearCellClass($("#scratch .exp"));
}

function createPayoutCells(n) {
	return "" + n + "	" +
	"<input type='text' class='form-control' id='p" + n +
	"' value='" + payout[n] + "'>	";
}

function createPayout(table) {
	for ( var i = payoutMin; i < payoutMin + Math.floor((payoutNum) / 2); i++ ) {
		table.append("
" + createPayoutCells(i) +
			createPayoutCells(i + Math.floor((payoutNum) / 2) + 1) + "
");
	}
	if ( payoutNum % 2 == 1 ) {
		var p = Math.floor(payoutNum / 2) + payoutMin;
		table.append("
" + createPayoutCells(p) + "
");
	}
}

function parsePayout() {
	for ( var i = payoutMin; i <= payoutMax; i++ ) {
		payout[i] = parseInt($("#p" + i).val());
	}
}

$(document).ready(function() {
	createScratch($("#scratch tbody"));
	createPayout($("#payout tbody"));
	var i18nopts = {
		fallbackLng: 'en',
		detectLngQS: 'lang',
		resGetPath: 'locales/__ns__-__lng__.json'
	};
	i18n.init(i18nopts, function (t) {
			$("title").text(t("title"));
			$('.i18n').i18n();
	});
	$(document).scroll(function(){
    	currentScrollPosition = $(this).scrollTop();
	});
	$("#scratch select").focus(function () {
		$(document).scrollTop(currentScrollPosition);
	});
});
<|endoftext|>


<commit_before>/* Conway's Game of Life */

document.addEventListener('DOMContentLoaded', () => {
  window.gol = {

    // BASIC ATTRIBUTES =======================================================

    cellColor: '#37474f',
    canvas: document.getElementById('gol'),
    ctx: document.getElementById('gol').getContext('2d'),

    fps: 15,

    idealCellSize: 20,
    cellSize: [20, 20], // This gets updated dynamically.

    boardSize: [10, 10],

    board: undefined,

    // HELPER FUNCTIONS =======================================================

    _getBlankBoard() {
      return new Array(this.boardSize[0]).fill(0).map(
        () => new Array(this.boardSize[1]).fill(false)
      );
    },

    _getRandomRow() {
      return new Array(window.gol.boardSize[0]).fill(0).map(() => Math.random() < 0.125);
    },

    // RENDERING FUNCTIONS ====================================================
    // These functions connect the simulation to the browser

    // Called to update the game if the canvas size
    // changes.
    sizeChanged() {
      // Spare loop variables
      let i;

      const width = window.gol.canvas.offsetWidth;
      const height = window.gol.canvas.offsetHeight;

      // Update canvas coordinate system
      window.gol.canvas.setAttribute('width', width);
      window.gol.canvas.setAttribute('height', height);

      // Update tile size by finding a width that will
      // evenly fill the canvas and is closest to the
      // idealCellSize, then doing the same thing for
      // height.

      window.gol.cellSize = [
        width / Math.round(width / window.gol.idealCellSize),
        height / Math.round(height / window.gol.idealCellSize),
      ];

      // When board size changes, kill cells that are
      // cut off and randomize new terrain.

      const oldBoardSize = window.gol.boardSize;  // Store old size
      window.gol.boardSize = [  // Adjust size
        Math.round(width / window.gol.cellSize[0]),
        Math.round(height / window.gol.cellSize[1]),
      ];
      const diff = [  // Calculate size difference
        window.gol.boardSize[0] - oldBoardSize[0],
        window.gol.boardSize[1] - oldBoardSize[1],
      ];

      // Kill dead cells

      if (diff[0] < 0) {
        window.gol.board = window.gol.board.slice(0, window.gol.boardSize[0]);
      }
      if (diff[1] < 0) {
        window.gol.board = window.gol.board.map(row => row.slice(0, window.gol.boardSize[1]));
      }

      // Populate new cells

      // Add new rows filled with random cells
      for (i = 0; i < diff[0]; i += 1) {
        window.gol.board.push(window.gol._getRandomRow());
      }
      // Add new random cells to existing rows (new columns)
      for (i = 0; i < diff[1]; i += 1) {
        for (let k = 0; k < window.gol.board.length; k += 1) {
          window.gol.board[k].push(Math.random() < 0.125);
        }
      }

      window.gol.redraw();
    },

    // Randomize the game state

    randomize() {
      this.board = this._getBlankBoard().map(() => this._getRandomRow());
    },

    // Render the board on the canvas

    redraw() {
      const width = this.canvas.getAttribute('width');
      const height = this.canvas.getAttribute('height');

      this.ctx.clearRect(0, 0, width, height);
      this.ctx.fillStyle = this.cellColor;
      // Render board
      for (let x = 0; x < this.boardSize[0]; x += 1) {
        for (let y = 0; y < this.boardSize[1]; y += 1) {
          if (this.board[x][y]) {
            this.ctx.fillRect(
              this.cellSize[0] * x,
              this.cellSize[1] * y,
              this.cellSize[0],
              this.cellSize[1]
            );
          }
        }
      }
    },

    // GAME LOGIC =============================================================

    countLiveNeighbors(x, y) {
      // Is there room in directions of:
      //   - negative x
      //   - negative y
      //   - positive x
      //   - positive y
      const xroomneg = x > 0;
      const yroomneg = y > 0;
      const xroompos = x < this.boardSize[0] - 1;
      const yroompos = y < this.boardSize[1] - 1;

      const neighbors = [
        // above
        yroomneg && this.board[x][y - 1],
        // above right
        xroompos && yroomneg && this.board[x + 1][y - 1],
        // right
        xroompos && this.board[x + 1][y],
        // below right
        xroompos && yroompos && this.board[x + 1][y + 1],
        // below
        yroompos && this.board[x][y + 1],
        // below left
        xroomneg && yroompos && this.board[x - 1][y + 1],
        // left
        xroomneg && this.board[x - 1][y],
        // above and left
        xroomneg && yroompos && this.board[x - 1][y - 1]
      ];

      // Number of true values in neighbors array
      return neighbors.filter(n => n).length;
    },

    judgeFate(isLive, liveNeighbors) {
      if (isLive) {
        // Any live cell with fewer than 2 live neighbors
        // dies of underpopulation; any live cell with more
        // than three dies of overpopulation.
        return (liveNeighbors === 2 || liveNeighbors === 3);
      }

      // Any dead cell with exactly 3 neighbors is born
      return liveNeighbors === 3;
    },

    step() {
      const newState = this._getBlankBoard();

      for (let x = 0; x < this.boardSize[0]; x += 1) {
        for (let y = 0; y < this.boardSize[1]; y += 1) {
          newState[x][y] = this.judgeFate(
            this.board[x][y],
            this.countLiveNeighbors(x, y)
          );
        }
      }

      this.board = newState;
    },

    // USER INTERACTION =======================================================

    // On a desktop computer, cells are born
    // when moused over. On a mobile device
    // it's wherever a touch occurs or is dragged.
    interacted(e) {
      // Position of the canvas in the viewport
      const bbox = window.gol.canvas.getBoundingClientRect();
      // Position of the mouse in the viewport
      const absx = e.clientX;
      const absy = e.clientY;

      // If these two positions intersect:
      if (absx > bbox.left &&
          absy > bbox.top &&
          absx < bbox.right &&
          absy < bbox.bottom
      ) {
        // Calculate mouse position relative to canvas
        const relx = absx - bbox.left;
        const rely = absy - bbox.top;
        // Calculate cell position
        const cellx = Math.floor(relx / window.gol.cellSize[0]);
        const celly = Math.floor(rely / window.gol.cellSize[1]);

        window.gol.board[cellx][celly] = true;
      }
    },

    // CONTROL FUNCTIONS ======================================================

    // Begin the loop

    start() {
      window.gol.step();
      window.gol.redraw();
      setTimeout(() => {
        requestAnimationFrame(window.gol.start);
      }, 1000 / window.gol.fps);
    },

    // Initialize and begin

    init() {
      // Temporary board
      this.board = this._getBlankBoard();
      // Calculate sizes
      this.sizeChanged();
      // Initialize board
      this.board = this._getBlankBoard();
      this.randomize();
      this.start();
    }
  };

  window.addEventListener('resize', window.gol.sizeChanged);
  document.addEventListener('mousemove', window.gol.interacted);
  window.gol.init();
});
<commit_msg>Add dangling commas<commit_after>/* Conway's Game of Life */

document.addEventListener('DOMContentLoaded', () => {
  window.gol = {

    // BASIC ATTRIBUTES =======================================================

    cellColor: '#37474f',
    canvas: document.getElementById('gol'),
    ctx: document.getElementById('gol').getContext('2d'),

    fps: 15,

    idealCellSize: 20,
    cellSize: [20, 20], // This gets updated dynamically.

    boardSize: [10, 10],

    board: undefined,

    // HELPER FUNCTIONS =======================================================

    _getBlankBoard() {
      return new Array(this.boardSize[0]).fill(0).map(
        () => new Array(this.boardSize[1]).fill(false)
      );
    },

    _getRandomRow() {
      return new Array(window.gol.boardSize[0]).fill(0).map(() => Math.random() < 0.125);
    },

    // RENDERING FUNCTIONS ====================================================
    // These functions connect the simulation to the browser

    // Called to update the game if the canvas size
    // changes.
    sizeChanged() {
      // Spare loop variables
      let i;

      const width = window.gol.canvas.offsetWidth;
      const height = window.gol.canvas.offsetHeight;

      // Update canvas coordinate system
      window.gol.canvas.setAttribute('width', width);
      window.gol.canvas.setAttribute('height', height);

      // Update tile size by finding a width that will
      // evenly fill the canvas and is closest to the
      // idealCellSize, then doing the same thing for
      // height.

      window.gol.cellSize = [
        width / Math.round(width / window.gol.idealCellSize),
        height / Math.round(height / window.gol.idealCellSize),
      ];

      // When board size changes, kill cells that are
      // cut off and randomize new terrain.

      const oldBoardSize = window.gol.boardSize;  // Store old size
      window.gol.boardSize = [  // Adjust size
        Math.round(width / window.gol.cellSize[0]),
        Math.round(height / window.gol.cellSize[1]),
      ];
      const diff = [  // Calculate size difference
        window.gol.boardSize[0] - oldBoardSize[0],
        window.gol.boardSize[1] - oldBoardSize[1],
      ];

      // Kill dead cells

      if (diff[0] < 0) {
        window.gol.board = window.gol.board.slice(0, window.gol.boardSize[0]);
      }
      if (diff[1] < 0) {
        window.gol.board = window.gol.board.map(row => row.slice(0, window.gol.boardSize[1]));
      }

      // Populate new cells

      // Add new rows filled with random cells
      for (i = 0; i < diff[0]; i += 1) {
        window.gol.board.push(window.gol._getRandomRow());
      }
      // Add new random cells to existing rows (new columns)
      for (i = 0; i < diff[1]; i += 1) {
        for (let k = 0; k < window.gol.board.length; k += 1) {
          window.gol.board[k].push(Math.random() < 0.125);
        }
      }

      window.gol.redraw();
    },

    // Randomize the game state

    randomize() {
      this.board = this._getBlankBoard().map(() => this._getRandomRow());
    },

    // Render the board on the canvas

    redraw() {
      const width = this.canvas.getAttribute('width');
      const height = this.canvas.getAttribute('height');

      this.ctx.clearRect(0, 0, width, height);
      this.ctx.fillStyle = this.cellColor;
      // Render board
      for (let x = 0; x < this.boardSize[0]; x += 1) {
        for (let y = 0; y < this.boardSize[1]; y += 1) {
          if (this.board[x][y]) {
            this.ctx.fillRect(
              this.cellSize[0] * x,
              this.cellSize[1] * y,
              this.cellSize[0],
              this.cellSize[1]
            );
          }
        }
      }
    },

    // GAME LOGIC =============================================================

    countLiveNeighbors(x, y) {
      // Is there room in directions of:
      //   - negative x
      //   - negative y
      //   - positive x
      //   - positive y
      const xroomneg = x > 0;
      const yroomneg = y > 0;
      const xroompos = x < this.boardSize[0] - 1;
      const yroompos = y < this.boardSize[1] - 1;

      const neighbors = [
        // above
        yroomneg && this.board[x][y - 1],
        // above right
        xroompos && yroomneg && this.board[x + 1][y - 1],
        // right
        xroompos && this.board[x + 1][y],
        // below right
        xroompos && yroompos && this.board[x + 1][y + 1],
        // below
        yroompos && this.board[x][y + 1],
        // below left
        xroomneg && yroompos && this.board[x - 1][y + 1],
        // left
        xroomneg && this.board[x - 1][y],
        // above and left
        xroomneg && yroompos && this.board[x - 1][y - 1],
      ];

      // Number of true values in neighbors array
      return neighbors.filter(n => n).length;
    },

    judgeFate(isLive, liveNeighbors) {
      if (isLive) {
        // Any live cell with fewer than 2 live neighbors
        // dies of underpopulation; any live cell with more
        // than three dies of overpopulation.
        return (liveNeighbors === 2 || liveNeighbors === 3);
      }

      // Any dead cell with exactly 3 neighbors is born
      return liveNeighbors === 3;
    },

    step() {
      const newState = this._getBlankBoard();

      for (let x = 0; x < this.boardSize[0]; x += 1) {
        for (let y = 0; y < this.boardSize[1]; y += 1) {
          newState[x][y] = this.judgeFate(
            this.board[x][y],
            this.countLiveNeighbors(x, y)
          );
        }
      }

      this.board = newState;
    },

    // USER INTERACTION =======================================================

    // On a desktop computer, cells are born
    // when moused over. On a mobile device
    // it's wherever a touch occurs or is dragged.
    interacted(e) {
      // Position of the canvas in the viewport
      const bbox = window.gol.canvas.getBoundingClientRect();
      // Position of the mouse in the viewport
      const absx = e.clientX;
      const absy = e.clientY;

      // If these two positions intersect:
      if (absx > bbox.left &&
          absy > bbox.top &&
          absx < bbox.right &&
          absy < bbox.bottom
      ) {
        // Calculate mouse position relative to canvas
        const relx = absx - bbox.left;
        const rely = absy - bbox.top;
        // Calculate cell position
        const cellx = Math.floor(relx / window.gol.cellSize[0]);
        const celly = Math.floor(rely / window.gol.cellSize[1]);

        window.gol.board[cellx][celly] = true;
      }
    },

    // CONTROL FUNCTIONS ======================================================

    // Begin the loop

    start() {
      window.gol.step();
      window.gol.redraw();
      setTimeout(() => {
        requestAnimationFrame(window.gol.start);
      }, 1000 / window.gol.fps);
    },

    // Initialize and begin

    init() {
      // Temporary board
      this.board = this._getBlankBoard();
      // Calculate sizes
      this.sizeChanged();
      // Initialize board
      this.board = this._getBlankBoard();
      this.randomize();
      this.start();
    },
  };

  window.addEventListener('resize', window.gol.sizeChanged);
  document.addEventListener('mousemove', window.gol.interacted);
  window.gol.init();
});
<|endoftext|>


<commit_before>Components.utils.import('resource://gre/modules/devtools/dbg-server.jsm');
Components.utils.import("resource://gre/modules/Services.jsm");

var EXPORTED_SYMBOLS = ["debugModule"];

var debugModule = {};

var DEBUG_MODE_PREF = "tenshi.enableDebug";
var MAIN_WINDOW_TYPE = "angel-player:main";
var debugMode = false;

debugModule.init = function() {
    debugMode = Services.prefs.getBoolPref(DEBUG_MODE_PREF);

    // Start remote debugger
    if (!DebuggerServer.initialized) {
      DebuggerServer.init();
      DebuggerServer.addBrowserActors(MAIN_WINDOW_TYPE);
    }
    DebuggerServer.openListener(6000);
};

debugModule.isDebugEnabled = function() {
    return debugMode;
};

debugModule.toggleDebug = function() {
    debugMode = !debugMode;
    Services.prefs.setBoolPref(DEBUG_MODE_PREF, debugMode);
};
<commit_msg>Make new style editor and inspector work<commit_after>Components.utils.import('resource://gre/modules/devtools/dbg-server.jsm');
Components.utils.import("resource://gre/modules/Services.jsm");

var EXPORTED_SYMBOLS = ["debugModule"];

var debugModule = {};

var DEBUG_MODE_PREF = "tenshi.enableDebug";
var MAIN_WINDOW_TYPE = "angel-player:main";
var debugMode = false;

debugModule.init = function() {
    debugMode = Services.prefs.getBoolPref(DEBUG_MODE_PREF);

    // Start remote debugger
    if (!DebuggerServer.initialized) {
      DebuggerServer.init();
      DebuggerServer.addBrowserActors(MAIN_WINDOW_TYPE);

      // In the current version of XULRunner, these actors are not registered
      // globally. TODO(rqou): Fix this when we update to XULRunner 28.
      // See https://bugzilla.mozilla.org/show_bug.cgi?id=928008,
      // https://bugzilla.mozilla.org/show_bug.cgi?id=946800 for more details.
      // Also, for some reason, the inspector does not seem to expose itself
      // under DebugServer the way StyleEditorActor does. We do a really awful
      // hack to fetch it from the list of tab actors and then add it into the
      // list of global actors.
      DebuggerServer.addGlobalActor(
        DebuggerServer.tabActorFactories.inspectorActor, "inspectorActor");
      DebuggerServer.addGlobalActor(DebuggerServer.StyleEditorActor,
        "styleEditorActor");
    }
    DebuggerServer.openListener(6000);
};

debugModule.isDebugEnabled = function() {
    return debugMode;
};

debugModule.toggleDebug = function() {
    debugMode = !debugMode;
    Services.prefs.setBoolPref(DEBUG_MODE_PREF, debugMode);
};
<|endoftext|>


<commit_before>(function ($){
  var app = $.app;
  var compat = app.utils.compat;

  var isearchStarted = 0;
  var isearchFinished = 0;

  function Importer() {  }

  function loadMusic(files) {
    var musicFiles = _(files).select(function (file) {
      var path = compat.getPath(file);
      var fileName = compat.getName(file);
      var size = compat.getSize(file);
      var lpath = path.toLowerCase();
      return !/\.$/.test(lpath) &&
        (/\.mp3$/.test(lpath)) ||
        (/\.ogg$/.test(lpath)) ||
        (/\.m4a$/.test(lpath))
    });

    $('input[name=search]', '#search_column').val('Search...');
    if($('#curtain').is(':visible')) { app.Skin.hideCurtain(); }
    if(!$('#player_container').is(':visible')) { app.Skin.showPlayerScreen(); }
    app.mainColumn.startProgress();
    app.mainColumn.showShelf();
    var artworkHints = [];
    var total = musicFiles.length, progress = 0;
    function onCreate(muFile) {

      /*
       * Artwork fetching from Google Image Search
       *
       * We seek unique album artworks for a group of songs to display in
       * the artwork grid. This algorithm, does this grouping of songs in
       * two steps.
       * 1. We find unique combinations of album+artist, then feed it
       * to Google image search. Thus all songs that have same album+artist
       * text will be grouped under the resulting image
       * 2. It's possible that due to inaccuracies in file naming we may
       * end up with album+artist strings that are different in characters
       * but are essentially the same e.g. "My Album Bryan Adams" and
       * "My Album Bryan_Adams". Fortunately Google Image search will
       * return same image search result for both these strings. Therefore
       * we check the returned URL and if we already have it for some
       * other album+artist string, then we combine the two groups.
       */

      if(muFile.album && muFile.album.length > 0 &&
        muFile.artist && muFile.artist.length > 0)
      {
        var artworkHint = {
          album : muFile.album,
          artist : muFile.artist,
        };
        var found = _(artworkHints).any(
          function (ah) {
            return
            (ah.artist.toLowerCase() == artworkHint.artist.toLowerCase()) &&
            (ah.album.toLowerCase() == artworkHint.album.toLowerCase());
          }
        );
        if(!found) {
          var detect =
            _.detect(app.localArtworks, function (artwork){
              return (artwork.album == artworkHint.album
                && artwork.artist == artworkHint.artist);
            });
          if(!detect){
            isearchStarted++;
            app.utils.searchImage(
              artworkHint.album, artworkHint.artist,
              function (url, artist, album) {
                isearchFinished++;
                if(_.isUndefined(app.localArtworks[url])) {
                  app.mainColumn.populateShelf(url, artist, album);
                  app.localArtworks[url] = {
                    album : album,
                    artist : artist
                  };
                  app.mainColumn.storeArtworkMap();
                }
              }
            );
          }
          artworkHints.push(artworkHint);
        }
      }

      progress++;
      if(progress == total) {
        app.Storage.save();
        app.printParseReport();
        app.mainColumn.completeProgress();
        console.log('Image search success '+isearchFinished+'/'+isearchStarted);
      } else {
        newMuFile(musicFiles[progress]);
        app.mainColumn.makeProgress(total, progress);
      }
    }

    $.app.liveFiles = {};

    function newMuFile(f) {
      $.app.liveFiles[compat.getPath(f)] = f;
      new $.app.MuFile(f, onCreate);
    }

    newMuFile(musicFiles[progress]);
  }

  app.Importer = Importer;
  app.Importer.loadMusic = loadMusic;
})(jQuery)
<commit_msg>compilation error fix<commit_after>(function ($){
  var app = $.app;
  var compat = app.utils.compat;

  var isearchStarted = 0;
  var isearchFinished = 0;

  function Importer() {  }

  function loadMusic(files) {
    var musicFiles = _(files).select(function (file) {
      var path = compat.getPath(file);
      var fileName = compat.getName(file);
      var size = compat.getSize(file);
      var lpath = path.toLowerCase();
      return !/\.$/.test(lpath) &&
        (/\.mp3$/.test(lpath)) ||
        (/\.ogg$/.test(lpath)) ||
        (/\.m4a$/.test(lpath))
    });

    $('input[name=search]', '#search_column').val('Search...');
    if($('#curtain').is(':visible')) { app.Skin.hideCurtain(); }
    if(!$('#player_container').is(':visible')) { app.Skin.showPlayerScreen(); }
    app.mainColumn.startProgress();
    app.mainColumn.showShelf();
    var artworkHints = [];
    var total = musicFiles.length, progress = 0;
    function onCreate(muFile) {

      /*
       * Artwork fetching from Google Image Search
       *
       * We seek unique album artworks for a group of songs to display in
       * the artwork grid. This algorithm, does this grouping of songs in
       * two steps.
       * 1. We find unique combinations of album+artist, then feed it
       * to Google image search. Thus all songs that have same album+artist
       * text will be grouped under the resulting image
       * 2. It's possible that due to inaccuracies in file naming we may
       * end up with album+artist strings that are different in characters
       * but are essentially the same e.g. "My Album Bryan Adams" and
       * "My Album Bryan_Adams". Fortunately Google Image search will
       * return same image search result for both these strings. Therefore
       * we check the returned URL and if we already have it for some
       * other album+artist string, then we combine the two groups.
       */

      if(muFile.album && muFile.album.length > 0 &&
        muFile.artist && muFile.artist.length > 0)
      {
        var artworkHint = {
          album : muFile.album,
          artist : muFile.artist
        };
        var found = _(artworkHints).any(
          function (ah) {
            return
            (ah.artist.toLowerCase() == artworkHint.artist.toLowerCase()) &&
            (ah.album.toLowerCase() == artworkHint.album.toLowerCase());
          }
        );
        if(!found) {
          var detect =
            _.detect(app.localArtworks, function (artwork){
              return (artwork.album == artworkHint.album
                && artwork.artist == artworkHint.artist);
            });
          if(!detect){
            isearchStarted++;
            app.utils.searchImage(
              artworkHint.album, artworkHint.artist,
              function (url, artist, album) {
                isearchFinished++;
                if(_.isUndefined(app.localArtworks[url])) {
                  app.mainColumn.populateShelf(url, artist, album);
                  app.localArtworks[url] = {
                    album : album,
                    artist : artist
                  };
                  app.mainColumn.storeArtworkMap();
                }
              }
            );
          }
          artworkHints.push(artworkHint);
        }
      }

      progress++;
      if(progress == total) {
        app.Storage.save();
        app.printParseReport();
        app.mainColumn.completeProgress();
        console.log('Image search success '+isearchFinished+'/'+isearchStarted);
      } else {
        newMuFile(musicFiles[progress]);
        app.mainColumn.makeProgress(total, progress);
      }
    }

    $.app.liveFiles = {};

    function newMuFile(f) {
      $.app.liveFiles[compat.getPath(f)] = f;
      new $.app.MuFile(f, onCreate);
    }

    newMuFile(musicFiles[progress]);
  }

  app.Importer = Importer;
  app.Importer.loadMusic = loadMusic;
})(jQuery);
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

"use strict";

var self = require("sdk/self");

const { Cu, Ci } = require("chrome");
const { Trace, TraceError } = require("../core/trace.js").get(module.id);
const { loadSheet, removeSheet } = require("sdk/stylesheet/utils");
const { ConsoleListener } = require("./consoleListener.js");
const { ConsoleProxy } = require("./console-proxy.js");
const { EventTarget } = require("sdk/event/target");
const { Class } = require("sdk/core/heritage");
const { getSelectedTab } = require("sdk/tabs/utils");
const { getMostRecentBrowserWindow } = require("sdk/window/utils");
const { gDevTools } = Cu.import("resource:///modules/devtools/gDevTools.jsm", {});
const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const { Domplate } = require("../core/domplate.js");
const { Dom } = require("../core/dom.js");
const { VariablesView } = require("./variables-view.js");
const { DomSidePanel } = require("../dom/domSidePanel.js");
const { DomTree } = require("../dom/domTree.js");
const { DomProvider } = require("../dom/domProvider.js");
const { DomCache } = require("../dom/domCache.js");
const { BaseOverlay } = require("../chrome/baseOverlay.js");
const { Theme } = require("../chrome/theme.js");
const { Win } = require("../core/window.js");
const { ToolbarButton } = require("../chrome/panelToolbar.js");

// Get the Messages object which holds the main classes of Messages
// used by the Web Console. Use helper syntax otherwise Add-on SDK
// parser fires false exception.
const { Messages, Widgets } = devtools["require"]("devtools/webconsole/console-output");
const Heritage = require("sdk/core/heritage");

const { Services } = Cu.import("resource://gre/modules/Services.jsm", {});

const PROMISE_URI = "resource://gre/modules/Promise.jsm";
let { Promise: promise } = Cu.import(PROMISE_URI, {});

const XHTML_NS = "http://www.w3.org/1999/xhtml";
const persistPrefName = "devtools.webconsole.persistlog";

// Domplate
const { SPAN, A, domplate } = Domplate;

/**
 * @overlay This object is responsible for {@WebConsole} panel customization.
 *
 * See the native structure of {@WebConsolePanel} panel:
 *
 * this.panel => {@WebConsolePanel}
 * this.panel.hud => {@WebConsole}
 * this.panel.hud.ui => {@WebConsoleFrame}
 * this.panel.hud.jsterm => {@JSTerm}
 * this.panel.hud.ui.proxy => {@WebConsoleConnectionProxy}
 */
const ConsoleOverlay = Class(
/** @lends ConsoleOverlay */
{
  extends: BaseOverlay,

  // Initialization
  initialize: function(options) {
    BaseOverlay.prototype.initialize.apply(this, arguments);

    Trace.sysout("consoleOverlay.initialize;", options);

    this.onVariablesViewOpen = this.onVariablesViewOpen.bind(this);
    this.onVariablesViewFetched = this.onVariablesViewFetched.bind(this);
    this.onSidebarClosed = this.onSidebarClosed.bind(this);
  },

  onReady: function(options) {
    BaseOverlay.prototype.onReady.apply(this, arguments);

    Trace.sysout("consoleOverlay.onReady;", options);

    this.listener = new ConsoleListener(options);

    if (!this.panel.hud) {
      TraceError.sysout("consoleOverlay.onReady; ERROR no hud!", this.panel);
      return;
    }

    // Hook the native VariablesView events.
    let jsterm = this.panel.hud.jsterm;
    jsterm.on("variablesview-open", this.onVariablesViewOpen);
    jsterm.on("variablesview-fetched", this.onVariablesViewFetched);
    jsterm.on("sidebar-closed", this.onSidebarClosed);

    // Install custom proxy to intercept console.* API and customize
    // rendering (using registered reps).
    this.overlayProxy();
    this.setupSidePanels();
    this.updateSideSplitterTheme();
  },

  destroy: function() {
    Trace.sysout("consoleOverlay.destroy;");

    this.listener.destroy();

    let jsterm = this.panel.hud.jsterm;
    if (!jsterm) {
      TraceError.sysout("consoleOverlay.destroy; ERROR jsterm is null!");
      return;
    }

    jsterm.off("variablesview-open", this.onVariablesViewOpen);
    jsterm.off("variablesview-fetched", this.onVariablesViewFetched);
    jsterm.off("sidebar-closed", this.onSidebarClosed);
  },

  getSidePanels: function() {
    // xxxHonza: the DOM should be removed eventually
    return [DomSidePanel];
  },

  setupSidePanels: function() {
    Trace.sysout("consoleOverlay.setupSidePanels;");

    // The panel is set in onReady and theme is applied sooner.
    if (!this.panel)
      return;

    // Make sure the Console panel side bar is created.
    // xxxHonza: we need better platform API.
    let jsterm = this.panel.hud.jsterm;
    if (!jsterm.sidebar) {
      // xxxHonza: we can't hide it since the "variables-view" would be created
      // in hidden <tabbox>, which would break selection (and also contentWindow
      // is not set from some reason).
      // Blocked by bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1056033
      return;

      jsterm._createSidebar();
      jsterm.sidebar.hide();
    }

    this.sidebar = jsterm.sidebar;

    BaseOverlay.prototype.setupSidePanels.apply(this, arguments);
  },

  // Sidebar Events

  onSidebarClosed: function(eventId) {
    this.updateSideSplitterTheme();
  },

  toggleSidebar: function() {
    let jsterm = this.panel.hud.jsterm;

    Trace.sysout("consoleOverlay.toggleSidebar; " + jsterm.sidebar);

    if (jsterm.sidebar) {
      jsterm.sidebar.toggle();
    } else {
      jsterm._createSidebar();

      this.updateSideSplitterTheme();

      // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1056033
      jsterm.sidebar._panelDoc.defaultView.setTimeout(() => {
        this.setupSidePanels();
      }, 200);
    }
  },

  // VariablesView Events
  onVariablesViewOpen: function(eventId, view, options) {
    Trace.sysout("consoleOverlay.onVariablesViewOpen; ", arguments);

    this.updateSideSplitterTheme();

    // Disable the DOM side panel for now.
    // See also: https://github.com/firebug/firebug.next/issues/56
    return;

    let theme = Theme.getCurrentTheme();
    if (theme != "firebug") {
      return;
    }

    // Render object structure at custom position in the UI (e.g. inside
    // the Console panel when console.dir() is used).
    let targetElement = options.targetElement;
    if (options.targetElement) {
      this.renderVariablesView(options.targetElement, options.objectActor);
      return;
    }

    let doc = view.document;
    let container = doc.querySelector("#variables");

    // xxxHonza: also hide the side tab
    // Remove the original {@VariablesView}.
    //Dom.clearNode(container);
    //this.panel.hud.jsterm.sidebar.hide();

    var config = {
      objectActor: options.objectActor,
      parentNode: container,
      toolbox: view.toolbox
    };

    for (let panel of this.sidePanels.values()) {
      if (panel.supportsObject(options.objectActor)) {
        panel.refresh(options.objectActor);
      }
    }

    this.selectSidePanel("domSidePanel");
  },

  onVariablesViewFetched: function(eventId, aVar) {
    Trace.sysout("consoleOverlay.onVariablesViewFetched; ", arguments);
  },

  // xxxHonza: renders view for console.dir() API
  // Should share implementation with DomSidePanel
  renderVariablesView: function(parentNode, actor) {
    Trace.sysout("consoleOverlay.renderDomView; ", arguments);

    Dom.clearNode(parentNode);

    // Create helper wrapper around the {@DomTree} widget.
    let doc = parentNode.ownerDocument;
    let wrapper = doc.createElementNS(XHTML_NS, "div");
    wrapper.className = "domTableWrapper";
    parentNode.appendChild(wrapper);

    // Get the current thread actor and render the object structure.
    let target = this.toolbox.target;
    target.activeTab.attachThread({}, (response, threadClient) => {
      let cache = new DomCache(threadClient);
      let provider = new DomProvider(cache);
      this.tree = new DomTree(provider);
      this.tree.replace(wrapper, {object: actor});
    });
  },

  overlayProxy: function() {
    // Usually WebConsoleFrame instance (wrapping the console output).
    let hud = this.panel.hud
    let frame = hud.ui;

    // xxxHonza: testing
    frame.on("messages-added", () => {
      //Trace.sysout("consoleOverlay; messageAdded", arguments);
    });

    frame.on("messages-updated", () => {
      //Trace.sysout("consoleOverlay; messageUpdated", arguments);
    });

    frame.on("onConsoleAPICall", () => {
      Trace.sysout("consoleOverlay; onConsoleAPICall", arguments);
    });

    // xxxHonza: disconnecting proxy is asynchronous and cached
    // messages get through before we install the new proxy.
    // See _onCachedMessages in webconsole.js
    // There must be a better way how to customize rendering
    // of existing logs (a new event fired with cancel support?).
    // xxxHonza: the custom proxy is not properly disconnected/destroyed
    // when the extension is disabled.
    /*frame.proxy.disconnect().then(() => {
      Trace.sysout("consoleOverlay.overlayProxy; Original proxy disconnected");
    });

    // Custom proxy
    frame.proxy = new ConsoleProxy(frame, frame.owner.target);

    frame.proxy.connect().then(() => {
      Trace.sysout("consoleOverlay.overlayProxy; New proxy connected");
    }, (reason) => {
      TraceError.sysout("consoleOverlay.overlayProxy; ERROR " + reason, reason);
    });*/
  },

  // Theme

  applyTheme: function(win, oldTheme) {
    BaseOverlay.prototype.applyTheme.apply(this, arguments);

    if (win.location.href.indexOf("VariablesView.xul") == -1)
      return;

    loadSheet(win, "chrome://firebug/skin/variables-view.css", "author");
  },

  unapplyTheme: function(win, newTheme) {
    BaseOverlay.prototype.unapplyTheme.apply(this, arguments);

    if (win.location.href.indexOf("VariablesView.xul") == -1)
      return;

    removeSheet(win, "chrome://firebug/skin/variables-view.css", "author");
  },

  onApplyTheme: function(iframeWin, oldTheme) {
    Trace.sysout("consoleOverlay.onApplyTheme;", iframeWin);

    let doc = iframeWin.document;
    let win = doc.getElementById("devtools-webconsole");

    // Remove the theme-light class name, we don't want to use
    // the default styles for now.
    // xxxHonza: hack FIX ME
    win.classList.remove("theme-light");

    Theme.customizeSideBarSplitter(iframeWin, true);

    Win.loaded(iframeWin).then(doc => {
      this.updateSideSplitterTheme();
      this.updatePersistButton(true);

      let toolbar = doc.querySelector(".hud-console-filter-toolbar");
      Theme.sideBarButton(this, toolbar, true);
    });

    // Load theme stylesheets into the Console frame.
    loadSheet(iframeWin, "chrome://firebug/skin/webconsole.css", "author");
    loadSheet(iframeWin, "chrome://firebug/skin/domTree.css", "author");
    loadSheet(iframeWin, "chrome://firebug/skin/html.css", "author");
  },

  onUnapplyTheme: function(iframeWin, newTheme) {
    Trace.sysout("consoleOverlay.onUnapplyTheme;", iframeWin);

    let doc = iframeWin.document;
    let win = doc.getElementById("devtools-webconsole");

    Theme.customizeSideBarSplitter(iframeWin, false);

    Win.loaded(iframeWin).then(doc => {
      this.updateSideSplitterTheme();
      this.updatePersistButton(false);

      let toolbar = doc.querySelector(".hud-console-filter-toolbar");
      Theme.sideBarButton(this, toolbar, true);
    });

    // Unload theme stylesheets from the Console frame.
    removeSheet(iframeWin, "chrome://firebug/skin/webconsole.css", "author");
    removeSheet(iframeWin, "chrome://firebug/skin/domTree.css", "author");
    removeSheet(iframeWin, "chrome://firebug/skin/html.css", "author");
  },

  updateSideSplitterTheme: function() {
    let doc = this.getPanelDocument();
    let splitter = doc.querySelector(".devtools-side-splitter");

    // Do not mess the styling if Firebug theme isn't active.
    if (!Theme.isFirebugActive()) {
      splitter.removeAttribute("collapsed");
      return;
    }

    // The HUD doesn't have to exist at this moment. It's available
    // when the 'ready' event is fired.
    let jsterm = this.panel.hud ? this.panel.hud.jsterm : null;
    if (!jsterm) {
      return;
    }

    // The splitter shouldn't be visible if the side bar is closed.
    let visible = isSideBarVisible(jsterm.sidebar);
    if (visible) {
      splitter.removeAttribute("collapsed");
    } else {
      splitter.setAttribute("collapsed", "true");
    }
  },

  /**
   * Create/Remove an additional 'Persist' button that is available
   * when the Firebug theme is active. The button can be used to
   * disable console-clear when the page is reloaded.
   */
  updatePersistButton : function(apply) {
    let doc = this.getPanelDocument();
    let toolbar = doc.querySelector(".hud-console-filter-toolbar");
    let clearButton = doc.querySelector(".webconsole-clear-console-button");

    if (apply) {
      let button = new ToolbarButton({
        id: "firebug-persist-console",
        toolbar: toolbar,
        referenceElement: clearButton.nextSibling,
        type: "checkbox",
        checked: Services.prefs.getBoolPref(persistPrefName),
        label: "firebug.menu.PersistConsole",
        tooltiptext: "firebug.menu.tip.PersistConsole",
        command: this.onPersist.bind(this)
      });
    } else {
      let persistButton = doc.getElementById("firebug-persist-console");
      if (persistButton)
        persistButton.remove();
    }
  },

  // Commands

  clearConsole: function() {
    let doc = this.getPanelDocument();

    // xxxHonza: TESTME (the id of the clear button could change).
    let clearButton = doc.querySelector(".webconsole-clear-console-button");
    clearButton.click();
  },

  onPersist: function() {
    let value = Services.prefs.getBoolPref(persistPrefName);
    Services.prefs.setBoolPref(persistPrefName, !value);
  }
});

// Helpers

// xxxHonza: could be implemented in {@BasePanel} or {@BaseOverlay}?
function isSideBarVisible(sidebar) {
  if (!sidebar)
    return false;

  return sidebar._tabbox.hasAttribute("hidden") ? false : true;
}

// Exports from this module
exports.ConsoleOverlay = ConsoleOverlay;
<commit_msg>Properly update the side splitter theme<commit_after>/* See license.txt for terms of usage */

"use strict";

var self = require("sdk/self");

const { Cu, Ci } = require("chrome");
const { Trace, TraceError } = require("../core/trace.js").get(module.id);
const { loadSheet, removeSheet } = require("sdk/stylesheet/utils");
const { ConsoleListener } = require("./consoleListener.js");
const { ConsoleProxy } = require("./console-proxy.js");
const { EventTarget } = require("sdk/event/target");
const { Class } = require("sdk/core/heritage");
const { getSelectedTab } = require("sdk/tabs/utils");
const { getMostRecentBrowserWindow } = require("sdk/window/utils");
const { gDevTools } = Cu.import("resource:///modules/devtools/gDevTools.jsm", {});
const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const { Domplate } = require("../core/domplate.js");
const { Dom } = require("../core/dom.js");
const { VariablesView } = require("./variables-view.js");
const { DomSidePanel } = require("../dom/domSidePanel.js");
const { DomTree } = require("../dom/domTree.js");
const { DomProvider } = require("../dom/domProvider.js");
const { DomCache } = require("../dom/domCache.js");
const { BaseOverlay } = require("../chrome/baseOverlay.js");
const { Theme } = require("../chrome/theme.js");
const { Win } = require("../core/window.js");
const { ToolbarButton } = require("../chrome/panelToolbar.js");

// Get the Messages object which holds the main classes of Messages
// used by the Web Console. Use helper syntax otherwise Add-on SDK
// parser fires false exception.
const { Messages, Widgets } = devtools["require"]("devtools/webconsole/console-output");
const Heritage = require("sdk/core/heritage");

const { Services } = Cu.import("resource://gre/modules/Services.jsm", {});

const PROMISE_URI = "resource://gre/modules/Promise.jsm";
let { Promise: promise } = Cu.import(PROMISE_URI, {});

const XHTML_NS = "http://www.w3.org/1999/xhtml";
const persistPrefName = "devtools.webconsole.persistlog";

// Domplate
const { SPAN, A, domplate } = Domplate;

/**
 * @overlay This object is responsible for {@WebConsole} panel customization.
 *
 * See the native structure of {@WebConsolePanel} panel:
 *
 * this.panel => {@WebConsolePanel}
 * this.panel.hud => {@WebConsole}
 * this.panel.hud.ui => {@WebConsoleFrame}
 * this.panel.hud.jsterm => {@JSTerm}
 * this.panel.hud.ui.proxy => {@WebConsoleConnectionProxy}
 */
const ConsoleOverlay = Class(
/** @lends ConsoleOverlay */
{
  extends: BaseOverlay,

  // Initialization
  initialize: function(options) {
    BaseOverlay.prototype.initialize.apply(this, arguments);

    Trace.sysout("consoleOverlay.initialize;", options);

    this.onVariablesViewOpen = this.onVariablesViewOpen.bind(this);
    this.onVariablesViewFetched = this.onVariablesViewFetched.bind(this);
    this.onSidebarClosed = this.onSidebarClosed.bind(this);
  },

  onReady: function(options) {
    BaseOverlay.prototype.onReady.apply(this, arguments);

    Trace.sysout("consoleOverlay.onReady;", options);

    this.listener = new ConsoleListener(options);

    if (!this.panel.hud) {
      TraceError.sysout("consoleOverlay.onReady; ERROR no hud!", this.panel);
      return;
    }

    // Hook the native VariablesView events.
    let jsterm = this.panel.hud.jsterm;
    jsterm.on("variablesview-open", this.onVariablesViewOpen);
    jsterm.on("variablesview-fetched", this.onVariablesViewFetched);
    jsterm.on("sidebar-closed", this.onSidebarClosed);

    // Install custom proxy to intercept console.* API and customize
    // rendering (using registered reps).
    this.overlayProxy();
    this.setupSidePanels();
    this.updateSideSplitterTheme();
  },

  destroy: function() {
    Trace.sysout("consoleOverlay.destroy;");

    this.listener.destroy();

    let jsterm = this.panel.hud.jsterm;
    if (!jsterm) {
      TraceError.sysout("consoleOverlay.destroy; ERROR jsterm is null!");
      return;
    }

    jsterm.off("variablesview-open", this.onVariablesViewOpen);
    jsterm.off("variablesview-fetched", this.onVariablesViewFetched);
    jsterm.off("sidebar-closed", this.onSidebarClosed);
  },

  getSidePanels: function() {
    // xxxHonza: the DOM should be removed eventually
    return [DomSidePanel];
  },

  setupSidePanels: function() {
    Trace.sysout("consoleOverlay.setupSidePanels;");

    // The panel is set in onReady and theme is applied sooner.
    if (!this.panel)
      return;

    // Make sure the Console panel side bar is created.
    // xxxHonza: we need better platform API.
    let jsterm = this.panel.hud.jsterm;
    if (!jsterm.sidebar) {
      // xxxHonza: we can't hide it since the "variables-view" would be created
      // in hidden <tabbox>, which would break selection (and also contentWindow
      // is not set from some reason).
      // Blocked by bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1056033
      return;

      jsterm._createSidebar();
      jsterm.sidebar.hide();
    }

    this.sidebar = jsterm.sidebar;

    BaseOverlay.prototype.setupSidePanels.apply(this, arguments);
  },

  // Sidebar Events

  onSidebarClosed: function(eventId) {
    this.updateSideSplitterTheme();
  },

  toggleSidebar: function() {
    let jsterm = this.panel.hud.jsterm;

    Trace.sysout("consoleOverlay.toggleSidebar; " + jsterm.sidebar);

    if (jsterm.sidebar) {
      jsterm.sidebar.toggle();
    } else {
      // xxxHonza: the timeout must be there, see:
      // https://bugzilla.mozilla.org/show_bug.cgi?id=1056033
      jsterm._createSidebar();
      jsterm.sidebar._panelDoc.defaultView.setTimeout(() => {
        this.setupSidePanels();
      }, 200);
    }

    this.updateSideSplitterTheme();
  },

  // VariablesView Events
  onVariablesViewOpen: function(eventId, view, options) {
    Trace.sysout("consoleOverlay.onVariablesViewOpen; ", arguments);

    this.updateSideSplitterTheme();

    // Disable the DOM side panel for now.
    // See also: https://github.com/firebug/firebug.next/issues/56
    return;

    let theme = Theme.getCurrentTheme();
    if (theme != "firebug") {
      return;
    }

    // Render object structure at custom position in the UI (e.g. inside
    // the Console panel when console.dir() is used).
    let targetElement = options.targetElement;
    if (options.targetElement) {
      this.renderVariablesView(options.targetElement, options.objectActor);
      return;
    }

    let doc = view.document;
    let container = doc.querySelector("#variables");

    // xxxHonza: also hide the side tab
    // Remove the original {@VariablesView}.
    //Dom.clearNode(container);
    //this.panel.hud.jsterm.sidebar.hide();

    var config = {
      objectActor: options.objectActor,
      parentNode: container,
      toolbox: view.toolbox
    };

    for (let panel of this.sidePanels.values()) {
      if (panel.supportsObject(options.objectActor)) {
        panel.refresh(options.objectActor);
      }
    }

    this.selectSidePanel("domSidePanel");
  },

  onVariablesViewFetched: function(eventId, aVar) {
    Trace.sysout("consoleOverlay.onVariablesViewFetched; ", arguments);
  },

  // xxxHonza: renders view for console.dir() API
  // Should share implementation with DomSidePanel
  renderVariablesView: function(parentNode, actor) {
    Trace.sysout("consoleOverlay.renderDomView; ", arguments);

    Dom.clearNode(parentNode);

    // Create helper wrapper around the {@DomTree} widget.
    let doc = parentNode.ownerDocument;
    let wrapper = doc.createElementNS(XHTML_NS, "div");
    wrapper.className = "domTableWrapper";
    parentNode.appendChild(wrapper);

    // Get the current thread actor and render the object structure.
    let target = this.toolbox.target;
    target.activeTab.attachThread({}, (response, threadClient) => {
      let cache = new DomCache(threadClient);
      let provider = new DomProvider(cache);
      this.tree = new DomTree(provider);
      this.tree.replace(wrapper, {object: actor});
    });
  },

  overlayProxy: function() {
    // Usually WebConsoleFrame instance (wrapping the console output).
    let hud = this.panel.hud
    let frame = hud.ui;

    // xxxHonza: testing
    frame.on("messages-added", () => {
      //Trace.sysout("consoleOverlay; messageAdded", arguments);
    });

    frame.on("messages-updated", () => {
      //Trace.sysout("consoleOverlay; messageUpdated", arguments);
    });

    frame.on("onConsoleAPICall", () => {
      Trace.sysout("consoleOverlay; onConsoleAPICall", arguments);
    });

    // xxxHonza: disconnecting proxy is asynchronous and cached
    // messages get through before we install the new proxy.
    // See _onCachedMessages in webconsole.js
    // There must be a better way how to customize rendering
    // of existing logs (a new event fired with cancel support?).
    // xxxHonza: the custom proxy is not properly disconnected/destroyed
    // when the extension is disabled.
    /*frame.proxy.disconnect().then(() => {
      Trace.sysout("consoleOverlay.overlayProxy; Original proxy disconnected");
    });

    // Custom proxy
    frame.proxy = new ConsoleProxy(frame, frame.owner.target);

    frame.proxy.connect().then(() => {
      Trace.sysout("consoleOverlay.overlayProxy; New proxy connected");
    }, (reason) => {
      TraceError.sysout("consoleOverlay.overlayProxy; ERROR " + reason, reason);
    });*/
  },

  // Theme

  applyTheme: function(win, oldTheme) {
    BaseOverlay.prototype.applyTheme.apply(this, arguments);

    if (win.location.href.indexOf("VariablesView.xul") == -1)
      return;

    loadSheet(win, "chrome://firebug/skin/variables-view.css", "author");
  },

  unapplyTheme: function(win, newTheme) {
    BaseOverlay.prototype.unapplyTheme.apply(this, arguments);

    if (win.location.href.indexOf("VariablesView.xul") == -1)
      return;

    removeSheet(win, "chrome://firebug/skin/variables-view.css", "author");
  },

  onApplyTheme: function(iframeWin, oldTheme) {
    Trace.sysout("consoleOverlay.onApplyTheme;", iframeWin);

    let doc = iframeWin.document;
    let win = doc.getElementById("devtools-webconsole");

    // Remove the theme-light class name, we don't want to use
    // the default styles for now.
    // xxxHonza: hack FIX ME
    win.classList.remove("theme-light");

    Theme.customizeSideBarSplitter(iframeWin, true);

    Win.loaded(iframeWin).then(doc => {
      this.updateSideSplitterTheme();
      this.updatePersistButton(true);

      let toolbar = doc.querySelector(".hud-console-filter-toolbar");
      Theme.sideBarButton(this, toolbar, true);
    });

    // Load theme stylesheets into the Console frame.
    loadSheet(iframeWin, "chrome://firebug/skin/webconsole.css", "author");
    loadSheet(iframeWin, "chrome://firebug/skin/domTree.css", "author");
    loadSheet(iframeWin, "chrome://firebug/skin/html.css", "author");
  },

  onUnapplyTheme: function(iframeWin, newTheme) {
    Trace.sysout("consoleOverlay.onUnapplyTheme;", iframeWin);

    let doc = iframeWin.document;
    let win = doc.getElementById("devtools-webconsole");

    Theme.customizeSideBarSplitter(iframeWin, false);

    Win.loaded(iframeWin).then(doc => {
      this.updateSideSplitterTheme();
      this.updatePersistButton(false);

      let toolbar = doc.querySelector(".hud-console-filter-toolbar");
      Theme.sideBarButton(this, toolbar, true);
    });

    // Unload theme stylesheets from the Console frame.
    removeSheet(iframeWin, "chrome://firebug/skin/webconsole.css", "author");
    removeSheet(iframeWin, "chrome://firebug/skin/domTree.css", "author");
    removeSheet(iframeWin, "chrome://firebug/skin/html.css", "author");
  },

  updateSideSplitterTheme: function() {
    let doc = this.getPanelDocument();
    let splitter = doc.querySelector(".devtools-side-splitter");

    // Do not mess the styling if Firebug theme isn't active.
    if (!Theme.isFirebugActive()) {
      splitter.removeAttribute("collapsed");
      return;
    }

    // The HUD doesn't have to exist at this moment. It's available
    // when the 'ready' event is fired.
    let jsterm = this.panel.hud ? this.panel.hud.jsterm : null;
    if (!jsterm) {
      return;
    }

    // The splitter shouldn't be visible if the side bar is closed.
    let visible = isSideBarVisible(jsterm.sidebar);
    if (visible) {
      splitter.removeAttribute("collapsed");
    } else {
      splitter.setAttribute("collapsed", "true");
    }
  },

  /**
   * Create/Remove an additional 'Persist' button that is available
   * when the Firebug theme is active. The button can be used to
   * disable console-clear when the page is reloaded.
   */
  updatePersistButton : function(apply) {
    let doc = this.getPanelDocument();
    let toolbar = doc.querySelector(".hud-console-filter-toolbar");
    let clearButton = doc.querySelector(".webconsole-clear-console-button");

    if (apply) {
      let button = new ToolbarButton({
        id: "firebug-persist-console",
        toolbar: toolbar,
        referenceElement: clearButton.nextSibling,
        type: "checkbox",
        checked: Services.prefs.getBoolPref(persistPrefName),
        label: "firebug.menu.PersistConsole",
        tooltiptext: "firebug.menu.tip.PersistConsole",
        command: this.onPersist.bind(this)
      });
    } else {
      let persistButton = doc.getElementById("firebug-persist-console");
      if (persistButton)
        persistButton.remove();
    }
  },

  // Commands

  clearConsole: function() {
    let doc = this.getPanelDocument();

    // xxxHonza: TESTME (the id of the clear button could change).
    let clearButton = doc.querySelector(".webconsole-clear-console-button");
    clearButton.click();
  },

  onPersist: function() {
    let value = Services.prefs.getBoolPref(persistPrefName);
    Services.prefs.setBoolPref(persistPrefName, !value);
  }
});

// Helpers

// xxxHonza: could be implemented in {@BasePanel} or {@BaseOverlay}?
function isSideBarVisible(sidebar) {
  if (!sidebar)
    return false;

  return sidebar._tabbox.hasAttribute("hidden") ? false : true;
}

// Exports from this module
exports.ConsoleOverlay = ConsoleOverlay;
<|endoftext|>


<commit_before>L.Angkot.Route = L.LayerGroup.extend({
  options: {
    editable: false,
  },

  initialize: function(layers, options) {
    L.LayerGroup.prototype.initialize.call(this, layers);
    L.Util.setOptions(this, options);

    this._polylines = [];
    this._active = null;
    this._guide = new L.Polyline.Color([], {
      color: 'blue'
    });
    this._shiftKey = false;
  },

  onAdd: function(map) {
    L.LayerGroup.prototype.onAdd.apply(this, arguments);

    if (this.options.editable) {
      this._setupEvents();
      this._guide.addTo(map);
    }
  },

  setEditable: function(editable) {
    this.options.editable = editable;
    if (editable) this._setupEvents();
    else this._removeEvents();

    // FIXME restructure
    if (this._map) {
      if (editable) this._guide.addTo(this._map);
      else this._map.removeLayer(this._guide);
    }
  },

  _setupEvents: function() {
    if (!this._map) return;

    this._map.on('click', this._onMapClick, this);
    this._map.on('mousemove', this._onMapMouseMove, this);

    L.DomEvent.addListener(document, 'keydown', function(e) {
      this._shiftKey = e.shiftKey;
    }, this);
    L.DomEvent.addListener(document, 'keyup', function(e) {
      this._shiftKey = e.shiftKey;
    }, this);
  },

  _removeEvents: function() {
    if (!this._map) return;

    this._map.off('click', this._onMapClick, this);
    this._map.off('mousemove', this._onMapMouseMove, this);
  },

  _onMapClick: function(e) {
    if (this._active) {
      this._addNextPoint(e);
    }
    else {
      this._startRoute(e);
    }
  },

  _startRoute: function(e) {
    var p = this._addPolyline();
    p.addLatLng(e.latlng);
    this._active = p;

    this._guide.spliceLatLngs(0, this._guide._latlngs.length);
    this._guide.addLatLng(e.latlng);
    this._guide.addLatLng(e.latlng);
  },

  _addNextPoint: function(e) {
    this._active.addLatLng(e.latlng);
    this._guide.spliceLatLngs(0, 1, e.latlng);
  },

  _onMapMouseMove: function(e) {
    if (this._active) {
      this._guide.spliceLatLngs(1, 1, e.latlng);
    }
  },

  _createPolyline: function() {
    var p = new L.Polyline.Editable([], {
      editable: true,
      color: 'blue',
    });
    return p;
  },

  _addPolyline: function() {
    var p = this._createPolyline();
    p.addTo(this._map);
    p.on('handle:click', this._onHandleClick, this);
    this._polylines.push(p);
    return p;
  },

  _removePolyline: function(p) {
    var index = this._polylines.indexOf(p);
    if (index >= 0) this._polylines.splice(index, 1);

    p.off('handle:click', this._onHandleClick, this);
    if (this._map) this._map.removeLayer(p);
  },

  _stopDrawing: function() {
    this._active.setColor('red');
    this._active = null;
    this._guide.spliceLatLngs(0, this._guide._latlngs.length);
  },

  _continueRoute: function(e) {
    var p = e.target;
    if (e.vertex === 0) {
      p.reverseLatLngs();
    }
    this._active = p;
    this._active.setColor('blue');
    this._guide.addLatLng(e.latlng);
    this._guide.addLatLng(e.latlng);
  },

  _mergeRoute: function(e) {
    var p = e.target;
    if (e.vertex !== 0) {
      p.reverseLatLngs();
    }
    this._active.addLatLngs(p._latlngs);
    this._removePolyline(p);
  },

  _onHandleClick: function(e) {
    var p = e.target;
    var length = p._latlngs.length;

    var tip = e.vertex === 0 || e.vertex === length-1;

    if (e.target == this._active) {
      if (e.vertex === length-1) {
        this._stopDrawing();
      }
      else {
        this._addNextPoint(e);
      }
    }
    else if (tip) {
      if (!this._active) {
        this._continueRoute(e);
      }
      else if (this._active && this._shiftKey) {
        this._mergeRoute(e);
        this._stopDrawing();
      }
      else if (this._active) {
        this._addNextPoint(e);
      }
    }
    else if (!this._active) {
      this._startRoute(e);
    }
    else {
      this._addNextPoint(e);
    }
  },
});

<commit_msg>Vertex removal<commit_after>L.Angkot.Route = L.LayerGroup.extend({
  options: {
    editable: false,
  },

  initialize: function(layers, options) {
    L.LayerGroup.prototype.initialize.call(this, layers);
    L.Util.setOptions(this, options);

    this._polylines = [];
    this._active = null;
    this._guide = new L.Polyline.Color([], {
      color: 'blue'
    });
    this._shiftKey = false;
  },

  onAdd: function(map) {
    L.LayerGroup.prototype.onAdd.apply(this, arguments);

    if (this.options.editable) {
      this._setupEvents();
      this._guide.addTo(map);
    }
  },

  setEditable: function(editable) {
    this.options.editable = editable;
    if (editable) this._setupEvents();
    else this._removeEvents();

    // FIXME restructure
    if (this._map) {
      if (editable) this._guide.addTo(this._map);
      else this._map.removeLayer(this._guide);
    }
  },

  _setupEvents: function() {
    if (!this._map) return;

    this._map.on('click', this._onMapClick, this);
    this._map.on('mousemove', this._onMapMouseMove, this);

    L.DomEvent.addListener(document, 'keydown', function(e) {
      this._shiftKey = e.shiftKey;
    }, this);
    L.DomEvent.addListener(document, 'keyup', function(e) {
      this._shiftKey = e.shiftKey;
    }, this);
  },

  _removeEvents: function() {
    if (!this._map) return;

    this._map.off('click', this._onMapClick, this);
    this._map.off('mousemove', this._onMapMouseMove, this);
  },

  _onMapClick: function(e) {
    if (this._active) {
      this._addNextPoint(e);
    }
    else {
      this._startRoute(e);
    }
  },

  _startRoute: function(e) {
    var p = this._addPolyline();
    p.addLatLng(e.latlng);
    this._active = p;

    this._guide.spliceLatLngs(0, this._guide._latlngs.length);
    this._guide.addLatLng(e.latlng);
    this._guide.addLatLng(e.latlng);
  },

  _addNextPoint: function(e) {
    this._active.addLatLng(e.latlng);
    this._guide.spliceLatLngs(0, 1, e.latlng);
  },

  _onMapMouseMove: function(e) {
    if (this._active) {
      this._guide.spliceLatLngs(1, 1, e.latlng);
    }
  },

  _createPolyline: function() {
    var p = new L.Polyline.Editable([], {
      editable: true,
      color: 'blue',
    });
    return p;
  },

  _addPolyline: function() {
    var p = this._createPolyline();
    p.addTo(this._map);
    p.on('handle:click', this._onHandleClick, this);
    this._polylines.push(p);
    return p;
  },

  _removePolyline: function(p) {
    var index = this._polylines.indexOf(p);
    if (index >= 0) this._polylines.splice(index, 1);

    p.off('handle:click', this._onHandleClick, this);
    if (this._map) this._map.removeLayer(p);
  },

  _stopDrawing: function() {
    this._active.setColor('red');
    this._active = null;
    this._guide.spliceLatLngs(0, this._guide._latlngs.length);
  },

  _continueRoute: function(e) {
    var p = e.target;
    if (e.vertex === 0) {
      p.reverseLatLngs();
    }
    this._active = p;
    this._active.setColor('blue');
    this._guide.addLatLng(e.latlng);
    this._guide.addLatLng(e.latlng);
  },

  _mergeRoute: function(e) {
    var p = e.target;
    if (e.vertex !== 0) {
      p.reverseLatLngs();
    }
    this._active.addLatLngs(p._latlngs);
    this._removePolyline(p);
  },

  _removeVertex: function(e) {
    var p = e.target;
    p.spliceLatLngs(e.vertex, 1);
    if (p._latlngs.length === 1) {
      this._removePolyline(p);
    }
  },

  _onHandleClick: function(e) {
    var p = e.target;
    var length = p._latlngs.length;

    var tip = e.vertex === 0 || e.vertex === length-1;

    if (e.target == this._active) {
      if (e.vertex === length-1) {
        if (length === 1) {
          this._removePolyline(p);
        }
        this._stopDrawing();
      }
      else {
        this._addNextPoint(e);
      }
    }
    else if (!this._active && this._shiftKey && e.vertex !== undefined) {
      this._removeVertex(e);
    }
    else if (tip) {
      if (!this._active) {
        this._continueRoute(e);
      }
      else if (this._active && this._shiftKey) {
        this._mergeRoute(e);
        this._stopDrawing();
      }
      else if (this._active) {
        this._addNextPoint(e);
      }
    }
    else if (!this._active) {
      this._startRoute(e);
    }
    else {
      this._addNextPoint(e);
    }
  },
});

<|endoftext|>


<commit_before>import thunk from 'redux-thunk'
import createLogger from 'redux-logger'
import { browserHistory } from 'react-router'
import { routerMiddleware } from 'react-router-redux'
import { combineReducers, compose, createStore, applyMiddleware } from 'redux'
import { autoRehydrate } from 'redux-persist'
import { analytics, authentication, requester, uploader } from './middleware'
import * as reducers from './reducers'

const reducer = combineReducers({
  ...reducers,
})

const createBrowserStore = (history = browserHistory) => {
  const logger = createLogger({ collapsed: true, predicate: () => ENV.APP_DEBUG })
  const reduxRouterMiddleware = routerMiddleware(history)

  const store = compose(
    autoRehydrate(),
    applyMiddleware(
      thunk,
      authentication,
      reduxRouterMiddleware,
      uploader,
      requester,
      analytics,
      logger
    ),
  )(createStore)(reducer, window.__INITIAL_STATE__ || {})

  return store
}

const createServerStore = (history) => {
  const reduxRouterMiddleware = routerMiddleware(history)
  const store = compose(
    applyMiddleware(thunk, uploader, reduxRouterMiddleware, requester),
  )(createStore)(reducer, {})

  return store
}

const createElloStore = (history = null) => {
  if (typeof window !== 'undefined') return createBrowserStore()
  return createServerStore(history)
}

export { createElloStore }

export default createElloStore()
<commit_msg>Clobber the prerendered router state (#538)<commit_after>import thunk from 'redux-thunk'
import createLogger from 'redux-logger'
import { browserHistory } from 'react-router'
import { routerMiddleware } from 'react-router-redux'
import { combineReducers, compose, createStore, applyMiddleware } from 'redux'
import { autoRehydrate } from 'redux-persist'
import { analytics, authentication, requester, uploader } from './middleware'
import * as reducers from './reducers'

const reducer = combineReducers({
  ...reducers,
})

const createBrowserStore = (history = browserHistory) => {
  const logger = createLogger({ collapsed: true, predicate: () => ENV.APP_DEBUG })
  const reduxRouterMiddleware = routerMiddleware(history)

  const initialState = window.__INITIAL_STATE__ || {}
  // react-router-redux doesn't know how to serialize
  // query params from server-side rendering, so we just kill it
  // and let the browser reconstruct the router state
  initialState.routing = {}

  const store = compose(
    autoRehydrate(),
    applyMiddleware(
      thunk,
      authentication,
      reduxRouterMiddleware,
      uploader,
      requester,
      analytics,
      logger
    ),
  )(createStore)(reducer, initialState || {})

  return store
}

const createServerStore = (history) => {
  const reduxRouterMiddleware = routerMiddleware(history)
  const store = compose(
    applyMiddleware(thunk, uploader, reduxRouterMiddleware, requester),
  )(createStore)(reducer, {})

  return store
}

const createElloStore = (history = null) => {
  if (typeof window !== 'undefined') return createBrowserStore()
  return createServerStore(history)
}

export { createElloStore }

export default createElloStore()
<|endoftext|>


<commit_before>import {createStore, applyMiddleware, compose} from 'redux';
import createSagaMiddleware from 'redux-saga';

import reducer from './reducer';
import saga from './saga';

const sagaMiddleware = createSagaMiddleware();

const middleware = compose(
    applyMiddleware(sagaMiddleware),
    window.devToolsExtension ? window.devToolsExtension() : (x) => x
);

const store = createStore(reducer, middleware);

sagaMiddleware.run(saga);

export default store;
<commit_msg>#6 reducer hot swapping<commit_after>import {createStore, applyMiddleware, compose} from 'redux';
import createSagaMiddleware from 'redux-saga';

import reducer from './reducer';
import saga from './saga';

const sagaMiddleware = createSagaMiddleware();

const middleware = compose(
    applyMiddleware(sagaMiddleware),
    window.devToolsExtension ? window.devToolsExtension() : (x) => x
);

const store = createStore(reducer, middleware);

sagaMiddleware.run(saga);

if (module.hot) {
    module.hot.accept('./reducer', () => System.import('./reducer').then((newReducer) => store.replaceReducer(newReducer.default)));
}

export default store;
<|endoftext|>