<commit_before>/*
    ***** BEGIN LICENSE BLOCK *****

    Copyright © 2009 Center for History and New Media
                     George Mason University, Fairfax, Virginia, USA
                     http://zotero.org

    This file is part of Zotero.

    Zotero is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Zotero is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with Zotero.  If not, see <http://www.gnu.org/licenses/>.

    ***** END LICENSE BLOCK *****
*/

Zotero.MIMETypeHandler = new function () {
	var _typeHandlers, _ignoreContentDispositionTypes, _observers;

	/**
	 * Registers URIContentListener to handle MIME types
	 */
	this.init = function() {
		Zotero.debug("Registering URIContentListener");
		// register our nsIURIContentListener and nsIObserver
		Components.classes["@mozilla.org/uriloader;1"].
			getService(Components.interfaces.nsIURILoader).
			registerContentListener(_URIContentListener);
		Components.classes["@mozilla.org/observer-service;1"].
			getService(Components.interfaces.nsIObserverService).
			addObserver(_Observer, "http-on-examine-response", false);
		this.initializeHandlers();
		Zotero.addShutdownListener(function() {
			Components.classes["@mozilla.org/observer-service;1"].
				getService(Components.interfaces.nsIObserverService).
				removeObserver(_Observer, "http-on-examine-response", false);
		});
	}

	/**
	 * Initializes handlers for MIME types
	 */
	this.initializeHandlers = function() {
		_typeHandlers = {};
		_ignoreContentDispositionTypes = [];
		_observers = [];

		if(Zotero.Prefs.get("parseEndNoteMIMETypes")) {
			this.addHandler("application/x-endnote-refer", _importHandler, true);
			this.addHandler("application/x-research-info-systems", _importHandler, true);
			// Add ISI
			this.addHandler("application/x-inst-for-scientific-info", _importHandler, true);
			//
			// And some non-standard ones
			//
			this.addHandler("text/x-research-info-systems", _importHandler, true);
			// Nature uses this one
			this.addHandler("text/application/x-research-info-systems", _importHandler, true);
			// Cell uses this one
			this.addHandler("text/ris", _importHandler, true);
			// Not even trying
			this.addHandler("ris", _importHandler, true);
		}
		this.addHandler("application/vnd.citationstyles.style+xml", function(a1, a2) { Zotero.Styles.install(a1, a2) });
		this.addHandler("text/x-csl", function(a1, a2) { Zotero.Styles.install(a1, a2) }); // deprecated
		this.addHandler("application/x-zotero-schema", Zotero.Schema.importSchema);
		this.addHandler("application/x-zotero-settings", Zotero.Prefs.importSettings);
	}

	/**
	 * Adds a handler to handle a specific MIME type
	 * @param {String} type MIME type to handle
	 * @param {Function} fn Function to call to handle type - fn(string, uri)
	 * @param {Boolean} ignoreContentDisposition If true, ignores the Content-Disposition header,
	 *	which is often used to force a file to download rather than let it be handled by the web
	 *	browser
	 */
	this.addHandler = function(type, fn, ignoreContentDisposition) {
		_typeHandlers[type] = fn;
		_ignoreContentDispositionTypes.push(type);
	}

	/**
	 * Adds an observer to inspect and possibly modify page headers
	 */
	this.addObserver = function(fn) {
		_observers.push(fn);
	}

	/**
	 * Handles Refer/RIS/ISI MIME types
	 * @param {String} string The Refer/RIS/ISI formatted records
	 * @param {String} uri The URI from which the Refer/RIS/ISI formatted records were downloaded
	 */
	function _importHandler(string, uri, contentType, channel) {
		var win = channel.notificationCallbacks.getInterface(Components.interfaces.nsIDOMWindow).top;
		if(!win) throw "Attempt to import from a channel without an attached document refused";

		var hostPort = channel.URI.hostPort.replace(";", "_", "g");

		var allowedSitesString = Zotero.Prefs.get("ingester.allowedSites");
		allowedSites = allowedSitesString.split(";");

		if(allowedSites.indexOf(hostPort) === -1) {
			var title = Zotero.getString("ingester.importReferRISDialog.title");
			var text = Zotero.getString("ingester.importReferRISDialog.text", channel.URI.hostPort)+"\n\n";
			var checkMsg = Zotero.getString("ingester.importReferRISDialog.checkMsg");
			var checkValue = {"value":false};

			// make tab-modal dialog (https://developer.mozilla.org/en/Using_tab-modal_prompts)
			var prompt = Components.classes["@mozilla.org/prompter;1"]
				 .getService(Components.interfaces.nsIPromptFactory)
				 .getPrompt(win, Components.interfaces.nsIPrompt);

			var bag = prompt.QueryInterface(Components.interfaces.nsIWritablePropertyBag2);
			bag.setPropertyAsBool("allowTabModal", true);

			var continueDownload = prompt.confirmCheck(title, text, checkMsg, checkValue);
			if(!continueDownload) return;
			if(checkValue.value) {
				// add to allowed sites if desired
				Zotero.Prefs.set("ingester.allowedSites", allowedSitesString+";"+hostPort);
			}
		}

		var frontWindow = Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
			getService(Components.interfaces.nsIWindowWatcher).activeWindow;

		// attempt to import through Zotero.Translate
		var translation = new Zotero.Translate("import");
		translation.setLocation(uri);
		translation.setString(string);

		// attempt to retrieve translators
		var translators = translation.getTranslators();
		if(!translators.length) {
			// we lied. we can't really translate this file.
			throw "No translator found for handled RIS, Refer or ISI file"
		}

		// translate using first available
		translation.setTranslator(translators[0]);
		frontWindow.Zotero_Browser.performTranslation(translation);
	}

	/**
	 * Called to observe a page load
	 */
	var _Observer = new function() {
		this.observe = function(channel) {
			if(Zotero.isConnector) return;

			channel.QueryInterface(Components.interfaces.nsIRequest);
			if(channel.loadFlags & Components.interfaces.nsIHttpChannel.LOAD_DOCUMENT_URI) {
				channel.QueryInterface(Components.interfaces.nsIHttpChannel);
				try {
					// remove content-disposition headers for EndNote, etc.
					var contentType = channel.getResponseHeader("Content-Type").toLowerCase();
					for each(var handledType in _ignoreContentDispositionTypes) {
						if(contentType.length < handledType.length) {
							break;
						} else {
							if(contentType.substr(0, handledType.length) == handledType) {
								channel.setResponseHeader("Content-Disposition", "", false);
								break;
							}
						}
					}
				} catch(e) {}

				for each(var observer in _observers) {
					observer(channel);
				}
			}
		}
	}

	var _URIContentListener = new function() {
		/**
		 * Standard QI definiton
		 */
		this.QueryInterface = function(iid) {
			if  (iid.equals(Components.interfaces.nsISupports)
			   || iid.equals(Components.interfaces.nsISupportsWeakReference)
			   || iid.equals(Components.interfaces.nsIURIContentListener)) {
				return this;
			}
			throw Components.results.NS_ERROR_NO_INTERFACE;
		}

		/**
		 * Called to see if we can handle a content type
		 */
		this.canHandleContent = this.isPreferred = function(contentType, isContentPreferred, desiredContentType) {
			if(Zotero.isConnector) return false;
			return !!_typeHandlers[contentType.toLowerCase()];
		}

		/**
		 * Called to begin handling a content type
		 */
		this.doContent = function(contentType, isContentPreferred, request, contentHandler) {
			Zotero.debug("MIMETypeHandler: handling "+contentType+" from " + request.name);
			contentHandler.value = new _StreamListener(request, contentType.toLowerCase());
			return false;
		}

		/**
		 * Called so that we could stop a load before it happened if we wanted to
		 */
		this.onStartURIOpen = function(URI) {
			return true;
		}
	}

	/**
	 * @class Implements nsIStreamListener and nsIRequestObserver interfaces to download MIME types
	 * 	we've registered ourself as the handler for
	 * @param {nsIRequest} request The request to handle
	 * @param {String} contenType The content type being handled
	 */
	var _StreamListener = function(request, contentType) {
		this._request = request;
		this._contentType = contentType
		this._storageStream = null;
		this._outputStream = null;
		this._binaryInputStream = null;
	}

	/**
	 * Standard QI definiton
	 */
	_StreamListener.prototype.QueryInterface = function(iid) {
		if (iid.equals(Components.interfaces.nsISupports)
		   || iid.equals(Components.interfaces.nsIRequestObserver)
		   || iid.equals(Components.interfaces.nsIStreamListener)) {
			return this;
		}
		throw Components.results.NS_ERROR_NO_INTERFACE;
	}

	/**
	 * Called when the request is started; we ignore this
	 */
	_StreamListener.prototype.onStartRequest = function(channel, context) {}

	/**
	 * Called when there's data available; we collect this data and keep it until the request is
	 * done
	 */
	_StreamListener.prototype.onDataAvailable = function(request, context, inputStream, offset, count) {
		Zotero.debug(count + " bytes available");

		if (!this._storageStream) {
			this._storageStream = Components.classes["@mozilla.org/storagestream;1"].
					createInstance(Components.interfaces.nsIStorageStream);
			this._storageStream.init(4096, 4294967295, null); // PR_UINT32_MAX
			this._outputStream = this._storageStream.getOutputStream(0);

			this._binaryInputStream = Components.classes["@mozilla.org/binaryinputstream;1"].
					createInstance(Components.interfaces.nsIBinaryInputStream);
			this._binaryInputStream.setInputStream(inputStream);
		}

		var bytes = this._binaryInputStream.readBytes(count);
		this._outputStream.write(bytes, count);
	}

	/**
	 * Called when the request is done
	 */
	_StreamListener.prototype.onStopRequest = function(channel, context, status) {
		Zotero.debug("charset is " + channel.contentCharset);

		var inputStream = this._storageStream.newInputStream(0);
		var charset = channel.contentCharset ? channel.contentCharset : "UTF-8";
		const replacementChar = Components.interfaces.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER;
		var convStream = Components.classes["@mozilla.org/intl/converter-input-stream;1"]
					.createInstance(Components.interfaces.nsIConverterInputStream);
		convStream.init(inputStream, charset, 1024, replacementChar);
		var readString = "";
		var str = {};
		while (convStream.readString(4096, str) != 0) {
			readString += str.value;
		}
		convStream.close();
		inputStream.close();

		try {
			_typeHandlers[this._contentType](readString, (this._request.name ? this._request.name : null),
				this._contentType, channel);
		} catch(e) {
			// if there was an error, handle using nsIExternalHelperAppService
			var externalHelperAppService = Components.classes["@mozilla.org/uriloader/external-helper-app-service;1"].
				getService(Components.interfaces.nsIExternalHelperAppService);
			var frontWindow = Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
				getService(Components.interfaces.nsIWindowWatcher).activeWindow;

			var inputStream = this._storageStream.newInputStream(0);
			var streamListener = externalHelperAppService.doContent(this._contentType, this._request, frontWindow, null);
			if (streamListener) {
				streamListener.onStartRequest(channel, context);
				streamListener.onDataAvailable(this._request, context, inputStream, 0, this._storageStream.length);
				streamListener.onStopRequest(channel, context, status);
			}
			this._storageStream.close();

			// then throw our error
			throw e;
		}

		this._storageStream.close();
	}
}
<commit_msg>Register as handler for BibTeX mime typese<commit_after>/*
    ***** BEGIN LICENSE BLOCK *****

    Copyright © 2009 Center for History and New Media
                     George Mason University, Fairfax, Virginia, USA
                     http://zotero.org

    This file is part of Zotero.

    Zotero is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Zotero is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with Zotero.  If not, see <http://www.gnu.org/licenses/>.

    ***** END LICENSE BLOCK *****
*/

