<commit_before>/**
 * Javascript features for the SilverStripe forum module. These have been
 * ported over from the old Prototype system
 *
 * @package Forum
 */

(function($) {
$(document).ready(function() {

	/**
	 * Handle the OpenID information Box.
	 * It will open / hide the little popup
	 */

	$("#ShowOpenIDdesc").click(function() {
		if($("#OpenIDDescription").hasClass("showing")) {
			$("#OpenIDDescription").hide().removeClass("showing");
		} else {
			$("#OpenIDDescription").show().addClass("showing");
		}
		return false;
	});

	$("#HideOpenIDdesc").click(function() {
		$("#OpenIDDescription").hide();
		return false;
	});

	/**
	 * BBCode Tools
	 * While editing / replying to a post you can get a little popup
	 * with all the BBCode tags
	 */

	$("#BBCodeHint").click(function() {
		if($("#BBTagsHolder").hasClass("showing")) {
			$(this).text("View Formatting Help");
			$("#BBTagsHolder").hide().removeClass("showing");
		} else {
			$(this).text("Hide Formatting Help");
			$("#BBTagsHolder").show().addClass("showing");
		}
		return false;
	});

	/**
	 * MultiFile Uploader called on Reply and Edit Forms
	 */
	$('#Form_ReplyForm_Attachment').MultiFile();
	$('#Form_EditPostForm_Attachment').MultiFile();

	/**
	 * Delete post Link.
	 * Add a popup to make sure user actually wants to do
	 * the dirty and remove that wonderful post
	 */

	$('.postModifiers a.deletelink').click(function(){
		if($(this).attr('id')== 'firstPost') {
			if(!confirm("Are you sure you wish to delete this thread?\nNote: This will delete ALL posts in this thread.")) return false;
		} else {
			if(!confirm("Are you sure you wish to delete this post?")) return false;
		}
		var id = $(this).attr("rel");
		$.post($(this).attr("href"), function(data) {
			if(data == 1) {
				// was successful
				$("ul#Posts li#post"+id).fadeOut();
			}
		});
		return false;
	});

	/**
	 * Mark Post as Spam Link.
	 * It needs to warn the user that the post will be deleted
	 */

	$('.postModifiers a.markAsSpamLink').click(function(){
		if(!confirm("Are you sure you wish to mark this post as spam?")) return false;
		var id = $(this).attr("rel");
		$.post($(this).attr("href"), function(data) {
			if(data == 1) {
				// was successful
				$("ul#Posts li#post"+id).fadeOut();
			}
		});
		return false;
	});
	/**
	 * Delete an Attachment via AJAX
	 */
	$('a.deleteAttachment').click(function() {
		if(!confirm("Are you sure you wish to delete this Attachment")) return false;
		var id = $(this).attr("rel");
		$.post($(this).attr("href"), function(data) {
			if(data == 1) {
				$(".currentAttachments li.attachment-"+id).fadeOut(); // hide the deleted attachment
			}
		});
		return false;
	});

	/**
	 * Do the Subscribe / Unsubscribe button
	 */
	$("td.replyButton a.subscribe").click(function() {
		$.post($(this).attr("href"), function(data) {
			if(data == 1) {
				$("td.replyButton a.subscribe").fadeOut().hide();
				$("td.replyButton a.unsubscribe").fadeIn();
			}
		});
		return false;
	});

	$("td.replyButton a.unsubscribe").click(function() {
		$.post($(this).attr("href"), function(data) {
			if(data == 1) {
				$("td.replyButton a.unsubscribe").fadeOut().hide();
				$("td.replyButton a.subscribe").fadeIn();
			}
		});
		return false;
	});
})
})(jQuery);<commit_msg>BUGFIX: fixed jquery attachement list item selector in attachement deletion<commit_after>/**
 * Javascript features for the SilverStripe forum module. These have been
 * ported over from the old Prototype system
 *
 * @package Forum
 */

(function($) {
$(document).ready(function() {

	/**
	 * Handle the OpenID information Box.
	 * It will open / hide the little popup
	 */

	$("#ShowOpenIDdesc").click(function() {
		if($("#OpenIDDescription").hasClass("showing")) {
			$("#OpenIDDescription").hide().removeClass("showing");
		} else {
			$("#OpenIDDescription").show().addClass("showing");
		}
		return false;
	});

	$("#HideOpenIDdesc").click(function() {
		$("#OpenIDDescription").hide();
		return false;
	});

	/**
	 * BBCode Tools
	 * While editing / replying to a post you can get a little popup
	 * with all the BBCode tags
	 */

	$("#BBCodeHint").click(function() {
		if($("#BBTagsHolder").hasClass("showing")) {
			$(this).text("View Formatting Help");
			$("#BBTagsHolder").hide().removeClass("showing");
		} else {
			$(this).text("Hide Formatting Help");
			$("#BBTagsHolder").show().addClass("showing");
		}
		return false;
	});

	/**
	 * MultiFile Uploader called on Reply and Edit Forms
	 */
	$('#Form_ReplyForm_Attachment').MultiFile();
	$('#Form_EditPostForm_Attachment').MultiFile();

	/**
	 * Delete post Link.
	 * Add a popup to make sure user actually wants to do
	 * the dirty and remove that wonderful post
	 */

	$('.postModifiers a.deletelink').click(function(){
		if($(this).attr('id')== 'firstPost') {
			if(!confirm("Are you sure you wish to delete this thread?\nNote: This will delete ALL posts in this thread.")) return false;
		} else {
			if(!confirm("Are you sure you wish to delete this post?")) return false;
		}
		var id = $(this).attr("rel");
		$.post($(this).attr("href"), function(data) {
			if(data == 1) {
				// was successful
				$("ul#Posts li#post"+id).fadeOut();
			}
		});
		return false;
	});

	/**
	 * Mark Post as Spam Link.
	 * It needs to warn the user that the post will be deleted
	 */

	$('.postModifiers a.markAsSpamLink').click(function(){
		if(!confirm("Are you sure you wish to mark this post as spam?")) return false;
		var id = $(this).attr("rel");
		$.post($(this).attr("href"), function(data) {
			if(data == 1) {
				// was successful
				$("ul#Posts li#post"+id).fadeOut();
			}
		});
		return false;
	});
	/**
	 * Delete an Attachment via AJAX
	 */
	$('a.deleteAttachment').click(function() {
		if(!confirm("Are you sure you wish to delete this Attachment")) return false;
		var id = $(this).attr("rel");
		$.post($(this).attr("href"), function(data) {
			if(data == 1) {
				$("#CurrentAttachments li.attachment-"+id).fadeOut(); // hide the deleted attachment
			}
		});
		return false;
	});

	/**
	 * Do the Subscribe / Unsubscribe button
	 */
	$("td.replyButton a.subscribe").click(function() {
		$.post($(this).attr("href"), function(data) {
			if(data == 1) {
				$("td.replyButton a.subscribe").fadeOut().hide();
				$("td.replyButton a.unsubscribe").fadeIn();
			}
		});
		return false;
	});

	$("td.replyButton a.unsubscribe").click(function() {
		$.post($(this).attr("href"), function(data) {
			if(data == 1) {
				$("td.replyButton a.unsubscribe").fadeOut().hide();
				$("td.replyButton a.subscribe").fadeIn();
			}
		});
		return false;
	});
})
})(jQuery);<|endoftext|>


<commit_before>var fs = require("fs");
var path = require("path");
var Future = require("fibers/future");
var _ = require("underscore");
var switchFunctions = [];
var pollingInterval = 500;

// Set this environment variable to a truthy value to force the use of
// fs.watchFile instead of pathwatcher.watch.
var canUsePathwatcher = !process.env.METEOR_WATCH_FORCE_POLLING;

// The pathwatcher library does not work on all platforms and file systems
// (notably, network file systems), so we have to do a little feature
// detection to see if we can use it.

// We optimistically watch files using pathwatcher.watch until one of the
// directories tested fails to support file system events. When that
// happens, we switch all previously created pathwatcher watches to use
// fs.watchFile, and set canUsePathwatcher to false so that all future
// watches will use fs.watchFile as well.

// There is some theoretical risk of missing file system events from
// pathwatcher watches created before we discover that we can't use
// pathwatcher.watch, but the window of time where that can happen is
// small enough (500ms) that developers are highly unlikely to care.

exports.testDirectory = function(dir) {
  if (! canUsePathwatcher) {
    // No need to test this directory if we've already decided we can't
    // use pathwatcher.watch.
    return;
  }

  var canaryFile = path.join(
    dir, "canary$" + Math.random().toString(36).slice(2)
  );

  fs.unlink(canaryFile, function(ignoredError) {
    function cleanUp(arg) {
      if (watcher) {
        watcher.close();
        watcher = null;
        fs.unlink(canaryFile, function(ignoredError) {});
      }
    }

    function fallBack() {
      // Disallow future uses of pathwatcher.watch.
      canUsePathwatcher = false;

      // Convert any pathwatcher watchers we previously created to
      // fs.watchFile watchers.
      _.each(switchFunctions.splice(0), function(switchToPolling) {
        switchToPolling();
      });

      require("./console.js").Console.debug(
        "Falling back to fs.watchFile instead of pathwatcher.watch..."
      );
    }

    // Watch the candidate directory using pathwatcher.watch.
    var watcher = require("pathwatcher").watch(dir, cleanUp);

    // Create a new file to trigger a change event (hopefully). It's fine
    // if other events sneak in while we're waiting, since all we care
    // about is whether pathwatcher.watch works.
    fs.writeFile(canaryFile, "ok", function(err) {
      if (err) {
        cleanUp();
        throw err;
      }
    });

    // Set a time limit of 500ms for the change event.
    setTimeout(function() {
      if (watcher) {
        cleanUp();
        fallBack();
      }
    }, 500);
  });
};

