<commit_before>import Service from '@ember/service';
import { inject } from '@ember/service';
import { camelize } from '@ember/string';
import { defaultBranch } from '@cardstack/plugin-utils/environment';
import { singularize, pluralize } from 'ember-inflector';
import DS from 'ember-data';

const noFields = '___no-fields___';

function getType(record) {
  return record.get('type') || record.constructor.modelName;
}

export default Service.extend({
  store: inject(),

  init() {
    this._super();
    this._loadedRecordsCache = {};
    this._contentTypeCache = {};
  },

  async load(branch, type, id, format) {
    branch = branch || defaultBranch;
    let store = this.get('store');
    let contentType = await this._getContentType(type);
    let fieldset = contentType.get(`fieldsets.${format}`);

    if (!fieldset) {
      return await store.findRecord(singularize(type), id, { branch });
    }

    let include = fieldset.map(i => i.field).join(',') || noFields; // note that ember data ignores an empty string includes, so setting to nonsense field
    let record = await store.findRecord(type, id, { include, branch });

    await this._loadRelatedRecords(branch, record, format);

    return record;
  },

  // caching the content types to more efficiently deal with parallel content type lookups
  async _getContentType(type) {
    if (this._contentTypeCache[type]) {
      return await this._contentTypeCache[type];
    }

    this._contentTypeCache[type] = await this.get('store').findRecord('content-type', pluralize(type));
    return await this._contentTypeCache[type];
  },

  async _loadRelatedRecords(branch, record, format) {
    if (!record || !getType(record)) { return; }

    let contentType = await this._getContentType(getType(record));
    let fieldset = contentType.get(`fieldsets.${format}`);

    if (!fieldset || !fieldset.length) { return; } // record is already loaded, you are all done

    let recordLoadPromises = [];
    for (let fieldItem of fieldset) {
      let fieldRecord = await record.get(camelize(fieldItem.field));
      if (!fieldRecord) { continue; }

      if (fieldRecord instanceof DS.ManyArray) {
        for (let fieldRecordItem of fieldRecord.toArray()) {
          recordLoadPromises.push(this._recurseRecord(branch, fieldRecordItem, fieldItem.format));
        }
      } else {
        recordLoadPromises.push(this._recurseRecord(branch, fieldRecord, fieldItem.format));
      }
    }

    await Promise.all(recordLoadPromises);
  },

  async _recurseRecord(branch, record, format) {
    let loadedRecord = await this._loadRecord(branch, getType(record), record.id, format);
    if (!loadedRecord) { return; }
    await this._loadRelatedRecords(branch, loadedRecord, format);
  },

  async _loadRecord(branch, type, id, format) {
    let store = this.get('store');
    let fieldRecordType = await this._getContentType(type);
    let fieldset = fieldRecordType.get(`fieldsets.${format}`);

    if (!fieldset) { return; }

    let include = fieldset.map(i => i.field).join(',') || noFields; // note that ember data ignores an empty string includes, so setting to nonsense field
    let cacheKey = `${branch}/${type}/${id}:${include}`;

    if (this._loadedRecordsCache[cacheKey]) {
      await this._loadedRecordsCache[cacheKey];
      return; // no need to process any further, as it has this record already been loaded into the store
    }

    // we need to specify `reload` in order to allow the included resources to be added to the store.
    // otherwise, if the primary resource is already in the store, ember data is skipping adding the
    // included resources into the store.
    this._loadedRecordsCache[cacheKey] = store.findRecord(type, id, { include, reload: true, branch });

    return await this._loadedRecordsCache[cacheKey];
  }
});<commit_msg>store promises in content type cache<commit_after>import Service from '@ember/service';
import { inject } from '@ember/service';
import { camelize } from '@ember/string';
import { defaultBranch } from '@cardstack/plugin-utils/environment';
import { singularize, pluralize } from 'ember-inflector';
import DS from 'ember-data';

const noFields = '___no-fields___';

function getType(record) {
  return record.get('type') || record.constructor.modelName;
}

export default Service.extend({
  store: inject(),

  init() {
    this._super();
    this._loadedRecordsCache = {};
    this._contentTypeCache = {};
  },

  async load(branch, type, id, format) {
    branch = branch || defaultBranch;
    let store = this.get('store');
    let contentType = await this._getContentType(type);
    let fieldset = contentType.get(`fieldsets.${format}`);

    if (!fieldset) {
      return await store.findRecord(singularize(type), id, { branch });
    }

    let include = fieldset.map(i => i.field).join(',') || noFields; // note that ember data ignores an empty string includes, so setting to nonsense field
    let record = await store.findRecord(type, id, { include, branch });

    await this._loadRelatedRecords(branch, record, format);

    return record;
  },

  // caching the content types to more efficiently deal with parallel content type lookups
  async _getContentType(type) {
    if (this._contentTypeCache[type]) {
      return await this._contentTypeCache[type];
    }

    this._contentTypeCache[type] = this.get('store').findRecord('content-type', pluralize(type));
    return await this._contentTypeCache[type];
  },

  async _loadRelatedRecords(branch, record, format) {
    if (!record || !getType(record)) { return; }

    let contentType = await this._getContentType(getType(record));
    let fieldset = contentType.get(`fieldsets.${format}`);

    if (!fieldset || !fieldset.length) { return; } // record is already loaded, you are all done

    let recordLoadPromises = [];
    for (let fieldItem of fieldset) {
      let fieldRecord = await record.get(camelize(fieldItem.field));
      if (!fieldRecord) { continue; }

      if (fieldRecord instanceof DS.ManyArray) {
        for (let fieldRecordItem of fieldRecord.toArray()) {
          recordLoadPromises.push(this._recurseRecord(branch, fieldRecordItem, fieldItem.format));
        }
      } else {
        recordLoadPromises.push(this._recurseRecord(branch, fieldRecord, fieldItem.format));
      }
    }

    await Promise.all(recordLoadPromises);
  },

  async _recurseRecord(branch, record, format) {
    let loadedRecord = await this._loadRecord(branch, getType(record), record.id, format);
    if (!loadedRecord) { return; }
    await this._loadRelatedRecords(branch, loadedRecord, format);
  },

  async _loadRecord(branch, type, id, format) {
    let store = this.get('store');
    let fieldRecordType = await this._getContentType(type);
    let fieldset = fieldRecordType.get(`fieldsets.${format}`);

    if (!fieldset) { return; }

    let include = fieldset.map(i => i.field).join(',') || noFields; // note that ember data ignores an empty string includes, so setting to nonsense field
    let cacheKey = `${branch}/${type}/${id}:${include}`;

    if (this._loadedRecordsCache[cacheKey]) {
      await this._loadedRecordsCache[cacheKey];
      return; // no need to process any further, as this record has already been loaded into the store
    }

    // we need to specify `reload` in order to allow the included resources to be added to the store.
    // otherwise, if the primary resource is already in the store, ember data is skipping adding the
    // included resources into the store.
    this._loadedRecordsCache[cacheKey] = store.findRecord(type, id, { include, reload: true, branch });

    return await this._loadedRecordsCache[cacheKey];
  }
});<|endoftext|>


<commit_before>import Mailgun from 'mailgun-js'
import {EmailTemplate} from 'email-templates'
import Handlebars from 'handlebars'
import path from 'path'
import fs from 'fs'
import log from './log'

const templateDir = path.resolve(__dirname, './email-templates')
const headerHTML = fs.readFileSync(templateDir + '/header.hbs', {encoding: 'utf-8'})
const footerHTML = fs.readFileSync(templateDir + '/footer.hbs', {encoding: 'utf-8'})

Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {
  switch (operator) {
    case '==':
      return (v1 == v2) ? options.fn(this) : options.inverse(this)
    case '===':
      return (v1 === v2) ? options.fn(this) : options.inverse(this)
    case '<':
      return (v1 < v2) ? options.fn(this) : options.inverse(this)
    case '<=':
      return (v1 <= v2) ? options.fn(this) : options.inverse(this)
    case '>':
      return (v1 > v2) ? options.fn(this) : options.inverse(this)
    case '>=':
      return (v1 >= v2) ? options.fn(this) : options.inverse(this)
    case '&&':
      return (v1 && v2) ? options.fn(this) : options.inverse(this)
    case '||':
      return (v1 || v2) ? options.fn(this) : options.inverse(this)
    default:
      return options.inverse(this)
  }
})

Handlebars.registerPartial('header', headerHTML)
Handlebars.registerPartial('footer', footerHTML)

const senderAddress = 'Team Bernie<info@berniesanders.com>'

export default class MG {
  constructor(apiKey, domain) {
    this.mailgun = Mailgun({apiKey: apiKey, domain: domain})
  }