Zotero.MIMETypeHandler = new function () {
	var _typeHandlers, _ignoreContentDispositionTypes, _observers;

	/**
	 * Registers URIContentListener to handle MIME types
	 */
	this.init = function() {
		Zotero.debug("Registering URIContentListener");
		// register our nsIURIContentListener and nsIObserver
		Components.classes["@mozilla.org/uriloader;1"].
			getService(Components.interfaces.nsIURILoader).
			registerContentListener(_URIContentListener);
		Components.classes["@mozilla.org/observer-service;1"].
			getService(Components.interfaces.nsIObserverService).
			addObserver(_Observer, "http-on-examine-response", false);
		this.initializeHandlers();
		Zotero.addShutdownListener(function() {
			Components.classes["@mozilla.org/observer-service;1"].
				getService(Components.interfaces.nsIObserverService).
				removeObserver(_Observer, "http-on-examine-response", false);
		});
	}

	/**
	 * Initializes handlers for MIME types
	 */
	this.initializeHandlers = function() {
		_typeHandlers = {};
		_ignoreContentDispositionTypes = [];
		_observers = [];

		if(Zotero.Prefs.get("parseEndNoteMIMETypes")) {
			this.addHandler("application/x-endnote-refer", _importHandler, true);
			this.addHandler("application/x-research-info-systems", _importHandler, true);
			this.addHandler("application/x-inst-for-scientific-info", _importHandler, true);

			this.addHandler("text/x-bibtex", _importHandler, true);
			this.addHandler("application/x-bibtex", _importHandler, true);

			//
			// And some non-standard ones
			//
			this.addHandler("text/x-research-info-systems", _importHandler, true);
			// Nature uses this one
			this.addHandler("text/application/x-research-info-systems", _importHandler, true);
			// Cell uses this one
			this.addHandler("text/ris", _importHandler, true);
			// Not even trying
			this.addHandler("ris", _importHandler, true);
		}
		this.addHandler("application/vnd.citationstyles.style+xml", function(a1, a2) { Zotero.Styles.install(a1, a2) });
		this.addHandler("text/x-csl", function(a1, a2) { Zotero.Styles.install(a1, a2) }); // deprecated
		this.addHandler("application/x-zotero-schema", Zotero.Schema.importSchema);
		this.addHandler("application/x-zotero-settings", Zotero.Prefs.importSettings);
	}

	/**
	 * Adds a handler to handle a specific MIME type
	 * @param {String} type MIME type to handle
	 * @param {Function} fn Function to call to handle type - fn(string, uri)
	 * @param {Boolean} ignoreContentDisposition If true, ignores the Content-Disposition header,
	 *	which is often used to force a file to download rather than let it be handled by the web
	 *	browser
	 */
	this.addHandler = function(type, fn, ignoreContentDisposition) {
		_typeHandlers[type] = fn;
		_ignoreContentDispositionTypes.push(type);
	}

	/**
	 * Adds an observer to inspect and possibly modify page headers
	 */
	this.addObserver = function(fn) {
		_observers.push(fn);
	}

	/**
	 * Handles Refer/RIS/ISI MIME types
	 * @param {String} string The Refer/RIS/ISI formatted records
	 * @param {String} uri The URI from which the Refer/RIS/ISI formatted records were downloaded
	 */
	function _importHandler(string, uri, contentType, channel) {
		var win = channel.notificationCallbacks.getInterface(Components.interfaces.nsIDOMWindow).top;
		if(!win) throw "Attempt to import from a channel without an attached document refused";

		var hostPort = channel.URI.hostPort.replace(";", "_", "g");

		var allowedSitesString = Zotero.Prefs.get("ingester.allowedSites");
		allowedSites = allowedSitesString.split(";");

		if(allowedSites.indexOf(hostPort) === -1) {
			var title = Zotero.getString("ingester.importReferRISDialog.title");
			var text = Zotero.getString("ingester.importReferRISDialog.text", channel.URI.hostPort)+"\n\n";
			var checkMsg = Zotero.getString("ingester.importReferRISDialog.checkMsg");
			var checkValue = {"value":false};

			// make tab-modal dialog (https://developer.mozilla.org/en/Using_tab-modal_prompts)
			var prompt = Components.classes["@mozilla.org/prompter;1"]
				 .getService(Components.interfaces.nsIPromptFactory)
				 .getPrompt(win, Components.interfaces.nsIPrompt);

			var bag = prompt.QueryInterface(Components.interfaces.nsIWritablePropertyBag2);
			bag.setPropertyAsBool("allowTabModal", true);

			var continueDownload = prompt.confirmCheck(title, text, checkMsg, checkValue);
			if(!continueDownload) return;
			if(checkValue.value) {
				// add to allowed sites if desired
				Zotero.Prefs.set("ingester.allowedSites", allowedSitesString+";"+hostPort);
			}
		}

		var frontWindow = Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
			getService(Components.interfaces.nsIWindowWatcher).activeWindow;

		// attempt to import through Zotero.Translate
		var translation = new Zotero.Translate("import");
		translation.setLocation(uri);
		translation.setString(string);

		// attempt to retrieve translators
		var translators = translation.getTranslators();
		if(!translators.length) {
			// we lied. we can't really translate this file.
			throw "No translator found for handled RIS, Refer or ISI file"
		}

		// translate using first available
		translation.setTranslator(translators[0]);
		frontWindow.Zotero_Browser.performTranslation(translation);
	}

	/**
	 * Called to observe a page load
	 */
	var _Observer = new function() {
		this.observe = function(channel) {
			if(Zotero.isConnector) return;

			channel.QueryInterface(Components.interfaces.nsIRequest);
			if(channel.loadFlags & Components.interfaces.nsIHttpChannel.LOAD_DOCUMENT_URI) {
				channel.QueryInterface(Components.interfaces.nsIHttpChannel);
				try {
					// remove content-disposition headers for EndNote, etc.
					var contentType = channel.getResponseHeader("Content-Type").toLowerCase();
					for each(var handledType in _ignoreContentDispositionTypes) {
						if(contentType.length < handledType.length) {
							break;
						} else {
							if(contentType.substr(0, handledType.length) == handledType) {
								channel.setResponseHeader("Content-Disposition", "", false);
								break;
							}
						}
					}
				} catch(e) {}

				for each(var observer in _observers) {
					observer(channel);
				}
			}
		}
	}

	var _URIContentListener = new function() {
		/**
		 * Standard QI definiton
		 */
		this.QueryInterface = function(iid) {
			if  (iid.equals(Components.interfaces.nsISupports)
			   || iid.equals(Components.interfaces.nsISupportsWeakReference)
			   || iid.equals(Components.interfaces.nsIURIContentListener)) {
				return this;
			}
			throw Components.results.NS_ERROR_NO_INTERFACE;
		}

		/**
		 * Called to see if we can handle a content type
		 */
		this.canHandleContent = this.isPreferred = function(contentType, isContentPreferred, desiredContentType) {
			if(Zotero.isConnector) return false;
			return !!_typeHandlers[contentType.toLowerCase()];
		}

		/**
		 * Called to begin handling a content type
		 */
		this.doContent = function(contentType, isContentPreferred, request, contentHandler) {
			Zotero.debug("MIMETypeHandler: handling "+contentType+" from " + request.name);
			contentHandler.value = new _StreamListener(request, contentType.toLowerCase());
			return false;
		}

		/**
		 * Called so that we could stop a load before it happened if we wanted to
		 */
		this.onStartURIOpen = function(URI) {
			return true;
		}
	}

	/**
	 * @class Implements nsIStreamListener and nsIRequestObserver interfaces to download MIME types
	 * 	we've registered ourself as the handler for
	 * @param {nsIRequest} request The request to handle
	 * @param {String} contenType The content type being handled
	 */
	var _StreamListener = function(request, contentType) {
		this._request = request;
		this._contentType = contentType
		this._storageStream = null;
		this._outputStream = null;
		this._binaryInputStream = null;
	}

	/**
	 * Standard QI definiton
	 */
	_StreamListener.prototype.QueryInterface = function(iid) {
		if (iid.equals(Components.interfaces.nsISupports)
		   || iid.equals(Components.interfaces.nsIRequestObserver)
		   || iid.equals(Components.interfaces.nsIStreamListener)) {
			return this;
		}
		throw Components.results.NS_ERROR_NO_INTERFACE;
	}

	/**
	 * Called when the request is started; we ignore this
	 */
	_StreamListener.prototype.onStartRequest = function(channel, context) {}

	/**
	 * Called when there's data available; we collect this data and keep it until the request is
	 * done
	 */
	_StreamListener.prototype.onDataAvailable = function(request, context, inputStream, offset, count) {
		Zotero.debug(count + " bytes available");

		if (!this._storageStream) {
			this._storageStream = Components.classes["@mozilla.org/storagestream;1"].
					createInstance(Components.interfaces.nsIStorageStream);
			this._storageStream.init(4096, 4294967295, null); // PR_UINT32_MAX
			this._outputStream = this._storageStream.getOutputStream(0);

			this._binaryInputStream = Components.classes["@mozilla.org/binaryinputstream;1"].
					createInstance(Components.interfaces.nsIBinaryInputStream);
			this._binaryInputStream.setInputStream(inputStream);
		}

		var bytes = this._binaryInputStream.readBytes(count);
		this._outputStream.write(bytes, count);
	}

	/**
	 * Called when the request is done
	 */
	_StreamListener.prototype.onStopRequest = function(channel, context, status) {
		Zotero.debug("charset is " + channel.contentCharset);

		var inputStream = this._storageStream.newInputStream(0);
		var charset = channel.contentCharset ? channel.contentCharset : "UTF-8";
		const replacementChar = Components.interfaces.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER;
		var convStream = Components.classes["@mozilla.org/intl/converter-input-stream;1"]
					.createInstance(Components.interfaces.nsIConverterInputStream);
		convStream.init(inputStream, charset, 1024, replacementChar);
		var readString = "";
		var str = {};
		while (convStream.readString(4096, str) != 0) {
			readString += str.value;
		}
		convStream.close();
		inputStream.close();

		try {
			_typeHandlers[this._contentType](readString, (this._request.name ? this._request.name : null),
				this._contentType, channel);
		} catch(e) {
			// if there was an error, handle using nsIExternalHelperAppService
			var externalHelperAppService = Components.classes["@mozilla.org/uriloader/external-helper-app-service;1"].
				getService(Components.interfaces.nsIExternalHelperAppService);
			var frontWindow = Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
				getService(Components.interfaces.nsIWindowWatcher).activeWindow;

			var inputStream = this._storageStream.newInputStream(0);
			var streamListener = externalHelperAppService.doContent(this._contentType, this._request, frontWindow, null);
			if (streamListener) {
				streamListener.onStartRequest(channel, context);
				streamListener.onDataAvailable(this._request, context, inputStream, 0, this._storageStream.length);
				streamListener.onStopRequest(channel, context, status);
			}
			this._storageStream.close();

			// then throw our error
			throw e;
		}

		this._storageStream.close();
	}
}
<|endoftext|>