exports.watch = function(absPath, callback) {
  if (canUsePathwatcher) {
    // In principle, all this logic for watching files should continue to
    // work perfectly if we substitute fs.watch for pathwatcher.watch, but
    // that will probably have to wait until we upgrade Node to v0.11.x,
    // so that fs.watch is more reliable.
    var watcher = require("pathwatcher").watch(absPath, callback);

    var closed = false;
    var switched = false;

    switchFunctions.push(function switchToPolling() {
      if (! switched && ! closed) {
        switched = true;
        watcher.close();

        // Re-watch the file using fs.watchFile instead.
        fs.watchFile(absPath, {
          interval: pollingInterval
        }, callback);
      }
    });

    return {
      close: function close() {
        if (! closed) {
          closed = true;
          if (switched) {
            fs.unwatchFile(absPath, callback);
          } else {
            watcher.close();
          }
        }
      }
    };
  }

  fs.watchFile(absPath, {
    interval: pollingInterval
  }, callback);

  return {
    close: function close() {
      fs.unwatchFile(absPath, callback);
    }
  };
};
<commit_msg>Avoid pathwatcher.watch failures in testDirectory.<commit_after>var fs = require("fs");
var path = require("path");
var Future = require("fibers/future");
var _ = require("underscore");
var switchFunctions = [];
var pollingInterval = 500;

// Set this environment variable to a truthy value to force the use of
// fs.watchFile instead of pathwatcher.watch.
var canUsePathwatcher = !process.env.METEOR_WATCH_FORCE_POLLING;

// The pathwatcher library does not work on all platforms and file systems
// (notably, network file systems), so we have to do a little feature
// detection to see if we can use it.

// We optimistically watch files using pathwatcher.watch until one of the
// directories tested fails to support file system events. When that
// happens, we switch all previously created pathwatcher watches to use
// fs.watchFile, and set canUsePathwatcher to false so that all future
// watches will use fs.watchFile as well.

// There is some theoretical risk of missing file system events from
// pathwatcher watches created before we discover that we can't use
// pathwatcher.watch, but the window of time where that can happen is
// small enough (500ms) that developers are highly unlikely to care.

exports.testDirectory = function(dir) {
  if (! canUsePathwatcher) {
    // No need to test this directory if we've already decided we can't
    // use pathwatcher.watch.
    return;
  }

  var canaryFile = path.join(
    dir, "canary$" + Math.random().toString(36).slice(2)
  );

  // Make sure the test directory exists.
  require("./files.js").mkdir_p(dir);

  fs.unlink(canaryFile, function(ignoredError) {
    function cleanUp(arg) {
      if (watcher) {
        watcher.close();
        watcher = null;
        fs.unlink(canaryFile, function(ignoredError) {});
      }
    }

    function fallBack() {
      // Disallow future uses of pathwatcher.watch.
      canUsePathwatcher = false;

      // Convert any pathwatcher watchers we previously created to
      // fs.watchFile watchers.
      _.each(switchFunctions.splice(0), function(switchToPolling) {
        switchToPolling();
      });

      require("./console.js").Console.debug(
        "Falling back to fs.watchFile instead of pathwatcher.watch..."
      );
    }

    // Watch the candidate directory using pathwatcher.watch.
    var pathwatcher = require("pathwatcher");
    try {
      var watcher = pathwatcher.watch(dir, cleanUp);
    } catch (err) {
      // If the directory did not exist, do not treat this failure as
      // evidence against pathwatcher.watch, but simply return and leave
      // canUsePathwatcher set to true.
      if (err instanceof TypeError &&
          err.message === "Unable to watch path") {
        return;
      }
      throw err;
    }

    // Create a new file to trigger a change event (hopefully). It's fine
    // if other events sneak in while we're waiting, since all we care
    // about is whether pathwatcher.watch works.
    fs.writeFile(canaryFile, "ok", function(err) {
      if (err) {
        cleanUp();
        throw err;
      }
    });

    // Set a time limit of 500ms for the change event.
    setTimeout(function() {
      if (watcher) {
        cleanUp();
        fallBack();
      }
    }, 500);
  });
};

exports.watch = function(absPath, callback) {
  if (canUsePathwatcher) {
    // In principle, all this logic for watching files should continue to
    // work perfectly if we substitute fs.watch for pathwatcher.watch, but
    // that will probably have to wait until we upgrade Node to v0.11.x,
    // so that fs.watch is more reliable.
    var watcher = require("pathwatcher").watch(absPath, callback);

    var closed = false;
    var switched = false;

    switchFunctions.push(function switchToPolling() {
      if (! switched && ! closed) {
        switched = true;
        watcher.close();

        // Re-watch the file using fs.watchFile instead.
        fs.watchFile(absPath, {
          interval: pollingInterval
        }, callback);
      }
    });

    return {
      close: function close() {
        if (! closed) {
          closed = true;
          if (switched) {
            fs.unwatchFile(absPath, callback);
          } else {
            watcher.close();
          }
        }
      }
    };
  }

  fs.watchFile(absPath, {
    interval: pollingInterval
  }, callback);

  return {
    close: function close() {
      fs.unwatchFile(absPath, callback);
    }
  };
};
<|endoftext|>


<commit_before>/*! ------------------------------------------------------------------------
//                                   Fusion
//  ------------------------------------------------------------------------
//
//                       Copyright 2014 Nicholas Gaulin
//
//       Licensed under the Apache License, Version 2.0 (the "License");
//      you may not use this file except in compliance with the License.
//                   You may obtain a copy of the License at
//
//                 http://www.apache.org/licenses/LICENSE-2.0
//
//     Unless required by applicable law or agreed to in writing, software
//      distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//     See the License for the specific language governing permissions and
//                       limitations under the License.
*/

// ########## PARSER ##########
var Parser   = function()
{
    //
},
  __Parser__ = Parser.prototype = {};

// --- PROTOTYPE ---
__Parser__.lexer = null;<commit_msg>update Parser.js<commit_after>/*! ------------------------------------------------------------------------
//                                   Fusion
//  ------------------------------------------------------------------------
//
//                       Copyright 2014 Nicholas Gaulin
//
//       Licensed under the Apache License, Version 2.0 (the "License");
//      you may not use this file except in compliance with the License.
//                   You may obtain a copy of the License at
//
//                 http://www.apache.org/licenses/LICENSE-2.0
//
//     Unless required by applicable law or agreed to in writing, software
//      distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//     See the License for the specific language governing permissions and
//                       limitations under the License.
*/

// ########## PARSER ##########
var Parser   = function()
{
    //
},
  __Parser__ = Parser.prototype = $__create(__Lexer__);

// --- PROTOTYPE ---
__Parser__._clone = Parser;<|endoftext|>


<commit_before>import objectAssign from "object-assign";
import defaultOptions from "./default-options";
import Config from "../config";
import Kotori from "../index";

/**
 * Create a new instance of the core CLI engine
 * @param {CLIEngineOptions} options - Kotori CLI options object (see: ./default-options.js)
 */
export default class CLIEngline {
  constructor(options) {
    this.currentOptions = objectAssign(defaultOptions, options);
    this.config = new Config(this.currentOptions.config);
  }

  /**
   * Executes the current configuration on an array of file and directory names
   * @param {String[]} patterns - An array of file and directory names
   * @returns {Stream} Readable/Writable stream
   */
  executeOnFiles(patterns) {
    const kotori = new Kotori();

    if (patterns.length === 1) {
      return kotori.src(patterns[0])
        .pipe(kotori.build(this.config))
        .pipe(kotori.dest(process.cwd()));
    } else if (patterns.length <= 2) {
      return kotori.src(patterns[0])
        .pipe(kotori.build(this.config))
        .pipe(kotori.dest(patterns[1]));
    } else {
      console.error("specify paths of too many");
      return;
    }
  }
}
<commit_msg>Remove code duplication<commit_after>import objectAssign from "object-assign";
import defaultOptions from "./default-options";
import Config from "../config";
import Kotori from "../index";

/**
 * Create a new instance of the core CLI engine
 * @param {CLIEngineOptions} options - Kotori CLI options object (see: ./default-options.js)
 */
export default class CLIEngline {
  constructor(options) {
    this.currentOptions = objectAssign(defaultOptions, options);
    this.config = new Config(this.currentOptions.config);
  }

  /**
   * Executes the current configuration on an array of file and directory names
   * @param {String[]} patterns - An array of file and directory names
   * @returns {Stream} Readable/Writable stream
   */
  executeOnFiles(patterns) {
    const kotori = new Kotori();
    const build = kotori.src(patterns[0])
                        .pipe(kotori.build(this.config));

    if (patterns.length > 2) {
      throw new Error("Specify paths of too many");
    } else if (patterns.length === 1) {
      return build.pipe(kotori.dest(process.cwd()));
    } else {
      return build.pipe(kotori.dest(patterns[1]));
    }
  }
}
<|endoftext|>