  async sendEventConfirmation(form, constituent, event_types, debugging) {
    if (form.capacity =='0') {
      form.capacity = 'unlimited'
    }

    // Sort event dates by date
    if (typeof form.event_dates == 'string') {
      form.event_dates = JSON.parse(form.event_dates)
    }

    form.event_dates.sort((a, b) => {
        return a.date.localeCompare(b.date)
    })

    // Get the event type name
    event_types.forEach((type) => {
      if (type.event_type_id == form.event_type_id) {
        form.event_type_name = type.name
      }
    })

    constituent.cons_email.forEach((email) => {
      if (email.is_primary == '1') {
        constituent['email'] = email.email
      }
    })

    let data = {
      event: form,
      user: constituent
    }

    let eventConfirmation = new EmailTemplate(templateDir + '/event-create-confirmation')
    let content = await eventConfirmation.render(data)

    let message = {
      from: senderAddress,
      to: form.cons_email,
      subject: 'Event Creation Confirmation',
      text: content.text,
      html: content.html
    }

    log.debug(message)

    if (debugging) {
      return message
    } else {
      return await this.mailgun.messages().send(message)
    }
  }

  async sendPhoneBankConfirmation(form, constituent, debugging) {
    constituent.cons_email.forEach((email) => {
      if (email.is_primary == '1') {
        constituent['email'] = email.email
      }
    })

    let data = {
      event: form,
      user: constituent
    }

    let template = new EmailTemplate(templateDir + '/event-create-confirmation')
    let content = await template.render(data)

    let message = {
      from: senderAddress,
      'h:Reply-To': 'help@berniesanders.com',
      to: form.cons_email,
      subject: 'Event Creation Confirmation',
      text: content.text,
      html: content.html
    }

    if (debugging) {
      return message
    } else {
      return await this.mailgun.messages().send(message)
    }
  }

  async sendAdminEventInvite(data, debugging) {
    let template = new EmailTemplate(templateDir + '/admin-event-invitation')
    let content = await template.render(data)

    let message = {
      from: data.senderAddress,
      'h:Reply-To': data.hostAddress,
      //to: data.recipientAddress,
      subject: 'Fwd: HELP! I need more people to come to my phonebank',
      text: content.text
    }

    log.info("Sending Mailgun message", message)

    if (debugging) {
      return message
    } else {
      return await this.mailgun.messages().send(message)
    }
  }
}
<commit_msg>Uncomment recipient<commit_after>import Mailgun from 'mailgun-js'
import {EmailTemplate} from 'email-templates'
import Handlebars from 'handlebars'
import path from 'path'
import fs from 'fs'
import log from './log'

const templateDir = path.resolve(__dirname, './email-templates')
const headerHTML = fs.readFileSync(templateDir + '/header.hbs', {encoding: 'utf-8'})
const footerHTML = fs.readFileSync(templateDir + '/footer.hbs', {encoding: 'utf-8'})

Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {
  switch (operator) {
    case '==':
      return (v1 == v2) ? options.fn(this) : options.inverse(this)
    case '===':
      return (v1 === v2) ? options.fn(this) : options.inverse(this)
    case '<':
      return (v1 < v2) ? options.fn(this) : options.inverse(this)
    case '<=':
      return (v1 <= v2) ? options.fn(this) : options.inverse(this)
    case '>':
      return (v1 > v2) ? options.fn(this) : options.inverse(this)
    case '>=':
      return (v1 >= v2) ? options.fn(this) : options.inverse(this)
    case '&&':
      return (v1 && v2) ? options.fn(this) : options.inverse(this)
    case '||':
      return (v1 || v2) ? options.fn(this) : options.inverse(this)
    default:
      return options.inverse(this)
  }
})

Handlebars.registerPartial('header', headerHTML)
Handlebars.registerPartial('footer', footerHTML)

const senderAddress = 'Team Bernie<info@berniesanders.com>'

export default class MG {
  constructor(apiKey, domain) {
    this.mailgun = Mailgun({apiKey: apiKey, domain: domain})
  }

  async sendEventConfirmation(form, constituent, event_types, debugging) {
    if (form.capacity =='0') {
      form.capacity = 'unlimited'
    }

    // Sort event dates by date
    if (typeof form.event_dates == 'string') {
      form.event_dates = JSON.parse(form.event_dates)
    }

    form.event_dates.sort((a, b) => {
        return a.date.localeCompare(b.date)
    })

    // Get the event type name
    event_types.forEach((type) => {
      if (type.event_type_id == form.event_type_id) {
        form.event_type_name = type.name
      }
    })

    constituent.cons_email.forEach((email) => {
      if (email.is_primary == '1') {
        constituent['email'] = email.email
      }
    })

    let data = {
      event: form,
      user: constituent
    }

    let eventConfirmation = new EmailTemplate(templateDir + '/event-create-confirmation')
    let content = await eventConfirmation.render(data)

    let message = {
      from: senderAddress,
      to: form.cons_email,
      subject: 'Event Creation Confirmation',
      text: content.text,
      html: content.html
    }

    log.debug(message)

    if (debugging) {
      return message
    } else {
      return await this.mailgun.messages().send(message)
    }
  }

  async sendPhoneBankConfirmation(form, constituent, debugging) {
    constituent.cons_email.forEach((email) => {
      if (email.is_primary == '1') {
        constituent['email'] = email.email
      }
    })

    let data = {
      event: form,
      user: constituent
    }

    let template = new EmailTemplate(templateDir + '/event-create-confirmation')
    let content = await template.render(data)

    let message = {
      from: senderAddress,
      'h:Reply-To': 'help@berniesanders.com',
      to: form.cons_email,
      subject: 'Event Creation Confirmation',
      text: content.text,
      html: content.html
    }

    if (debugging) {
      return message
    } else {
      return await this.mailgun.messages().send(message)
    }
  }

  async sendAdminEventInvite(data, debugging) {
    let template = new EmailTemplate(templateDir + '/admin-event-invitation')
    let content = await template.render(data)

    let message = {
      from: data.senderAddress,
      'h:Reply-To': data.hostAddress,
      to: data.recipientAddress,
      subject: 'Fwd: HELP! I need more people to come to my phonebank',
      text: content.text
    }

    log.info("Sending Mailgun message", message)

    if (debugging) {
      return message
    } else {
      return await this.mailgun.messages().send(message)
    }
  }
}
<|endoftext|>


<commit_before>var map;
var layer_mapnik;
var layer_tah;
var layer_markers;
var PI = Math.PI;
var latfield = '';
var lonfield = '';
var latfield_id='';
var lonfield_id='';
var centerlon = 10;
var centerlat = 52;
var zoom = 6;

function lon2merc(lon) {
    return 20037508.34 * lon / 180;
}

function lat2merc(lat) {
	lat = Math.log(Math.tan( (90 + lat) * PI / 360)) / PI;
	return 20037508.34 * lat;
}

function merc2lon(lon) {
	return lon*180/20037508.34;
};

function merc2lat(lat) {
	return Math.atan(Math.exp(lat*PI/20037508.34))*360/PI-90;
};

OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
	defaultHandlerOptions: {
		'single': true,
		'double': false,
		'pixelTolerance': 0,
		'stopSingle': false,
		'stopDouble': false
	},

	initialize: function(options) {
		this.handlerOptions = OpenLayers.Util.extend(
			{}, this.defaultHandlerOptions
		);
		OpenLayers.Control.prototype.initialize.apply(
			this, arguments
		);
			this.handler = new OpenLayers.Handler.Click(
				this, {
					'click': this.trigger
			}, this.handlerOptions
		);
	},

	trigger: function(e) {
		var lonlat = map.getLonLatFromViewPortPx(e.xy);
		lat=merc2lat(lonlat.lat);
		lon=merc2lon(lonlat.lon);
		if(parent.document.getElementById(latfield_id)==null){
			latfield=document.getElementById('osmlat');
		}else{
			latfield=parent.document.getElementById(latfield_id);
		}
		if(parent.document.getElementById(lonfield_id)==null){
			lonfield=document.getElementById('osmlon');
		}else{
			lonfield=parent.document.getElementById(lonfield_id);
		}
		latfield.value = lat;
		lonfield.value = lon;
	}
});

function init(){
	var field = window.name.substring(0, window.name.lastIndexOf("."));
	if(parent.document.getElementById(field+".latfield")!=null){
		latfield_id = parent.document.getElementById(field+".latfield").value;
		document.getElementById('osm').style.display="none";
	}
	if(parent.document.getElementById(field+".lonfield")!=null){
		lonfield_id = parent.document.getElementById(field+".lonfield").value;
	}
	if(parent.document.getElementById(field+".centerlat")!=null){
		centerlat =parseFloat(parent.document.getElementById(field+".centerlat").value);
	}
	if(parent.document.getElementById(field+".centerlon")!=null){
		centerlon = parseFloat(parent.document.getElementById(field+".centerlon").value);
	}
	if(parent.document.getElementById(field+".zoom")!=null){
		zoom = parseFloat(parent.document.getElementById(field+".zoom").value);
	}
}