<commit_before>//bundleStructure.js
//for every policy check fileName per Apigee recommendations
//for every policy check if fileName matches policyName
//plugin methods and variables

var bundle,
  root,
  plugin = {
    ruleId: "BN001",
    name: "Bundle Structure",
    message:
      "Bundle Structure: Check bundle structure, bundles have a specific structure, extra folder or files may be problematic.",
    fatal: false,
    severity: 2, //error
    nodeType: "Bundle",
    enabled: true
  },
  fs = require("fs"),
  hadWarnErr = false;

function eq(lh, rh) {
  return lh === rh;
}

function contains(a, obj, f) {
  if (!a || !a.length) {
    return false;
  }
  f = f || eq;
  for (var i = 0; i < a.length; i++) {
    if (f(a[i], obj)) {
      if (!a[i]) {
        return true;
      }
      return a[i];
    }
  }
  return false;
}

function mark(source) {
  var result = {
    ruleId: plugin.ruleId,
    severity: plugin.severity,
    nodeType: plugin.nodeType,
    message: source
  };
  bundle.addMessage(result);
  hadWarnErr = true;
}

function checkNode(node, curRoot) {
  //node has two arrays files and folders
  //check if files is correct
  var files,
    compareNodeToFolder = function(n, f) {
      return n.name === f;
    };

  if (!curRoot) {
    curRoot = root;
  }

  try {
    files = fs.readdirSync(curRoot);
  } catch (e) {
    mark({ curRoot, error: e });
    return;
  }

  if (node.folders && node.folders.length) {
    node.folders.forEach(function(folder) {
      if (folder.required && !contains(files, folder.name)) {
        mark('Required folder "' + folder.name + '" not found.');
      }
    });
  }

  //walk the folders in files
  files.forEach(function(file) {
    if (fs.statSync(curRoot + "/" + file).isDirectory()) {
      //is there a child node that matches? if not error if so recurse
      var foundNode;
      if (!foundNode && node.folders && node.folders.any === true) {
        //create a node that corresponds to the current node with the correct name
        foundNode = JSON.parse(JSON.stringify(node));
        foundNode.name = file;
      } else {
        foundNode = contains(node.folders, file, compareNodeToFolder);
      }
      if (foundNode) {
        checkNode(foundNode, curRoot + "/" + foundNode.name);
      } else {
        //we may have an unknown folder
        var allowedFolders = [];
        if (node.folders) {
          allowedFolders = JSON.parse(JSON.stringify(node.folders));
          allowedFolders.forEach(function(f) {
            delete f.files;
            delete f.folders;
          });
        }

        mark(
          'Unexpected folder found "' +
            file +
            '". Current root:"' +
            curRoot.substring(curRoot.indexOf("/apiproxy")) +
            "/" +
            file +
            '". Valid folders: ' +
            JSON.stringify(allowedFolders) +
            "."
        );
      }
    } else if (file !== ".DS_Store") {
      //does the file extension match those valid for this node
      var extension = file.split(".");
      if (extension.length > 1) {
        extension = extension[extension.length - 1];
      } else {
        extension = "";
      }
      if (
        node.files &&
        node.files.extensions &&
        !contains(node.files.extensions, extension)
      ) {
        mark(
          'Unexpected extension found with file "' +
            curRoot +
            "/" +
            file +
            '". Valid extensions: ' +
            JSON.stringify(node.files.extensions)
        );
      }
    }
  });
}

var bundleStructure = {
    name: "apiproxy",
    files: { extensions: ["xml", "md"], maxCount: 1 },
    folders: [
	  { name: "manifests", required: false, files: { extensions: ["xml"] } },
      { name: "policies", required: false, files: { extensions: ["xml"] } },
      {
        name: "stepdefinitions",
        required: false,
        files: { extensions: ["xml"] }
      },
      {
        name: "proxies",
        required: true,
        files: { extensions: ["xml", "flowfrag"] }
      },
      { name: "targets", required: false, files: { extensions: ["xml"] } },
      {
        name: "resources",
        required: false,
        folders: [
          {
            name: "jsc",
            required: false,
            files: { extensions: ["js", "jsc", "json"] },
            folders: { any: true }
          },
          {
            name: "java",
            required: false,
            files: {
              extensions: ["jar", "zip", "properties", "inf"]
            },
            folders: { any: true }
          },
          {
            name: "py",
            required: false,
            files: {
              extensions: ["py", ""]
            }
          },
          {
            name: "xsl",
            required: false,
            files: {
              extensions: ["xslt", "xsl"]
            }
          },
          {
            name: "openapi",
            required: false,
            files: {
              extensions: ["json"]
            }
          },
          {
            name: "node",
            required: false,
            files: {
              extensions: [
                "js",
                "jsc",
                "json",
                "zip",
                "png",
                "jpg",
                "jpeg",
                "css",
                "ejs",
                "eot",
                "svg",
                "ttf",
                "woff",
                "html",
                "htm"
              ]
            },
            folders: { any: true }
          }
        ]
      }
    ]
  },
  onBundle = function(b, cb) {
    bundle = b;
    root = bundle.proxyRoot;
    checkNode(bundleStructure);
    if (typeof cb == "function") {
      cb(null, hadWarnErr);
    }
  };

module.exports = {
  plugin,
  onBundle
};
<commit_msg>Add hosted target support<commit_after>//bundleStructure.js
//for every policy check fileName per Apigee recommendations
//for every policy check if fileName matches policyName
//plugin methods and variables

var bundle,
  root,
  plugin = {
    ruleId: "BN001",
    name: "Bundle Structure",
    message:
      "Bundle Structure: Check bundle structure, bundles have a specific structure, extra folder or files may be problematic.",
    fatal: false,
    severity: 2, //error
    nodeType: "Bundle",
    enabled: true
  },
  fs = require("fs"),
  hadWarnErr = false;

function eq(lh, rh) {
  return lh === rh;
}

function contains(a, obj, f) {
  if (!a || !a.length) {
    return false;
  }
  f = f || eq;
  for (var i = 0; i < a.length; i++) {
    if (f(a[i], obj)) {
      if (!a[i]) {
        return true;
      }
      return a[i];
    }
  }
  return false;
}

function mark(source) {
  var result = {
    ruleId: plugin.ruleId,
    severity: plugin.severity,
    nodeType: plugin.nodeType,
    message: source
  };
  bundle.addMessage(result);
  hadWarnErr = true;
}

function checkNode(node, curRoot) {
  //node has two arrays files and folders
  //check if files is correct
  var files,
    compareNodeToFolder = function(n, f) {
      return n.name === f;
    };

  if (!curRoot) {
    curRoot = root;
  }

  try {
    files = fs.readdirSync(curRoot);
  } catch (e) {
    mark({ curRoot, error: e });
    return;
  }

  if (node.folders && node.folders.length) {
    node.folders.forEach(function(folder) {
      if (folder.required && !contains(files, folder.name)) {
        mark('Required folder "' + folder.name + '" not found.');
      }
    });
  }

  //walk the folders in files
  files.forEach(function(file) {
    if (fs.statSync(curRoot + "/" + file).isDirectory()) {
      //is there a child node that matches? if not error if so recurse
      var foundNode;
      if (!foundNode && node.folders && node.folders.any === true) {
        //create a node that corresponds to the current node with the correct name
        foundNode = JSON.parse(JSON.stringify(node));
        foundNode.name = file;
      } else {
        foundNode = contains(node.folders, file, compareNodeToFolder);
      }
      if (foundNode) {
        checkNode(foundNode, curRoot + "/" + foundNode.name);
      } else {
        //we may have an unknown folder
        var allowedFolders = [];
        if (node.folders) {
          allowedFolders = JSON.parse(JSON.stringify(node.folders));
          allowedFolders.forEach(function(f) {
            delete f.files;
            delete f.folders;
          });
        }

        mark(
          'Unexpected folder found "' +
            file +
            '". Current root:"' +
            curRoot.substring(curRoot.indexOf("/apiproxy")) +
            "/" +
            file +
            '". Valid folders: ' +
            JSON.stringify(allowedFolders) +
            "."
        );
      }
    } else if (file !== ".DS_Store") {
      //does the file extension match those valid for this node
      var extension = file.split(".");
      if (extension.length > 1) {
        extension = extension[extension.length - 1];
      } else {
        extension = "";
      }
      if (
        node.files &&
        node.files.extensions &&
        !contains(node.files.extensions, extension)
      ) {
        mark(
          'Unexpected extension found with file "' +
            curRoot +
            "/" +
            file +
            '". Valid extensions: ' +
            JSON.stringify(node.files.extensions)
        );
      }
    }
  });
}

var bundleStructure = {
    name: "apiproxy",
    files: { extensions: ["xml", "md"], maxCount: 1 },
    folders: [
	  { name: "manifests", required: false, files: { extensions: ["xml"] } },
      { name: "policies", required: false, files: { extensions: ["xml"] } },
      {
        name: "stepdefinitions",
        required: false,
        files: { extensions: ["xml"] }
      },
      {
        name: "proxies",
        required: true,
        files: { extensions: ["xml", "flowfrag"] }
      },
      { name: "targets", required: false, files: { extensions: ["xml"] } },
      {
        name: "resources",
        required: false,
        folders: [
          {
            name: "jsc",
            required: false,
            files: { extensions: ["js", "jsc", "json"] },
            folders: { any: true }
          },
          {
            name: "java",
            required: false,
            files: {
              extensions: ["jar", "zip", "properties", "inf"]
            },
            folders: { any: true }
          },
          {
            name: "py",
            required: false,
            files: {
              extensions: ["py", ""]
            }
          },
          {
            name: "xsl",
            required: false,
            files: {
              extensions: ["xslt", "xsl"]
            }
          },
          {
            name: "openapi",
            required: false,
            files: {
              extensions: ["json"]
            }
          },
          {
            name: "node",
            required: false,
            files: {
              extensions: [
                "js",
                "jsc",
                "json",
                "zip",
                "png",
                "jpg",
                "jpeg",
                "css",
                "ejs",
                "eot",
                "svg",
                "ttf",
                "woff",
                "html",
                "htm"
              ]
            },
            folders: { any: true }
          },
          {
            name: "hosted",
            required: false,
            files: {
              extensions: ["js", "json", "yaml", "ejs"]
            },
            folders: { any: true }
          }
        ]
      }
    ]
  },
  onBundle = function(b, cb) {
    bundle = b;
    root = bundle.proxyRoot;
    checkNode(bundleStructure);
    if (typeof cb == "function") {
      cb(null, hadWarnErr);
    }
  };