<commit_before>$(function () {
    dtable = new webix.ui({
        container: "browsetable",
        id: "dtable",
        view: "datatable",
        css:"salmonet_table protein_link",
        columns: [
            {id: "uniprot", map: "#data1#", header: ["UniProt AC", {content: "textFilter"}], width: 150},
            {id: "genename", map: "#data2#", header: ["Gene name", {content: "textFilter"}], width: 250},
            {id: "locus", map: "#data3#", header: ["Locus", {content: "textFilter"}], width: 250},
            {id: "numort", map: "#data4#", header: ["Number of","Homologs"], width: 150},
            {id: "numint", map: "#data5#", header: ["Number of","Interactions"], width: 150}
        ],
        resizeColumn: true,
        datatype: "csv",
        url: data_url_prefix+'data/nodes.csv',
        autoheight: true,
        autowidth: true,
        pager: {
            css:"salmonet_table",
            template: "{common.prev()}{common.next()}Page {common.page()} from #limit#",
            container: "paging_here",
            size: 25,
            group: 5
        },
        hover: "browse_row_hover",
        on: {
            "onItemClick": function (id, e, trg) {
                window.location.href = data_url_prefix+"protein/"+dtable.getItem(id.row).uniprot.toLowerCase()+"/";
                // window.location.href = "uniprot.html";
                //webix.message("Click on row: "+dtable.getItem(id.row).uniprot);
            }
        }
    });
    webix.extend($$("dtable"), webix.ProgressBar);
    var strain_select = [
        {view: "label", label: "Select a Salmonella enterica strain:"},
        {
            view: "select",
            name: "strain",
            options: data_url_prefix+"data/strain_select.json"
        }];
    strain_select_form = new webix.ui({
        css:"salmonet_form",
        container: "strain_select_div",
        id: "strain_select_form",
        view: "form",
        scroll: false,
        width: 300,
        elements: strain_select
    });
    $$("strain_select_form").elements["strain"].attachEvent("onChange", function (newv, oldv) {
        $$("dtable").showProgress({
            type: "bottom",
            delay: 3000,
            hide: true
        });
        dtable.clearAll();
        dtable.load(data_url_prefix+"data/nodes" + newv + ".csv");
        $$("dtable").refresh();
        // webix.message("Value changed from: "+oldv+" to: "+newv);
    });
    $(window).resize(function() {
        if ($(window).width() < 1050){
            dtable.hideColumn("numort");
            dtable.hideColumn("numint");
        }
        if ($(window).width() >= 1050){
            dtable.showColumn("numort");
            dtable.showColumn("numint");
        }
        if ($(window).width() < 850){
            dtable.setColumnWidth("uniprot", 80);
            dtable.setColumnWidth("genename", 120);
            dtable.setColumnWidth("locus", 120);
        }
        if ($(window).width() >= 850){
            dtable.setColumnWidth("uniprot", 150);
            dtable.setColumnWidth("genename", 250);
            dtable.setColumnWidth("locus", 250);
        }
    });
    if ($(window).width() < 1050){
        dtable.hideColumn("numort");
        dtable.hideColumn("numint");
    }
    if ($(window).width() < 850){
        dtable.setColumnWidth("uniprot", 80);
        dtable.setColumnWidth("genename", 120);
        dtable.setColumnWidth("locus", 120);
    }
    // protein page
    // interactiontable = webix.ui({
    //     container: "interactiontable",
    //     view: "datatable",
    //     columns: [
    //         {id: "data0", header: ["Interactor", {content: "textFilter"}], css: "rank", width: 120},
    //         {id: "data1", header: ["Interactor", {content: "textFilter"}], width: 120},
    //         {id: "data2", header: "Source", width: 200},
    //         {id: "data3", header: ["Layer", {content: "selectFilter"}], width: 200}
    //     ],
    //     autoheight: true,
    //     autowidth: true,
    //
    //     datatype: "csv",
    //     data: '{{ .Content }}'
    // });
});
<commit_msg>[balazsbohar] Fix browse table<commit_after>$(function () {
    dtable = new webix.ui({
        container: "browsetable",
        id: "dtable",
        view: "datatable",
        css:"salmonet_table protein_link",
        columns: [
            {id: "uniprot", map: "#data1#", header: ["OMA identifier", {content: "textFilter"}], width: 150},
            {id: "genename", map: "#data2#", header: ["Gene name/Locus tag (old)", {content: "textFilter"}], width: 250},
            {id: "locus_pld", map: "#data4#", header: ["Locus tag (old)", {content: "textFilter"}], width: 250},
            {id: "locus", map: "#data3#", header: ["Locus tag (new)", {content: "textFilter"}], width: 250},
            {id: "numort", map: "#data5#", header: ["Number of","Homologs"], width: 150},
            {id: "numint", map: "#data6#", header: ["Number of","Interactions"], width: 150}
        ],
        resizeColumn: true,
        datatype: "csv",
        url: data_url_prefix+'data/nodes.csv',
        autoheight: true,
        autowidth: true,
        pager: {
            css:"salmonet_table",
            template: "{common.prev()}{common.next()}Page {common.page()} from #limit#",
            container: "paging_here",
            size: 25,
            group: 5
        },
        hover: "browse_row_hover",
        on: {
            "onItemClick": function (id, e, trg) {
                window.location.href = data_url_prefix+"protein/"+dtable.getItem(id.row).uniprot.toLowerCase()+"/";
                // window.location.href = "uniprot.html";
                //webix.message("Click on row: "+dtable.getItem(id.row).uniprot);
            }
        }
    });
    webix.extend($$("dtable"), webix.ProgressBar);
    var strain_select = [
        {view: "label", label: "Select a Salmonella enterica strain:"},
        {
            view: "select",
            name: "strain",
            options: data_url_prefix+"data/strain_select.json"
        }];
    strain_select_form = new webix.ui({
        css:"salmonet_form",
        container: "strain_select_div",
        id: "strain_select_form",
        view: "form",
        scroll: false,
        width: 300,
        elements: strain_select
    });
    $$("strain_select_form").elements["strain"].attachEvent("onChange", function (newv, oldv) {
        $$("dtable").showProgress({
            type: "bottom",
            delay: 3000,
            hide: true
        });
        dtable.clearAll();
        dtable.load(data_url_prefix+"data/nodes" + newv + ".csv");
        $$("dtable").refresh();
        // webix.message("Value changed from: "+oldv+" to: "+newv);
    });
    $(window).resize(function() {
        if ($(window).width() < 1050){
            dtable.hideColumn("numort");
            dtable.hideColumn("numint");
        }
        if ($(window).width() >= 1050){
            dtable.showColumn("numort");
            dtable.showColumn("numint");
        }
        if ($(window).width() < 850){
            dtable.setColumnWidth("uniprot", 80);
            dtable.setColumnWidth("genename", 120);
            dtable.setColumnWidth("locus", 120);
        }
        if ($(window).width() >= 850){
            dtable.setColumnWidth("uniprot", 150);
            dtable.setColumnWidth("genename", 250);
            dtable.setColumnWidth("locus", 250);
        }
    });
    if ($(window).width() < 1050){
        dtable.hideColumn("numort");
        dtable.hideColumn("numint");
    }
    if ($(window).width() < 850){
        dtable.setColumnWidth("uniprot", 80);
        dtable.setColumnWidth("genename", 120);
        dtable.setColumnWidth("locus", 120);
    }
    // protein page
    // interactiontable = webix.ui({
    //     container: "interactiontable",
    //     view: "datatable",
    //     columns: [
    //         {id: "data0", header: ["Interactor", {content: "textFilter"}], css: "rank", width: 120},
    //         {id: "data1", header: ["Interactor", {content: "textFilter"}], width: 120},
    //         {id: "data2", header: "Source", width: 200},
    //         {id: "data3", header: ["Layer", {content: "selectFilter"}], width: 200}
    //     ],
    //     autoheight: true,
    //     autowidth: true,
    //
    //     datatype: "csv",
    //     data: '{{ .Content }}'
    // });
});
<|endoftext|>


<commit_before>
var Transform = require('../Transform');
var isTextAsset = require('../helper/isTextAsset');
var contentSize = require('../helper/contentSize');
var transformCache = require('../helper/transformCache');
var zlib = require('zlib');

function compressTextAsset(cache, asset, callback) {
	if ('gzip' in asset.content) {
		return callback(null, asset);
	}

	var startTime;
	var compressions = 0;

	function compressionDone() {
		if (++compressions !== 2) return;

		var dataSize = contentSize(asset);
		var gzipSize = contentSize(asset, 'gzip');
		var deflateSize = contentSize(asset, 'deflate');

		var endTime = new Date();
		var transform = {
			name: 'compressText',
			time: endTime - startTime,
			gzipRatio: dataSize ? (gzipSize / dataSize) : 0,
			deflateRatio: dataSize ? (deflateSize / dataSize) : 0
		};

		if (transform.gzipRatio > 1) {
			asset.content.gzip = null;
		}

		if (transform.deflateRatio > 1) {
			asset.content.deflate = null;
		}

		asset.transforms = asset.transforms || [];
		asset.transforms.push(transform);

		cache.put(asset, asset, function(error) {
			callback(null, asset);
		});
	}

	cache.get(asset, function(error, cachedAsset) {
		if (!error && cachedAsset && 'gzip' in cachedAsset.content) {
			return callback(null, cachedAsset);
		}

		startTime = new Date();

		zlib.gzip(asset.content.data, function(error, gzip) {
			if (error) {
				console.error('Gzip error:', error.stack || error);
				// Ignoring error. TODO: What to do?
			} else {
				asset.content.gzip = gzip;
			}
			compressionDone();
		});

		zlib.deflate(asset.content.data, function(error, deflate) {
			if (error) {
				console.error('Deflate error:', error.stack || error);
				// Ignoring error. TODO: What to do?
			} else {
				asset.content.deflate = deflate;
			}
			compressionDone();
		});

	});
}

module.exports = Transform.create(function(options) {
	options = options || {};
	var cache = options.cache || transformCache.nullCache;

	return function(asset, callback) {
		if (asset.event === 'update' && isTextAsset(asset)) {
			compressTextAsset(cache, asset, callback);
		} else {
			callback(null, asset);
		}
	};
});
<commit_msg>Exporting internal function for easier testing.<commit_after>
var Transform = require('../Transform');
var isTextAsset = require('../helper/isTextAsset');
var contentSize = require('../helper/contentSize');
var transformCache = require('../helper/transformCache');
var zlib = require('zlib');

function compressTextAsset(cache, asset, callback) {
	if ('gzip' in asset.content) {
		return callback(null, asset);
	}

	var startTime;
	var compressions = 0;

	function compressionDone() {
		if (++compressions !== 2) return;

		var dataSize = contentSize(asset);
		var gzipSize = contentSize(asset, 'gzip');
		var deflateSize = contentSize(asset, 'deflate');

		var endTime = new Date();
		var transform = {
			name: 'compressText',
			time: endTime - startTime,
			gzipRatio: dataSize ? (gzipSize / dataSize) : 0,
			deflateRatio: dataSize ? (deflateSize / dataSize) : 0
		};

		if (transform.gzipRatio > 1) {
			asset.content.gzip = null;
		}

		if (transform.deflateRatio > 1) {
			asset.content.deflate = null;
		}

		asset.transforms = asset.transforms || [];
		asset.transforms.push(transform);

		cache.put(asset, asset, function(error) {
			callback(null, asset);
		});
	}

	cache.get(asset, function(error, cachedAsset) {
		if (!error && cachedAsset && 'gzip' in cachedAsset.content) {
			return callback(null, cachedAsset);
		}

		startTime = new Date();

		zlib.gzip(asset.content.data, function(error, gzip) {
			if (error) {
				console.error('Gzip error:', error.stack || error);
				// Ignoring error. TODO: What to do?
			} else {
				asset.content.gzip = gzip;
			}
			compressionDone();
		});

		zlib.deflate(asset.content.data, function(error, deflate) {
			if (error) {
				console.error('Deflate error:', error.stack || error);
				// Ignoring error. TODO: What to do?
			} else {
				asset.content.deflate = deflate;
			}
			compressionDone();
		});

	});
}