function drawmap() {
	OpenLayers.Lang.setCode('de');
	mapdiv=document.getElementById('map');
	mapdiv.style.height=window.innerHeight+"px";
	mapdiv.style.width=window.innerWidth+"px";
	map = new OpenLayers.Map('map', {
		projection: new OpenLayers.Projection("EPSG:900913"),
		displayProjection: new OpenLayers.Projection("EPSG:4326"),
		controls: [
			new OpenLayers.Control.MouseDefaults(),
			new OpenLayers.Control.PanZoomBar()],
		maxExtent:
			new OpenLayers.Bounds(-20037508.34,-20037508.34, 20037508.34, 20037508.34),
		numZoomLevels: 18,
		maxResolution: 156543,
		units: 'meters'
	});

	layer_mapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");

	map.addLayers([layer_mapnik]);
	var y =lat2merc(centerlat);
	var x =lon2merc(centerlon);
	map.setCenter(new OpenLayers.LonLat(x, y), zoom);

	// Check for geolocation support
	if(navigator.geolocation){
		navigator.geolocation.getCurrentPosition(function(position){
			var y =lat2merc(position.coords.latitude);
			var x =lon2merc(position.coords.longitude);
			map.setCenter(new OpenLayers.LonLat(x, y), '17');
		});
	}

	var click = new OpenLayers.Control.Click();
	map.addControl(click);
	click.activate();
}
<commit_msg>mod-freifunk: Fix problem with osm map, OpenLayers.Control.MouseDefaults() was removed in OpenLayers 2.12<commit_after>var map;
var layer_mapnik;
var layer_tah;
var layer_markers;
var PI = Math.PI;
var latfield = '';
var lonfield = '';
var latfield_id='';
var lonfield_id='';
var centerlon = 10;
var centerlat = 52;
var zoom = 6;

function lon2merc(lon) {
    return 20037508.34 * lon / 180;
}

function lat2merc(lat) {
	lat = Math.log(Math.tan( (90 + lat) * PI / 360)) / PI;
	return 20037508.34 * lat;
}

function merc2lon(lon) {
	return lon*180/20037508.34;
};

function merc2lat(lat) {
	return Math.atan(Math.exp(lat*PI/20037508.34))*360/PI-90;
};

OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
	defaultHandlerOptions: {
		'single': true,
		'double': false,
		'pixelTolerance': 0,
		'stopSingle': false,
		'stopDouble': false
	},

	initialize: function(options) {
		this.handlerOptions = OpenLayers.Util.extend(
			{}, this.defaultHandlerOptions
		);
		OpenLayers.Control.prototype.initialize.apply(
			this, arguments
		);
			this.handler = new OpenLayers.Handler.Click(
				this, {
					'click': this.trigger
			}, this.handlerOptions
		);
	},

	trigger: function(e) {
		var lonlat = map.getLonLatFromViewPortPx(e.xy);
		lat=merc2lat(lonlat.lat);
		lon=merc2lon(lonlat.lon);
		if(parent.document.getElementById(latfield_id)==null){
			latfield=document.getElementById('osmlat');
		}else{
			latfield=parent.document.getElementById(latfield_id);
		}
		if(parent.document.getElementById(lonfield_id)==null){
			lonfield=document.getElementById('osmlon');
		}else{
			lonfield=parent.document.getElementById(lonfield_id);
		}
		latfield.value = lat;
		lonfield.value = lon;
	}
});

function init(){
	var field = window.name.substring(0, window.name.lastIndexOf("."));
	if(parent.document.getElementById(field+".latfield")!=null){
		latfield_id = parent.document.getElementById(field+".latfield").value;
		document.getElementById('osm').style.display="none";
	}
	if(parent.document.getElementById(field+".lonfield")!=null){
		lonfield_id = parent.document.getElementById(field+".lonfield").value;
	}
	if(parent.document.getElementById(field+".centerlat")!=null){
		centerlat =parseFloat(parent.document.getElementById(field+".centerlat").value);
	}
	if(parent.document.getElementById(field+".centerlon")!=null){
		centerlon = parseFloat(parent.document.getElementById(field+".centerlon").value);
	}
	if(parent.document.getElementById(field+".zoom")!=null){
		zoom = parseFloat(parent.document.getElementById(field+".zoom").value);
	}
}

function drawmap() {
	OpenLayers.Lang.setCode('de');
	mapdiv=document.getElementById('map');
	mapdiv.style.height=window.innerHeight+"px";
	mapdiv.style.width=window.innerWidth+"px";
	map = new OpenLayers.Map('map', {
		projection: new OpenLayers.Projection("EPSG:900913"),
		displayProjection: new OpenLayers.Projection("EPSG:4326"),
		controls: [
			new OpenLayers.Control.Navigation(),
			new OpenLayers.Control.PanZoomBar()],
		maxExtent:
			new OpenLayers.Bounds(-20037508.34,-20037508.34, 20037508.34, 20037508.34),
		numZoomLevels: 18,
		maxResolution: 156543,
		units: 'meters'
	});

	layer_mapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");

	map.addLayers([layer_mapnik]);
	var y =lat2merc(centerlat);
	var x =lon2merc(centerlon);
	map.setCenter(new OpenLayers.LonLat(x, y), zoom);

	// Check for geolocation support
	if(navigator.geolocation){
		navigator.geolocation.getCurrentPosition(function(position){
			var y =lat2merc(position.coords.latitude);
			var x =lon2merc(position.coords.longitude);
			map.setCenter(new OpenLayers.LonLat(x, y), '17');
		});
	}

	var click = new OpenLayers.Control.Click();
	map.addControl(click);
	click.activate();
}
<|endoftext|>


<commit_before>
function buildMessageAggregator(parent, initName, destroyName) {
	var childCnt = 0;
	var reportCnt = 0;

	parent.on(initName, up);
	parent.on('before:' + destroyName, down);

	function addChild(child) {
		child.on('all:' + initName, up);
		child.on('before:all:' + destroyName, down);
		childCnt++;
	}

	function up() {
		if (++reportCnt === childCnt + 1) {
			parent.trigger('all:' + initName);
		}
	}

	function down() {
		if (--reportCnt === childCnt) {
			parent.trigger('before:all:' + destroyName);
		}
	}

	return { addChild: addChild };
}
<commit_msg>export buildMessageAggregator<commit_after>
function buildMessageAggregator(parent, initName, destroyName) {
	var childCnt = 0;
	var reportCnt = 0;

	parent.on(initName, up);
	parent.on('before:' + destroyName, down);

	function addChild(child) {
		child.on('all:' + initName, up);
		child.on('before:all:' + destroyName, down);
		childCnt++;
	}

	function up() {
		if (++reportCnt === childCnt + 1) {
			parent.trigger('all:' + initName);
		}
	}

	function down() {
		if (--reportCnt === childCnt) {
			parent.trigger('before:all:' + destroyName);
		}
	}

	return { addChild: addChild };
}

FC.buildMessageAggregator = buildMessageAggregator;
<|endoftext|>


<commit_before>var awaitingResponse = [];

/**
 *  Gets the string from the locales
 *
 *  @param {string} name A valid localized string which doesn't include 'settingsJs'
 *  @returns {string} The localized string
 */
function getString(name) {
	return chrome.i18n.getMessage("contentScript_" + name);
}