module.exports = {
  plugin,
  onBundle
};
<|endoftext|>


<commit_before>function APIedit (pagename, summary, editfunc, minoredit = false, finish) {
	content = "";
	revisions = "";
	if (finish === undefined) {
		finish = function(){};
	} else if (finish === false) {
		finish = function(){location.reload()};
	}
    function getPageContent() {
		$.ajax({
			type: 'GET',
			url: 'https://zh.wikipedia.org/w/index.php?title='+pagename+'&action=raw',
			success: function success(data) {
				content = data;
				console.log(data);
				console.log("getPageContent Success");
				getPageRevision();
			},
			error: function error(e) {
				content = "";
				revisions = "";
				console.log("getPageContent Error!");
				editPage();
			}
		});
	}
	function getPageRevision() {
		$.ajax({
			type: 'POST',
			url: location.protocol + mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php',
			data: {
				'action': 'query',
				'format': 'json',
				'prop': 'revisions',
				'rvprop': 'timestamp',
				'titles': pagename
			},
			success: function success(data) {
				console.log("getPageRevision Success");
				console.log(data);
				var info = data.query.pages;
				for (var key in info) {
					revisions = info[key].revisions[0].timestamp;
					break;
				}
				editPage();
			},
			error: function error(e) {
				alert("getPageRevision Error!");
			}
		});
	}
	function editPage() {
		content = editfunc(content);
		temp = {
			type: 'POST',
			url: location.protocol + mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php',
			data: {
				'action': 'edit',
				'format': 'json',
				'title': pagename,
				'summary': summary,
				'basetimestamp': revisions,
				'text': content,
				'token': mw.user.tokens.get('editToken')
			},
			success: function success(data) {
				console.log(data);
				console.log("editPage Success");
				finish();
			},
			error: function error(e) {
				alert("editPage Error!");
			}
		};
		if (minoredit) {
			temp.data.minor = "";
		}
		$.ajax(temp);
	}
	getPageContent();
}
<commit_msg>APIedit fix api url<commit_after>function APIedit (pagename, summary, editfunc, minoredit = false, finish) {
	content = "";
	revisions = "";
	if (finish === undefined) {
		finish = function(){};
	} else if (finish === false) {
		finish = function(){location.reload()};
	}
    function getPageContent() {
		$.ajax({
			type: 'GET',
			url: mw.config.get("wgServer")+mw.config.get("wgArticlePath").replace("$1", pagename)+'?action=raw',
			success: function success(data) {
				content = data;
				console.log(data);
				console.log("getPageContent Success");
				getPageRevision();
			},
			error: function error(e) {
				content = "";
				revisions = "";
				console.log("getPageContent Error!");
				editPage();
			}
		});
	}
	function getPageRevision() {
		$.ajax({
			type: 'POST',
			url: mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php',
			data: {
				'action': 'query',
				'format': 'json',
				'prop': 'revisions',
				'rvprop': 'timestamp',
				'titles': pagename
			},
			success: function success(data) {
				console.log("getPageRevision Success");
				console.log(data);
				var info = data.query.pages;
				for (var key in info) {
					revisions = info[key].revisions[0].timestamp;
					break;
				}
				editPage();
			},
			error: function error(e) {
				alert("getPageRevision Error!");
			}
		});
	}
	function editPage() {
		content = editfunc(content);
		temp = {
			type: 'POST',
			url: mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php',
			data: {
				'action': 'edit',
				'format': 'json',
				'title': pagename,
				'summary': summary,
				'basetimestamp': revisions,
				'text': content,
				'token': mw.user.tokens.get('editToken')
			},
			success: function success(data) {
				console.log(data);
				console.log("editPage Success");
				finish();
			},
			error: function error(e) {
				alert("editPage Error!");
			}
		};
		if (minoredit) {
			temp.data.minor = "";
		}
		$.ajax(temp);
	}
	getPageContent();
}
<|endoftext|>


<commit_before>/**
 * @file rule: unnecessary-whitespace-in-text
 * @author Oleg Krivtsov <oleg@webmarketingroi.com.au>
 */

module.exports = {

    name: 'unnecessary-whitespace-in-text',

    desc: 'Unnecessary usage of white-space(s) in text',

    target: 'parser',

    lint: function (getCfg, parser, reporter) {

        parser.on('text', function (data) {
            if (!getCfg()) {
                return;
            }

            var pattern = /^.+([ \t]+)$/;
            var match = data.match(pattern);
            if (match) {
                reporter.warn(
                    this.startIndex + match.length + 1,
                        '028',
                        'Unnecessary usage of a trailing white-space(s) in text'
                    );

            }
        });
    }
};
<commit_msg>Fixing: New rule - Unnecessary usage of white-space #61<commit_after>/**
 * @file rule: unnecessary-whitespace-in-text
 * @author Oleg Krivtsov <oleg@webmarketingroi.com.au>
 */

module.exports = {

    name: 'unnecessary-whitespace-in-text',

    desc: 'Unnecessary usage of white-space(s) in text',

    target: 'parser',

    lint: function (getCfg, parser, reporter) {

        parser.on('text', function (data) {
            if (!getCfg()) {
                return;
            }

            var pattern = /^.+([ \t]+)$/;
            var match = data.match(pattern);
            if (match) {
                reporter.warn(
                    this.startIndex + match.length + 1,
                        '028',
                        'Unnecessary usage of a trailing white-space(s) in text'
                    );

            }
        });
    }
};
<|endoftext|>