module.exports = Transform.create(function(options) {
	options = options || {};
	var cache = options.cache || transformCache.nullCache;

	return function(asset, callback) {
		if (asset.event === 'update' && isTextAsset(asset)) {
			compressTextAsset(cache, asset, callback);
		} else {
			callback(null, asset);
		}
	};
});

module.exports.compressTextAsset = compressTextAsset;
<|endoftext|>


<commit_before>/**
 * @file MOZTracker main script
 * @author Matt Schoen
 * @version 0.1
 *
 * @namespace moztrack
 */
var moztrack = moztrack || {};
(function(){
	var progress;

	var startDate = new Date(2015, 5, 26, 12);
	var endDate = new Date(2015, 7, 6, 19, 17);

	var episodeNum = 2659;

	var showStartDate = new Date(1999, 0, 11);
	var showEndDate = new Date(2015, 8, 6);

	var showTime, realTime;

	var perEpisode = 28;
	var perEpisodeOverride = 24;
	moztrack.startOverride = new Date(2015,5,25,4,0);

	$(document).ready(function() {
		//Setup local DB
		moztrack.db = openDatabase('moztrack', '0.1', 'Daily show episodes', 1*1024*1024);
		//moztrack.createLocalStorage();
		//Screw it, just reset every time
		moztrack.clearLocalStorage();

		//Create tracker
		var content = document.getElementById("moztrack-content");
		progress = Div();

		content.appendChild(Div({}, ["Stream started at " + startDate]));
		content.appendChild(Div({}, ["Stream ends at " + endDate]));
		content.appendChild(Div({}, [sprintf("Stream duration: %.2f hours", (endDate - startDate) / (60 * 60 * 1000))]));
		content.appendChild(Div({}, ["Episode count: " + episodeNum]));
		perEpisode = (endDate - startDate) / episodeNum;
		content.appendChild(Div({}, [sprintf("Computed %.2f minutes per episode", ((perEpisode / (60 * 1000))))]));
		content.appendChild(Div({}, ["Episode length overridden to: " + perEpisodeOverride]));
		var realEpCount = ((endDate - startDate) / (60 * 1000) / perEpisodeOverride);
		content.appendChild(Div({}, [sprintf("Actual stream length: %.2f episodes", realEpCount)]));
		content.appendChild(Div({}, [sprintf("Skipped about %.2f episodes", (episodeNum - realEpCount))]));
		var overDiff = (startDate - moztrack.startOverride) / (24 * 60 * 1000);
		content.appendChild(Div({}, [sprintf("Start time override: " + moztrack.startOverride + ", which means %.2f/180 skipped episodes so far", overDiff)]));

		showTime = Input({},[],{"onkeyup":function(){
			var date = new Date(this.value);
			moztrack.getRealTime(date);
		}});

		realTime = Input({},[],{"onkeyup":function(){
			var date = new Date(this.value);
			moztrack.getShowTime(date);
		}});

		content.appendChild(Div({"style":"margin-top:25px;"},[
			Div({},[
				"Show Time: ", showTime,
				" Real Time: ", realTime
			]),
			Elm("button", {"type":"button"}, ["Reset Local Storage"], {"onclick":moztrack.clearLocalStorage}),
			progress
		]));

		//start on a delay for the first load
		// setTimeout(function(){
			// realTime.value = new Date().format("Y-m-d H:i:s");
			// moztrack.getShowTime(new Date());
		// }, 1500);
	});
	moztrack.createLocalStorage = function(){
		//If table exists, assume we've done this before
		doIfTableNotExist(moztrack.db, "episodes", function(){
			moztrack.db.transaction(function(tx){
				tx.executeSql('CREATE TABLE IF NOT EXISTS "episodes" ("id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , "guest" VARCHAR, "date" DATETIME NOT NULL, "realtime" DATETIME NOT NULL );', [],
					function(tx, results){
						//TODO: non-blocking solution
						$.ajax({
							//Use absolute URL for local testing, Chrome blocks ajax requests to file:///
							"url":"http://mtschoen.github.io/month-of-zen-tracker/episodes/all.json",
							//"url":"http://mtschoen.github.io/month-of-zen-tracker/episodes/" + 1999 + ".json",
							//"url":"episodes/" + episodeLists[i] + ".json",
							"crossDomain":true,
							"async":false,
							"success":function(data){
								episodeNum = data.length - 1;	//-1 for sept11
								var perEpisode = (endDate - startDate) / episodeNum;

								perEpisode = perEpisodeOverride * 60 * 1000;
								var streamTime = 0;
								var query = "INSERT INTO episodes (guest,date,realtime) VALUES (?,?,?)";
								episodeNum = 0;
								console.log(moztrack.startOverride);
								for(var j in data){
									//Skip over the unaired sept11 episode
									if(data[j].extra == "sept11")
										continue;
									episodeNum++;
									data[j].date = new Date(data[j].date);

									progress.innerHTML = j;

									var realtime = moztrack.startOverride.getTime() + streamTime;
									tx.executeSql(query, [data[j].guest, data[j].date.getTime(), realtime],
										function(tx, results){

										},
										function(tx, error){
											console.log(error);
											console.log(query);
											console.log(data[j].guest, data[j].date.format("Y-m-d"));
											throw error;
										}
									);
									streamTime += perEpisode;
								}
							}
						});
					},
					function(tx, error){
						console.log(error);
						throw error;
					}
				);
			});
		});
	};
	moztrack.clearLocalStorage = function(){
		moztrack.db.transaction(function(tx){
			tx.executeSql("DROP TABLE IF EXISTS episodes;",[],
			function(){

			},
			function(tx, error){
				throw error;
			});
		});
		moztrack.createLocalStorage();
		setTimeout(function(){
			realTime.value = new Date().format("Y-m-d H:i:s");
			moztrack.getShowTime(new Date());
		}, 1000);
		ga('send', 'event', 'clearStorage');
	};

	function doIfTableNotExist(db, table, callback){
		db.transaction(function(tx){
			tx.executeSql("SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?", ["table", table],
				function(tx, results){
					if(results.rows[0]["COUNT(*)"] == 0)
						callback();
				},
				function(tx, error){
					throw error;
				}
			);
		});
	}

	moztrack.getRealTime = function(date){
		if(date < showStartDate || date > showEndDate){
			console.log("Invalid show date: ", date, showStartDate);
			ga('send', 'event', 'getRealTimeInvalid', date.format("Y-m-d H:i:s"));
			return;
		}
		ga('send', 'event', 'getRealTime', date.format("Y-m-d"));
		ga('send', 'event', 'getRealTimeFull', date.format("Y-m-d H:i:s"));
		moztrack.db.transaction(function(tx){
			tx.executeSql("SELECT * FROM episodes WHERE date >= ? ORDER BY date LIMIT 1", [date.getTime()],
			function(tx, results){
				if(results.rows.length > 0){
					progress.innerHTML = "Guest: " + results.rows[0].guest + "";
					realTime.value = new Date(results.rows[0].realtime).format("Y-m-d H:i:s");
				} else {
					console.log("no results?");
				}
			},
			function(tx, error){
				console.log(error);
				throw error;
			});
		});
	};
	moztrack.getShowTime = function(date){
		if(date < startDate || date > endDate){
			console.log("Invalid real date");
			ga('send', 'event', 'getShowTimeInvalid', date.format("Y-m-d H:i:s"));
			return;
		}
		ga('send', 'event', 'getShowTimeFull', date.format("Y-m-d H:i:s"));
		moztrack.db.transaction(function(tx){
			tx.executeSql("SELECT * FROM episodes WHERE realtime <= ? ORDER BY date DESC LIMIT 1", [date.getTime()],
			function(tx, results){
				if(results.rows.length > 0){
					progress.innerHTML = "Guest: " + results.rows[0].guest + "";
					showTime.value = new Date(results.rows[0].date).format("Y-m-d");
				} else {
					console.log("no results?");
				}
			},
			function(tx, error){
				console.log(error);
				throw error;
			});
		});
	};
})();
<commit_msg>Update main.js<commit_after>/**
 * @file MOZTracker main script
 * @author Matt Schoen
 * @version 0.1
 *
 * @namespace moztrack
 */