$(function(){
	chrome.runtime.sendMessage({type: "showAddButton"}, function(response){
		if(response){
			launch();
			setInterval(function(){
				launch();
			}, 1000);
		}
	});

	chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
		switch (request.type) {
			case "contentScript_response":
				onMessageResponse(request.responseType, request.id);
				break;
		}
	});

	$(document).on("click", "#ytn-btn, .ytn-btn", function(){
		var elem = $(this),
			channelId = elem.attr("data-channelId");

		if(elem.hasClass("yt-uix-button-subscribe-branded")){// Add channel
			awaitingResponse.push({
				id: channelId,
				elem: elem
			});
			chrome.runtime.sendMessage({type: "addYoutubeChannel", contentScript: true, name: channelId, refresh: true});
		}else if(elem.hasClass("yt-uix-button-subscribed-branded")){// Remove channel
			awaitingResponse.push({
				id: channelId,
				elem: elem
			});
			chrome.runtime.sendMessage({type: "removeYoutube", num: 1, contentScript: true, name: channelId, refresh: true});
		}
	});
});
function onMessageResponse(type, id){
	awaitingResponse.forEach(function(item, i) {
		if(item.id == id){
			if(type)
				item.elem.removeClass("yt-uix-button-subscribe-branded").addClass("yt-uix-button-subscribed-branded");
			else
				item.elem.addClass("yt-uix-button-subscribe-branded").removeClass("yt-uix-button-subscribed-branded");
			awaitingResponse.pop(i);
		}
	});
}
function launch(){
	var slashes = window.location.href.split("/");
	if(slashes.indexOf("user") < 0 && slashes.indexOf("channel") < 0 && slashes.indexOf("subscription_manager") < 0 && slashes.pop().split("?").shift() != "watch"){
		return;
	}
	if(slashes.indexOf("subscription_manager") > -1 && $(".ytn-btn").length == 0){// If is on page: https://www.youtube.com/subscription_manager
		var elem = '<button class="yt-uix-button yt-uix-button-size-default yt-uix-button-has-icon no-icon-markup hover-enabled ytn-btn" type="button" style="margin-left: 5px;">\
			\
				' + getString("addChannel") + '\
				' + getString("channelAdded") + '\
				' + getString("removeAdded") + '\
			\
		</button>';
		var elems = $(elem).insertBefore(".yt-uix-overlay");
		for(var i = 0; i < elems.length; i++){
			var channelId = $($(".yt-uix-overlay")[i]).parent().children(".yt-uix-button").attr("data-channel-external-id");
			$(elems[i]).attr("data-channelId", channelId);
			chrome.runtime.sendMessage({type: "doesYoutubeExist", id: channelId, index: i}, function(response){
				if(response.status)
					$(elems[response.index]).removeClass("yt-uix-button-subscribe-branded").addClass("yt-uix-button-subscribed-branded");
				else
					$(elems[response.index]).addClass("yt-uix-button-subscribe-branded").removeClass("yt-uix-button-subscribed-branded");
			});
		}
	}else if($("#ytn-btn").length == 0 && slashes.indexOf("subscription_manager") < 0){// For everything else
		var elem = '<button id="ytn-btn" class="yt-uix-button yt-uix-button-size-default yt-uix-button-has-icon no-icon-markup hover-enabled" type="button" style="margin-left: 5px;">\
			\
				' + getString("addChannel") + '\
				' + getString("channelAdded") + '\
				' + getString("removeAdded") + '\
			\
		</button>';
		$(elem).insertBefore(".yt-uix-overlay");

		var channelId = $(".yt-uix-button.yt-uix-subscription-button").attr("data-channel-external-id");
		$("#ytn-btn").attr("data-channelId", channelId);
		chrome.runtime.sendMessage({type: "doesYoutubeExist", id: channelId}, function(response){
			if(response.status)
				$("#ytn-btn").removeClass("yt-uix-button-subscribe-branded").addClass("yt-uix-button-subscribed-branded");
			else
				$("#ytn-btn").addClass("yt-uix-button-subscribe-branded").removeClass("yt-uix-button-subscribed-branded");
		});
	}
}
<commit_msg>Fixed the remove button acting weird<commit_after>var awaitingResponse = [];

/**
 *  Gets the string from the locales
 *
 *  @param {string} name A valid localized string which doesn't include 'settingsJs'
 *  @returns {string} The localized string
 */
function getString(name) {
	return chrome.i18n.getMessage("contentScript_" + name);
}

$(function(){
	chrome.runtime.sendMessage({type: "showAddButton"}, function(response){
		if(response){
			launch();
			setInterval(function(){
				launch();
			}, 1000);
		}
	});

	chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
		switch (request.type) {
			case "contentScript_response":
				onMessageResponse(request.responseType, request.id);
				break;
		}
	});

	$(document).on("click", "#ytn-btn, .ytn-btn", function(){
		var elem = $(this),
			channelId = elem.attr("data-channelId");

		if(elem.hasClass("yt-uix-button-subscribe-branded")){// Add channel
			awaitingResponse.push({
				id: channelId,
				elem: elem
			});
			chrome.runtime.sendMessage({type: "addYoutubeChannel", contentScript: true, name: channelId, refresh: true});
		}else if(elem.hasClass("yt-uix-button-subscribed-branded")){// Remove channel
			awaitingResponse.push({
				id: channelId,
				elem: elem
			});
			chrome.runtime.sendMessage({type: "removeYoutube", num: 1, contentScript: true, name: channelId, refresh: true});
		}
	});
});
function onMessageResponse(type, id){
	awaitingResponse.forEach(function(item, i) {
		if(item.id == id){
			if(type)
				item.elem.removeClass("yt-uix-button-subscribe-branded").addClass("yt-uix-button-subscribed-branded");
			else
				item.elem.addClass("yt-uix-button-subscribe-branded").removeClass("yt-uix-button-subscribed-branded");
			awaitingResponse.pop(i);
		}
	});
}
function launch(){
	var slashes = window.location.href.split("/");
	if(slashes.indexOf("user") < 0 && slashes.indexOf("channel") < 0 && slashes.indexOf("subscription_manager") < 0 && slashes.pop().split("?").shift() != "watch"){
		return;
	}
	if(slashes.indexOf("subscription_manager") > -1 && $(".ytn-btn").length == 0){// If is on page: https://www.youtube.com/subscription_manager
		var elem = '<button class="yt-uix-button yt-uix-button-size-default yt-uix-button-has-icon no-icon-markup hover-enabled ytn-btn" type="button" style="margin-left: 5px;">\
			\
				' + getString("addChannel") + '\
				' + getString("channelAdded") + '\
				' + getString("removeChannel") + '\
			\
		</button>';
		var elems = $(elem).insertBefore(".yt-uix-overlay");
		for(var i = 0; i < elems.length; i++){
			var channelId = $($(".yt-uix-overlay")[i]).parent().children(".yt-uix-button").attr("data-channel-external-id");
			$(elems[i]).attr("data-channelId", channelId);
			chrome.runtime.sendMessage({type: "doesYoutubeExist", id: channelId, index: i}, function(response){
				if(response.status)
					$(elems[response.index]).removeClass("yt-uix-button-subscribe-branded").addClass("yt-uix-button-subscribed-branded");
				else
					$(elems[response.index]).addClass("yt-uix-button-subscribe-branded").removeClass("yt-uix-button-subscribed-branded");
			});
		}
	}else if($("#ytn-btn").length == 0 && slashes.indexOf("subscription_manager") < 0){// For everything else
		var elem = '<button id="ytn-btn" class="yt-uix-button yt-uix-button-size-default yt-uix-button-has-icon no-icon-markup hover-enabled" type="button" style="margin-left: 5px;">\
			\
				' + getString("addChannel") + '\
				' + getString("channelAdded") + '\
				' + getString("removeAdded") + '\
			\
		</button>';
		$(elem).insertBefore(".yt-uix-overlay");

		var channelId = $(".yt-uix-button.yt-uix-subscription-button").attr("data-channel-external-id");
		$("#ytn-btn").attr("data-channelId", channelId);
		chrome.runtime.sendMessage({type: "doesYoutubeExist", id: channelId}, function(response){
			if(response.status)
				$("#ytn-btn").removeClass("yt-uix-button-subscribe-branded").addClass("yt-uix-button-subscribed-branded");
			else
				$("#ytn-btn").addClass("yt-uix-button-subscribe-branded").removeClass("yt-uix-button-subscribed-branded");
		});
	}
}
<|endoftext|>


<commit_before>
var mime = require( 'mime-lib' )
var iconv = require( 'codes' )

function Body( header, body, envelope ) {

  var boundary = header.contentType && header.contentType.boundary
  var bounds   = []
  var index    = -1

  if( boundary ) {

    var start = body.indexOf( '--' + boundary + '\r\n' )
    var end   = body.lastIndexOf( '--' + boundary + '--' )

    if( ~start ) {

      var parts = body
        .slice( start + boundary.length + 4, end )
        .split( '--' + boundary + '\r\n' )

      for( var i = 0; i < parts.length; i++ ) {
        this[i] = require('../envelope')( parts[i] )
      }

    } else {
      boundary = null
    }

  }

  if( !boundary ) {

    var isText = header.contentType &&
      ~header.contentType.mime.indexOf( 'text' )

    this[0] = body.trim()

    // Automatically create a buffer from
    // non-text base64 encoded data
    if( !isText && header.contentTransferEncoding === 'base64' ) {
      this[0] = new Buffer( this[0], 'base64' )
    }

    // Automatically decode text from either
    // base64 or quoted-printable encoding
    if( isText ) {
      if( header.contentTransferEncoding === 'quoted-printable' )
        this[0] = mime.decodeQP( this[0] )
      if( header.contentTransferEncoding === 'base64' )
        this[0] = new Buffer( this[0], 'base64' ).toString()
    }

    // Try to convert to UTF8, if it's not UTF8 yet
    var charset = header.contentType &&
      header.contentType.charset

    if( charset ) {
      try { this[0] = iconv.decode( this[0], charset ) }
      catch( e ) { /* unsupported by iconv */ }
    }

    // Convert this part to an Envelope,
    // if this part appears to be an attached message
    if( header.contentType && header.contentType.mime === 'message/rfc822' ) {
      this[0] = require('../envelope')( this[0] )
    }

  }

}