<commit_before>/* eslint-disable react/forbid-prop-types */
/* eslint-disable import/prefer-default-export */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React, { useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';

import { MODAL_KEYS } from '../../utilities';
import { usePageReducer } from '../../hooks';
import { getItemLayout } from '../../pages/dataTableUtilities';

import { GenericChoiceList } from '../GenericChoiceList';
import { PageInfo, DataTablePageView, PageButton } from '..';
import { DataTable, DataTableHeaderRow, DataTableRow } from '../DataTable';

import globalStyles from '../../globalStyles';

import { UIDatabase } from '../../database';
import ModalContainer from './ModalContainer';
import { buttonStrings } from '../../localization/index';

/**
 * Renders a stateful modal with a stocktake item and it's batches loaded
 * for editing.
 *
 * State:
 * Uses a reducer to manage state with `backingData` being a realm results
 * of items to display. `data` is a plain JS array of realm objects. data is
 * hydrated from the `backingData` for displaying in the interface.
 * i.e: When filtering, data is populated from filtered items of `backingData`.
 *
 * dataState is a simple map of objects corresponding to a row being displayed,
 * holding the state of a given row. Each object has the shape :
 * { isSelected, isFocused, isDisabled },
 *
 * @prop {Object} stocktakeItem The realm transaction object for this invoice.
 *
 */
export const StocktakeBatchModal = ({ stocktakeItem }) => {
  const usingReasons = useMemo(() => UIDatabase.objects('StocktakeReasons').length > 0, []);

  const initialState = {
    page: usingReasons ? 'stocktakeBatchEditModalWithReasons' : 'stocktakeBatchEditModal',
    pageObject: stocktakeItem,
  };

  const [state, dispatch, instantDebouncedDispatch] = usePageReducer(initialState);

  const {
    pageObject,
    data,
    dataState,
    sortBy,
    isAscending,
    modalKey,
    modalValue,
    keyExtractor,
    PageActions,
    columns,
    getPageInfoColumns,
  } = state;

  const onEditReason = rowKey => PageActions.openModal(MODAL_KEYS.STOCKTAKE_REASON, rowKey);
  const onCloseModal = () => dispatch(PageActions.closeModal());
  const onApplyReason = ({ item }) => dispatch(PageActions.applyReason(item));
  const onAddBatch = () => dispatch(PageActions.addStocktakeBatch());

  const toggles = useCallback(getPageInfoColumns(pageObject, dispatch, PageActions), []);

  const getAction = colKey => {
    switch (colKey) {
      case 'batch':
        return PageActions.editStocktakeBatchName;
      case 'countedTotalQuantity':
        return PageActions.editStocktakeBatchCountedQuantity;
      case 'expiryDate':
        return PageActions.editStocktakeBatchExpiryDate;
      case 'reasonTitle':
        return onEditReason;
      default:
        return null;
    }
  };

  const renderRow = useCallback(
    listItem => {
      const { item, index } = listItem;
      const rowKey = keyExtractor(item);
      return (
        <DataTableRow
          rowData={data[index]}
          rowState={dataState.get(rowKey)}
          rowKey={rowKey}
          columns={columns}
          dispatch={dispatch}
          getAction={getAction}
          rowIndex={index}
        />
      );
    },
    [data, dataState]
  );

  const renderHeader = useCallback(
    () => (
      <DataTableHeaderRow
        columns={columns}
        dispatch={instantDebouncedDispatch}
        sortAction={PageActions.sortData}
        isAscending={isAscending}
        sortBy={sortBy}
      />
    ),
    [sortBy, isAscending]
  );

  const PageButtons = () => {
    const { stocktake = {} } = stocktakeItem;
    const { isFinalised = false } = stocktake;
    return (
      <PageButton text={buttonStrings.add_batch} onPress={onAddBatch} isDisabled={isFinalised} />
    );
  };

  const {
    pageTopSectionContainer,
    pageTopLeftSectionContainer,
    pageTopRightSectionContainer,
  } = globalStyles;
  return (
    <DataTablePageView>
      <View style={pageTopSectionContainer}>
        <View style={pageTopLeftSectionContainer}>
          <PageInfo columns={toggles} />
        </View>
        <View style={pageTopRightSectionContainer}>
          <PageButtons />
        </View>
      </View>
      <DataTable
        data={data}
        extraData={dataState}
        renderRow={renderRow}
        renderHeader={renderHeader}
        keyExtractor={keyExtractor}
        getItemLayout={getItemLayout}
        columns={columns}
        windowSize={1}
        initialNumToRender={0}
      />
      <ModalContainer
        fullScreen={modalKey === MODAL_KEYS.ENFORCE_STOCKTAKE_REASON}
        isVisible={!!modalKey}
        onClose={onCloseModal}
      >
        <GenericChoiceList
          data={UIDatabase.objects('StocktakeReasons')}
          highlightValue={(modalValue && modalValue.reasonTitle) || ''}
          keyToDisplay="title"
          onPress={onApplyReason}
        />
      </ModalContainer>
    </DataTablePageView>
  );
};

StocktakeBatchModal.propTypes = {
  stocktakeItem: PropTypes.object.isRequired,
};

export default StocktakeBatchModal;
<commit_msg>Add further update to StocktakeBatchModal pagebutton<commit_after>/* eslint-disable react/forbid-prop-types */
/* eslint-disable import/prefer-default-export */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React, { useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';

import { MODAL_KEYS } from '../../utilities';
import { usePageReducer } from '../../hooks';
import { getItemLayout } from '../../pages/dataTableUtilities';

import { GenericChoiceList } from '../GenericChoiceList';
import { PageInfo, DataTablePageView, PageButton } from '..';
import { DataTable, DataTableHeaderRow, DataTableRow } from '../DataTable';

import globalStyles from '../../globalStyles';

import { UIDatabase } from '../../database';
import ModalContainer from './ModalContainer';
import { buttonStrings } from '../../localization/index';

/**
 * Renders a stateful modal with a stocktake item and it's batches loaded
 * for editing.
 *
 * State:
 * Uses a reducer to manage state with `backingData` being a realm results
 * of items to display. `data` is a plain JS array of realm objects. data is
 * hydrated from the `backingData` for displaying in the interface.
 * i.e: When filtering, data is populated from filtered items of `backingData`.
 *
 * dataState is a simple map of objects corresponding to a row being displayed,
 * holding the state of a given row. Each object has the shape :
 * { isSelected, isFocused, isDisabled },
 *
 * @prop {Object} stocktakeItem The realm transaction object for this invoice.
 *
 */
export const StocktakeBatchModal = ({ stocktakeItem }) => {
  const usingReasons = useMemo(() => UIDatabase.objects('StocktakeReasons').length > 0, []);

  const initialState = {
    page: usingReasons ? 'stocktakeBatchEditModalWithReasons' : 'stocktakeBatchEditModal',
    pageObject: stocktakeItem,
  };

  const [state, dispatch, instantDebouncedDispatch] = usePageReducer(initialState);

  const {
    pageObject,
    data,
    dataState,
    sortBy,
    isAscending,
    modalKey,
    modalValue,
    keyExtractor,
    PageActions,
    columns,
    getPageInfoColumns,
  } = state;

  const { stocktake = {} } = stocktakeItem;
  const { isFinalised = false } = stocktake;

  const onEditReason = rowKey => PageActions.openModal(MODAL_KEYS.STOCKTAKE_REASON, rowKey);
  const onCloseModal = () => dispatch(PageActions.closeModal());
  const onApplyReason = ({ item }) => dispatch(PageActions.applyReason(item));
  const onAddBatch = () => dispatch(PageActions.addStocktakeBatch());

  const toggles = useCallback(getPageInfoColumns(pageObject, dispatch, PageActions), []);

  const getAction = colKey => {
    switch (colKey) {
      case 'batch':
        return PageActions.editStocktakeBatchName;
      case 'countedTotalQuantity':
        return PageActions.editStocktakeBatchCountedQuantity;
      case 'expiryDate':
        return PageActions.editStocktakeBatchExpiryDate;
      case 'reasonTitle':
        return onEditReason;
      default:
        return null;
    }
  };

  const renderRow = useCallback(
    listItem => {
      const { item, index } = listItem;
      const rowKey = keyExtractor(item);
      return (
        <DataTableRow
          rowData={data[index]}
          rowState={dataState.get(rowKey)}
          rowKey={rowKey}
          columns={columns}
          dispatch={dispatch}
          getAction={getAction}
          rowIndex={index}
        />
      );
    },
    [data, dataState]
  );

  const renderHeader = useCallback(
    () => (
      <DataTableHeaderRow
        columns={columns}
        dispatch={instantDebouncedDispatch}
        sortAction={PageActions.sortData}
        isAscending={isAscending}
        sortBy={sortBy}
      />
    ),
    [sortBy, isAscending]
  );

  const {
    pageTopSectionContainer,
    pageTopLeftSectionContainer,
    pageTopRightSectionContainer,
  } = globalStyles;
  return (
    <DataTablePageView>
      <View style={pageTopSectionContainer}>
        <View style={pageTopLeftSectionContainer}>
          <PageInfo columns={toggles} />
        </View>
        <View style={pageTopRightSectionContainer}>
          <PageButton
            text={buttonStrings.add_batch}
            onPress={onAddBatch}
            isDisabled={isFinalised}
          />
        </View>
      </View>
      <DataTable
        data={data}
        extraData={dataState}
        renderRow={renderRow}
        renderHeader={renderHeader}
        keyExtractor={keyExtractor}
        getItemLayout={getItemLayout}
        columns={columns}
        windowSize={1}
        initialNumToRender={0}
      />
      <ModalContainer
        fullScreen={modalKey === MODAL_KEYS.ENFORCE_STOCKTAKE_REASON}
        isVisible={!!modalKey}
        onClose={onCloseModal}
      >
        <GenericChoiceList
          data={UIDatabase.objects('StocktakeReasons')}
          highlightValue={(modalValue && modalValue.reasonTitle) || ''}
          keyToDisplay="title"
          onPress={onApplyReason}
        />
      </ModalContainer>
    </DataTablePageView>
  );
};

StocktakeBatchModal.propTypes = {
  stocktakeItem: PropTypes.object.isRequired,
};

export default StocktakeBatchModal;
<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular
    .module('dopplerRelay')
    .controller('dKimConfigCtrl', dKimConfigCtrl);

  dKimConfigCtrl.$inject = [
    '$scope',
    '$location',
    'settings'
  ];

  function dKimConfigCtrl($scope, $location, settings) {
    var vm = this;
    var queryParams = $location.search();
    vm.domain = queryParams['d'];
    vm.loading = true;
    vm.dKimStatus = null;
    vm.spfStatus = null;
    vm.dKimPublicKey = null;
    vm.dKimSelector = null;
	  vm.activationPromise = activate();

  function activate() {
    return loadDataDomain();
  }

  function loadDataDomain() {
    return settings.getDomain(vm.domain)
      .then(function(response) {
        vm.loading = false;
        vm.dKimStatus = response.data.dkim_ready;
        vm.spfStatus = response.data.spf_ready;
        vm.dKimPublicKey = 'k=rsa; p=' + response.data.dkim_public_key;
        vm.dKimSelector = response.data.dkim_selector + '._domainkey.' + vm.domain;
      });
  }
}
})();
<commit_msg>Update dKimConfigCtrl.js<commit_after>(function() {
  'use strict';

  angular
    .module('dopplerRelay')
    .controller('dKimConfigCtrl', dKimConfigCtrl);

  dKimConfigCtrl.$inject = [
    '$scope',
    '$location',
    'settings'
  ];

  function dKimConfigCtrl($scope, $location, settings) {
    var vm = this;
    var queryParams = $location.search();
    vm.domain = queryParams['d'];
    vm.loading = true;
    vm.dKimStatus = null;
    vm.spfStatus = null;
    vm.dKimPublicKey = null;
    vm.dKimSelector = null;
    vm.activationPromise = activate();

  function activate() {
    return loadDataDomain();
  }

  function loadDataDomain() {
    return settings.getDomain(vm.domain)
      .then(function(response) {
        vm.loading = false;
        vm.dKimStatus = response.data.dkim_ready;
        vm.spfStatus = response.data.spf_ready;
        vm.dKimPublicKey = 'k=rsa; p=' + response.data.dkim_public_key;
        vm.dKimSelector = response.data.dkim_selector + '._domainkey.' + vm.domain;
      });
  }
}
})();
<|endoftext|>


<commit_before>// Custom settings

$([IPython.events]).on('command_mode.Cell', function (event, data) {

      function clearRulers(cm) {
        for (var i = cm.display.lineSpace.childNodes.length - 1; i >= 0; i--) {
          var node = cm.display.lineSpace.childNodes[i];
          if (/(^|\s)CodeMirror-ruler($|\s)/.test(node.className))
            node.parentNode.removeChild(node);
        }
      }

      selected_cell = IPython.notebook.get_selected_cell();
        if ((selected_cell instanceof IPython.CodeCell)) {
            var cm = selected_cell.code_mirror;
            clearRulers(cm);
            cm.setOption('styleActiveLine', false);
        }

});

$([IPython.events]).on('edit_mode.Cell', function (event, data) {

    function setRulers(cm) {
        var val = cm.getOption("rulers");
        var cw = cm.defaultCharWidth();
        var left = cm.charCoords(CodeMirror.Pos(cm.firstLine(), 0), "div").left;
        var minH = cm.display.scroller.offsetHeight + 30;
        for (var i = 0; i < val.length; i++) {
          var elt = document.createElement("div");
          elt.className = "CodeMirror-ruler";
          var col, cls = null, conf = val[i];
          if (typeof conf == "number") {
            col = conf;
          } else {
            col = conf.column;
            if (conf.className) elt.className += " " + conf.className;
            if (conf.color) elt.style.borderColor = conf.color;
            if (conf.lineStyle) elt.style.borderLeftStyle = conf.lineStyle;
            if (conf.width) elt.style.borderLeftWidth = conf.width;
            cls = val[i].className;
          }
          elt.style.left = (left + col * cw) + "px";
          elt.style.top = "-60px";
          elt.style.bottom = "-20px";
          elt.style.minHeight = minH + "px";
          cm.display.lineSpace.insertBefore(elt, cm.display.cursorDiv);
        }
      }

    var ruler = [{column: 79}];

    selected_cell = IPython.notebook.get_selected_cell();
    if ((selected_cell instanceof IPython.CodeCell)) {
        var cm = selected_cell.code_mirror;
        cm.setOption('rulers', ruler);
        cm.setOption('styleActiveLine', true);
        setRulers(cm);
    }
});