var moztrack = moztrack || {};
(function(){
	var progress;

	var startDate = new Date(2015, 5, 26, 12);
	var endDate = new Date(2015, 7, 6, 19, 17);

	var episodeNum = 2659;

	var showStartDate = new Date(1999, 0, 11);
	var showEndDate = new Date(2015, 8, 6);

	var showTime, realTime;

	var perEpisode = 28;
	var perEpisodeOverride = 24;
	moztrack.startOverride = new Date(2015,5,25,2,45);

	$(document).ready(function() {
		//Setup local DB
		moztrack.db = openDatabase('moztrack', '0.1', 'Daily show episodes', 1*1024*1024);
		//moztrack.createLocalStorage();
		//Screw it, just reset every time
		moztrack.clearLocalStorage();

		//Create tracker
		var content = document.getElementById("moztrack-content");
		progress = Div();

		content.appendChild(Div({}, ["Stream started at " + startDate]));
		content.appendChild(Div({}, ["Stream ends at " + endDate]));
		content.appendChild(Div({}, [sprintf("Stream duration: %.2f hours", (endDate - startDate) / (60 * 60 * 1000))]));
		content.appendChild(Div({}, ["Episode count: " + episodeNum]));
		perEpisode = (endDate - startDate) / episodeNum;
		content.appendChild(Div({}, [sprintf("Computed %.2f minutes per episode", ((perEpisode / (60 * 1000))))]));
		content.appendChild(Div({}, ["Episode length overridden to: " + perEpisodeOverride]));
		var realEpCount = ((endDate - startDate) / (60 * 1000) / perEpisodeOverride);
		content.appendChild(Div({}, [sprintf("Actual stream length: %.2f episodes", realEpCount)]));
		content.appendChild(Div({}, [sprintf("Skipped about %.2f episodes", (episodeNum - realEpCount))]));
		var overDiff = (startDate - moztrack.startOverride) / (24 * 60 * 1000);
		content.appendChild(Div({}, [sprintf("Start time override: " + moztrack.startOverride + ", which means %.2f/180 skipped episodes so far", overDiff)]));

		showTime = Input({},[],{"onkeyup":function(){
			var date = new Date(this.value);
			moztrack.getRealTime(date);
		}});

		realTime = Input({},[],{"onkeyup":function(){
			var date = new Date(this.value);
			moztrack.getShowTime(date);
		}});

		content.appendChild(Div({"style":"margin-top:25px;"},[
			Div({},[
				"Show Time: ", showTime,
				" Real Time: ", realTime
			]),
			Elm("button", {"type":"button"}, ["Reset Local Storage"], {"onclick":moztrack.clearLocalStorage}),
			progress
		]));

		//start on a delay for the first load
		// setTimeout(function(){
			// realTime.value = new Date().format("Y-m-d H:i:s");
			// moztrack.getShowTime(new Date());
		// }, 1500);
	});
	moztrack.createLocalStorage = function(){
		//If table exists, assume we've done this before
		doIfTableNotExist(moztrack.db, "episodes", function(){
			moztrack.db.transaction(function(tx){
				tx.executeSql('CREATE TABLE IF NOT EXISTS "episodes" ("id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , "guest" VARCHAR, "date" DATETIME NOT NULL, "realtime" DATETIME NOT NULL );', [],
					function(tx, results){
						//TODO: non-blocking solution
						$.ajax({
							//Use absolute URL for local testing, Chrome blocks ajax requests to file:///
							"url":"http://mtschoen.github.io/month-of-zen-tracker/episodes/all.json",
							//"url":"http://mtschoen.github.io/month-of-zen-tracker/episodes/" + 1999 + ".json",
							//"url":"episodes/" + episodeLists[i] + ".json",
							"crossDomain":true,
							"async":false,
							"success":function(data){
								episodeNum = data.length - 1;	//-1 for sept11
								var perEpisode = (endDate - startDate) / episodeNum;

								perEpisode = perEpisodeOverride * 60 * 1000;
								var streamTime = 0;
								var query = "INSERT INTO episodes (guest,date,realtime) VALUES (?,?,?)";
								episodeNum = 0;
								console.log(moztrack.startOverride);
								for(var j in data){
									//Skip over the unaired sept11 episode
									if(data[j].extra == "sept11")
										continue;
									episodeNum++;
									data[j].date = new Date(data[j].date);

									progress.innerHTML = j;

									var realtime = moztrack.startOverride.getTime() + streamTime;
									tx.executeSql(query, [data[j].guest, data[j].date.getTime(), realtime],
										function(tx, results){

										},
										function(tx, error){
											console.log(error);
											console.log(query);
											console.log(data[j].guest, data[j].date.format("Y-m-d"));
											throw error;
										}
									);
									streamTime += perEpisode;
								}
							}
						});
					},
					function(tx, error){
						console.log(error);
						throw error;
					}
				);
			});
		});
	};
	moztrack.clearLocalStorage = function(){
		moztrack.db.transaction(function(tx){
			tx.executeSql("DROP TABLE IF EXISTS episodes;",[],
			function(){

			},
			function(tx, error){
				throw error;
			});
		});
		moztrack.createLocalStorage();
		setTimeout(function(){
			realTime.value = new Date().format("Y-m-d H:i:s");
			moztrack.getShowTime(new Date());
		}, 1000);
		ga('send', 'event', 'clearStorage');
	};

	function doIfTableNotExist(db, table, callback){
		db.transaction(function(tx){
			tx.executeSql("SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?", ["table", table],
				function(tx, results){
					if(results.rows[0]["COUNT(*)"] == 0)
						callback();
				},
				function(tx, error){
					throw error;
				}
			);
		});
	}

	moztrack.getRealTime = function(date){
		if(date < showStartDate || date > showEndDate){
			console.log("Invalid show date: ", date, showStartDate);
			ga('send', 'event', 'getRealTimeInvalid', date.format("Y-m-d H:i:s"));
			return;
		}
		ga('send', 'event', 'getRealTime', date.format("Y-m-d"));
		ga('send', 'event', 'getRealTimeFull', date.format("Y-m-d H:i:s"));
		moztrack.db.transaction(function(tx){
			tx.executeSql("SELECT * FROM episodes WHERE date >= ? ORDER BY date LIMIT 1", [date.getTime()],
			function(tx, results){
				if(results.rows.length > 0){
					progress.innerHTML = "Guest: " + results.rows[0].guest + "";
					realTime.value = new Date(results.rows[0].realtime).format("Y-m-d H:i:s");
				} else {
					console.log("no results?");
				}
			},
			function(tx, error){
				console.log(error);
				throw error;
			});
		});
	};
	moztrack.getShowTime = function(date){
		if(date < startDate || date > endDate){
			console.log("Invalid real date");
			ga('send', 'event', 'getShowTimeInvalid', date.format("Y-m-d H:i:s"));
			return;
		}
		ga('send', 'event', 'getShowTimeFull', date.format("Y-m-d H:i:s"));
		moztrack.db.transaction(function(tx){
			tx.executeSql("SELECT * FROM episodes WHERE realtime <= ? ORDER BY date DESC LIMIT 1", [date.getTime()],
			function(tx, results){
				if(results.rows.length > 0){
					progress.innerHTML = "Guest: " + results.rows[0].guest + "";
					showTime.value = new Date(results.rows[0].date).format("Y-m-d");
				} else {
					console.log("no results?");
				}
			},
			function(tx, error){
				console.log(error);
				throw error;
			});
		});
	};
})();
<|endoftext|>


<commit_before>
  var field = document.querySelector("#student");
  var studentName = "";
  var studentArray = [];
  var suggestionsDiv = document.querySelector("#suggestions");
  var headerHold = suggestionsDiv.innerHTML;

	field.addEventListener("keypress", function(event) {
		if (event.keyCode == "$".charCodeAt(0) ||
		    event.keyCode == "?".charCodeAt(0) ||
		    event.keyCode == "'".charCodeAt(0) ||
		    event.keyCode == "&".charCodeAt(0) ||
		    event.keyCode == "<".charCodeAt(0) ||
		    event.keyCode == ">".charCodeAt(0) ||
		    event.keyCode == "/".charCodeAt(0) ||
		    event.keyCode == "\\".charCodeAt(0) ||
		    event.keyCode == "@".charCodeAt(0) ||
		    event.keyCode == "#".charCodeAt(0) ||
		    event.keyCode == "*".charCodeAt(0) ||
		    event.keyCode == "+".charCodeAt(0) ||
		    event.keyCode == "!".charCodeAt(0)
		    ) {
			      event.preventDefault();
		   }
	});

  var addStudentBtn = document.querySelector("#addStudent");

  addStudentBtn.addEventListener("click", function() {
  	// Alt way of removing trouble characters
	// var cleanedUp = field.value.split("$").join("");
  	if (field.value){
  		studentArray.push(field.value);
  	}
    field.value = "";
    studentName = "";

  });

  var add14ListRadio = document.querySelector('input[value="class14List"]');

  add14ListRadio.addEventListener("click", function() {
  	var class14List = [
  		'Abila',
  		'Harry',
  		'Mel',
  		'Asal',
  		'Ethan',
  		'Francisco',
  		'Harry',
  		'Jesse',
  		'Julian',
  		'Kelly',
  		'Mark',
  		'Rachel'
  		];
  	studentArray = class14List;
    field.value = "";
    studentName = "";
    console.log("Added 1-4pm class list!");

  });

  //var add69ListRadio = document.querySelector('input[value="class69List"]');

  //add69ListRadio.addEventListener("click", function() {
  //	var class69List = ['AK', 'Harry', 'Mel', 'Abila', 'AJay', 'Asal', 'Craig', 'Ethan', 'Francisco', 'Jeff', 'Jesse', 'Jessica', 'Josh', 'Julian', 'Kelly', 'Mewpeter', 'Rachel'];
  //	studentArray = class69List;
  //  field.value = "";
  //  studentName = "";
  //  console.log("Added 6:30-9:30pm class list!");

  //});

  var clearStudentBtn = document.querySelector("#clearStudent");

  clearStudentBtn.addEventListener("click", function() {
    studentArray = [];
    field.value = "";
    studentName = "";
    suggestionsDiv.innerHTML = "" + headerHold;
  });

  var printStudentBtn = document.querySelector("#printStudent");

  printStudentBtn.addEventListener("click", function() {
    console.log(studentArray);
  	var printingList = _.shuffle(studentArray);

  	// clear old html
    suggestionsDiv.innerHTML = "" + headerHold;

    // begin printing
		if (printingList[0]){
			var newList = document.createElement("UL");
			suggestionsDiv.appendChild(newList);

			if (printingList.length % 2){
				var thirdPerson = printingList.pop();
			}

			for (var i = 0; i < printingList.length-1; i = i + 2){
				var newListLI = document.createElement("LI");
				newList.appendChild(newListLI);

				var studentArrayTemp = document.createTextNode(printingList[i] + " :: " + printingList[i+1]);
				newListLI.appendChild(studentArrayTemp);
			}

			if (thirdPerson){
				var newListLI = document.createElement("LI");
				newList.appendChild(newListLI);

				var studentArrayTemp = document.createTextNode(thirdPerson + " can join any pair");
				newListLI.appendChild(studentArrayTemp);
			}
		}
  });