Body.prototype = Object.create( null )

module.exports = Body
<commit_msg>Removed unused variables in body/index<commit_after>
var mime = require( 'mime-lib' )
var iconv = require( 'codes' )

function Body( header, body, envelope ) {

  var boundary = header.contentType &&
    header.contentType.boundary

  if( boundary ) {

    var start = body.indexOf( '--' + boundary + '\r\n' )
    var end   = body.lastIndexOf( '--' + boundary + '--' )

    if( ~start ) {

      var parts = body
        .slice( start + boundary.length + 4, end )
        .split( '--' + boundary + '\r\n' )

      for( var i = 0; i < parts.length; i++ ) {
        this[i] = require('../envelope')( parts[i] )
      }

    } else {
      boundary = null
    }

  }

  if( !boundary ) {

    var isText = header.contentType &&
      ~header.contentType.mime.indexOf( 'text' )

    this[0] = body.trim()

    // Automatically create a buffer from
    // non-text base64 encoded data
    if( !isText && header.contentTransferEncoding === 'base64' ) {
      this[0] = new Buffer( this[0], 'base64' )
    }

    // Automatically decode text from either
    // base64 or quoted-printable encoding
    if( isText ) {
      if( header.contentTransferEncoding === 'quoted-printable' )
        this[0] = mime.decodeQP( this[0] )
      if( header.contentTransferEncoding === 'base64' )
        this[0] = new Buffer( this[0], 'base64' ).toString()
    }

    // Try to convert to UTF8, if it's not UTF8 yet
    var charset = header.contentType &&
      header.contentType.charset

    if( charset ) {
      try { this[0] = iconv.decode( this[0], charset ) }
      catch( e ) { /* unsupported by iconv */ }
    }

    // Convert this part to an Envelope,
    // if this part appears to be an attached message
    if( header.contentType && header.contentType.mime === 'message/rfc822' ) {
      this[0] = require('../envelope')( this[0] )
    }

  }

}

Body.prototype = Object.create( null )

module.exports = Body
<|endoftext|>


<commit_before>function initMap() { // Initialize Google Map
    map = new google.maps.Map(document.getElementById('map'), { // Define Map Settings
        center: {
            lat: 35,
            lng: -98
        },
        zoom: 4,
        disableDefaultUI: true,
        zoomControl: true,
        mapTypeControl: false,
        streetViewControl: false,
        rotateControl: false,
        fullscreenControl: false,
        backgroundColor: '#333333',
        styles: [
            {
                featureType: 'water',
                elementType: 'geometry',
                stylers: [{
                    color: '#222222'
                }]
            },
            {
                featureType: 'landscape',
                elementType: 'geometry',
                stylers: [{
                    color: '#444444'
                }]
            },
            {
                featureType: 'road',
                elementType: 'geometry',
                stylers: [
                    {
                        color: '#444444'
                    },
                    {
                        lightness: -37
                    }
                ]
            },
            {
                featureType: 'poi',
                elementType: 'geometry',
                stylers: [{
                    color: '#666666'
                }]
            },
            {
                elementType: 'labels.text.stroke',
                stylers: [
                    {
                        visibility: 'on'
                    },
                    {
                        color: '#666666'
                    },
                    {
                        weight: 2
                    },
                    {
                        gamma: 0.84
                    }
                ]
            },
            {
                elementType: 'labels.text.fill',
                stylers: [{
                    color: '#ffffff'
                }]
            },
            {
                featureType: 'administrative',
                elementType: 'geometry',
                stylers: [
                    {
                        weight: 0.6
                    },
                    {
                        color: '#d12727'
                    }
                ]
            },
            {
                elementType: 'labels.icon',
                stylers: [{
                    visibility: 'off'
                }]
            },
            {
                featureType: 'poi.park',
                elementType: 'geometry',
                stylers: [{
                    color: '#333333'
                }]
            }
        ]
    });
}
<commit_msg>Start drawing colleges on alumni map<commit_after>var colleges = [
    {
        name: 'WPI',
        position: {
            lat: 42.2746,
            lng: -71.8063
        },
    }
];