require([
    'base/js/namespace',
    'base/js/events',
    'codemirror/addon/search/search',
    'codemirror/addon/search/searchcursor',
    'codemirror/addon/dialog/dialog',
    'codemirror/addon/selection/active-line'
], $([IPython.events]).on('app_initialized.NotebookApp', function() {

        IPython.CodeCell.options_default.cm_config.autoCloseBrackets = false;
        IPython.CodeCell.options_default.cm_config.lineNumbers = true;
        IPython.CodeCell.options_default.cm_config.cursorBlinkRate = 330;
        IPython.CodeCell.options_default.cm_config.lineWrapping = true;

        $('div#header-container').toggle();
        $('.header-bar').toggle(); // 1px high! WTF?!
        $('div#maintoolbar').toggle();
        Jupyter.menubar._size_header()

        IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-m', {
            help : 'toggle menu bar',
            help_index : 'zz',
            handler : function (event) {
                $('div#menubar-container').toggle();
                Jupyter.menubar._size_header()
                return false;
            }
        });

        IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-h', {
            help : 'toggle header',
            help_index : 'zz',
            handler : function (event) {
                $('div#header-container').toggle();
                $('.header-bar').toggle();
                Jupyter.menubar._size_header()
                return false;
            }
        });

        IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-c', {
            help : 'clear all output',
            help_index : 'zz',
            handler : function (event) {
                IPython.notebook.clear_all_output();
                return false;
            }
        });

        IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-x', {
            help : 'clear output',
            help_index : 'zz',
            handler : function (event) {
                IPython.notebook.clear_output();
                return false;
            }
        });

        IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-a', {
            help : 'merge cell above',
            help_index : 'zz',
            handler : function (event) {
                IPython.notebook.merge_cell_above();
                return false;
            }
        });

        IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-b', {
            help : 'merge cell below',
            help_index : 'zz',
            handler : function (event) {
                IPython.notebook.merge_cell_below();
                return false;
            }
        });

        IPython.keyboard_manager.edit_shortcuts.add_shortcut('Alt-s', {
            help : 'split cell',
            help_index : 'zz',
            handler : function (event) {
                IPython.notebook.split_cell();
                return false;
            }
        });

        IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-n', {
            help : 'toggle line number all cells',
            help_index : 'zz',
            handler : function (event) {
                var c = IPython.notebook.get_cells();
                for(var i in c){
                    c[i].toggle_line_numbers();
                }
                return false;
            }
        });

        IPython.keyboard_manager.command_shortcuts.add_shortcut('Ctrl-up', {
            help : 'go to top cell',
            help_index : 'zz',
            handler : function (event) {
                IPython.notebook.select(0);
                IPython.notebook.scroll_to_top();
                return false;
            }
        });

        IPython.keyboard_manager.command_shortcuts.add_shortcut('Ctrl-down', {
            help : 'go to bottom cell',
            help_index : 'zz',
            handler : function (event) {
                var ncells = IPython.notebook.ncells();
                IPython.notebook.select(ncells-1);
                IPython.notebook.scroll_to_bottom();
                return false;
            }
        });

        IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-k', {
            help : 'move cell up',
            help_index : 'zz',
            handler : function (event) {
                IPython.notebook.move_cell_up();
                return false;
            }
        });

        IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-j', {
            help : 'move cell down',
            help_index : 'zz',
            handler : function (event) {
                IPython.notebook.move_cell_down();
                return false;
            }
        });
    });
);
<commit_msg>Fixed JS file for parens<commit_after>require([
    'base/js/namespace',
    'base/js/events',
    'codemirror/addon/search/search',
    'codemirror/addon/search/searchcursor',
    'codemirror/addon/dialog/dialog',
    'codemirror/addon/selection/active-line'],
    $([IPython.events]).on('app_initialized.NotebookApp', function() {

    IPython.CodeCell.options_default.cm_config.autoCloseBrackets = false;
    IPython.CodeCell.options_default.cm_config.lineNumbers = true;
    IPython.CodeCell.options_default.cm_config.cursorBlinkRate = 330;
    IPython.CodeCell.options_default.cm_config.lineWrapping = true;

    $('div#header-container').toggle();
    $('.header-bar').toggle(); // 1px high! WTF?!
    $('div#maintoolbar').toggle();
    Jupyter.menubar._size_header()

    IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-m', {
        help : 'toggle menu bar',
        help_index : 'zz',
        handler : function (event) {
            $('div#menubar-container').toggle();
            Jupyter.menubar._size_header();
            return false;
        }
    });

    IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-h', {
        help : 'toggle header',
        help_index : 'zz',
        handler : function (event) {
            $('div#header-container').toggle();
            $('.header-bar').toggle();
            Jupyter.menubar._size_header()
            return false;
        }
    });

    IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-c', {
        help : 'clear all output',
        help_index : 'zz',
        handler : function (event) {
            IPython.notebook.clear_all_output();
            return false;
        }
    });

    IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-x', {
        help : 'clear output',
        help_index : 'zz',
        handler : function (event) {
            IPython.notebook.clear_output();
            return false;
        }
    });

    IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-a', {
        help : 'merge cell above',
        help_index : 'zz',
        handler : function (event) {
            IPython.notebook.merge_cell_above();
            return false;
        }
    });

    IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-b', {
        help : 'merge cell below',
        help_index : 'zz',
        handler : function (event) {
            IPython.notebook.merge_cell_below();
            return false;
        }
    });

    IPython.keyboard_manager.edit_shortcuts.add_shortcut('Alt-s', {
        help : 'split cell',
        help_index : 'zz',
        handler : function (event) {
            IPython.notebook.split_cell();
            return false;
        }
    });

    IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-n', {
        help : 'toggle line number all cells',
        help_index : 'zz',
        handler : function (event) {
            var c = IPython.notebook.get_cells();
            for(var i in c){
                c[i].toggle_line_numbers();
            }
            return false;
        }
    });

    IPython.keyboard_manager.command_shortcuts.add_shortcut('Ctrl-up', {
        help : 'go to top cell',
        help_index : 'zz',
        handler : function (event) {
            IPython.notebook.select(0);
            IPython.notebook.scroll_to_top();
            return false;
        }
    });

    IPython.keyboard_manager.command_shortcuts.add_shortcut('Ctrl-down', {
        help : 'go to bottom cell',
        help_index : 'zz',
        handler : function (event) {
            var ncells = IPython.notebook.ncells();
            IPython.notebook.select(ncells-1);
            IPython.notebook.scroll_to_bottom();
            return false;
        }
    });

    IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-k', {
        help : 'move cell up',
        help_index : 'zz',
        handler : function (event) {
            IPython.notebook.move_cell_up();
            return false;
        }
    });

    IPython.keyboard_manager.command_shortcuts.add_shortcut('Alt-j', {
        help : 'move cell down',
        help_index : 'zz',
        handler : function (event) {
            IPython.notebook.move_cell_down();
            return false;
        }
    });
}));

$([IPython.events]).on('command_mode.Cell', function (event, data) {

      function clearRulers(cm) {
        for (var i = cm.display.lineSpace.childNodes.length - 1; i >= 0; i--) {
          var node = cm.display.lineSpace.childNodes[i];
          if (/(^|\s)CodeMirror-ruler($|\s)/.test(node.className))
            node.parentNode.removeChild(node);
        }
      }

      selected_cell = IPython.notebook.get_selected_cell();
        if ((selected_cell instanceof IPython.CodeCell)) {
            var cm = selected_cell.code_mirror;
            clearRulers(cm);
            cm.setOption('styleActiveLine', false);
        }

});

$([IPython.events]).on('edit_mode.Cell', function (event, data) {

    function setRulers(cm) {
        var val = cm.getOption("rulers");
        var cw = cm.defaultCharWidth();
        var left = cm.charCoords(CodeMirror.Pos(cm.firstLine(), 0), "div").left;
        var minH = cm.display.scroller.offsetHeight + 30;
        for (var i = 0; i < val.length; i++) {
          var elt = document.createElement("div");
          elt.className = "CodeMirror-ruler";
          var col, cls = null, conf = val[i];
          if (typeof conf == "number") {
            col = conf;
          } else {
            col = conf.column;
            if (conf.className) elt.className += " " + conf.className;
            if (conf.color) elt.style.borderColor = conf.color;
            if (conf.lineStyle) elt.style.borderLeftStyle = conf.lineStyle;
            if (conf.width) elt.style.borderLeftWidth = conf.width;
            cls = val[i].className;
          }
          elt.style.left = (left + col * cw) + "px";
          elt.style.top = "-60px";
          elt.style.bottom = "-20px";
          elt.style.minHeight = minH + "px";
          cm.display.lineSpace.insertBefore(elt, cm.display.cursorDiv);
        }
      }

    var ruler = [{column: 79}];

    selected_cell = IPython.notebook.get_selected_cell();
    if ((selected_cell instanceof IPython.CodeCell)) {
        var cm = selected_cell.code_mirror;
        cm.setOption('rulers', ruler);
        cm.setOption('styleActiveLine', true);
        setRulers(cm);
    }
});
<|endoftext|>