<commit_msg>Update swap.js<commit_after>
  var field = document.querySelector("#student");
  var studentName = "";
  var studentArray = [];
  var suggestionsDiv = document.querySelector("#suggestions");
  var headerHold = suggestionsDiv.innerHTML;

	field.addEventListener("keypress", function(event) {
		if (event.keyCode == "$".charCodeAt(0) ||
		    event.keyCode == "?".charCodeAt(0) ||
		    event.keyCode == "'".charCodeAt(0) ||
		    event.keyCode == "&".charCodeAt(0) ||
		    event.keyCode == "<".charCodeAt(0) ||
		    event.keyCode == ">".charCodeAt(0) ||
		    event.keyCode == "/".charCodeAt(0) ||
		    event.keyCode == "\\".charCodeAt(0) ||
		    event.keyCode == "@".charCodeAt(0) ||
		    event.keyCode == "#".charCodeAt(0) ||
		    event.keyCode == "*".charCodeAt(0) ||
		    event.keyCode == "+".charCodeAt(0) ||
		    event.keyCode == "!".charCodeAt(0)
		    ) {
			      event.preventDefault();
		   }
	});

  var addStudentBtn = document.querySelector("#addStudent");

  addStudentBtn.addEventListener("click", function() {
  	// Alt way of removing trouble characters
	// var cleanedUp = field.value.split("$").join("");
  	if (field.value){
  		studentArray.push(field.value);
  	}
    field.value = "";
    studentName = "";

  });

  var add14ListRadio = document.querySelector('input[value="class14List"]');

  add14ListRadio.addEventListener("click", function() {
  	var class14List = [
  		'Abila',
  		'Harry',
  		'Mel',
  		'Asal',
  		'Ethan',
  		'Francisco',
  		'Jesse',
  		'Julian',
  		'Kelly',
  		'Mark',
  		'Rachel'
  		];
  	studentArray = class14List;
    field.value = "";
    studentName = "";
    console.log("Added 1-4pm class list!");

  });

  //var add69ListRadio = document.querySelector('input[value="class69List"]');

  //add69ListRadio.addEventListener("click", function() {
  //	var class69List = ['AK', 'Harry', 'Mel', 'Abila', 'AJay', 'Asal', 'Craig', 'Ethan', 'Francisco', 'Jeff', 'Jesse', 'Jessica', 'Josh', 'Julian', 'Kelly', 'Mewpeter', 'Rachel'];
  //	studentArray = class69List;
  //  field.value = "";
  //  studentName = "";
  //  console.log("Added 6:30-9:30pm class list!");

  //});

  var clearStudentBtn = document.querySelector("#clearStudent");

  clearStudentBtn.addEventListener("click", function() {
    studentArray = [];
    field.value = "";
    studentName = "";
    suggestionsDiv.innerHTML = "" + headerHold;
  });

  var printStudentBtn = document.querySelector("#printStudent");

  printStudentBtn.addEventListener("click", function() {
    console.log(studentArray);
  	var printingList = _.shuffle(studentArray);

  	// clear old html
    suggestionsDiv.innerHTML = "" + headerHold;

    // begin printing
		if (printingList[0]){
			var newList = document.createElement("UL");
			suggestionsDiv.appendChild(newList);

			if (printingList.length % 2){
				var thirdPerson = printingList.pop();
			}

			for (var i = 0; i < printingList.length-1; i = i + 2){
				var newListLI = document.createElement("LI");
				newList.appendChild(newListLI);

				var studentArrayTemp = document.createTextNode(printingList[i] + " :: " + printingList[i+1]);
				newListLI.appendChild(studentArrayTemp);
			}

			if (thirdPerson){
				var newListLI = document.createElement("LI");
				newList.appendChild(newListLI);

				var studentArrayTemp = document.createTextNode(thirdPerson + " can join any pair");
				newListLI.appendChild(studentArrayTemp);
			}
		}
  });

<|endoftext|>


<commit_before>import _ from 'lodash'
import stringify from 'fast-stable-stringify'

import { TMP_ID_PREFIX } from './collection-util'

export const defaultGetFetchKey = (query, option) => stringify({ ..._.omitBy(option, (v, k) => k[0] === '_'), ...query })

// @auto-fold here
const markPromise = (coll, fetchKey, func) => {
  const { _fetchPromises } = coll
  const oldPromise = _fetchPromises[fetchKey]
  if (oldPromise) return oldPromise

  const markPromiseDone = () => {
    delete _fetchPromises[fetchKey]
    if (Object.keys(_fetchPromises).length === 0) {
      coll.getDb().dispatch(coll.name, { fetchingAt: { $set: undefined } })
    }
  }
  const promise = (_fetchPromises[fetchKey] = func()
    .then(ret => {
      markPromiseDone()
      return ret
    })
    .catch(err => {
      markPromiseDone()
      return Promise.reject(err)
    }))
  // ensure fetchingAt is set to coll instantaneously
  const fetchingAt = Date.now()
  coll.getDb().dispatch(coll.name, { fetchingAt: { $set: fetchingAt } })
  return promise
}

const isTmpId = id => !id || _.startsWith(id, TMP_ID_PREFIX)
const sortUniqFilter = ids => _.filter(_.sortedUniq(ids.sort()), id => !isTmpId(id))
// @auto-fold here
const defaultGetFetchQuery = (query, idField) => {
  if (!query) return query

  if (Array.isArray(query)) {
    const ids = sortUniqFilter(query)
    if (ids.length === 0) return false
    return { [idField]: { $in: ids } }
  }

  const fetchQuery = { ...query }
  const entries = Object.entries(query)
  for (let i = 0, ii = entries.length; i < ii; i++) {
    const [key, matcher] = entries[i]
    if (matcher) {
      if (typeof matcher === 'string' && isTmpId(matcher)) {
        return false
      } else if (matcher.$in) {
        const $in = sortUniqFilter(matcher.$in)
        if ($in.length === 0) {
          return false
        }
        fetchQuery[key] = { $in }
      }
    } else if (key === idField) {
      // idField is falsy
      return false
    }
  }

  const idFieldStr = fetchQuery[idField]
  if (typeof idFieldStr === 'string') {
    fetchQuery[idField] = { $in: [idFieldStr] }
  }
  return fetchQuery
}

const isAllIdHit = (coll, query) => {
  const ids = _.get(query, [coll.idField, '$in'])
  if (!ids) return false
  const expire = coll.fetchMaxAge > 0 ? Date.now() - coll.fetchMaxAge : 0
  return _.every(ids, id => coll._byIdAts[id] > expire)
}

function doFetch(db, name, query, option) {
  const coll = db.getFetchData(name)
  if (!coll.onFetch) return undefined

  // use getFetchQuery to modify final ajax call query
  const fetchQuery = (coll.getFetchQuery || defaultGetFetchQuery)(query, coll.idField)
  const notForce = !option.force
  if (notForce && fetchQuery === false) return undefined
  if (notForce && isAllIdHit(coll, fetchQuery)) return undefined

  // use getFetchKey to stringify into querystring like key
  const fetchKey = (coll.getFetchKey || defaultGetFetchKey)(fetchQuery, option)
  if (notForce && fetchKey === false) return undefined
  option._fetchKey = fetchKey

  if (notForce) {
    // collection.fetchMaxAge: 1, // in seconds; null, 0 or -1 means no maxAge
    const now = Date.now()
    // console.log('>>>', fetchKey, fetchAts, fetchAts[fetchKey])
    if (coll.fetchMaxAge > 0 ? coll.fetchAts[fetchKey] > now - coll.fetchMaxAge : coll.fetchAts[fetchKey]) {
      if (option._keepFetchResult) return coll._fetchPromises[fetchKey] || coll._fetchResults[fetchKey]
      return false
    }
  }

  // doFetch
  coll.fetchAts[fetchKey] = Date.now()
  return markPromise(coll, fetchKey, () =>
    Promise.resolve(coll.onFetch(fetchQuery, option, coll)).then(res => {
      if (option._keepFetchResult) coll._fetchResults[fetchKey] = res
      db.load(name, res)
      return res
    })
  )
}

export default {
  fetch(name, query, option = {}) {
    option._keepFetchResult = true
    return doFetch(this, name, query, option)
  },

  get(name, id, option = {}) {
    doFetch(this, name, [id], option)
    return this.getById(name)[id]
  },
  pick(name, query, option = {}) {
    doFetch(this, name, query, option)
    return this.pickInMemory(name, query)
  },
  find(name, query, option = {}) {
    doFetch(this, name, query, option)
    return this.findInMemory(name, query)
  },
  pickAsync(name, query, option = {}) {
    return Promise.resolve(doFetch(this, name, query, option)).then(() => this.pickInMemory(name, query))
  },
  findAsync(name, query, option = {}) {
    return Promise.resolve(doFetch(this, name, query, option)).then(() => this.findInMemory(name, query))
  },
}
<commit_msg>fix: always do basic normalize before getFetchQuery<commit_after>import _ from 'lodash'
import stringify from 'fast-stable-stringify'

import { TMP_ID_PREFIX } from './collection-util'

export const defaultGetFetchKey = (query, option) => stringify({ ..._.omitBy(option, (v, k) => k[0] === '_'), ...query })

// @auto-fold here
const markPromise = (coll, fetchKey, func) => {
  const { _fetchPromises } = coll
  const oldPromise = _fetchPromises[fetchKey]
  if (oldPromise) return oldPromise

  const markPromiseDone = () => {
    delete _fetchPromises[fetchKey]
    if (Object.keys(_fetchPromises).length === 0) {
      coll.getDb().dispatch(coll.name, { fetchingAt: { $set: undefined } })
    }
  }
  const promise = (_fetchPromises[fetchKey] = func()
    .then(ret => {
      markPromiseDone()
      return ret
    })
    .catch(err => {
      markPromiseDone()
      return Promise.reject(err)
    }))
  // ensure fetchingAt is set to coll instantaneously
  const fetchingAt = Date.now()
  coll.getDb().dispatch(coll.name, { fetchingAt: { $set: fetchingAt } })
  return promise
}