// Called by Maps API upon loading.
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), { // Define Map Settings
        center: {
            lat: 35,
            lng: -98
        },
        zoom: 4,
        disableDefaultUI: true,
        zoomControl: true,
        mapTypeControl: false,
        streetViewControl: false,
        rotateControl: false,
        fullscreenControl: false,
        backgroundColor: '#333333',
        styles: [
            {
                featureType: 'water',
                elementType: 'geometry',
                stylers: [{
                    color: '#222222'
                }]
            },
            {
                featureType: 'landscape',
                elementType: 'geometry',
                stylers: [{
                    color: '#444444'
                }]
            },
            {
                featureType: 'road',
                elementType: 'geometry',
                stylers: [
                    {
                        color: '#444444'
                    },
                    {
                        lightness: -37
                    }
                ]
            },
            {
                featureType: 'poi',
                elementType: 'geometry',
                stylers: [{
                    color: '#666666'
                }]
            },
            {
                elementType: 'labels.text.stroke',
                stylers: [
                    {
                        visibility: 'on'
                    },
                    {
                        color: '#666666'
                    },
                    {
                        weight: 2
                    },
                    {
                        gamma: 0.84
                    }
                ]
            },
            {
                elementType: 'labels.text.fill',
                stylers: [{
                    color: '#ffffff'
                }]
            },
            {
                featureType: 'administrative',
                elementType: 'geometry',
                stylers: [
                    {
                        weight: 0.6
                    },
                    {
                        color: '#d12727'
                    }
                ]
            },
            {
                elementType: 'labels.icon',
                stylers: [{
                    visibility: 'off'
                }]
            },
            {
                featureType: 'poi.park',
                elementType: 'geometry',
                stylers: [{
                    color: '#333333'
                }]
            }
        ]
    });

    for (college of colleges) {
        new google.maps.Marker({
            position: college.position,
            title: college.name,
        }).setMap(map);
    }
}
<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        var nodemap = [];
        var origroomlist = [];
        var roomlist = [];
        var removelist = [];
        document.getElementById("paintbtn").onclick = paint;

        function removeRooms(){
            origroomlist = roomlist.slice(0);
            removelist = [];
            for(var i = 0; i< roomlist.length; i++){
                var remove = 1;
                var tempHeight = roomlist[i].height;
                var tempWidth = roomlist[i].width;
                for(var j = 0; j< tempWidth; j++){
                    for(var k = 0; k< tempHeight; k++){
                        if(nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited == 1){
                            remove = 0;
                            break;
                        }
                    }
                }

                if(remove ==1 ){
                    roomlist[i].removed = 1;
                }
            }
        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }
          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
            nodemap = [];
            roomlist = [];
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }
            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );

            for(i = 0; i< randw; i++){
                for(j = 0; j< randh; j++){
                    nodemap[x+i][y+j].isRoom = 1;
                }
            }
            var room = {
              x:x,
              y:y,
              width: randw,
              height: randh,
              removed: 0
            };
            roomlist.push(room);
            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;
            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                nodemap.push([]);
                for(var j = 0; j< pathHeight; j++){
                    var node = {
                        isVisited: 0,
                        isRoom:0,
                        n:0,
                        s:0,
                        e:0,
                        w:0,
                        x:i,
                        y:j
                    };
                    nodemap[i].push(node);
               }
           }

           //create a random path that we will walk
           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //set the start node as visited in the beginning
           nodemap[startpoint.x][startpoint.y].isVisited = 1;

           //loop through the walk
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
                }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               if(movedirX < 0){
                   nodemap[movingpointold.x][movingpointold.y].w = 1;
                   nodemap[movingpoint.x][movingpoint.y].e = 1;
               }else if(movedirX > 0){
                   nodemap[movingpointold.x][movingpointold.y].e = 1;
                   nodemap[movingpoint.x][movingpoint.y].w = 1;
               }
               if(movedirY < 0){
                   nodemap[movingpointold.x][movingpointold.y].n =1;
                   nodemap[movingpoint.x][movingpoint.y].s = 1;
               }else if(movedirY >0){
                   nodemap[movingpointold.x][movingpointold.y].s = 1;
                   nodemap[movingpoint.x][movingpoint.y].n = 1;
               }

               nodemap[movingpoint.x][movingpoint.y].isVisited = 1

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

           //create a branch point
           var branchpoints = [];
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j< nodemap[i].length; j++){
                   var neighboorcount = 0;
                   if(typeof nodemap[i][j - 1] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++
                       }
                   }
                   if(typeof nodemap[i][j + 1] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++
                       }
                   }
                   if(typeof nodemap[i - 1][j] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++
                       }
                   }
                   if(typeof nodemap[i + 1][] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++
                       }
                   }

                   if(neighboorcount <=2 && neighboorcount > 0){
                       branchpoints.push(nodemap[i][j]);
                   }
               }
           }

           //create random rooms
           for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        //c.beginPath();
                        //c.fillStyle = "#FFFFFF";
                        //c.fillRect(i*30 + 6, j*30 + 6, roomDim[0]*30 - 6*2, roomDim[1]*30 - 6*2);
                        //c.stroke();
                    }
                }
            }

            //get rid of rooms that aren't attached
            removeRooms();

           //paint the map data
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j < nodemap[i].length; j++){
                   c.fillStyle = "#000000";
                   c.fillRect(i*30, j*30, 30, 30);
                   if(nodemap[i][j].isVisited == 1){
                       c.fillStyle = "#FFFFFF";
                       c.fillRect(i*30 + 6, j*30 + 6, 18, 18);
                       if(nodemap[i][j].n){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30, 6, 6);
                       }
                       if(nodemap[i][j].s){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30 + 24, 6, 6);
                       }
                       if(nodemap[i][j].e){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 24, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].w){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30 + 12, 6, 6);
                       }
                   }
                   if(nodemap[i][j].isRoom == 1){
                       //c.fillStyle = "#FFFFFF";
                       //c.fillRect(i*30, j*30, 30, 30);

                   }
               }
           }

           //paint the original rooms
           /*for(var i = 0; i< origroomlist.length; i++){
                c.beginPath();
                c.fillStyle = "#33CCFF";
                c.fillRect(origroomlist[i].x*30 + 6, origroomlist[i].y*30 + 6, origroomlist[i].width*30 - 6*2, origroomlist[i].height*30 - 6*2);
                c.stroke();
            }*/

           //paint the rooms so they look nice
           for(var i = 0; i< roomlist.length; i++){
               if(roomlist[i].removed == 0){
                   c.beginPath();
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(roomlist[i].x*30 + 6, roomlist[i].y*30 + 6, roomlist[i].width*30 - 6*2, roomlist[i].height*30 - 6*2);
                   c.stroke();
               }
            }

            for(var i = 0; i< branchpoints.length; i++){
                c.fillStyle = "#CC66FF";
                c.fillRect(branchpoints[i].x*30 + 6, branchpoints[i].y*30 + 6, 18, 18);
            }

            //paint the start, branch, and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30 + 6, startpoint.y*30 + 6, 18, 18);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30 + 6, endpoint.y*30 + 6, 18, 18);

        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        var nodemap = [];
        var origroomlist = [];
        var roomlist = [];
        var removelist = [];
        document.getElementById("paintbtn").onclick = paint;

        function removeRooms(){
            origroomlist = roomlist.slice(0);
            removelist = [];
            for(var i = 0; i< roomlist.length; i++){
                var remove = 1;
                var tempHeight = roomlist[i].height;
                var tempWidth = roomlist[i].width;
                for(var j = 0; j< tempWidth; j++){
                    for(var k = 0; k< tempHeight; k++){
                        if(nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited == 1){
                            remove = 0;
                            break;
                        }
                    }
                }

                if(remove ==1 ){
                    roomlist[i].removed = 1;
                }
            }
        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }
          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
            nodemap = [];
            roomlist = [];
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }
            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );

            for(i = 0; i< randw; i++){
                for(j = 0; j< randh; j++){
                    nodemap[x+i][y+j].isRoom = 1;
                }
            }
            var room = {
              x:x,
              y:y,
              width: randw,
              height: randh,
              removed: 0
            };
            roomlist.push(room);
            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;
            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                nodemap.push([]);
                for(var j = 0; j< pathHeight; j++){
                    var node = {
                        isVisited: 0,
                        isRoom:0,
                        n:0,
                        s:0,
                        e:0,
                        w:0,
                        x:i,
                        y:j
                    };
                    nodemap[i].push(node);
               }
           }

           //create a random path that we will walk
           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //set the start node as visited in the beginning
           nodemap[startpoint.x][startpoint.y].isVisited = 1;

           //loop through the walk
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
                }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               if(movedirX < 0){
                   nodemap[movingpointold.x][movingpointold.y].w = 1;
                   nodemap[movingpoint.x][movingpoint.y].e = 1;
               }else if(movedirX > 0){
                   nodemap[movingpointold.x][movingpointold.y].e = 1;
                   nodemap[movingpoint.x][movingpoint.y].w = 1;
               }
               if(movedirY < 0){
                   nodemap[movingpointold.x][movingpointold.y].n =1;
                   nodemap[movingpoint.x][movingpoint.y].s = 1;
               }else if(movedirY >0){
                   nodemap[movingpointold.x][movingpointold.y].s = 1;
                   nodemap[movingpoint.x][movingpoint.y].n = 1;
               }

               nodemap[movingpoint.x][movingpoint.y].isVisited = 1

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

           //create a branch point
           var branchpoints = [];
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j< nodemap[i].length; j++){
                   var neighboorcount = 0;
                   if(typeof nodemap[i][j - 1] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++
                       }
                   } else{
                       neighboorcount++
                   }
                   if(typeof nodemap[i][j + 1] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++
                       }
                   }else{
                       neighboorcount++
                   }
                   if(typeof nodemap[i - 1][j] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++
                       }
                   }else{
                       neighboorcount++
                   }
                   if(typeof nodemap[i + 1][] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++
                       }
                   }else{
                       neighboorcount++
                   }

                   if(neighboorcount <=2 && neighboorcount > 0){
                       branchpoints.push(nodemap[i][j]);
                   }
               }
           }

           //create random rooms
           for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        //c.beginPath();
                        //c.fillStyle = "#FFFFFF";
                        //c.fillRect(i*30 + 6, j*30 + 6, roomDim[0]*30 - 6*2, roomDim[1]*30 - 6*2);
                        //c.stroke();
                    }
                }
            }

            //get rid of rooms that aren't attached
            removeRooms();

           //paint the map data
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j < nodemap[i].length; j++){
                   c.fillStyle = "#000000";
                   c.fillRect(i*30, j*30, 30, 30);
                   if(nodemap[i][j].isVisited == 1){
                       c.fillStyle = "#FFFFFF";
                       c.fillRect(i*30 + 6, j*30 + 6, 18, 18);
                       if(nodemap[i][j].n){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30, 6, 6);
                       }
                       if(nodemap[i][j].s){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30 + 24, 6, 6);
                       }
                       if(nodemap[i][j].e){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 24, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].w){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30 + 12, 6, 6);
                       }
                   }
                   if(nodemap[i][j].isRoom == 1){
                       //c.fillStyle = "#FFFFFF";
                       //c.fillRect(i*30, j*30, 30, 30);

                   }
               }
           }

           //paint the original rooms
           /*for(var i = 0; i< origroomlist.length; i++){
                c.beginPath();
                c.fillStyle = "#33CCFF";
                c.fillRect(origroomlist[i].x*30 + 6, origroomlist[i].y*30 + 6, origroomlist[i].width*30 - 6*2, origroomlist[i].height*30 - 6*2);
                c.stroke();
            }*/

           //paint the rooms so they look nice
           for(var i = 0; i< roomlist.length; i++){
               if(roomlist[i].removed == 0){
                   c.beginPath();
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(roomlist[i].x*30 + 6, roomlist[i].y*30 + 6, roomlist[i].width*30 - 6*2, roomlist[i].height*30 - 6*2);
                   c.stroke();
               }
            }

            for(var i = 0; i< branchpoints.length; i++){
                c.fillStyle = "#CC66FF";
                c.fillRect(branchpoints[i].x*30 + 6, branchpoints[i].y*30 + 6, 18, 18);
            }

            //paint the start, branch, and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30 + 6, startpoint.y*30 + 6, 18, 18);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30 + 6, endpoint.y*30 + 6, 18, 18);

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