<commit_before>$(function() {
    // Setup redirect after login
    $('#mytba-login').click(function() {
      window.location.href = '/account?redirect=' + escape(document.URL);
    });

    updateFavoritesList();  // Setup

    // Setup typeahead
    $('#add-favorite-team-input').attr('autocomplete', 'off');
    $('#add-favorite-team-input').typeahead([
      {
        prefetch: {
          url: '/_/typeahead/teams-all',
          filter: unicodeFilter
        },
      }
    ]);
    // Submit form when entry chosen
    function doAction(obj, datum) {
      var team_re = datum.value.match(/(\d+) [|] .+/);
      if (team_re != null) {
        team_key = 'frc' + team_re[1];
        $('#add-favorite-team-model-key').attr('value', team_key);
        $('#add-favorite-team-form').submit();
      }
    }
    $('#add-favorite-team-input').bind('typeahead:selected', doAction);
    $('#add-favorite-team-input').bind('typeahead:autocompleted', doAction);

    // Form for adding favorites
    $('#add-favorite-team-form').on('submit', function(e) {
        e.preventDefault();
        var data = $("#add-favorite-team-form :input").serializeArray();
        $.ajax({
          type: 'POST',
          dataType: 'json',
          url: '/_/account/favorites/add',
          data: data,
          success: function(msg) {
            updateFavoritesList();
            $('#add-favorite-team-input').typeahead('setQuery', '');
          },
          error: function(xhr, textStatus, errorThrown) {
            $('#mytba-alert-container').append('
<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>Oops! Failed to add favorite.
Something went wrong on our end. Please try again later.
');
          }
        });
    });
});

// For getting favorites from server
function updateFavoritesList() {
  $.ajax({
    type: 'GET',
    dataType: 'json',
    url: '/_/account/favorites/1',
    success: function(favorites) {
      for (var key in favorites) {
        insertFavoriteTeam(favorites[key]);
      }
      updateAllMatchbars();
    },
    error: function(xhr, textStatus, errorThrown) {
      if (xhr.status == 401) {  // User not logged in
        var last_login_prompt = $.cookie("tba-gameday-last-login-prompt");
        var cur_epoch_ms = new Date().getTime();
        if (last_login_prompt == null || parseInt(last_login_prompt) + 1000*60*60*24 < cur_epoch_ms) {  // Show prompt at most once per day
          $('#login-modal').modal('show');
          $.cookie("tba-gameday-last-login-prompt", cur_epoch_ms);
        }
        $('#settings-button').attr('href', '#login-modal');
      }
      $('#mytba-alert-container').append('
<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>Oops! Unable to get favorites.
Something went wrong on our end. Please try again later.
');
    }
  });
}

function insertFavoriteTeam(favorite_team) {
  var team_number = favorite_team['model_key'].substring(3);
  var existing_favorites = $("#favorite-teams")[0].children;

  // Insert team sorted by team number. Don't re-add if the team is already listed.
  var added = false;
  var element = $("
" + team_number + "
");
  for (var i=0; i<existing_favorites.length; i++) {
    var existing_team_number = parseInt(existing_favorites[i].id.replace(/[A-Za-z$-]/g, ""));
    if (existing_team_number > team_number) {
      element.insertBefore($("#" + existing_favorites[i].id));
      added = true;
      break;
    } else if (existing_team_number == team_number) {
      added = true;
      break;
    }
  }
  if (!added) {
    $("#favorite-teams").append(element);
  }

  // Attach deletion callback
  $(".remove-favorite").click(function() {
    var teamNum = $(this).attr("data-team-number");
    var data = {
      'action': 'delete',
      'model_type': 1,
      'model_key': 'frc' + teamNum
    };
    $.ajax({
      type: 'POST',
      dataType: 'json',
      url: '/_/account/favorites/delete',
      data: data,
      success: function(msg) {
        $("#favorite-" + teamNum).remove();
        updateAllMatchbars();
      },
      error: function(xhr, textStatus, errorThrown) {
        $('#mytba-alert-container').append('
<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>Oops! Failed to delete favorite.
Something went wrong on our end. Please try again later.
');
      }
    });
  });
}
<commit_msg>fix ajax erroring<commit_after>$(function() {
    // Setup redirect after login
    $('#mytba-login').click(function() {
      window.location.href = '/account?redirect=' + escape(document.URL);
    });

    updateFavoritesList();  // Setup

    // Setup typeahead
    $('#add-favorite-team-input').attr('autocomplete', 'off');
    $('#add-favorite-team-input').typeahead([
      {
        prefetch: {
          url: '/_/typeahead/teams-all',
          filter: unicodeFilter
        },
      }
    ]);
    // Submit form when entry chosen
    function doAction(obj, datum) {
      var team_re = datum.value.match(/(\d+) [|] .+/);
      if (team_re != null) {
        team_key = 'frc' + team_re[1];
        $('#add-favorite-team-model-key').attr('value', team_key);
        $('#add-favorite-team-form').submit();
      }
    }
    $('#add-favorite-team-input').bind('typeahead:selected', doAction);
    $('#add-favorite-team-input').bind('typeahead:autocompleted', doAction);

    // Form for adding favorites
    $('#add-favorite-team-form').on('submit', function(e) {
        e.preventDefault();
        var data = $("#add-favorite-team-form :input").serializeArray();
        $.ajax({
          type: 'POST',
          url: '/_/account/favorites/add',
          data: data,
          success: function(data, textStatus, xhr) {
            updateFavoritesList();
            $('#add-favorite-team-input').typeahead('setQuery', '');
          },
          error: function(xhr, textStatus, errorThrown) {
            $('#mytba-alert-container').append('
<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>Oops! Failed to add favorite.
Something went wrong on our end. Please try again later.
');
          }
        });
    });
});

// For getting favorites from server
function updateFavoritesList() {
  $.ajax({
    type: 'GET',
    dataType: 'json',
    url: '/_/account/favorites/1',
    success: function(favorites, textStatus, xhr) {
      for (var key in favorites) {
        insertFavoriteTeam(favorites[key]);
      }
      updateAllMatchbars();
    },
    error: function(xhr, textStatus, errorThrown) {
      if (xhr.status == 401) {  // User not logged in
        var last_login_prompt = $.cookie("tba-gameday-last-login-prompt");
        var cur_epoch_ms = new Date().getTime();
        if (last_login_prompt == null || parseInt(last_login_prompt) + 1000*60*60*24 < cur_epoch_ms) {  // Show prompt at most once per day
          $('#login-modal').modal('show');
          $.cookie("tba-gameday-last-login-prompt", cur_epoch_ms);
        }
        $('#settings-button').attr('href', '#login-modal');
      }
      $('#mytba-alert-container').append('
<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>Oops! Unable to get favorites.
Something went wrong on our end. Please try again later.
');
    }
  });
}

function insertFavoriteTeam(favorite_team) {
  var team_number = favorite_team['model_key'].substring(3);
  var existing_favorites = $("#favorite-teams")[0].children;

  // Insert team sorted by team number. Don't re-add if the team is already listed.
  var added = false;
  var element = $("
" + team_number + "
");
  for (var i=0; i<existing_favorites.length; i++) {
    var existing_team_number = parseInt(existing_favorites[i].id.replace(/[A-Za-z$-]/g, ""));
    if (existing_team_number > team_number) {
      element.insertBefore($("#" + existing_favorites[i].id));
      added = true;
      break;
    } else if (existing_team_number == team_number) {
      added = true;
      break;
    }
  }
  if (!added) {
    $("#favorite-teams").append(element);
  }

  // Attach deletion callback
  $(".remove-favorite").click(function() {
    var teamNum = $(this).attr("data-team-number");
    var data = {
      'action': 'delete',
      'model_type': 1,
      'model_key': 'frc' + teamNum
    };
    $.ajax({
      type: 'POST',
      url: '/_/account/favorites/delete',
      data: data,
      success: function(data, textStatus, xhr) {
        $("#favorite-" + teamNum).remove();
        updateAllMatchbars();
      },
      error: function(xhr, textStatus, errorThrown) {
        $('#mytba-alert-container').append('
<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>Oops! Failed to delete favorite.
Something went wrong on our end. Please try again later.
');
      }
    });
  });
}
<|endoftext|>


<commit_before>/* globals systems path sync persistent */
/* eslint camelcase: [2, {properties: "never"}] */
/* eslint comma-dangle: [0, {properties: "never"}] */

/* see Azkfile.md */
systems({
  feedbin: {
    // Dependent systems
    depends: ["clock", "worker-slow", "worker", "redis", "postgres", "elasticsearch", "memcached"],
    // More images:  http://images.azk.io
    image: {"docker": "azukiapp/ruby:2.1.4"},
    // Steps to execute before running instances
    provision: [],
    workdir: "/azk/#{manifest.dir}",
    shell: "/bin/bash",
    command: "bundle exec rackup config.ru --pid /tmp/ruby.pid --port $HTTP_PORT --host 0.0.0.0",
    wait: {"retry": 40, "timeout": 10000},
    mounts: {
      // Uncomment the line below to use with two-way share (slower)
      //'/azk/#{manifest.dir}': path("."),
      // Run with one-way share rsync (faster)
      '/azk/#{manifest.dir}'        : sync("."),
      '/azk/bundler'                : persistent("bundler"),
      '/azk/#{manifest.dir}/tmp'    : persistent("tmp"),
      '/azk/#{manifest.dir}/.bundle': path(".bundle"),
      '/azk/#{manifest.dir}/log'    : path("log"),
    },
    scalable: {"default": 1},
    http: {
      domains: [
        "#{system.name}.#{azk.default_domain}", // default azk domain
        '#{process.env.HOST_DOMAIN}',           // used if deployed
        '#{process.env.HOST_IP}',               // used if deployed
      ]
    },
    envs: {
      // set instances variables
      RACK_ENV: "development",
      RUBY_ENV: "development",
    },
  },
  worker: {
    extends: 'feedbin',
    provision: [
      "bundle install --path /azk/bundler",
      "bundle exec rake db:setup",
    ],
    depends: ["postgres", "redis", "elasticsearch", "memcached"],
    command: 'bundle exec sidekiq -c 12 -q critical,2 -q feed_refresher_receiver,1 -q default',
    scalable: { limit: 1, default: 1},
    http: null,
    envs: {
      RACK_ENV: "development",
      RUBY_ENV: "development",
      DB_POOL: 12,
      LIBRATO_AUTORUN: 1,
    }
  },
  "worker-slow": {
    extends: 'feedbin',
    depends: ["postgres", "redis", "elasticsearch", "memcached"],
    command: 'bundle exec sidekiq -c 1 -q worker_slow_critical,3 -q worker_slow,2 -q favicon,1',
    scalable: { default: 1,  limit: 1 },
    http: null,
    envs: {
      RACK_ENV: "development",
      RUBY_ENV: "development",
      DB_POOL: 1
    }
  },
  clock: {
    extends: 'feedbin',
    depends: ["postgres", "redis", "elasticsearch", "memcached"],
    command: 'bundle exec clockwork lib/clock.rb',
    scalable: { default: 1,  limit: 1 },
    http: null,
    envs: {
      RACK_ENV: "development",
      RUBY_ENV: "development",
    }
  },
  redis: {
    image: {"docker": "redis"},
    export_envs: {
      "REDIS_HOST": "#{net.host}",
      "REDIS_PORT": "#{net.port.data}",
      "REDIS_URL": "redis://#{net.host}:#{net.port[6379]}",
    },
  },
  postgres: {
    // Dependent systems
    depends: [],
    // More images:  http://images.azk.io
    image: {"docker": "azukiapp/postgres:9.3"},
    shell: "/bin/bash",
    wait: {"retry": 20, "timeout": 1000},
    mounts: {
      '/var/lib/postgresql': persistent("postgresql"),
      '/var/log/postgresql': path("./log/postgresql"),
    },
    ports: {
      // exports global variables
      data: "5432/tcp",
    },
    envs: {
      // set instances variables
      POSTGRES_USER: "azk",
      POSTGRES_PASS: "azk",
      POSTGRES_DB  : "#{manifest.dir}",
    },
    export_envs: {
      // check this gist to configure your database
      // https://gist.github.com/gullitmiranda/62082f2e47c364ef9617
      DATABASE_URL: "postgres://#{envs.POSTGRES_USER}:#{envs.POSTGRES_PASS}@#{net.host}:#{net.port.data}/${envs.POSTGRES_DB}",
    },
  },
  elasticsearch: {
    image: { "docker": "barnybug/elasticsearch:0.90.13" },
    http: {
      domains: [ "#{system.name}.#{azk.default_domain}" ]
    },
    ports: {
      http: "9200",
    },
    wait: {"retry": 40, "timeout": 1000},
    export_envs : {
      ELASTICSEARCH_URL: "#{system.name}.#{azk.default_domain}:#{net.port[9200]}",
    },
  },
  memcached: {
    image: { "docker": "memcached" },
    ports: {
      http: "11211",
    },
    export_envs: {
      MEMCACHED_HOSTS: "#{system.name}.#{azk.default_domain}:#{net.port[11211]}"
    }
  },

  deploy: {
    image: {"docker": "azukiapp/deploy-digitalocean"},
    mounts: {

      // your files on remote machine
      // will be on /home/git folder
      "/azk/deploy/src":  path("."),

      // will use your public key on server
      // that way you can connect with:
      // $ ssh git@REMOTE.IP
      // $ bash
      "/azk/deploy/.ssh": path("#{process.env.HOME}/.ssh")
    },

    // this is not a server
    // just call with azk shell deploy
    scalable: {"default": 0, "limit": 0},

    envs: {
      BOX_SIZE: '2gb',
      GIT_CHECKOUT_COMMIT_BRANCH_TAG: 'azkfile',
      AZK_RESTART_COMMAND: 'azk restart -Rvv',
      RUN_SETUP: 'true',
      RUN_CONFIGURE: 'true',
      RUN_DEPLOY: 'true',
    }
  },
  "fast-deploy": {
    extends: 'deploy',
    envs: {
      BOX_SIZE: '2gb',
      GIT_CHECKOUT_COMMIT_BRANCH_TAG: 'azkfile',
      AZK_RESTART_COMMAND: 'azk restart -Rvv',
      RUN_SETUP: 'false',
      RUN_CONFIGURE: 'false',
      RUN_DEPLOY: 'true',
    }
  },

});
<commit_msg>Azkfile updated<commit_after>/* globals systems path sync persistent */
/* eslint camelcase: [2, {properties: "never"}] */
/* eslint comma-dangle: [0, {properties: "never"}] */

/* see Azkfile.md */
systems({
  feedbin: {
    // Dependent systems
    depends: ["clock", "worker-slow", "worker", "redis", "postgres", "elasticsearch", "memcached"],
    // More images:  http://images.azk.io
    image: {"docker": "azukiapp/ruby:2.2"},
    // Steps to execute before running instances
    provision: [],
    workdir: "/azk/#{manifest.dir}",
    shell: "/bin/bash",
    command: "bundle exec rackup config.ru --pid /tmp/ruby.pid --port $HTTP_PORT --host 0.0.0.0",
    wait: {"retry": 40, "timeout": 10000},
    mounts: {
      // Uncomment the line below to use with two-way share (slower)
      //'/azk/#{manifest.dir}': path("."),
      // Run with one-way share rsync (faster)
      '/azk/#{manifest.dir}'        : sync("."),
      '/azk/bundler'                : persistent("bundler"),
      '/azk/#{manifest.dir}/tmp'    : persistent("tmp"),
      '/azk/#{manifest.dir}/.bundle': path(".bundle"),
      '/azk/#{manifest.dir}/log'    : path("log"),
    },
    scalable: {"default": 1},
    http: {
      domains: [
        "#{system.name}.#{azk.default_domain}", // default azk domain
        '#{process.env.HOST_DOMAIN}',           // used if deployed
        '#{process.env.HOST_IP}',               // used if deployed
      ]
    },
    envs: {
      // set instances variables
      RACK_ENV: "development",
      RUBY_ENV: "development",
    },
  },
  worker: {
    extends: 'feedbin',
    provision: [
      "bundle install --path /azk/bundler",
      "bundle exec rake db:setup",
    ],
    depends: ["postgres", "redis", "elasticsearch", "memcached"],
    command: 'bundle exec sidekiq -c 12 -q critical,3 -q feed_refresher_receiver,2 -q default',
    scalable: { limit: 1, default: 1},
    http: null,
    envs: {
      RACK_ENV: "development",
      RUBY_ENV: "development",
      DB_POOL: 12,
      LIBRATO_AUTORUN: 1,
    }
  },
  "worker-slow": {
    extends: 'feedbin',
    depends: ["postgres", "redis", "elasticsearch", "memcached"],
    command: 'bundle exec sidekiq -c 2 -q worker_slow_critical,3 -q worker_slow,2 -q favicon,1',
    scalable: { default: 1,  limit: 1 },
    http: null,
    envs: {
      RACK_ENV: "development",
      RUBY_ENV: "development",
      DB_POOL: 2
    }
  },
  clock: {
    extends: 'feedbin',
    depends: ["postgres", "redis", "elasticsearch", "memcached"],
    command: 'bundle exec clockwork lib/clock.rb',
    scalable: { default: 1,  limit: 1 },
    http: null,
    envs: {
      RACK_ENV: "development",
      RUBY_ENV: "development",
    }
  },
  redis: {
    image: {"docker": "redis"},
    export_envs: {
      "REDIS_HOST": "#{net.host}",
      "REDIS_PORT": "#{net.port.data}",
      "REDIS_URL": "redis://#{net.host}:#{net.port[6379]}",
    },
  },
  postgres: {
    // Dependent systems
    depends: [],
    // More images:  http://images.azk.io
    image: {"docker": "azukiapp/postgres:9.3"},
    shell: "/bin/bash",
    wait: {"retry": 40, "timeout": 1000},
    mounts: {
      '/var/lib/postgresql': persistent("postgresql"),
      '/var/log/postgresql': path("./log/postgresql"),
    },
    ports: {
      // exports global variables
      data: "5432/tcp",
    },
    envs: {
      // set instances variables
      POSTGRES_USER: "azk",
      POSTGRES_PASS: "azk",
      POSTGRES_DB  : "#{manifest.dir}",
    },
    export_envs: {
      // check this gist to configure your database
      // https://gist.github.com/gullitmiranda/62082f2e47c364ef9617
      DATABASE_URL: "postgres://#{envs.POSTGRES_USER}:#{envs.POSTGRES_PASS}@#{net.host}:#{net.port.data}/${envs.POSTGRES_DB}",
    },
  },
  elasticsearch: {
    image: { "docker": "barnybug/elasticsearch:0.90.13" },
    http: {
      domains: [ "#{system.name}.#{azk.default_domain}" ]
    },
    ports: {
      http: "9200",
    },
    wait: {"retry": 80, "timeout": 1000},
    export_envs : {
      ELASTICSEARCH_URL: "#{system.name}.#{azk.default_domain}:#{net.port[9200]}",
    },
  },
  memcached: {
    image: { "docker": "memcached" },
    ports: {
      http: "11211",
    },
    export_envs: {
      MEMCACHED_HOSTS: "#{system.name}.#{azk.default_domain}:#{net.port[11211]}"
    }
  },

  deploy: {
    image: {"docker": "azukiapp/deploy-digitalocean"},
    mounts: {

      // your files on remote machine
      // will be on /home/git folder
      "/azk/deploy/src":  path("."),

      // will use your public key on server
      // that way you can connect with:
      // $ ssh git@REMOTE.IP
      // $ bash
      "/azk/deploy/.ssh": path("#{process.env.HOME}/.ssh")
    },

    // this is not a server
    // just call with azk shell deploy
    scalable: {"default": 0, "limit": 0},

    envs: {
      BOX_SIZE: '2gb',
      GIT_CHECKOUT_COMMIT_BRANCH_TAG: 'azkfile',
      AZK_RESTART_COMMAND: 'azk restart -Rvv',
      RUN_SETUP: 'true',
      RUN_CONFIGURE: 'true',
      RUN_DEPLOY: 'true',
    }
  },
  "fast-deploy": {
    extends: 'deploy',
    envs: {
      BOX_SIZE: '2gb',
      GIT_CHECKOUT_COMMIT_BRANCH_TAG: 'azkfile',
      AZK_RESTART_COMMAND: 'azk restart -Rvv',
      RUN_SETUP: 'false',
      RUN_CONFIGURE: 'false',
      RUN_DEPLOY: 'true',
    }
  },

});
<|endoftext|>


<commit_before>/*
 *  NullTransport.js
 *
 *  David Janes
 *  IOTDB.org
 *  2015-08-17
 *
 *  Copyright [2013-2015] [David P. Janes]
 *
 *  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.
 */

"use strict";

var iotdb = require('iotdb');
var iotdb_transport = require('iotdb-transport');
var errors = iotdb_transport.errors;
var _ = iotdb._;

var path = require('path');

var util = require('util');
var url = require('url');

var logger = iotdb.logger({
    name: 'iotdb-transport-proto',
    module: 'NullTransport',
});

/* --- constructor --- */

/**
 *  Create a transport for Null.
 */
var NullTransport = function (initd, native) {
    var self = this;

    self.initd = _.defaults(
        initd,
        {
        },
        iotdb.keystore().get("/transports/NullTransport/initd"),
        {
            prefix: ""
        }
    );

    self.native = native;
};

NullTransport.prototype = new iotdb_transport.Transport;
NullTransport.prototype._class = "NullTransport";

/* --- methods --- */

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 */
NullTransport.prototype.list = function(paramd, callback) {
    var self = this;

    self._validate_list(paramd, callback);

    callback(null, null);
};

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 */
NullTransport.prototype.added = function(paramd, callback) {
    var self = this;

    self._validate_added(paramd, callback);
};

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 */
NullTransport.prototype.get = function(paramd, callback) {
    var self = this;

    self._validate_get(paramd, callback);

    var gd = _.d.clone.shallow(paramd);
    gd.value = null;

    callback(new errors.NotFound(), gd);
};

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 */
NullTransport.prototype.put = function(paramd, callback) {
    var self = this;

    self._validate_update(paramd, callback);

    var pd = _.d.clone.shallow(paramd);

    callback(new errors.NotImplemented(), pd);
};

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 */
NullTransport.prototype.updated = function(paramd, callback) {
    var self = this;

    self._validate_updated(paramd, callback);
};

/**
 *  See {iotdb_transport.Transport#bands} for documentation.
 */
NullTransport.prototype.bands = function (paramd, callback) {
    var self = this;

    self._validate_bands(paramd, callback);

    var bd = _.d.clone.shallow(paramd);

    callback(new errors.NeverImplemented(), bd);
};

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 */
NullTransport.prototype.remove = function(paramd, callback) {
    var self = this;

    self._validate_remove(paramd, callback);

    var rd = _.d.clone.shallow(paramd);
    delete rd.band;
    delete rd.value;

    callback(new errors.NeverImplemented(), rd);
};

/* --- internals --- */
/**
 *  API
 */
exports.NullTransport = NullTransport;
<commit_msg>missing checkin<commit_after>/*
 *  NullTransport.js
 *
 *  David Janes
 *  IOTDB.org
 *  2015-08-17
 *
 *  Copyright [2013-2015] [David P. Janes]
 *
 *  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.
 */

"use strict";

var iotdb = require('iotdb');
var iotdb_transport = require('iotdb-transport');
const errors = require('iotdb-errors');
var _ = iotdb._;

var path = require('path');

var util = require('util');
var url = require('url');

var logger = iotdb.logger({
    name: 'iotdb-transport-proto',
    module: 'NullTransport',
});

/* --- constructor --- */

/**
 *  Create a transport for Null.
 */
var NullTransport = function (initd, native) {
    var self = this;

    self.initd = _.defaults(
        initd,
        {
        },
        iotdb.keystore().get("/transports/NullTransport/initd"),
        {
            prefix: ""
        }
    );

    self.native = native;
};

NullTransport.prototype = new iotdb_transport.Transport;
NullTransport.prototype._class = "NullTransport";

/* --- methods --- */

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 */
NullTransport.prototype.list = function(paramd, callback) {
    var self = this;

    self._validate_list(paramd, callback);

    callback(null, null);
};

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 */
NullTransport.prototype.added = function(paramd, callback) {
    var self = this;

    self._validate_added(paramd, callback);
};

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 */
NullTransport.prototype.get = function(paramd, callback) {
    var self = this;

    self._validate_get(paramd, callback);

    var gd = _.d.clone.shallow(paramd);
    gd.value = null;

    callback(new errors.NotFound(), gd);
};

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 */
NullTransport.prototype.put = function(paramd, callback) {
    var self = this;

    self._validate_update(paramd, callback);

    var pd = _.d.clone.shallow(paramd);

    callback(new errors.NotImplemented(), pd);
};

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 */
NullTransport.prototype.updated = function(paramd, callback) {
    var self = this;

    self._validate_updated(paramd, callback);
};

/**
 *  See {iotdb_transport.Transport#bands} for documentation.
 */
NullTransport.prototype.bands = function (paramd, callback) {
    var self = this;

    self._validate_bands(paramd, callback);

    var bd = _.d.clone.shallow(paramd);

    callback(new errors.NeverImplemented(), bd);
};

/**
 *  See {iotdb_transport.Transport#Transport} for documentation.
 */
NullTransport.prototype.remove = function(paramd, callback) {
    var self = this;

    self._validate_remove(paramd, callback);

    var rd = _.d.clone.shallow(paramd);
    delete rd.band;
    delete rd.value;

    callback(new errors.NeverImplemented(), rd);
};

/* --- internals --- */
/**
 *  API
 */
exports.NullTransport = NullTransport;
<|endoftext|>