const normalizeQueryBasic = (query, idField) => {
  // query = [ids]
  if (Array.isArray(query)) {
    if (query.length === 0) return false
    return { [idField]: { $in: query } }
  }
  const fetchQuery = { ...query }
  if (idField in query) {
    const idFieldValue = fetchQuery[idField]
    if (!idFieldValue) {
      // query = { id: falsy }
      return false
    } else if (typeof idFieldValue === 'string') {
      // query = { id: idStr }
      fetchQuery[idField] = { $in: [idFieldValue] }
    }
  }
  return fetchQuery
}

const isTmpId = id => !id || _.startsWith(id, TMP_ID_PREFIX)
const sortUniqFilter = ids => _.filter(_.sortedUniq(ids.sort()), id => !isTmpId(id))
// @auto-fold here
const defaultGetFetchQuery = fetchQuery => {
  const entries = Object.entries(fetchQuery)
  for (let i = 0, ii = entries.length; i < ii; i++) {
    const [key, matcher] = entries[i]
    if (matcher) {
      if (typeof matcher === 'string' && isTmpId(matcher)) {
        return false
      } else if (matcher.$in) {
        const $in = sortUniqFilter(matcher.$in)
        if ($in.length === 0) {
          return false
        }
        fetchQuery[key] = { $in }
      }
    }
  }
  return fetchQuery
}

const isAllIdHit = (coll, query) => {
  const ids = _.get(query, [coll.idField, '$in'])
  if (!ids) return false
  const expire = coll.fetchMaxAge > 0 ? Date.now() - coll.fetchMaxAge : 0
  return _.every(ids, id => coll._byIdAts[id] > expire)
}

function doFetch(db, name, query, option) {
  const coll = db.getFetchData(name)
  if (!coll.onFetch) return undefined
  const notForce = !option.force

  // use getFetchQuery to modify final ajax call query
  let fetchQuery = normalizeQueryBasic(query, coll.idField)
  if (notForce && fetchQuery === false) return undefined
  fetchQuery = (coll.getFetchQuery || defaultGetFetchQuery)(fetchQuery, coll.idField, coll)
  if (notForce && fetchQuery === false) return undefined
  if (notForce && isAllIdHit(coll, fetchQuery)) return undefined

  // use getFetchKey to stringify into querystring like key
  const fetchKey = (coll.getFetchKey || defaultGetFetchKey)(fetchQuery, option)
  if (notForce && fetchKey === false) return undefined
  option._fetchKey = fetchKey

  if (notForce) {
    // collection.fetchMaxAge: 1, // in seconds; null, 0 or -1 means no maxAge
    const now = Date.now()
    // console.log('>>>', fetchKey, fetchAts, fetchAts[fetchKey])
    if (coll.fetchMaxAge > 0 ? coll.fetchAts[fetchKey] > now - coll.fetchMaxAge : coll.fetchAts[fetchKey]) {
      if (option._keepFetchResult) return coll._fetchPromises[fetchKey] || coll._fetchResults[fetchKey]
      return false
    }
  }

  // doFetch
  coll.fetchAts[fetchKey] = Date.now()
  return markPromise(coll, fetchKey, () =>
    Promise.resolve(coll.onFetch(fetchQuery, option, coll)).then(res => {
      if (option._keepFetchResult) coll._fetchResults[fetchKey] = res
      db.load(name, res)
      return res
    })
  )
}

export default {
  fetch(name, query, option = {}) {
    option._keepFetchResult = true
    return doFetch(this, name, query, option)
  },

  get(name, id, option = {}) {
    doFetch(this, name, [id], option)
    return this.getById(name)[id]
  },
  pick(name, query, option = {}) {
    doFetch(this, name, query, option)
    return this.pickInMemory(name, query)
  },
  find(name, query, option = {}) {
    doFetch(this, name, query, option)
    return this.findInMemory(name, query)
  },
  pickAsync(name, query, option = {}) {
    return Promise.resolve(doFetch(this, name, query, option)).then(() => this.pickInMemory(name, query))
  },
  findAsync(name, query, option = {}) {
    return Promise.resolve(doFetch(this, name, query, option)).then(() => this.findInMemory(name, query))
  },
}
<|endoftext|>


<commit_before>exports.run = (client, comment, issue, repository) => {
  const commenter = comment.user.login;
  const repoName = repository.name;
  const repoOwner = repository.owner.login;
  if (issue.assignees && issue.assignees.find(assignee => assignee.login === commenter)) {
    return client.newComment(issue, repository, "**ERROR:** You have already claimed this issue.");
  }
  client.repos.checkCollaborator({
    owner: repoOwner, repo: repoName, username: commenter
  }).then((response) => {
    if (response.meta.status !== "204 No Content") {
      return client.newComment(issue, repository, "**ERROR:** Unexpected response from GitHub API.");
    }
    exports.claimIssue(client, comment, issue, repository);
  }, (response) => {
    if (response.headers.status !== "404 Not Found") {
      return client.newComment(issue, repository, "**ERROR:** Unexpected response from GitHub API.");
    }
    exports.addCollaborator(client, comment, issue, repository);
  });
};

exports.addCollaborator = (client, comment, issue, repository) => {
  const commenter = comment.user.login;
  const repoName = repository.name;
  const repoOwner = repository.owner.login;
  if (!client.cfg.addCollabPermission) {
    const comment = "**ERROR:** `client.cfg.addCollabPermission` wasn't specified in `src/config.js`.";
    return client.newComment(issue, repository, comment);
  }
  client.repos.addCollaborator({
    owner: repoOwner, repo: repoName, username: commenter, permission: client.cfg.addCollabPermission
  }).then(() => exports.claimIssue(client, comment, issue, repository, true));
};

exports.claimIssue = (client, comment, issue, repository, newContrib) => {
  const commenter = comment.user.login;
  const issueNumber = issue.number;
  const repoName = repository.name;
  const repoOwner = repository.owner.login;
  client.issues.addAssigneesToIssue({
    owner: repoOwner, repo: repoName, number: issueNumber, assignees: [commenter]
  }).then(() => {
    if (newContrib) {
      client.newComment(issue, repository, client.templates.get("newContributor").replace("[commenter]", commenter));
    }
  });
};

exports.aliases = require("../config.js").claimCommands;
exports.args = false;
<commit_msg>issues: Throw error if no assignee was added during issue claiming.<commit_after>exports.run = (client, comment, issue, repository) => {
  const commenter = comment.user.login;
  const repoName = repository.name;
  const repoOwner = repository.owner.login;
  if (issue.assignees && issue.assignees.find(assignee => assignee.login === commenter)) {
    return client.newComment(issue, repository, "**ERROR:** You have already claimed this issue.");
  }
  client.repos.checkCollaborator({
    owner: repoOwner, repo: repoName, username: commenter
  }).then((response) => {
    if (response.meta.status !== "204 No Content") {
      return client.newComment(issue, repository, "**ERROR:** Unexpected response from GitHub API.");
    }
    exports.claimIssue(client, comment, issue, repository);
  }, (response) => {
    if (response.headers.status !== "404 Not Found") {
      return client.newComment(issue, repository, "**ERROR:** Unexpected response from GitHub API.");
    }
    exports.addCollaborator(client, comment, issue, repository);
  });
};

exports.addCollaborator = (client, comment, issue, repository) => {
  const commenter = comment.user.login;
  const repoName = repository.name;
  const repoOwner = repository.owner.login;
  if (!client.cfg.addCollabPermission) {
    const comment = "**ERROR:** `client.cfg.addCollabPermission` wasn't specified in `src/config.js`.";
    return client.newComment(issue, repository, comment);
  }
  client.repos.addCollaborator({
    owner: repoOwner, repo: repoName, username: commenter, permission: client.cfg.addCollabPermission
  }).then(() => exports.claimIssue(client, comment, issue, repository, true));
};

exports.claimIssue = (client, comment, issue, repository, newContrib) => {
  const commenter = comment.user.login;
  const issueNumber = issue.number;
  const repoName = repository.name;
  const repoOwner = repository.owner.login;
  client.issues.addAssigneesToIssue({
    owner: repoOwner, repo: repoName, number: issueNumber, assignees: [commenter]
  }).then((response) => {
    if (!response.data.assignees) {
      return client.newComment(issue, repository, "**ERROR:** Issue claiming failed (no assignee was added).");
    }
    if (!newContrib) return;
    client.newComment(issue, repository, client.templates.get("newContributor").replace("[commenter]", commenter));
  });
};

exports.aliases = require("../config.js").claimCommands;
exports.args = false;
<|endoftext|>


<commit_before>/*
 * grunt-data-uri
 * http://github.com/ahomu/grunt-data-uri
 * http://aho.mu
 *
 * Copyright (c) 2012 ahomu
 * Licensed under the MIT license.
 */