<commit_before>module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json');
    yeoman: {
      // Configurable paths
      app: 'dev',
      dist: 'prod'
    },
    clean: {
      files: ['<%%=yeoman.dist%>',
              '<%%=yeoman.app%>/css',
              '<%%=yeoman.app%>/js']
    },
    compass: {
      dev: {
        options: {
          basePath: '<%%=yeoman.app%>/',
          config: '<%%=yeoman.app%>/config.rb'
        }
      },
      prod: {
        options: {
          basePath: '<%%=yeoman.app%>/',
          config: '<%%=yeoman.app%>/config.rb',
          environment: 'production'
        }
      }
    },
    assemble: {
      options: {
        flatten: true,
        layout: 'main.html',
        layoutdir: '<%%=yeoman.app%>/layouts/',
        partials: ['<%%=yeoman.app%>/partials/*.html'],
        data: ['<%%=yeoman.app%>/datas/*.json']
      },
      pages: {
        files: {
          '<%%=yeoman.dist%>/': ['<%%=yeoman.app%>/pages/*.html']
        }
      }
    },
    concat: {
      options: {
        separator: ';',
        stripBanners: true,
        banner: '/*! <%%= pkg.name %> - v<%%= pkg.version %> - ' +
                '<%%= grunt.template.today("yyyy-mm-dd hh:ii:ss") %> */',
      },
      appjs: {
        src: ['<%%=yeoman.app%>/src/plugins.js',
              '<%%=yeoman.app%>/src/plugins/*.js',
              '<%%=yeoman.app%>/src/main.js'],
        dest: '<%%=yeoman.app%>/js/app.js'
      },
      total: {
        src: ['<%%=yeoman.app%>/bower_components/jquery/jquery.min.js',
              '<%%=yeoman.dist%>/js/app.js'],
        dest: '<%%=yeoman.dist%>/js/app.js'
      }
    },
    uglify: {
      minify: {
        files: [{
          expand: true,
          cwd: '<%%=yeoman.dist%>/js',
          src: ['*.js'],
          dest: '<%%=yeoman.dist%>/js',
          ext: '.js'
        }]
      }
    },
    copy: {
      // Copie les fichiers HTML vers target
      html: {
        files: [
          {
            expand: true,
            dot: true,
            cwd: '<%%=yeoman.app%>/',
            src: ['*.{ico,png,txt,xml,html,htc}',
                  '.htaccess'],
            dest: '<%%=yeoman.dist%>/'
          }
        ]
      },
      font: {
        files: [{
          expand: true,
          cwd: '<%%=yeoman.app%>/font',
          src: ['*.{eot,woff,svg,ttf,txt}'],
          dest: '<%%=yeoman.dist%>/font/'
        }]
      },
      js: {
        files: [
          {
            expand: true,
            cwd: '<%%=yeoman.app%>/js',
            src: ['*.js'],
            dest: '<%%=yeoman.dist%>/js/',
            ext: '.js'
          }
        ]
      },
      jscustom: {
        files: [
          {
            expand: true,
            cwd: '<%%=yeoman.app%>/src/custom',
            src: ['*.{js,swf}'],
            dest: '<%%=yeoman.dist%>/js/'
          }
        ]
      },
      css: {
        files: [
          {
            expand: true,
            cwd: '<%%=yeoman.app%>/css/',
            src: ['*.css'],
            dest: '<%%=yeoman.dist%>/css/',
            ext: '.css'
          }
        ]
      },
      resources: {
        files: [
          {
            expand: true,
            cwd: '<%%=yeoman.app%>/img',
            src: ['**/*'],
            dest: '<%%=yeoman.dist%>/img/'
          }
        ]
      }
    },
    watch: {
      sass: {
        files: ['<%%=yeoman.app%>/scss/**/*.scss'],
        tasks: ['compass:dev']
      },
      html: {
        files: ['<%%=yeoman.app%>/**/*.{html,json}'],
        tasks: ['copy:html','assemble:pages']
      },
      css: {
        files: ['<%%=yeoman.app%>/css/*.css'],
        tasks: ['copy:css']
      },
      img: {
        files: ['<%%=yeoman.app%>/img/**/*'],
        tasks: ['copy:resources']
      },
      js: {
        files: ['<%%=yeoman.app%>/src/**/*.js'],
        tasks: ['jshint:use_defaults',
                'concat:appjs',
                'copy:js',
                'copy:jscustom',
                'concat:total']
      },
      livereload: {
        files: ['<%%=yeoman.app%>/**/*.{html,json}',
                '<%%=yeoman.app%>/css/*.css',
                '<%%=yeoman.app%>/img/*',
                '<%%=yeoman.app%>/src/**/*.js'],
        options: {
          livereload: true
        }
      },
    },
    connect: {
      server: {
        options: {
          hostname: '*',
          port: 9001,
          base: '<%%=yeoman.dist%>/'
        }
      }
    },
    modernizr: {
      dist: {
        devFile: '<%%= yeoman.app %>/bower_components/modernizr/modernizr.js',
        outputFile: '<%%= yeoman.dist %>/js/modernizr.min.js',
        files: {
            "src" : ['<%%= yeoman.dist %>/js/{,*/}*.js',
                     '<%%= yeoman.dist %>/css/{,*/}*.css',
                     '!<%%= yeoman.dist %>/js/modernizer.min.js']
        },
        extra : {
          shiv : true,
          printshiv : false,
          load : true,
          mq : false,
          cssclasses : true
        },
        extensibility : {
          "addtest" : false,
          "prefixed" : false,
          "teststyles" : false,
          "testprops" : false,
          "testallprops" : false,
          "hasevents" : false,
          "prefixes" : false,
          "domprefixes" : false
        } ,
        "uglify" : true
      }
    },
    imagemin: {
      dynamic: {
        files: [{
          expand: true,
          cwd: '<%%=yeoman.dist%>/img/',
          src: ['**/*.{png,jpg,gif}'],
          dest: '<%%=yeoman.dist%>/img/'
        }]
      }
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        eqnull: true,
        browser: true,
        globals: {
          jQuery: true
        },
      },
      use_defaults: ['<%%=yeoman.app%>/src/main.js',
                     '<%%=yeoman.app%>/src/plugins.js'
                     '<%%=yeoman.app%>/src/custom/*.js']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-modernizr');
  grunt.loadNpmTasks('grunt-contrib-imagemin');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('assemble');

  grunt.registerTask('dev', [
    'clean',
    'compass:dev',
    'jshint:use_defaults',
    'concat:appjs',
    'copy:js',
    'copy:jscustom',
    'concat:total',
    'copy:html',
    'assemble:pages',
    'copy:css',
    'copy:font',
    'copy:resources',
    'modernizr:dist',
    'connect:server',
    'watch'
  ]);

  grunt.registerTask('production', [
    'clean',
    'compass:prod',
    'jshint:use_defaults',
    'concat:appjs',
    'copy:js',
    'copy:jscustom',
    'uglify:minify',
    'concat:total',
    'copy:css',
    'copy:font',
    'copy:html',
    'assemble:pages',
    'copy:resources',
    'modernizr:dist',
    'imagemin:dynamic'
  ]);

  grunt.registerTask('default', ['dev']);

};
<commit_msg>Error in Gruntfile.js<commit_after>module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    yeoman: {
      // Configurable paths
      app: 'dev',
      dist: 'prod'
    },
    clean: {
      files: ['<%%=yeoman.dist%>',
              '<%%=yeoman.app%>/css',
              '<%%=yeoman.app%>/js']
    },
    compass: {
      dev: {
        options: {
          basePath: '<%%=yeoman.app%>/',
          config: '<%%=yeoman.app%>/config.rb'
        }
      },
      prod: {
        options: {
          basePath: '<%%=yeoman.app%>/',
          config: '<%%=yeoman.app%>/config.rb',
          environment: 'production'
        }
      }
    },
    assemble: {
      options: {
        flatten: true,
        layout: 'main.html',
        layoutdir: '<%%=yeoman.app%>/layouts/',
        partials: ['<%%=yeoman.app%>/partials/*.html'],
        data: ['<%%=yeoman.app%>/datas/*.json']
      },
      pages: {
        files: {
          '<%%=yeoman.dist%>/': ['<%%=yeoman.app%>/pages/*.html']
        }
      }
    },
    concat: {
      options: {
        separator: ';',
        stripBanners: true,
        banner: '/*! <%%= pkg.name %> - v<%%= pkg.version %> - ' +
                '<%%= grunt.template.today("yyyy-mm-dd hh:ii:ss") %> */',
      },
      appjs: {
        src: ['<%%=yeoman.app%>/src/plugins.js',
              '<%%=yeoman.app%>/src/plugins/*.js',
              '<%%=yeoman.app%>/src/main.js'],
        dest: '<%%=yeoman.app%>/js/app.js'
      },
      total: {
        src: ['<%%=yeoman.app%>/bower_components/jquery/jquery.min.js',
              '<%%=yeoman.dist%>/js/app.js'],
        dest: '<%%=yeoman.dist%>/js/app.js'
      }
    },
    uglify: {
      minify: {
        files: [{
          expand: true,
          cwd: '<%%=yeoman.dist%>/js',
          src: ['*.js'],
          dest: '<%%=yeoman.dist%>/js',
          ext: '.js'
        }]
      }
    },
    copy: {
      // Copie les fichiers HTML vers target
      html: {
        files: [
          {
            expand: true,
            dot: true,
            cwd: '<%%=yeoman.app%>/',
            src: ['*.{ico,png,txt,xml,html,htc}',
                  '.htaccess'],
            dest: '<%%=yeoman.dist%>/'
          }
        ]
      },
      font: {
        files: [{
          expand: true,
          cwd: '<%%=yeoman.app%>/font',
          src: ['*.{eot,woff,svg,ttf,txt}'],
          dest: '<%%=yeoman.dist%>/font/'
        }]
      },
      js: {
        files: [
          {
            expand: true,
            cwd: '<%%=yeoman.app%>/js',
            src: ['*.js'],
            dest: '<%%=yeoman.dist%>/js/',
            ext: '.js'
          }
        ]
      },
      jscustom: {
        files: [
          {
            expand: true,
            cwd: '<%%=yeoman.app%>/src/custom',
            src: ['*.{js,swf}'],
            dest: '<%%=yeoman.dist%>/js/'
          }
        ]
      },
      css: {
        files: [
          {
            expand: true,
            cwd: '<%%=yeoman.app%>/css/',
            src: ['*.css'],
            dest: '<%%=yeoman.dist%>/css/',
            ext: '.css'
          }
        ]
      },
      resources: {
        files: [
          {
            expand: true,
            cwd: '<%%=yeoman.app%>/img',
            src: ['**/*'],
            dest: '<%%=yeoman.dist%>/img/'
          }
        ]
      }
    },
    watch: {
      sass: {
        files: ['<%%=yeoman.app%>/scss/**/*.scss'],
        tasks: ['compass:dev']
      },
      html: {
        files: ['<%%=yeoman.app%>/**/*.{html,json}'],
        tasks: ['copy:html','assemble:pages']
      },
      css: {
        files: ['<%%=yeoman.app%>/css/*.css'],
        tasks: ['copy:css']
      },
      img: {
        files: ['<%%=yeoman.app%>/img/**/*'],
        tasks: ['copy:resources']
      },
      js: {
        files: ['<%%=yeoman.app%>/src/**/*.js'],
        tasks: ['jshint:use_defaults',
                'concat:appjs',
                'copy:js',
                'copy:jscustom',
                'concat:total']
      },
      livereload: {
        files: ['<%%=yeoman.app%>/**/*.{html,json}',
                '<%%=yeoman.app%>/css/*.css',
                '<%%=yeoman.app%>/img/*',
                '<%%=yeoman.app%>/src/**/*.js'],
        options: {
          livereload: true
        }
      },
    },
    connect: {
      server: {
        options: {
          hostname: '*',
          port: 9001,
          base: '<%%=yeoman.dist%>/'
        }
      }
    },
    modernizr: {
      dist: {
        devFile: '<%%= yeoman.app %>/bower_components/modernizr/modernizr.js',
        outputFile: '<%%= yeoman.dist %>/js/modernizr.min.js',
        files: {
            "src" : ['<%%= yeoman.dist %>/js/{,*/}*.js',
                     '<%%= yeoman.dist %>/css/{,*/}*.css',
                     '!<%%= yeoman.dist %>/js/modernizer.min.js']
        },
        extra : {
          shiv : true,
          printshiv : false,
          load : true,
          mq : false,
          cssclasses : true
        },
        extensibility : {
          "addtest" : false,
          "prefixed" : false,
          "teststyles" : false,
          "testprops" : false,
          "testallprops" : false,
          "hasevents" : false,
          "prefixes" : false,
          "domprefixes" : false
        } ,
        "uglify" : true
      }
    },
    imagemin: {
      dynamic: {
        files: [{
          expand: true,
          cwd: '<%%=yeoman.dist%>/img/',
          src: ['**/*.{png,jpg,gif}'],
          dest: '<%%=yeoman.dist%>/img/'
        }]
      }
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        eqnull: true,
        browser: true,
        globals: {
          jQuery: true
        },
      },
      use_defaults: ['<%%=yeoman.app%>/src/main.js',
                     '<%%=yeoman.app%>/src/plugins.js'
                     '<%%=yeoman.app%>/src/custom/*.js']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-modernizr');
  grunt.loadNpmTasks('grunt-contrib-imagemin');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('assemble');

  grunt.registerTask('dev', [
    'clean',
    'compass:dev',
    'jshint:use_defaults',
    'concat:appjs',
    'copy:js',
    'copy:jscustom',
    'concat:total',
    'copy:html',
    'assemble:pages',
    'copy:css',
    'copy:font',
    'copy:resources',
    'modernizr:dist',
    'connect:server',
    'watch'
  ]);

  grunt.registerTask('production', [
    'clean',
    'compass:prod',
    'jshint:use_defaults',
    'concat:appjs',
    'copy:js',
    'copy:jscustom',
    'uglify:minify',
    'concat:total',
    'copy:css',
    'copy:font',
    'copy:html',
    'assemble:pages',
    'copy:resources',
    'modernizr:dist',
    'imagemin:dynamic'
  ]);

  grunt.registerTask('default', ['dev']);

};
<|endoftext|>