module.exports = function(grunt) {

  'use strict';

  var fs       = require('fs'),
      path     = require('path'),
      datauri  = require('datauri');

  var RE_CSS_URLFUNC = /(?:url\(["']?)(.*?)(?:["']?\))/,
      util = grunt.util,
      gruntfileDir = path.resolve('./'),
      expandFiles;

  if (grunt.file.expandFiles) {
    expandFiles = grunt.file.expandFiles;
  } else {
    expandFiles = function(files) {
      return grunt.file.expand({filter: 'isFile'}, files);
    };
  }

  grunt.registerMultiTask('dataUri', 'Convert your css file image path!!', function() {

    var options  = this.options(),
        srcFiles = expandFiles(this.data.src),
        destDir  = path.resolve(this.data.dest),
        haystack = [];

    expandFiles(options.target).forEach(function(imgPath) {
      haystack.push(path.resolve(imgPath));
    });

    srcFiles.forEach(function(src) {
      var content  = grunt.file.read(src),
          matches  = content.match(new RegExp(RE_CSS_URLFUNC.source, 'g')),
          outputTo = destDir+'/'+path.basename(src),
          baseDir,
          uris;

      // Detect baseDir for using traversal image files
      baseDir = options.baseDir ? path.resolve(options.baseDir)    // specified base dir
                                : path.resolve(path.dirname(src)); // detected from src

      // Not found image path
      if (!matches) {
        grunt.log.subhead('SRC: file uri not found on '+src);
        grunt.file.write(outputTo, content);
        grunt.log.ok('Skipped');
        grunt.log.ok('=> ' + outputTo);
        return;
      }

      // Change base to src(css, html, js) existing dir
      grunt.file.setBase(baseDir);

      // List uniq image URIs
      uris = util._.uniq(matches.map(function(m) {
        return m.match(RE_CSS_URLFUNC)[1];
      }));

      // Exclude external http resource
      uris = uris.filter(function(u) {
        return !u.match('(data:|http)');
      });

      grunt.log.subhead('SRC: '+uris.length+' file uri found on '+src);

      // Process urls
      uris.forEach(function(uri) {
        var src, replacement, needle, fixedUri;

        // fixed current dir when specified uri is like root
        fixedUri = (uri.indexOf('/') === 0 ? '.' + uri : uri).split('?')[0].split('#')[0];

        // Resolve image realpath
        needle = path.resolve(fixedUri);

        // Assume file existing cause found from haystack
        if (haystack.indexOf(needle) !== -1) {

          // check if file exceeds the max bytes
          var fileSize = getFileSize(needle);
          if (options.maxBytes && fileSize > options.maxBytes) {
            // file is over the max size
            grunt.log.ok('Skipping (size ' + fileSize + ' > ' + options.maxBytes +'): ' + uri);
            return;
          } else {
            // Encoding to Data uri
            replacement = datauri(needle);

            grunt.log.ok('Encode: '+needle);
          }
        } else {
          if (options.fixDirLevel) {
            // Diff of directory level
            replacement = adjustDirectoryLevel(fixedUri, destDir, baseDir);
            grunt.log.ok('Adjust: '+ uri + ' -> ' + replacement);
          } else {
            replacement = uri;
            grunt.log.ok('Ignore: '+ uri);
          }
        }

        var escapedUri = uri.replace(/\?/g, '\\$&');
        content = content.replace(new RegExp(escapedUri, 'g'), replacement);
      });

      // Revert base to gruntjs executing current dir
      grunt.file.setBase(gruntfileDir);
      grunt.file.write(outputTo, content);
      grunt.log.ok('=> ' + outputTo);
    });
  });

  /**
   *
   * @param fullPath
   * @param options
   * @return {boolean} the file size, or undefined if not found
   */
  function getFileSize(fullPath) {

    if (!fs.existsSync(fullPath)) {
      return false;
    }

    var stats = fs.statSync(fullPath);
    if (!stats.isFile()) {
      return false;
    }
    return stats.size;
  }

  /**
   * @method adjustDirectoryLevel
   * @param {String} relativePath
   * @param {String} toDir
   * @param {String} fromDir
   * @return {String} resolvedPath
   */
  function adjustDirectoryLevel(relativePath, toDir, fromDir) {
    // fix ../path/to/img.jpg to path/to/img.jpg
    var resolvedPath = relativePath.replace(/^\.\//, '');

    if (toDir === fromDir) {
      // both toDir and fromDir are same base.
    }
    else if (fromDir.indexOf(toDir) === 0) {
      // fromDir is shallow than toDir
      path.relative(fromDir, toDir).split('/').forEach(function() {
        resolvedPath = resolvedPath.replace(/^\.\.\//, '');
      });
    }
    else if (toDir.indexOf(fromDir) === 0 ) {
      // toDir is deep than fromDir
      path.relative(fromDir, toDir).split('/').forEach(function() {
        resolvedPath = '../'+resolvedPath;
      });
    }
    return resolvedPath;
  }

};
<commit_msg>fix: symlinks were resolved, which caused problems when used with "npm link"<commit_after>/*
 * grunt-data-uri
 * http://github.com/ahomu/grunt-data-uri
 * http://aho.mu
 *
 * Copyright (c) 2012 ahomu
 * Licensed under the MIT license.
 */
module.exports = function(grunt) {

  'use strict';

  var fs       = require('fs'),
      path     = require('path'),
      datauri  = require('datauri');

  var RE_CSS_URLFUNC = /(?:url\(["']?)(.*?)(?:["']?\))/,
      util = grunt.util,
      gruntfileDir = path.resolve('./'),
      expandFiles;

  if (grunt.file.expandFiles) {
    expandFiles = grunt.file.expandFiles;
  } else {
    expandFiles = function(files) {
      return grunt.file.expand({filter: 'isFile'}, files);
    };
  }

  grunt.registerMultiTask('dataUri', 'Convert your css file image path!!', function() {

    var options  = this.options(),
        srcFiles = expandFiles(this.data.src),
        destDir  = path.resolve(this.data.dest),
        haystack = [];

    expandFiles(options.target).forEach(function(imgPath) {
      haystack.push(path.resolve(imgPath));
    });

    srcFiles.forEach(function(src) {
      var content  = grunt.file.read(src),
          matches  = content.match(new RegExp(RE_CSS_URLFUNC.source, 'g')),
          outputTo = destDir+'/'+path.basename(src),
          baseDir,
          uris;

      // Detect baseDir for using traversal image files
      baseDir = options.baseDir ? path.resolve(options.baseDir)    // specified base dir
                                : path.resolve(path.dirname(src)); // detected from src

      // Not found image path
      if (!matches) {
        grunt.log.subhead('SRC: file uri not found on '+src);
        grunt.file.write(outputTo, content);
        grunt.log.ok('Skipped');
        grunt.log.ok('=> ' + outputTo);
        return;
      }

      // List uniq image URIs
      uris = util._.uniq(matches.map(function(m) {
        return m.match(RE_CSS_URLFUNC)[1];
      }));

      // Exclude external http resource
      uris = uris.filter(function(u) {
        return !u.match('(data:|http)');
      });

      grunt.log.subhead('SRC: '+uris.length+' file uri found on '+src);

      // Process urls
      uris.forEach(function(uri) {
        var src, replacement, needle, fixedUri;

        // fixed current dir when specified uri is like root
        fixedUri = (uri.indexOf('/') === 0 ? '.' + uri : uri).split('?')[0].split('#')[0];

        // Resolve image realpath
        needle = path.join(baseDir, fixedUri);

        // Assume file existing cause found from haystack
        if (haystack.indexOf(needle) !== -1) {

          // check if file exceeds the max bytes
          var fileSize = getFileSize(needle);
          if (options.maxBytes && fileSize > options.maxBytes) {
            // file is over the max size
            grunt.log.ok('Skipping (size ' + fileSize + ' > ' + options.maxBytes +'): ' + uri);
            return;
          } else {
            // Encoding to Data uri
            replacement = datauri(needle);

            grunt.log.ok('Encode: '+needle);
          }
        } else {
          if (options.fixDirLevel) {
            // Diff of directory level
            replacement = adjustDirectoryLevel(fixedUri, destDir, baseDir);
            grunt.log.ok('Adjust: '+ uri + ' -> ' + replacement);
          } else {
            replacement = uri;
            grunt.log.ok('Ignore: '+ uri);
          }
        }

        var escapedUri = uri.replace(/\?/g, '\\$&');
        content = content.replace(new RegExp(escapedUri, 'g'), replacement);
      });

      // Revert base to gruntjs executing current dir
      grunt.file.setBase(gruntfileDir);
      grunt.file.write(outputTo, content);
      grunt.log.ok('=> ' + outputTo);
    });
  });

  /**
   *
   * @param fullPath
   * @param options
   * @return {boolean} the file size, or undefined if not found
   */
  function getFileSize(fullPath) {

    if (!fs.existsSync(fullPath)) {
      return false;
    }

    var stats = fs.statSync(fullPath);
    if (!stats.isFile()) {
      return false;
    }
    return stats.size;
  }

  /**
   * @method adjustDirectoryLevel
   * @param {String} relativePath
   * @param {String} toDir
   * @param {String} fromDir
   * @return {String} resolvedPath
   */
  function adjustDirectoryLevel(relativePath, toDir, fromDir) {
    // fix ../path/to/img.jpg to path/to/img.jpg
    var resolvedPath = relativePath.replace(/^\.\//, '');

    if (toDir === fromDir) {
      // both toDir and fromDir are same base.
    }
    else if (fromDir.indexOf(toDir) === 0) {
      // fromDir is shallow than toDir
      path.relative(fromDir, toDir).split('/').forEach(function() {
        resolvedPath = resolvedPath.replace(/^\.\.\//, '');
      });
    }
    else if (toDir.indexOf(fromDir) === 0 ) {
      // toDir is deep than fromDir
      path.relative(fromDir, toDir).split('/').forEach(function() {
        resolvedPath = '../'+resolvedPath;
      });
    }
    return resolvedPath;
  }

};
<|endoftext|>


<commit_before>import { addTag } from '../actions/tags'
import { getTagId, hasTag } from '../selectors/tags'

let nextColumnId = 3

export const addColumn = () => {
  return {
    payload: nextColumnId++,
    type: 'ADD_COMPANIES'
  }
}

export const addCompanyTag = (companyId, categoryId, value) => {
  return (dispatch, getState) => {
    const state = getState()
    if (!hasTag(state, categoryId, value)) {
      dispatch(addTag(categoryId, value))
    }
    const tagId = getTagId(categoryId, value)
    dispatch({
      companyId,
      tagId,
      type: 'ADD_COMPANY_TAG'
    })
  }
}

export const removeColumn = id => {
  return {
    payload: id,
    type: 'REMOVE_COMPANIES'
  }
}
<commit_msg>Fix tags import<commit_after>import { addTag } from './tags'
import { getTagId, hasTag } from '../selectors/tags'

let nextColumnId = 3

export const addColumn = () => {
  return {
    payload: nextColumnId++,
    type: 'ADD_COMPANIES'
  }
}

export const addCompanyTag = (companyId, categoryId, value) => {
  return (dispatch, getState) => {
    const state = getState()
    if (!hasTag(state, categoryId, value)) {
      dispatch(addTag(categoryId, value))
    }
    const tagId = getTagId(categoryId, value)
    dispatch({
      companyId,
      tagId,
      type: 'ADD_COMPANY_TAG'
    })
  }
}

export const removeColumn = id => {
  return {
    payload: id,
    type: 'REMOVE_COMPANIES'
  }
}
<|endoftext|>