<commit_before>module.exports = {
    app : {
        lang : 'ru',
        themeColor : '#000'
    },
    pageTitle : 'frontender'
};<commit_msg>началные значения по умолчанию для конфига<commit_after>module.exports = {
    app      : {
        lang      : 'ru',
        themeColor: '#000',
        package   : 'ключ перезаписывается значениями из package.json marmelad-сборщика',
        settings  : 'ключ перезаписывается значениями из файла настроек marmelad.settings.js',
    },
    pageTitle: 'MARMELAD'
};<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';

let useHasFeature;
if (ExecutionEnvironment.canUseDOM) {
  useHasFeature =
    document.implementation &&
    document.implementation.hasFeature &&
    // always returns true in newer browsers as per the standard.
    // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature
    document.implementation.hasFeature('', '') !== true;
}

/**
 * Checks if an event is supported in the current execution environment.
 *
 * NOTE: This will not work correctly for non-generic events such as `change`,
 * `reset`, `load`, `error`, and `select`.
 *
 * Borrows from Modernizr.
 *
 * @param {string} eventNameSuffix Event name, e.g. "click".
 * @param {?boolean} capture Check if the capture phase is supported.
 * @return {boolean} True if the event is supported.
 * @internal
 * @license Modernizr 3.0.0pre (Custom Build) | MIT
 */
function isEventSupported(eventNameSuffix, capture) {
  if (
    !ExecutionEnvironment.canUseDOM ||
    (capture && !('addEventListener' in document))
  ) {
    return false;
  }

  const eventName = 'on' + eventNameSuffix;
  let isSupported = eventName in document;

  if (!isSupported) {
    const element = document.createElement('div');
    element.setAttribute(eventName, 'return;');
    isSupported = typeof element[eventName] === 'function';
  }

  if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') {
    // This is the only way to test support for the `wheel` event in IE9+.
    isSupported = document.implementation.hasFeature('Events.wheel', '3.0');
  }

  return isSupported;
}

export default isEventSupported;
<commit_msg>Remove unused wheel event detection in isEventSupported (#11822)<commit_after>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';

/**
 * Checks if an event is supported in the current execution environment.
 *
 * NOTE: This will not work correctly for non-generic events such as `change`,
 * `reset`, `load`, `error`, and `select`.
 *
 * Borrows from Modernizr.
 *
 * @param {string} eventNameSuffix Event name, e.g. "click".
 * @param {?boolean} capture Check if the capture phase is supported.
 * @return {boolean} True if the event is supported.
 * @internal
 * @license Modernizr 3.0.0pre (Custom Build) | MIT
 */
function isEventSupported(eventNameSuffix, capture) {
  if (
    !ExecutionEnvironment.canUseDOM ||
    (capture && !('addEventListener' in document))
  ) {
    return false;
  }

  const eventName = 'on' + eventNameSuffix;
  let isSupported = eventName in document;

  if (!isSupported) {
    const element = document.createElement('div');
    element.setAttribute(eventName, 'return;');
    isSupported = typeof element[eventName] === 'function';
  }

  return isSupported;
}

export default isEventSupported;
<|endoftext|>


<commit_before>/**
*
* Load the global `app` Object which will be used as reference throughout the project. By default the only thing that
* will automatically be loaded is the current environment configuration.
*
* @author Salvatore Garbesi <sal@dolox.com>
* @module bootstrap/app
*
**/
module.exports = !function(global) {
	'use strict';

	// The application namespace.
	global.app = {};
}(global);
<commit_msg>Update app.js<commit_after>/**
*
* Define the global `app` Object which will be used as a reference throughout the project. By default the only thing that
* will automatically be loaded is the current environment configuration.
*
* @author Salvatore Garbesi <sal@dolox.com>
* @module bootstrap/app
*
**/
module.exports = !function(global) {
	'use strict';

	// The application namespace.
	global.app = {};
}(global);
<|endoftext|>