text:
package edu.duke.cabig.c3pr.web.ajax;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.extremecomponents.table.bean.Column;
import org.extremecomponents.table.bean.Row;
import org.extremecomponents.table.bean.Table;
import org.extremecomponents.table.context.Context;
import org.extremecomponents.table.context.HttpServletRequestContext;
import org.extremecomponents.table.core.TableModel;
import org.extremecomponents.table.core.TableModelImpl;

import edu.duke.cabig.c3pr.constants.RandomizationType;
import edu.duke.cabig.c3pr.dao.StudyDao;
import edu.duke.cabig.c3pr.domain.Arm;
import edu.duke.cabig.c3pr.domain.BookRandomization;
import edu.duke.cabig.c3pr.domain.BookRandomizationEntry;
import edu.duke.cabig.c3pr.domain.Epoch;
import edu.duke.cabig.c3pr.domain.StratumGroup;
import edu.duke.cabig.c3pr.utils.StringUtils;
import edu.duke.cabig.c3pr.web.study.AmendCompanionStudyController;
import edu.duke.cabig.c3pr.web.study.AmendStudyController;
import edu.duke.cabig.c3pr.web.study.CreateCompanionStudyController;
import edu.duke.cabig.c3pr.web.study.CreateStudyController;
import edu.duke.cabig.c3pr.web.study.EditCompanionStudyController;
import edu.duke.cabig.c3pr.web.study.EditStudyController;
import edu.duke.cabig.c3pr.web.study.StudyController;
import edu.duke.cabig.c3pr.web.study.StudyWrapper;

public class BookRandomizationAjaxFacade {

    private static Log log = LogFactory.getLog(BookRandomizationAjaxFacade.class);

    protected StudyDao studyDao;

    /*
     * This is the method that is called from the study_randomization.jsp on clicking the "Upload
     * Randomization Book" (text upload using dwr)
     */
    public String getTable(Map<String, List> parameterMap, String content, String epochIndexString,
                    HttpServletRequest req, String flowType) {
    		return getTableForWrapper(parameterMap, content, epochIndexString, req, flowType, null);
    }

    /*
     * This is the method that is called from the study_randomization for the file upload and
     * the text upload. This is also consequently called on clicking any of the table
     * buttons like pagination. As this does all the binding of uploaded data, the
     * implementation of postProcess() in StudyRandomizationTab.java contains a call to this and
     * itself is activated in turn for file upload.
     *
     * epochIndexString - This is the index of the epoch being dealt with. content - This is the
     * data pasted in the textarea by the user. parameterMap - this is used by the table to run its
     * own functionality like pagination.
     */
    public String getTableForWrapper(Map<String, List> parameterMap, String content,
			String epochIndexString, HttpServletRequest req, String flowType, StudyWrapper wrapper) {
		Context context;
		if (parameterMap != null) {
			context = new HttpServletRequestContext(req, parameterMap);
		} else {
			context = new HttpServletRequestContext(req);
		}

		//the wrapper is passed in in case of File upload and refData but its null in case of text upload.
		if(wrapper == null){
			wrapper = getCommandOnly(flowType, req);
		}
    	String action = getAction(flowType, wrapper);

		TableModel model = new TableModelImpl(context);
		Epoch tEpoch = null;
		if (wrapper != null
				&& wrapper.getStudy().getRandomizationType() != null
				&& wrapper.getStudy().getRandomizationType().equals(
						RandomizationType.BOOK)) {
			String bookRandomizations;
			int selectedEpoch = StringUtils.getBlankIfNull(epochIndexString)
					.equals("") ? -1 : Integer.parseInt(epochIndexString);
			tEpoch = wrapper.getStudy().getEpochs().get(selectedEpoch);
			bookRandomizations = StringUtils.getBlankIfNull(content);
			if (!StringUtils.isEmpty(bookRandomizations)) {
				if (tEpoch != null) {
					try {
						if (tEpoch.getStratificationIndicator()) {
							parseBookRandomization(bookRandomizations, tEpoch);
						} else {
							parseBookRandomizationWithoutStratification(
									bookRandomizations, tEpoch);
						}
					} catch (Exception e) {
						log
								.error("Error while calling parseBookRandomization: "
										+ e.getMessage());
						return "

Incorrect format. Please try again.
";
					}
					if (tEpoch.getStratificationIndicator()) {
						validatePositions(((BookRandomization) tEpoch
								.getRandomization())
								.getBookRandomizationEntry());
					} else {
						validatePositionsWithoutStratification(((BookRandomization) tEpoch
								.getRandomization())
								.getBookRandomizationEntry());
					}
				} else {
					log.error("Invalid epoch Index");
				}
			}

			if (tEpoch != null && tEpoch.getRandomization() != null) {
				List<BookRandomizationEntry> breList = ((BookRandomization) tEpoch
						.getRandomization()).getBookRandomizationEntry();
				try {
					if (tEpoch.getStratificationIndicator()) {
						return build(model, breList,
								"Book Randomization :" + selectedEpoch, action,
								flowType).toString();
					} else {
						return buildWithoutStratification(model, breList,
								"Book Randomization :" + selectedEpoch, action,
								flowType).toString();
					}
				} catch (Exception e) {
					log.error(e.getMessage());
				}
			}
		}
		return "";
	}

    private StudyWrapper getCommandOnly(String flowType, HttpServletRequest req){
    	StudyWrapper wrapper = null;
    	if (flowType.equals(StudyController.CREATE_STUDY)) {
    		return (StudyWrapper) req.getSession().getAttribute(CreateStudyController.class.getName() + ".FORM.command");
    	}
    	if (flowType.equals(StudyController.CREATE_COMPANION_STUDY)) {
    		return (StudyWrapper) req.getSession().getAttribute(CreateCompanionStudyController.class.getName() + ".FORM.command");
		}
    	if (flowType.equals(StudyController.AMEND_STUDY)) {
    		return (StudyWrapper) req.getSession().getAttribute(AmendStudyController.class.getName() + ".FORM.command");
        }
    	if(flowType.equals(StudyController.AMEND_COMPANION_STUDY)){
    		return (StudyWrapper) req.getSession().getAttribute(AmendCompanionStudyController.class.getName() + ".FORM.command");
        }
    	if(flowType.equals(StudyController.EDIT_STUDY)){
    		return (StudyWrapper) req.getSession().getAttribute(EditStudyController.class.getName() + ".FORM.command");
        }
    	if(flowType.equals(StudyController.EDIT_COMPANION_STUDY)){
    		return (StudyWrapper) req.getSession().getAttribute(EditCompanionStudyController.class.getName() + ".FORM.command");
        }
    	return wrapper;
    }

    private String getAction(String flowType, StudyWrapper wrapper){
    	String action ="";
    	if (flowType.equals(StudyController.CREATE_STUDY)) {
    		return "/pages/study/createStudy";
    	}
    	if (flowType.equals(StudyController.CREATE_COMPANION_STUDY)) {
    		return "/pages/study/createCompanionStudy";
		}
    	if (flowType.equals(StudyController.AMEND_STUDY)) {
    		return "/pages/study/amendStudy";
        }
    	if(flowType.equals(StudyController.AMEND_COMPANION_STUDY)){
    		return "/pages/study/amendCompanionStudy";
        }
    	if(flowType.equals(StudyController.EDIT_STUDY)){
    		return "/pages/study/editStudy";
        }
    	if(flowType.equals(StudyController.EDIT_COMPANION_STUDY)){
    		return "/pages/study/editCompanionStudy";
        }
    	return action;
    }

    /*
	 * This method goes through the positions and ensures that they start with 0
	 * and increment by 1 for every stratum group number. if any incorrect
	 * number is found it is replaced by null. the buildTable replaces blank
	 * string with "Invalid Entry".
	 */
    private void validatePositions(List<BookRandomizationEntry> breList) {
        Iterator iter = breList.iterator();
        BookRandomizationEntry bre;
        int i = 0;
        int strGroupNumber = 0;
        while (iter.hasNext()) {
            bre = (BookRandomizationEntry) iter.next();
            if (bre.getStratumGroup() != null
                            && bre.getStratumGroup().getStratumGroupNumber() != null
                            && bre.getStratumGroup().getStratumGroupNumber().intValue() != strGroupNumber) {
                i = 0;
            }
            strGroupNumber = bre.getStratumGroup().getStratumGroupNumber().intValue();
            if (bre.getPosition() != null && bre.getPosition().intValue() != i) {
                bre.setPosition(null);
            }
            ++i;
        }
    }

    /*
     * This method goes through the positions and ensures that they start with 0 and increment by 1
     * for every stratum group number. if any incorrect number is found it is replaced by null. the
     * buildTable replaces blank string with "Invalid Entry".
     */
    private void validatePositionsWithoutStratification(List<BookRandomizationEntry> breList) {
        Iterator iter = breList.iterator();
        BookRandomizationEntry bre;
        int i = 0;
        while (iter.hasNext()) {
            bre = (BookRandomizationEntry) iter.next();
            if (bre.getPosition() != null && bre.getPosition().intValue() != i) {
                bre.setPosition(null);
            }
            ++i;
        }
    }

    /*
     * This method accepts the comma seperated string which is the formatted content for book
     * randomization and populated the domain object with the corresponding data. the format is
     * "Stratum Group, Position, Arm Assignment" e.g: 0, 0, A 0, 1, C 1, 0, A 2, 1, B
     */
    private void parseBookRandomization(String bookRandomizations, Epoch tEpoch)
                    throws Exception {

        try {
            // we do not create a new instance of bookRandomization, we use the existing instance
            // which was created in StudyDesignTab.java
            // based on the randomizationType selected on the study_details page.
        	BookRandomization randomization = null;
        	if(tEpoch.getRandomization() instanceof BookRandomization){
        		randomization = (BookRandomization)tEpoch.getRandomization();
        	} else {
        		return;
        	}

            List<BookRandomizationEntry> breList = randomization.getBookRandomizationEntry();
            //clear existing bookEntries
            breList.clear();
            clearStratumGroups(tEpoch);

            StringTokenizer outer = new StringTokenizer(bookRandomizations, "\n");
            String entry;
            String[] entries;
            Arm arm;
            StratumGroup sGroup;
            BookRandomizationEntry bookRandomizationEntry = null;
            while (outer.hasMoreElements()) {
                entry = outer.nextToken();
                if (entry.trim().length() > 0) {
                    entries = entry.split(",");
                    bookRandomizationEntry = breList.get(breList.size());

                    // find the stratum group with this id and set it here even if its null
                    sGroup = getStratumGroupByNumber(tEpoch, entries[0].trim());
                    bookRandomizationEntry.setStratumGroup(sGroup);
                    sGroup.getBookRandomizationEntry().add(bookRandomizationEntry);
                    // set the position
                    Integer position = null;
                    try {
                        position = Integer.valueOf(entries[1].trim());
                    }
                    catch (NumberFormatException nfe) {
                        log.debug("Illegal Position Entered.");
                    }
                    bookRandomizationEntry.setPosition(position);
                    // find the arm with this id and set it here even if its null
                    // Empty stratum groups with negetive stratum Group Numbers and arms are checked
                    // for while generating the table and replaced with the string
                    // "Invalid Entry" so the user can see which entries are incorrect.
                    arm = getArmByName(tEpoch, entries[2].trim());
                    bookRandomizationEntry.setArm(arm);
                }
            }
        }
        catch (Exception e) {
            log.error("parseBookRandomizatrion Failed");
            log.error(e.getMessage());
            throw e;
        }
    }

    private void parseBookRandomizationWithoutStratification(String bookRandomizations, Epoch tEpoch)
    	throws Exception {

		try {
			// we do not create a new instance of bookRandomization, we use the existing instance
			// which was created in StudyDesignTab.java
			// based on the randomizationType selected on the study_details page.
			BookRandomization randomization = null;
        	if(tEpoch.getRandomization() instanceof BookRandomization){
        		randomization = (BookRandomization)tEpoch.getRandomization();
        	} else {
        		return;
        	}

            List<BookRandomizationEntry> breList = randomization.getBookRandomizationEntry();
            //clear existing bookEntries
            breList.clear();
            clearStratumGroups(tEpoch);

			StringTokenizer outer = new StringTokenizer(bookRandomizations, "\n");
			String entry;
			String[] entries;
			Arm arm;
			BookRandomizationEntry bookRandomizationEntry = null;
			while (outer.hasMoreElements()) {
				entry = outer.nextToken();
				if (entry.trim().length() > 0) {
				    entries = entry.split(",");
				    bookRandomizationEntry = breList.get(breList.size());

				    // set the position
				    Integer position = null;
				    try {
				        position = Integer.valueOf(entries[0].trim());
				    }
				    catch (NumberFormatException nfe) {
				        log.debug("Illegal Position Entered.");
				    }
				    bookRandomizationEntry.setPosition(position);
				    // find the arm with this id and set it here even if its null
				    // Empty stratum groups with negetive stratum Group Numbers and arms are checked
				    // for while generating the table and replaced with the string
				    // "Invalid Entry" so the user can see which entries are incorrect.
				    arm = getArmByName(tEpoch, entries[1].trim());
				    bookRandomizationEntry.setArm(arm);
				}
			}
		}
		catch (Exception e) {
			log.error("parseBookRandomizationWithoutStratification Failed");
			log.error(e.getMessage());
			throw e;
		}
	}

    /*
     * Takes the treatementEpoch and arm.name and returns the arm (from that epoch)which has that
     * name. returns null if no arm is found
     */
    private Arm getArmByName(Epoch tEpoch, String armName) {
        Arm selectedArm = null;
        if (tEpoch != null) {
            List<Arm> armList = tEpoch.getArms();
            for (Arm individualArm : armList) {
                if (individualArm.getName().equals(armName.trim())) {
                    selectedArm = individualArm;
                }
            }
        }
        return selectedArm;
    }

    /*
     * Takes the treatementEpoch and groupNumber and returns the Stratum Group(from that epoch)which
     * has that group number. returns null if no Group is found
     */
    private StratumGroup getStratumGroupByNumber(Epoch tEpoch, String sgPos) {
        StratumGroup selectedStratumGroup = new StratumGroup();
        // returning a negetive group number if entered num is illegal(e.g: a, & etc) or
        // invalid(1008 etc)
        selectedStratumGroup.setStratumGroupNumber(new Integer(-1));
        int sgNumber;
        try {
            sgNumber = Integer.parseInt(sgPos);
        }
        catch (NumberFormatException nfe) {
            log.debug("Illegal Stratum Group Number Entered.");
            return selectedStratumGroup;
        }

        if (tEpoch != null) {
            List<StratumGroup> sgList = tEpoch.getStratumGroups();
            for (StratumGroup individualStratumGroup : sgList) {
                if (individualStratumGroup.getStratumGroupNumber() == sgNumber) {
                    selectedStratumGroup = individualStratumGroup;
                }
            }
        }
        //log.debug("Invalid Stratum Group Number Entered.");
        return selectedStratumGroup;
    }

    /*
     * This is the method that has all the extreme Table API calls.It is set to display 11 rowqs at
     * a time. Also the onclick method call is set to uploadBook() and pagination is enabled. We use
     * the BookRandomizationCustomCell to check for null arms/groups and add the "invalid entry"
     * string in such cases.
     */
    public Object build(TableModel model, Collection bookRandomizationEntries, String title,
                    String action, String flowType) throws Exception {

        String index = title.substring(title.indexOf(":") + 1);
        String tableId = "bookRandomizationEntries" + index;
        Table table = model.getTableInstance();
        table.setTitle("Randomization Book");
        table.setAutoIncludeParameters(true);
        table.setAction(model.getContext().getContextPath() + action);
        table.setTableId(tableId);
        table.setItems(bookRandomizationEntries);
        table
                        .setOnInvokeAction("uploadBook('" + tableId + "', '" + index + "','"
                                        + flowType + "')");
        table.setShowPagination(true);
        table.setFilterable(false);
        table.setImagePath(model.getContext().getContextPath() + "/images/table/*.gif");
        table.setRowsDisplayed(10);
        model.addTable(table);

        Row row = model.getRowInstance();
        row.setHighlightRow(Boolean.TRUE);
        model.addRow(row);

        Column columnStratumGroupNumber = model.getColumnInstance();
        columnStratumGroupNumber.setProperty("stratumGroup.stratumGroupNumber");
        columnStratumGroupNumber.setTitle("Stratum Group Number");
        columnStratumGroupNumber.setCell((BookRandomizationCustomCell.class).getName());
        model.addColumn(columnStratumGroupNumber);

        Column columnPosition = model.getColumnInstance();
        columnPosition.setProperty("position");
        columnPosition.setCell((BookRandomizationCustomCell.class).getName());
        columnPosition.setTitle("Position");
        model.addColumn(columnPosition);

        Column columnArm = model.getColumnInstance();
        columnArm.setProperty("arm.name");
        columnArm.setTitle("Arm Name");
        columnArm.setCell((BookRandomizationCustomCell.class).getName());
        model.addColumn(columnArm);

        return model.assemble();
    }

    /*
     * This is the method that has all the extreme Table API calls.It is set to display 11 rowqs at
     * a time. Also the onclick method call is set to uploadBook() and pagination is enabled. We use
     * the BookRandomizationCustomCell to check for null arms/groups and add the "invalid entry"
     * string in such cases.
     */
    public Object buildWithoutStratification(TableModel model, Collection bookRandomizationEntries, String title,
                    String action, String flowType) throws Exception {

        String index = title.substring(title.indexOf(":") + 1);
        String tableId = "bookRandomizationEntries" + index;
        Table table = model.getTableInstance();
        table.setTitle("Randomization Book");
        table.setAutoIncludeParameters(true);
        table.setAction(model.getContext().getContextPath() + action);
        table.setTableId(tableId);
        table.setItems(bookRandomizationEntries);
        table.setOnInvokeAction("uploadBook('" + tableId + "', '" + index + "','"+ flowType + "')");
        table.setShowPagination(true);
        table.setFilterable(false);
        table.setImagePath(model.getContext().getContextPath() + "/images/table/*.gif");
        table.setRowsDisplayed(10);
        model.addTable(table);

        Row row = model.getRowInstance();
        row.setHighlightRow(Boolean.TRUE);
        model.addRow(row);

        Column columnPosition = model.getColumnInstance();
        columnPosition.setProperty("position");
        columnPosition.setCell((BookRandomizationCustomCell.class).getName());
        columnPosition.setTitle("Position");
        model.addColumn(columnPosition);

        Column columnArm = model.getColumnInstance();
        columnArm.setProperty("arm.name");
        columnArm.setTitle("Arm Name");
        columnArm.setCell((BookRandomizationCustomCell.class).getName());
        model.addColumn(columnArm);

        return model.assemble();
    }

    private void clearStratumGroups(Epoch tEpoch){
    	for(StratumGroup sg: tEpoch.getStratumGroups()){
    		sg.getBookRandomizationEntry().clear();
    	}
    }

    public StudyDao getStudyDao() {
        return studyDao;
    }

    public void setStudyDao(StudyDao studyDao) {
        this.studyDao = studyDao;
    }
}


text:
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options.internet', function() {

  /**
   * Network settings constants. These enums usually match their C++
   * counterparts.
   */
  function Constants() {}
  // Minimum length for wireless network password.
  Constants.MIN_WIRELESS_PASSWORD_LENGTH = 5;
  // Minimum length for SSID name.
  Constants.MIN_WIRELESS_SSID_LENGTH = 1;
  // Cellular activation states:
  Constants.ACTIVATION_STATE_UNKNOWN             = 0;
  Constants.ACTIVATION_STATE_ACTIVATED           = 1;
  Constants.ACTIVATION_STATE_ACTIVATING          = 2;
  Constants.ACTIVATION_STATE_NOT_ACTIVATED       = 3;
  Constants.ACTIVATION_STATE_PARTIALLY_ACTIVATED = 4;
  // Network types:
  Constants.TYPE_UNKNOWN   = 0;
  Constants.TYPE_ETHERNET  = 1;
  Constants.TYPE_WIFI      = 2;
  Constants.TYPE_WIMAX     = 3;
  Constants.TYPE_BLUETOOTH = 4;
  Constants.TYPE_CELLULAR  = 5;
  Constants.TYPE_VPN       = 6;
  // ONC sources:
  Constants.ONC_SOURCE_USER_IMPORT   = 1;
  Constants.ONC_SOURCE_DEVICE_POLICY = 2;
  Constants.ONC_SOURCE_USER_POLICY   = 3;

  /**
   * Creates a new network list div.
   * @param {Object=} opt_propertyBag Optional properties.
   * @constructor
   * @extends {HTMLDivElement}
   */
  var NetworkElement = cr.ui.define('div');

  NetworkElement.prototype = {
    __proto__: HTMLDivElement.prototype,

    /** @inheritDoc */
    decorate: function() {
      this.addEventListener('click', this.handleClick_);
    },

    /**
     * Loads given network list.
     * @param {Array} networks An array of network object.
     */
    load: function(networks) {
      this.textContent = '';

      for (var i = 0; i < networks.length; ++i) {
        this.appendChild(new NetworkItem(networks[i]));
      }
    },

    /**
     * Handles click on network list and triggers actions when clicked on
     * a NetworkListItem button.
     * @private
     * @param {!Event} e The click event object.
     */
    handleClick_: function(e) {
      // We shouldn't respond to click events selecting an input,
      // so return on those.
      if (e.target.tagName == 'INPUT') {
        return;
      }
      // Handle left button click
      if (e.button == 0) {
        var el = e.target;
        // If click is on action buttons of a network item.
        if (!(el.buttonType && el.networkType && el.servicePath)) {
          if (el.buttonType) {
            return;
          }
          // If click is on a network item or its label, walk up the DOM tree
          // to find the network item.
          var item = el;
          while (item && !item.data) {
            item = item.parentNode;
          }
          if (item.connecting)
            return;

          if (item) {
            var data = item.data;
            // Don't try to connect to Ethernet or unactivated Cellular.
            if (data && (data.networkType == 1 ||
                        (data.networkType == 5 && data.activation_state != 1)))
              return;
            // If clicked on other networks item.
            if (data && data.servicePath == '?') {
              chrome.send('buttonClickCallback',
                          [String(data.networkType),
                           data.servicePath,
                           'connect']);
            }
          }
        }
      }
    }
  };

  /**
   * Creates a new network item.
   * @param {Object} network The network this represents.
   * @constructor
   * @extends {HTMLDivElement}
   */
  function NetworkItem(network) {
    var el = cr.doc.createElement('div');
    el.data = network;
    NetworkItem.decorate(el);
    return el;
  }

  /**
   * Decorates an element as a network item.
   * @param {!HTMLElement} el The element to decorate.
   */
  NetworkItem.decorate = function(el) {
    el.__proto__ = NetworkItem.prototype;
    el.decorate();
  };

  NetworkItem.prototype = {
    __proto__: HTMLDivElement.prototype,

    /** @inheritDoc */
    decorate: function() {
      this.className = 'network-item';
      this.connectable = this.data.connectable;
      this.connected = this.data.connected;
      this.connecting = this.data.connecting;
      this.other = this.data.servicePath == '?';
      this.id = this.data.servicePath;

      // Insert a div holding the policy-managed indicator.
      var policyIndicator = this.ownerDocument.createElement('div');
      policyIndicator.className = 'controlled-setting-indicator';
      cr.ui.decorate(policyIndicator, options.ControlledSettingIndicator);

      if (this.data.policyManaged) {
        policyIndicator.controlledBy = 'policy';
        policyIndicator.setAttribute('textPolicy',
                                     localStrings.getString('managedNetwork'));
      }
      this.appendChild(policyIndicator);

      // textDiv holds icon, name and status text.
      var textDiv = this.ownerDocument.createElement('div');
      textDiv.className = 'network-item-text';
      if (this.data.iconURL) {
        textDiv.style.backgroundImage = url(this.data.iconURL);
      }

      var nameEl = this.ownerDocument.createElement('div');
      nameEl.className = 'network-name-label';
      nameEl.textContent = this.data.networkName;
      textDiv.appendChild(nameEl);

      if (this.other) {
        // No status and buttons for "Other..."
        this.appendChild(textDiv);
        return;
      }

      // Only show status text if not empty.
      if (this.data.networkStatus) {
        var statusEl = this.ownerDocument.createElement('div');
        statusEl.className = 'network-status-label';
        statusEl.textContent = this.data.networkStatus;
        textDiv.appendChild(statusEl);
      }

      this.appendChild(textDiv);

      var spacerDiv = this.ownerDocument.createElement('div');
      spacerDiv.className = 'network-item-box-spacer';
      this.appendChild(spacerDiv);

      var buttonsDiv = this.ownerDocument.createElement('div');
      var self = this;
      if (!this.data.remembered) {
        var no_plan =
            this.data.networkType == Constants.TYPE_CELLULAR &&
            this.data.needs_new_plan;
        var show_activate =
          (this.data.networkType == Constants.TYPE_CELLULAR &&
           this.data.activation_state !=
               Constants.ACTIVATION_STATE_ACTIVATED &&
           this.data.activation_state !=
               Constants.ACTIVATION_STATE_ACTIVATING);

        // Show [Activate] button for non-activated Cellular network.
        if (show_activate || no_plan) {
          var button_name = no_plan ? 'buyplan_button' : 'activate_button';
          buttonsDiv.appendChild(
              this.createButton_(button_name, 'activate',
                                 function(e) {
                chrome.send('buttonClickCallback',
                            [String(self.data.networkType),
                             self.data.servicePath,
                             'activate']);
              }));
        }
        // Show disconnect button if not ethernet.
        if (this.data.networkType != Constants.TYPE_ETHERNET &&
            this.data.connected) {
          buttonsDiv.appendChild(
              this.createButton_('disconnect_button', 'disconnect',
                                  function(e) {
                 chrome.send('buttonClickCallback',
                             [String(self.data.networkType),
                              self.data.servicePath,
                              'disconnect']);
               }));
        }
        if (!this.data.connected && !this.data.connecting) {
          // connect button (if not ethernet and not showing activate button)
          if (this.data.networkType != Constants.TYPE_ETHERNET &&
              !show_activate && !no_plan) {
            buttonsDiv.appendChild(
                this.createButton_('connect_button', 'connect',
                                   function(e) {
                  chrome.send('buttonClickCallback',
                              [String(self.data.networkType),
                               self.data.servicePath,
                               'connect']);
                }));
          }
        }
        if (this.data.connected ||
                this.data.networkType == Constants.TYPE_ETHERNET ||
                this.data.networkType == Constants.TYPE_VPN ||
                this.data.networkType == Constants.TYPE_WIFI ||
                this.data.networkType == Constants.TYPE_CELLULAR) {
          buttonsDiv.appendChild(
              this.createButton_('options_button', 'options',
                                 function(e) {
                options.ProxyOptions.getInstance().setNetworkName(
                    self.data.networkName);
                chrome.send('buttonClickCallback',
                            [String(self.data.networkType),
                             self.data.servicePath,
                             'options']);
              }));
        }
      } else {
        // Put "Forget this network" button.
        var button = this.createButton_('forget_button', 'forget',
                                        function(e) {
                       chrome.send('buttonClickCallback',
                                   [String(self.data.networkType),
                                   self.data.servicePath,
                                   'forget']);
                     });
        button.disabled = this.data.policyManaged;
        buttonsDiv.appendChild(button);
      }
      this.appendChild(buttonsDiv);
    },

    /**
     * Creates a button for interacting with a network.
     * @param {Object} name The name of the localStrings to use for the text.
     * @param {Object} type The type of button.
     */
    createButton_: function(name, type, callback) {
      var buttonEl = this.ownerDocument.createElement('button');
      buttonEl.buttonType = type;
      buttonEl.textContent = localStrings.getString(name);
      buttonEl.addEventListener('click', callback);
      return buttonEl;
    }
  };

  /**
   * Whether the underlying network is connected. Only used for display purpose.
   * @type {boolean}
   */
  cr.defineProperty(NetworkItem, 'connected', cr.PropertyKind.BOOL_ATTR);

  /**
   * Whether the underlying network is currently connecting.
   * Only used for display purpose.
   * @type {boolean}
   */
  cr.defineProperty(NetworkItem, 'connecting', cr.PropertyKind.BOOL_ATTR);

  /**
   * Whether the underlying network is an other network for adding networks.
   * Only used for display purpose.
   * @type {boolean}
   */
  cr.defineProperty(NetworkItem, 'other', cr.PropertyKind.BOOL_ATTR);

  /**
   * Whether the underlying network is connectable.
   * @type {boolean}
   */
  cr.defineProperty(NetworkItem, 'connectable', cr.PropertyKind.BOOL_ATTR);

  return {
    Constants: Constants,
    NetworkElement: NetworkElement
  };
});

redpajama_set_name: RedPajamaGithub


text:
package batch

import (
	"github.com/tendermint/tendermint/crypto"
	"github.com/tendermint/tendermint/crypto/ed25519"
	"github.com/tendermint/tendermint/crypto/sr25519"
)

// CreateBatchVerifier checks if a key type implements the batch verifier interface.
// Currently only ed25519 & sr25519 supports batch verification.
func CreateBatchVerifier(pk crypto.PubKey) (crypto.BatchVerifier, bool) {
	switch pk.Type() {
	case ed25519.KeyType:
		return ed25519.NewBatchVerifier(), true
	case sr25519.KeyType:
		return sr25519.NewBatchVerifier(), true
	}

	// case where the key does not support batch verification
	return nil, false
}

// SupportsBatchVerifier checks if a key type implements the batch verifier
// interface.
func SupportsBatchVerifier(pk crypto.PubKey) bool {
	switch pk.Type() {
	case ed25519.KeyType, sr25519.KeyType:
		return true
	}

	return false
}


text:
@import 'first.css';
@import 'second.css';
@import 'third.css';


text:
'use strict';

//Ranks service used to communicate Ranks REST endpoints
angular.module('ranks').factory('Ranks', ['$resource', function($resource) {
    return $resource('ranks/:rankId', {
        rankId: '@_id'
    }, {
        update: {
            method: 'PUT'
        },
        query: {
          method: 'GET',
          params: { sort: '-votes', limit: 100 },
          isArray: true
        }
    });
}]);


text:
'use strict';

const Strings = require('core-functions/strings');
const trim = Strings.trim;
const trimOrEmpty = Strings.trimOrEmpty;
const isBlank = Strings.isBlank;
const isNotBlank = Strings.isNotBlank;
const stringify = Strings.stringify;

const copying = require('core-functions/copying');
const copy = copying.copy;
const merging = require('core-functions/merging');
const merge = merging.merge;
const deep = {deep: true};

const streamEvents = require('./stream-events');

const lambdas = require('./lambdas');

const Arrays = require('core-functions/arrays');

const logging = require('logging-utils');

/**
 * Stage handling utilities (primarily for AWS Lambda usage), which include the following:
 * - Utilities for resolving or deriving the current stage (e.g. dev, qa, prod) from various sources.
 * - Utilities for configuration of stage handling.
 * - Configurable and default functions for generating stage-qualified stream and resource names.
 * - Configurable and default functions for extracting stages from stage-qualified stream and resource names.
 *
 * @module aws-core-utils/stages
 * @author Byron du Preez
 */
exports._$_ = '_$_'; //IDE workaround

// Stage handling configuration
exports.isStageHandlingConfigured = isStageHandlingConfigured;
exports.configureStageHandling = configureStageHandling;
exports.configureDefaultStageHandling = configureDefaultStageHandling;
exports.getDefaultStageHandlingSettings = getDefaultStageHandlingSettings;

// Functions providing access to configured stage handling settings & functions by name
exports.getStageHandlingSetting = getStageHandlingSetting;
exports.getStageHandlingFunction = getStageHandlingFunction;

// Stage resolution
exports.resolveStage = resolveStage;

// Stage resolution and configuration
exports.configureStage = configureStage;

// Stream name qualification
exports.toStageQualifiedStreamName = toStageQualifiedStreamName;
exports.extractStageFromQualifiedStreamName = extractStageFromQualifiedStreamName;
exports.extractNameAndStageFromQualifiedStreamName = extractNameAndStageFromQualifiedStreamName;

// Resource name qualification
exports.toStageQualifiedResourceName = toStageQualifiedResourceName;
exports.extractStageFromQualifiedResourceName = extractStageFromQualifiedResourceName;
exports.extractNameAndStageFromQualifiedResourceName = extractNameAndStageFromQualifiedResourceName;

// noinspection JSUnusedGlobalSymbols
/**
 * Default implementations of specialized versions of some of the above functions, which are NOT meant to be used
 * directly and are ONLY exposed to facilitate re-using some of these functions if needed in a customised stage
 * handling configuration.
 */
exports.DEFAULTS = {
  // Alias conversion
  convertAliasToStage: convertAliasToStage,
  // Stage-suffixed stream name qualification
  toStageSuffixedStreamName: toStageSuffixedStreamName,
  extractStageFromSuffixedStreamName: extractStageFromSuffixedStreamName,
  extractNameAndStageFromSuffixedStreamName: extractNameAndStageFromSuffixedStreamName,
  // Stage-suffixed resource name qualification
  toStageSuffixedResourceName: toStageSuffixedResourceName,
  extractStageFromSuffixedResourceName: extractStageFromSuffixedResourceName,
  extractNameAndStageFromSuffixedResourceName: extractNameAndStageFromSuffixedResourceName,
  // Generic utils
  toStageSuffixedName: toStageSuffixedName,
  toCase: toCase
};

exports.FOR_TESTING_ONLY = {
  configureStageHandlingWithSettings: configureStageHandlingWithSettings
};

/**
 * The names of all of the standard stage handling settings.
 * @namespace
 */
const settingNames = {
  envStageName: 'envStageName',
  customToStage: 'customToStage',
  convertAliasToStage: 'convertAliasToStage',
  streamNameStageSeparator: 'streamNameStageSeparator',
  injectStageIntoStreamName: 'injectStageIntoStreamName',
  extractStageFromStreamName: 'extractStageFromStreamName',
  extractNameAndStageFromStreamName: 'extractNameAndStageFromStreamName',
  resourceNameStageSeparator: 'resourceNameStageSeparator',
  injectStageIntoResourceName: 'injectStageIntoResourceName',
  extractStageFromResourceName: 'extractStageFromResourceName',
  extractNameAndStageFromResourceName: 'extractNameAndStageFromResourceName',
  injectInCase: 'injectInCase',
  extractInCase: 'extractInCase'
};
exports.settingNames = settingNames;

/**
 * Returns true if stage handling is already configured on the given context; false otherwise.
 * @param {Object} context - the context to check
 * @returns {boolean} true if configured; false otherwise
 */
function isStageHandlingConfigured(context) {
  return context && context.stageHandling && typeof context.stageHandling === 'object';
}

/**
 * Configures the given context with the given stage handling settings, but only if stage handling is not already
 * configured on the given context OR if forceConfiguration is true. The stage handling settings determine how
 * {@linkcode resolveStage}, {@linkcode toStageQualifiedStreamName}, {@linkcode extractStageFromQualifiedStreamName},
 * {@linkcode toStageQualifiedResourceName}, {@linkcode extractStageFromQualifiedStreamName} and other internal
 * functions will behave when invoked.
 *
 * @param {Object|StandardContext|StageHandling|Logger} context - the context onto which to configure stage handling settings
 * @param {StageHandlingSettings} [context.stageHandling] - previously configured stage handling settings on the context (if any)
 * @param {StageHandlingSettings} settings - the new stage handling settings to use
 * @param {Object|StandardSettings|undefined} [otherSettings] - optional other configuration settings to use
 * @param {LoggingSettings|undefined} [otherSettings.logging] - optional logging settings to use to configure logging
 * @param {LoggingSettings|undefined} [otherSettings.loggingSettings] - LEGACY optional logging settings to use to
 *        configure logging (NB: otherSettings.loggingSettings will be ignored if otherSettings.logging is defined)
 * @param {Object|StandardOptions|undefined} [otherOptions] - optional other configuration options to use if no corresponding other settings are provided
 * @param {LoggingOptions|undefined} [otherOptions.logging] - optional logging options to use to configure logging
 * @param {LoggingOptions|undefined} [otherOptions.loggingOptions] - LEGACY optional logging options to use to configure
 *        logging (NB: otherOptions.loggingOptions will be ignored if otherOptions.logging is defined)
 * @param {boolean|undefined} [forceConfiguration] - whether or not to force configuration of the given settings, which
 * will override any previously configured stage handling settings on the given context
 * @return {StageHandling|StandardContext} the context object configured with stage handling settings and logging functionality
 */
function configureStageHandlingWithSettings(context, settings, otherSettings, otherOptions, forceConfiguration) {
  // Configure all dependencies if not configured
  configureDependencies(context, otherSettings, otherOptions, false);

  // If forceConfiguration is false check if the given context already has stage handling configured on it
  // and, if so, do nothing more and simply return the context as is (to prevent overriding an earlier configuration)
  if (!forceConfiguration && isStageHandlingConfigured(context)) {
    return context;
  }
  // Configure the stage handling settings
  context.stageHandling = settings;
  return context;
}

/**
 * Configures the given context with the default stage handling settings partially overridden by the given stage
 * handling options (if any), but only if stage handling is NOT already configured on the given context OR if
 * forceConfiguration is true.
 *
 * Default stage handling makes the following assumptions:
 * - Stages are all lowercase.
 * - AWS Lambda aliases are stages.
 * - The customToStage function is left undefined.
 * - A defaultStage is NOT defined (and it is probably not a good idea to set it in general).
 * - Stream names will be suffixed with an underscore and an uppercase stage.
 *   For example:
 *   - Injecting an unqualified stream name of "TestStream" with a stage of "qa" would give "TestStream_QA"
 *   - Extracting the stage from a qualified stream name of "My_Stream_PROD" would give "prod"
 * - Other resource names will also be suffixed with an underscore and an uppercase stage.
 *
 * Some or all of this default behaviour can be overridden using {@linkcode configureStageHandling}.
 *
 * @see {@linkcode configureStageHandling} for more information.
 *
 * @param {Object|StandardContext|StageHandling|Logger} context - the context onto which to configure the default stage handling settings
 * @param {StageHandlingSettings} [context.stageHandling] - previously configured stage handling settings on the context (if any)
 * @param {StageHandlingOptions|undefined} [options] - optional stage handling options to use to override the default options
 * @param {Object|StandardSettings|undefined} [otherSettings] - optional other configuration settings to use
 * @param {LoggingSettings|undefined} [otherSettings.logging] - optional logging settings to use to configure logging
 * @param {LoggingSettings|undefined} [otherSettings.loggingSettings] - LEGACY optional logging settings to use to
 *        configure logging (NB: otherSettings.loggingSettings will be ignored if otherSettings.logging is defined)
 * @param {Object|StandardOptions|undefined} [otherOptions] - optional other configuration options to use if no corresponding other settings are provided
 * @param {LoggingOptions|undefined} [otherOptions.logging] - optional logging options to use to configure logging
 * @param {LoggingOptions|undefined} [otherOptions.loggingOptions] - LEGACY optional logging options to use to configure
 *        logging (NB: otherOptions.loggingOptions will be ignored if otherOptions.logging is defined)
 * @param {boolean|undefined} [forceConfiguration] - whether or not to force configuration of the default settings, which
 * will override any previously configured stage handling settings on the given context
 * @return {StageHandling|StandardContext} the context object configured with stage handling settings (either existing or defaults or
 * overrides) and logging functionality
 */
function configureDefaultStageHandling(context, options, otherSettings, otherOptions, forceConfiguration) {
  const settings = getDefaultStageHandlingSettings(options);
  return configureStageHandlingWithSettings(context, settings, otherSettings, otherOptions, forceConfiguration);
}

/**
 * Returns the default stage handling settings partially overridden by the given stage handling options (if any).
 *
 * This function is used internally by {@linkcode configureDefaultStageHandling}, but could also be used in custom
 * configurations to get the default settings as a base to be overridden with your custom settings before calling
 * {@linkcode configureStageHandling}.
 *
 * @param {StageHandlingOptions|undefined} [options] - optional stage handling options to use to override the default options
 * @returns {StageHandlingSettings} a stage handling settings object
 */
function getDefaultStageHandlingSettings(options) {
  const settings = options && typeof options === 'object' ? copy(options, deep) : {};

  const defaultOptions = loadDefaultStageHandlingOptions();
  merge(defaultOptions, settings);

  const defaultSettings = {
    customToStage: undefined,
    convertAliasToStage: convertAliasToStage,

    injectStageIntoStreamName: toStageSuffixedStreamName,
    extractStageFromStreamName: extractStageFromSuffixedStreamName,
    extractNameAndStageFromStreamName: extractNameAndStageFromSuffixedStreamName,

    injectStageIntoResourceName: toStageSuffixedResourceName,
    extractStageFromResourceName: extractStageFromSuffixedResourceName,
    extractNameAndStageFromResourceName: extractNameAndStageFromSuffixedResourceName
  };
  return merge(defaultSettings, settings);
}

/**
 * Loads the default stage handling options from the local stages-options.json file and fills in any missing options with the
 * static default options.
 * @returns {StageHandlingOptions} the default stage handling options
 */
function loadDefaultStageHandlingOptions() {
  const options = require('./stages-options.json');
  const defaultOptions = options ? options.stageHandlingOptions : {};

  const defaults = {
    envStageName: 'STAGE',
    streamNameStageSeparator: '_',
    resourceNameStageSeparator: '_',
    injectInCase: 'upper',
    extractInCase: 'lower',
    defaultStage: undefined
  };
  return merge(defaults, defaultOptions);
}

/**
 * Returns the value of the named stage handling setting (if any) on the given context.
 * @param {StageHandling} context - the context from which to fetch the named setting's value
 * @param {string} settingName - the name of the stage handling setting
 * @returns {*|undefined} the value of the named setting (if any); otherwise undefined
 */
function getStageHandlingSetting(context, settingName) {
  return context && context.stageHandling && isNotBlank(settingName) && context.stageHandling[settingName] ?
    context.stageHandling[settingName] : undefined;
}

/**
 * Returns the function configured at the named stage handling setting on the given context (if any and if it's a real
 * function); otherwise returns undefined.
 * @param {StageHandling} context - the context from which to fetch the function
 * @param {string} settingName - the name of the stage handling setting
 * @returns {Function|undefined} the named function (if it's a function); otherwise undefined
 */
function getStageHandlingFunction(context, settingName) {
  const fn = getStageHandlingSetting(context, settingName);
  return typeof fn === 'function' ? fn : undefined;
}

/**
 * Configures the given context with the given stage handling settings (if any) otherwise with the default stage
 * handling settings partially overridden by the given stage handling options (if any), but only if stage handling is
 * not already configured on the given context OR if forceConfiguration is true.
 *
 * The distinction between options and settings is that options are meant to contain only non-function properties
 * typically loaded from a JSON file, whereas settings are meant to be constructed in code and hence can contain both
 * non-function properties and functions if needed.
 *
 * @param {Object|StandardContext|StageHandling|Logger} context - the context to configure
 * @param {StageHandlingSettings|undefined} [settings] - optional stage handling settings to use to configure stage handling
 * @param {StageHandlingOptions|undefined} [options] - optional stage handling options to use to override default options
 * @param {Object|StandardSettings|undefined} [otherSettings] - optional other settings to use to configure dependencies
 * @param {LoggingSettings|undefined} [otherSettings.logging] - optional logging settings to use to configure logging
 * @param {LoggingSettings|undefined} [otherSettings.loggingSettings] - LEGACY optional logging settings to use to
 *        configure logging (NB: otherSettings.loggingSettings will be ignored if otherSettings.logging is defined)
 * @param {Object|StandardOptions|undefined} [otherOptions] - optional other options to use to configure dependencies if corresponding settings are not provided
 * @param {LoggingOptions|undefined} [otherOptions.logging] - optional logging options to use to configure logging
 * @param {LoggingOptions|undefined} [otherOptions.loggingOptions] - LEGACY optional logging options to use to configure
 *        logging (NB: otherOptions.loggingOptions will be ignored if otherOptions.logging is defined)
 * @param {boolean|undefined} [forceConfiguration] - whether or not to force configuration of the given settings, which
 * will override any previously configured stage handling settings on the given context
 * @return {StageHandling|StandardContext} the given context object configured with stage handling settings and logging functionality
 */
function configureStageHandling(context, settings, options, otherSettings, otherOptions, forceConfiguration) {
  // Determine the stage handling settings to be used
  const settingsAvailable = settings && typeof settings === 'object';
  const optionsAvailable = options && typeof options === 'object';

  // Check if stage handling was already configured
  const stageHandlingWasConfigured = isStageHandlingConfigured(context);

  const defaultSettings = getDefaultStageHandlingSettings(options);

  const stageHandlingSettings = settingsAvailable ?
    merge(defaultSettings, settings) : defaultSettings;

  // Configure stage handling with the given or derived stage handling settings
  configureStageHandlingWithSettings(context, stageHandlingSettings, otherSettings, otherOptions, forceConfiguration);

  if (!settingsAvailable && !optionsAvailable && (forceConfiguration || !stageHandlingWasConfigured)) {
    context.debug(`Stage handling was configured without settings or options - used default configuration`);
  }
  return context;
}

/**
 * Configures the given context with the stage handling dependencies (currently only logging) using the given other
 * settings and given other options.
 *
 * @param {Object|StandardContext|Logger} context - the context onto which to configure the given stage handling dependencies
 * @param {Object|StandardSettings|undefined} [otherSettings] - optional other configuration settings to use
 * @param {LoggingSettings|undefined} [otherSettings.logging] - optional logging settings to use to configure logging
 * @param {LoggingSettings|undefined} [otherSettings.loggingSettings] - LEGACY optional logging settings to use to
 *        configure logging (NB: otherSettings.loggingSettings will be ignored if otherSettings.logging is defined)
 * @param {Object|StandardOptions|undefined} [otherOptions] - optional other configuration options to use if no corresponding other settings are provided
 * @param {LoggingOptions|undefined} [otherOptions.logging] - optional logging options to use to configure logging
 * @param {LoggingOptions|undefined} [otherOptions.loggingOptions] - LEGACY optional logging options to use to configure
 *        logging (NB: otherOptions.loggingOptions will be ignored if otherOptions.logging is defined)
 * @param {boolean|undefined} [forceConfiguration] - whether or not to force configuration of the given settings, which
 * will override any previously configured dependencies' settings on the given context
 * @returns {Logger|StandardContext} the context object configured with stage handling dependencies (i.e. logging functionality)
 */
function configureDependencies(context, otherSettings, otherOptions, forceConfiguration) {
  // Configure logging if not configured yet
  logging.configureLogging(context, otherSettings ? (otherSettings.logging || otherSettings.loggingSettings) :
    undefined, otherOptions ? (otherOptions.logging || otherOptions.loggingOptions) : undefined, forceConfiguration);
}

/**
 * Attempts to resolve the stage from the given AWS event, AWS context and context using the following process:
 *
 * 1. Uses an explicit (or previously resolved) context.stage (if non-blank).
 *
 * 2. Uses the stage in the process.env[context.envStageName] environment variable (if any), which must be configured
 *    using AWS Lambda's new environment support. This is now the preferred way of configuring the current stage.
 *
 * 3. Uses the given context's stageHandling.customToStage function (if any) to attempt to somehow extract a stage from
 *    the AWS event and/or AWS context. This function has no default implementation and is merely provided as a hook for
 *    callers to add their own custom technique for resolving a stage, which will take precedence over all other steps
 *    other step 1, which uses an explicit context.stage.
 *
 * 4. Uses the AWS event's stage (if non-blank).
 *    NB: event.stage is NOT a standard AWS event property, but it may be set by API Gateway or tools like serverless.
 *
 * 5. Extracts the alias from the AWS context's invokedFunctionArn (if any) and then uses the given context's
 *    stageHandling.convertAliasToStage function (if any) to convert the extracted alias (if any) into a stage.
 *
 *    NB: This step relies on a convention of using Lambda aliases as stages. If you are NOT using such a convention,
 *    then disable this step by simply NOT configuring a stageHandling.convertAliasToStage function on the context (see
 *    {@linkcode configureStageHandling}).
 *
 * 6. Extracts the stream (or table) names from the AWS event's records' eventSourceARNs (if any) and then uses the
 *    given context's configured stageHandling.extractStageFromStreamName (or stageHandling.extractStageFromResourceName)
 *    function (if defined) to extract the stages from these stream (or table) names and returns the first non-blank
 *    stage (if any and if there are NOT multiple distinct results).
 *
 *    NB: This step relies on a convention of qualifying stream and table names with a stage. If you are NOT using such
 *    a convention, then disable this step by simply NOT configuring stageHandling.extractStageFromStreamName and
 *    stageHandling.extractStageFromResourceName functions on the context (see {@linkcode configureStageHandling}).
 *    Note that doing this will also disable the {@linkcode extractStageFromQualifiedStreamName} and
 *    {@linkcode extractStageFromQualifiedResourceName} functions.
 *
 * 7. Uses context.stageHandling.defaultStage (if non-blank).
 *
 * 8. Uses context.defaultStage (if non-blank).
 *
 * 9. Gives up and returns an empty string.
 *
 * NB: If no stage handling settings have been configured by the time this function is first called, then the given
 * context will be configured with the default stage handling settings (see {@linkcode configureDefaultStageHandling}).
 *
 * @param {Object} event - the AWS event
 * @param {Object} awsContext - the AWS context, which was passed to your lambda
 * @param {StageHandling|StageAware|Object} context - the context to use, which should ideally contain any and all of
 * the pre-configured stage handling settings
 * @returns {string} the resolved stage (if non-blank); otherwise an empty string
 */
function resolveStage(event, awsContext, context) {
  // Ensure at least default configuration is in place at this point
  configureDefaultStageHandling(context, undefined, undefined, require('./stages-options.json'), false);

  // Resolve extractInCase
  const extractInCase = getStageHandlingSetting(context, settingNames.extractInCase);

  // Attempt 1
  if (context && isNotBlank(context.stage)) {
    context.debug(`Resolved stage (${context.stage}) from context.stage)`);
    return toCase(trim(context.stage), extractInCase);
  }

  // Attempt 2
  const envStageName = getStageHandlingSetting(context, settingNames.envStageName);

  if (isNotBlank(envStageName)) {
    // Look up the current stage from the named process.env environment variable
    const stage = process.env[envStageName];

    if (isNotBlank(stage) && stage !== 'undefined' && stage !== 'null') {
      context.debug(`Resolved stage (${stage}) from process.env.${envStageName}`);
      return toCase(trim(stage), extractInCase);
    }
  }

  // Attempt 3
  const customToStage = getStageHandlingFunction(context, settingNames.customToStage);

  if (customToStage) {
    const stage = customToStage(event, awsContext, context);

    if (isNotBlank(stage)) {
      context.debug(`Resolved stage (${stage}) from custom function`);
      return toCase(trim(stage), extractInCase);
    }
  }

  // Attempt 4
  if (event && isNotBlank(event.stage)) {
    context.debug(`Resolved stage (${event.stage}) from event.stage)`);
    return toCase(trim(event.stage), extractInCase);
  }

  // Attempt 5
  // Check have all the pieces needed to extract an alias and apply the given convertAliasToStage function to it
  const convertAliasToStage = getStageHandlingFunction(context, settingNames.convertAliasToStage);

  if (convertAliasToStage && awsContext && isNotBlank(awsContext.functionVersion) && isNotBlank(awsContext.invokedFunctionArn)) {
    // Extract the alias
    const alias = lambdas.getAlias(awsContext);

    // If the alias is not blank, apply the convertAliasToStage function to it to derive a stage
    const stage = isNotBlank(alias) ? convertAliasToStage(trim(alias), event, awsContext, context) : '';

    if (isNotBlank(stage)) {
      context.debug(`Resolved stage (${stage}) from alias (${alias})`);
      return toCase(trim(stage), extractInCase);
    }
  }

  // Attempt 6
  const eventSources = Arrays.distinct(streamEvents.getEventSources(event).filter(isNotBlank));

  if (eventSources.length < 1) {
    // No eventSources
    context.warn(`Cannot resolve a stage from a stream or table name from an event WITHOUT an eventSource - event (${stringify(event)})!`);
  } else if (eventSources.length > 1) {
    // Multiple distinct eventSources
    context.warn(`Cannot resolve a stage from a stream or table name from an event with MULTIPLE distinct event sources ${stringify(eventSources)} - event (${stringify(event)})!`);
  } else {
    // Only 1 distinct eventSource
    const eventSource = eventSources[0];
    const eventSourceIsKinesis = eventSource === 'aws:kinesis';
    const eventSourceIsDynamoDB = eventSource === 'aws:dynamodb';
    let stages = [];

    if (!eventSourceIsKinesis && !eventSourceIsDynamoDB) {
      context.warn(`Cannot resolve a stage from a stream or table name from an event with an unexpected event source ${eventSource} - event (${stringify(event)})!`);
    } else {
      if (eventSourceIsKinesis) {
        // Check have all the pieces needed to extract a stream name and apply the given extractStageFromStreamName function to it
        const extractStageFromStreamName = getStageHandlingFunction(context, settingNames.extractStageFromStreamName);
        if (extractStageFromStreamName && event && event.Records) {
          stages = streamEvents.getKinesisEventSourceStreamNames(event)
            .map(streamName => isNotBlank(streamName) ? extractStageFromStreamName(trim(streamName), context) : '')
            .filter(isNotBlank);
        }
      } else if (eventSourceIsDynamoDB) {
        // Check have all the pieces needed to extract a table name and apply the given extractStageFromResourceName function to it
        const extractStageFromTableName = getStageHandlingFunction(context, settingNames.extractStageFromResourceName);
        if (extractStageFromTableName && event && event.Records) {
          stages = streamEvents.getDynamoDBEventSourceTableNames(event)
            .map(tableName => isNotBlank(tableName) ? extractStageFromTableName(trim(tableName), context) : '')
            .filter(isNotBlank);
        }
      }
      let stage = stages.length > 0 ? stages[0] : undefined;

      if (stages.length > 1) {
        const distinctStages = Arrays.distinct(stages);
        if (distinctStages > 1) {
          context.warn(`Ignoring arbitrary first stage (${stage}), since found MULTIPLE distinct stages ${stringify(distinctStages)} on event (${stringify(event)})!`);
          stage = ''; // too many choices, so choose none
        }
      }

      if (isNotBlank(stage)) {
        context.debug(`Resolved stage (${stage}) from event source ARN ${eventSourceIsKinesis ? 'stream' : 'table'} name`);
        return toCase(trim(stage), extractInCase);
      }
    }
  }

  // Attempt 7
  const stageHandlingDefaultStage = getStageHandlingSetting(context, 'defaultStage');

  if (isNotBlank(stageHandlingDefaultStage)) {
    context.debug(`Resolved stage (${event.stage}) from context.stageHandling.defaultStage)`);
    return toCase(trim(stageHandlingDefaultStage), extractInCase);
  }

  // Attempt 8
  const defaultStage = context && context.defaultStage ? context.defaultStage : undefined;

  if (isNotBlank(defaultStage)) {
    context.debug(`Resolved stage (${event.stage}) from context.defaultStage)`);
    return toCase(trim(defaultStage), extractInCase);
  }

  // Give up 9
  return '';
}

//noinspection JSUnusedLocalSymbols
/**
 * A default convertAliasToStage function that simply returns the given alias (if any) exactly as it is as the stage.
 *
 * @param {string} [alias] the alias (if any) previously extracted from the AWS context's invokedFunctionArn
 * @param {Object} event - the AWS event
 * @param {Object} awsContext - the AWS context
 * @param {StageHandling|Object} context - the context to use with stage handling settings and logging functionality
 * @returns {string} the resolved stage (if non-blank); otherwise an empty string
 */
function convertAliasToStage(alias, event, awsContext, context) {
  return isNotBlank(alias) ? trim(alias) : '';
}

// =====================================================================================================================
// Stream name qualification
// =====================================================================================================================

/**
 * Converts the given unqualified stream name (if non-blank) into a stage-qualified stream name by injecting the given
 * stage into it (if an injectStageIntoStreamName function is configured); otherwise returns the given stream name.
 *
 * This function uses the configured injectStageIntoStreamName function (if any) on the given context to determine its
 * actual behaviour.
 *
 * @param {string} unqualifiedStreamName - the unqualified name of the stream
 * @param {string} stage - the stage to inject
 * @param {StageHandling|Object} context - the context to use with stage handling settings and logging functionality
 * @returns {string} a stage-qualified stream name (or the given stream name)
 */
function toStageQualifiedStreamName(unqualifiedStreamName, stage, context) {
  return _toStageQualifiedName(unqualifiedStreamName, stage, settingNames.injectStageIntoStreamName, context);
}

/**
 * Extracts the stage from the given stage-qualified stream name (if non-blank and an extractStageFromStreamName
 * function is configured); otherwise returns an empty string.
 *
 * This function uses the configured extractStageFromStreamName function (if any) on the given context to determine its
 * actual behaviour.
 *
 * @param {string} qualifiedStreamName - the stage-qualified stream name
 * @param {StageHandling|Object} context - the context to use with stage handling settings and logging functionality
 * @returns {string} the stage extracted from the stage-qualified stream name or an empty string
 */
function extractStageFromQualifiedStreamName(qualifiedStreamName, context) {
  const stage = _extractStageFromQualifiedName(qualifiedStreamName, settingNames.extractStageFromStreamName, context);
  return isNotBlank(stage) ? stage :
    _extractNameAndStageFromQualifiedName(qualifiedStreamName, settingNames.extractNameAndStageFromStreamName, context)[1];
}

/**
 * Extracts the unqualified stream name and the stage from the given stage-qualified stream name (if non-blank and an
 * extractNameAndStageFromStreamName function is configured); otherwise returns the given stream name and an empty stage
 * string.
 *
 * This function uses the configured extractNameAndStageFromStreamName function (if any) on the given context to
 * determine its actual behaviour.
 *
 * @param {string} qualifiedStreamName - the stage-qualified stream name
 * @param {StageHandling|Object} context - the context to use with stage handling settings and logging functionality
 * @returns {[string,string]} an array containing: the unqualified name and the stage (if extracted); otherwise the
 * given name and an empty stage string
 */
function extractNameAndStageFromQualifiedStreamName(qualifiedStreamName, context) {
  return _extractNameAndStageFromQualifiedName(qualifiedStreamName, settingNames.extractNameAndStageFromStreamName, context);
}

// =====================================================================================================================
// Stream name qualification (default)
// =====================================================================================================================

/**
 * Returns a stage-suffixed version of the given unsuffixed stream name with an appended stage suffix, which will
 * contain the configured streamNameToStageSeparator followed by the given stage, which will be appended in uppercase,
 * lowercase or kept as is according to the configured injectInCase.
 *
 * @param {string} unsuffixedStreamName - the unsuffixed name of the stream
 * @param {string} stage - the stage to append
 * @param {StageHandling|Object} context - the context to use with stage handling settings and logging functionality
 * @returns {string} the stage-suffixed stream name
 */
function toStageSuffixedStreamName(unsuffixedStreamName, stage, context) {
  return _toStageSuffixedName(unsuffixedStreamName, stage, settingNames.streamNameStageSeparator, context);
}

/**
 * A default extractStageFromStreamName function that extracts the stage from the given stage-suffixed stream name.
 *
 * The suffix is extracted from the given stream name by taking everything after the last occurrence of the configured
 * streamNameStageSeparator (if any).
 *
 * @param {string} stageSuffixedStreamName - the stage-suffixed name of the stream
 * @param {StageHandling|Object} context - the context to use with stage handling settings and logging functionality
 * @returns {string} the stage (if extracted) or an empty string
 */
function extractStageFromSuffixedStreamName(stageSuffixedStreamName, context) {
  return _extractStageFromSuffixedName(stageSuffixedStreamName, settingNames.streamNameStageSeparator, context);
}

/**
 * A default extractNameAndStageFromStreamName function that extracts the unqualified name and stage from the given
 * stage-suffixed stream name.
 *
 * The unqualified name prefix is extracted from the given stream name by taking everything before the last occurrence
 * of the configured streamNameStageSeparator (if any).
 *
 * The stage suffix is extracted from the given stream name by taking everything after the last occurrence of the configured
 * streamNameStageSeparator (if any).
 *
 * @param {string} stageSuffixedStreamName - the stage-suffixed name of the stream
 * @param {StageHandling|Object} context - the context to use with stage handling settings and logging functionality
 * @returns {[string,string]} an array containing: the unqualified name and the stage (if extracted); otherwise the
 * given name and an empty stage string
 */
function extractNameAndStageFromSuffixedStreamName(stageSuffixedStreamName, context) {
  return _extractNameAndStageFromSuffixedName(stageSuffixedStreamName, settingNames.streamNameStageSeparator, context);
}

// =====================================================================================================================
// Resource name qualification
// =====================================================================================================================

/**
 * Converts the given unqualified resource name (if non-blank) into a stage-qualified resource name by injecting the
 * given stage into it (if an injectStageIntoResourceName function is configured); otherwise returns the given resource
 * name as is.
 *
 * This function uses the configured injectStageIntoResourceName function (if any) on the given context function to
 * determine its actual behaviour.
 *
 * @param {string} unqualifiedResourceName - the unqualified name of the resource
 * @param {string} stage - the stage to inject
 * @param {StageHandling|Object} context - the context to use with stage handling settings and logging functionality
 * @returns {string} a stage-qualified resource name
 */
function toStageQualifiedResourceName(unqualifiedResourceName, stage, context) {
  return _toStageQualifiedName(unqualifiedResourceName, stage, settingNames.injectStageIntoResourceName, context);
}

/**
 * Extracts the stage from the given stage-qualified resource name (if non-blank and an extractStageFromResourceName
 * function is configured); otherwise returns an empty string.
 *
 * This function uses the configured extractStageFromResourceName function (if any) on the given context to determine
 * its actual behaviour.
 *
 * @param {string} qualifiedResourceName - the stage-qualified resource name
 * @param {StageHandling|Object} context - the context to use with stage handling settings and logging functionality
 * @returns {string} the stage extracted from the stage-qualified resource name; or an empty string
 */
function extractStageFromQualifiedResourceName(qualifiedResourceName, context) {
  const stage = _extractStageFromQualifiedName(qualifiedResourceName, settingNames.extractStageFromResourceName, context);
  return isNotBlank(stage) ? stage :
    _extractNameAndStageFromQualifiedName(qualifiedResourceName, settingNames.extractNameAndStageFromResourceName, context)[1];

}

/**
 * Extracts the unqualified resource name and the stage from the given stage-qualified resource name (if non-blank and
 * an extractNameAndStageFromResourceName function is configured); otherwise returns the given resource name and an
 * empty stage string.
 *
 * This function uses the configured extractNameAndStageFromResourceName function (if any) on the given context to
 * determine its actual behaviour.
 *
 * @param {string} qualifiedResourceName - the stage-qualified resource name
 * @param {StageHandling|Object} context - the context to use with stage handling settings and logging functionality
 * @returns {[string,string]} an array containing: the unqualified name and the stage (if extracted); otherwise the
 * given name and an empty stage string
 */
function extractNameAndStageFromQualifiedResourceName(qualifiedResourceName, context) {
  return _extractNameAndStageFromQualifiedName(qualifiedResourceName, settingNames.extractNameAndStageFromResourceName, context);
}

// =====================================================================================================================
// Resource name qualification (default)
// =====================================================================================================================

/**
 * Returns a stage-suffixed version of the given unsuffixed resource name with an appended stage suffix, which will
 * contain the configured resourceNameToStageSeparator followed by the given stage, which will be appended in uppercase,
 * lowercase or kept as is according to the configured injectInCase.
 * @param {string} unsuffixedResourceName - the unsuffixed name of the resource (e.g. an unsuffixed DynamoDB table name)
 * @param {string} stage - the stage to append
 * @param {StageHandling|Object} context - the context to use with stage handling settings and logging functionality
 * @returns {string} the stage-suffixed resource name
 */
function toStageSuffixedResourceName(unsuffixedResourceName, stage, context) {
  return _toStageSuffixedName(unsuffixedResourceName, stage, settingNames.resourceNameStageSeparator, context);
}

/**
 * A default extractStageFromResourceName function that extracts the stage from the given stage-suffixed resource name.
 * The suffix is extracted from the given resource name by taking everything after the last occurrence of the configured
 * resourceNameStageSeparator (if any).
 *
 * @param {string} stageSuffixedResourceName the stage-suffixed name of the resource
 * @param {StageHandling|Object} context - the context to use with stage handling settings and logging functionality
 * @returns {string} the stage (if extracted) or an empty string
 */
function extractStageFromSuffixedResourceName(stageSuffixedResourceName, context) {
  return _extractStageFromSuffixedName(stageSuffixedResourceName, settingNames.resourceNameStageSeparator, context)
}

/**
 * A default extractNameAndStageFromResourceName function that extracts the unqualified name and stage from the given
 * stage-suffixed resource name.
 *
 * The unqualified name prefix is extracted from the given resource name by taking everything before the last occurrence
 * of the configured resourceNameStageSeparator (if any).
 *
 * The stage suffix is extracted from the given resource name by taking everything after the last occurrence of the
 * configured resourceNameStageSeparator (if any).
 *
 * @param {string} stageSuffixedResourceName - the stage-suffixed name of the resource
 * @param {StageHandling|Object} context - the context to use with stage handling settings and logging functionality
 * @returns {[string,string]} an array containing: the unqualified name and the stage (if extracted); otherwise the
 * given name and an empty stage string
 */
function extractNameAndStageFromSuffixedResourceName(stageSuffixedResourceName, context) {
  return _extractNameAndStageFromSuffixedName(stageSuffixedResourceName, settingNames.resourceNameStageSeparator, context);
}

// =====================================================================================================================
// Generic name qualification
// =====================================================================================================================

function _toStageQualifiedName(unqualifiedName, stage, injectStageIntoNameSettingName, context) {
  if (isNotBlank(unqualifiedName)) {
    configureDefaultStageHandling(context);

    // Resolve injectStageIntoName function to use
    const injectStageIntoName = getStageHandlingFunction(context, injectStageIntoNameSettingName);

    return injectStageIntoName ? injectStageIntoName(trim(unqualifiedName), stage, context) : unqualifiedName;
  }
  return unqualifiedName;
}

function _extractStageFromQualifiedName(qualifiedName, extractStageFromNameSettingName, context) {
  if (isNotBlank(qualifiedName)) {
    qualifiedName = trim(qualifiedName);
    configureDefaultStageHandling(context);

    // Resolve extractStageFromName function to use
    const extractStageFromName = getStageHandlingFunction(context, extractStageFromNameSettingName);
    return extractStageFromName ? trimOrEmpty(extractStageFromName(qualifiedName, context)) : '';
  }
  return '';
}

function _extractNameAndStageFromQualifiedName(qualifiedName, extractNameAndStageFromNameSettingName, context) {
  qualifiedName = trimOrEmpty(qualifiedName);
  if (isNotBlank(qualifiedName)) {
    configureDefaultStageHandling(context);

    // Resolve extractNameAndStageFromName function to use
    const extractNameAndStageFromName = getStageHandlingFunction(context, extractNameAndStageFromNameSettingName);
    if (extractNameAndStageFromName) {
      const nameAndStage = extractNameAndStageFromName(qualifiedName, context);
      if (Array.isArray(nameAndStage)) {
        if (nameAndStage.length !== 2) {
          const extractFnName = extractNameAndStageFromName.name ? extractNameAndStageFromName.name : 'extractNameAndStageFromName';
          context.warn(`Extracted name and stage ${stringify(nameAndStage)} contains ${nameAndStage.length} elements, but ${extractFnName} function should return an array with a resolved name & stage`);
        }
        return [trimOrEmpty(nameAndStage[0]), trimOrEmpty(nameAndStage[1])];
      }
      if (nameAndStage) {
        const extractFnName = extractNameAndStageFromName.name ? extractNameAndStageFromName.name : 'extractNameAndStageFromName';
        context.warn(`Ignoring extracted name and stage (${stringify(nameAndStage)}), since ${extractFnName} function MUST return an array with a resolved name & stage`);
      }
    }
  }
  return [qualifiedName, ''];
}

// =====================================================================================================================
// Generic name qualification (default)
// =====================================================================================================================

function _toStageSuffixedName(unsuffixedName, stage, separatorSettingName, context) {
  if (isNotBlank(unsuffixedName)) {
    configureDefaultStageHandling(context);

    // Resolve separator
    const separator = getStageHandlingSetting(context, separatorSettingName);

    // Resolve injectInCase
    const injectInCase = getStageHandlingSetting(context, settingNames.injectInCase);

    return toStageSuffixedName(unsuffixedName, separator, stage, injectInCase);
  }
  return '';
}

function _extractStageFromSuffixedName(stageSuffixedName, separatorSettingName, context) {
  if (isNotBlank(stageSuffixedName)) {
    configureDefaultStageHandling(context);

    // Resolve separator
    const separator = getStageHandlingSetting(context, separatorSettingName);

    // Resolve extractInCase
    const extractInCase = getStageHandlingSetting(context, settingNames.extractInCase);

    // Extract stage using separator and convert to case specified by extractInCase
    const suffixStartPos = stageSuffixedName.lastIndexOf(separator);
    return suffixStartPos !== -1 ? trimOrEmpty(toCase(stageSuffixedName.substring(suffixStartPos + 1), extractInCase)) : '';
  }
  return '';
}

function _extractNameAndStageFromSuffixedName(stageSuffixedName, separatorSettingName, context) {
  if (isNotBlank(stageSuffixedName)) {
    configureDefaultStageHandling(context);

    // Resolve separator
    const separator = getStageHandlingSetting(context, separatorSettingName);

    // Resolve extractInCase
    const extractInCase = getStageHandlingSetting(context, settingNames.extractInCase);

    // Extract stage using separator and convert to case specified by extractInCase
    const suffixStartPos = stageSuffixedName.lastIndexOf(separator);
    return suffixStartPos !== -1 ?
      [trimOrEmpty(stageSuffixedName.substring(0, suffixStartPos)), trimOrEmpty(toCase(stageSuffixedName.substring(suffixStartPos + 1), extractInCase))] :
      [trimOrEmpty(stageSuffixedName), ''];
  }
  return [trimOrEmpty(stageSuffixedName), ''];
}

/**
 * Returns a stage-suffixed version of the given unsuffixed name with an appended stage suffix, which will contain the
 * given separator followed by the given stage, which will be appended in uppercase, lowercase or kept as is according
 * to the given inCase.
 * @param {string} unsuffixedName - the unsuffixed name
 * @param {string} separator - the separator to use to separate the resource name from the stage
 * @param {string} stage - the stage to append
 * @param {string} inCase - specifies whether to convert the stage to uppercase (if 'uppercase' or 'upper') or to
 * lowercase (if 'lowercase' or 'lower') or keep it as provided (if 'as_is' or anything else)
 * @return {string} the stage-suffixed name
 */
function toStageSuffixedName(unsuffixedName, separator, stage, inCase) {
  const name = trim(unsuffixedName);
  const stageSuffix = isNotBlank(stage) ? `${trimOrEmpty(separator)}${toCase(trim(stage), inCase)}` : '';
  return isNotBlank(name) && isNotBlank(stageSuffix) && !name.endsWith(stageSuffix) ? `${name}${stageSuffix}` : name;
}

/**
 * Converts the given value to uppercase, lowercase or keeps it as is according to the given asCase argument.
 * @param value - the value to convert or keep as is
 * @param {string} asCase - specifies whether to convert the value to uppercase (if 'uppercase' or 'upper') or to
 * lowercase (if 'lowercase' or 'lower') or to keep it as provided (if 'as_is' or anything else)
 * @return {string} the converted or given value
 */
function toCase(value, asCase) {
  if (isNotBlank(value)) {
    // Convert the given asCase argument to lowercase to facilitate matching
    const caseToUse = trimOrEmpty(asCase && asCase.toLowerCase ? asCase.toLowerCase() : asCase);

    // Convert the given stage into the requested case
    return caseToUse === 'lowercase' || caseToUse === 'lower' ? value.toLowerCase() :
      caseToUse === 'uppercase' || caseToUse === 'upper' ? value.toUpperCase() : value;
  }
  return value;
}

/**
 * Returns context.stage from the given context if it is already defined; otherwise attempts to resolve the stage and
 * then, if non-blank, configure the stage on the given context (as context.stage); otherwise either raises an error
 * (if failFast is explicitly true) or logs a warning.
 * @param {StageHandling|StageAware|Object} context - a context with stage handling settings and logging functionality
 * on which to set the stage
 * @param {Object} event - the AWS event
 * @param {Object} awsContext - the AWS context, which was passed to your lambda
 * @param {boolean|undefined} [failFast] - an optional failFast flag, which is only used when a needed resolved stage is
 * blank and which determines whether the error will be raised (if failFast is explicitly true) or logged as a warning
 * @returns {StageAware} the given context with its existing stage or the resolved stage or an empty string stage.
 * @throws {Error} if failFast is explicitly true and a needed resolved stage is blank
 */
function configureStage(context, event, awsContext, failFast) {
  if (!context.stage) {
    const stage = resolveStage(event, awsContext, context);
    if (isBlank(stage)) {
      const errorMsg = `Failed to resolve stage from event (${JSON.stringify(event)}) and awsContext (${JSON.stringify(awsContext)}) - consider configuring a fallback stage on context.defaultStage (or on context.stageHandling.defaultStage via configureStageHandling); or, less preferable, on context.stage (as a complete override)`;
      // If failFast is explicitly true, then log and raise this error
      if (failFast === true) {
        context.error(errorMsg);
        throw new Error(errorMsg);
      }
      // Otherwise log the error as a warning and set context.stage to an empty string
      context.warn(errorMsg);
      context.stage = '';
    } else {
      // Resolved a non-blank stage!
      context.stage = stage;
    }
  }
  context.info(`Using stage (${context.stage})`);
  return context;
}


text:
<?php

namespace Xyster\Data\Symbol;
/**
 * A sort clause
 *
 * @category  Xyster
 * @package   Xyster_Data
 * @copyright Copyright LibreWorks, LLC (http://libreworks.net)
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD License
 */
class SortClause extends AbstractClause
{
    /**
     * @var \Xyster\Type\Type
     */
    static private $_type;

    /**
     * Creates a new Sort clause
     *
     * @param ISymbol $symbol The symbol or clause to add to this one
     */
    public function __construct(ISymbol $symbol = null)
    {
        if (!self::$_type instanceof \Xyster\Type\Type) {
            self::$_type = new \Xyster\Type\Type('\Xyster\Data\Symbol\Sort');
        }
        parent::__construct(self::$_type, $symbol);
    }
}


text:
#ifndef BDB_H_
#define BDB_H_

// TODO, could make this configurable
#define BDB_MAX_INDEX_ATTRIBUTE     256

#define BDB_FLAGS_ZERO            0
#define BDB_FILE_MODE_ZERO        0
#define BDB_TXN_NULL              NULL
#define BDB_PARENT_TXN_NULL       NULL

#define INDEX_KEY_TYPE_FWD     '0'
#define INDEX_KEY_TYPE_REV     '1'

#define MAX_DB_NAME_LEN         100

// candidates.c
void
AddToCandidates(
    VDIR_CANDIDATES * cans,
    db_seq_t     eId);

// config.c
extern DWORD
InitBdbConfig();

// indexer.c

int
CreateEntryIdIndex(
    DB_TXN *    txn,
    db_seq_t    eId,
    VDIR_BERVALUE *  encodedEntry,
    BOOLEAN     new);

int
CreateId2ChildrenIndex(
    DB_TXN *    txn,
    VDIR_BERVALUE *  pdn,
    db_seq_t    entryId);

int
DeleteEntryIdIndex(
    DB_TXN *    txn,
    db_seq_t    entryId);

int
DeleteParentIdIndex(
    PVDIR_BACKEND_CTX   pBECtx,
    VDIR_BERVALUE *          pdn,
    db_seq_t            entryId);

int
UpdateAttributeMetaData(
    DB_TXN *    txn,
    VDIR_ATTRIBUTE * attr,
    db_seq_t    entryId,
    ULONG       ulOPMask);

extern int
UpdateIndicesForAttribute(
    DB_TXN *    txn,
    VDIR_BERVALUE *  attrType,
    VDIR_BERVARRAY   attrVals, // Normalized Attribute Values
    unsigned    numVals,
    db_seq_t    entryId,
    ULONG       ulOPMask
    );

extern int
CreateParentIdIndex(
    PVDIR_BACKEND_CTX   pBECtx,
    VDIR_BERVALUE *          pdn,
    db_seq_t            entryId);

extern void
EntryIdToDBT(
    db_seq_t eId,
    DBT *    dbt);

// logmgmt.c
DWORD
InitializeDbChkpointThread(
    VOID
    );

// init.c
DWORD
BdbToBackendError(
    DWORD   dwBdbError,
    DWORD   dwFromBdbError,
    DWORD   dwToBEError,
    PVDIR_BACKEND_CTX   pBECtx);

#endif /* BDB_H_ */


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.applicationinsights.generated;

import com.azure.core.util.Context;

/** Samples for Workbooks GetByResourceGroup. */
public final class WorkbooksGetByResourceGroupSamples {
    /*
     * x-ms-original-file: specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbookGet1.json
     */
    /**
     * Sample code: WorkbookGet1.
     *
     * @param manager Entry point to ApplicationInsightsManager.
     */
    public static void workbookGet1(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) {
        manager
            .workbooks()
            .getByResourceGroupWithResponse(
                "my-resource-group", "deadb33f-5e0d-4064-8ebb-1a4ed0313eb2", null, Context.NONE);
    }

    /*
     * x-ms-original-file: specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbookManagedGet.json
     */
    /**
     * Sample code: WorkbookManagedGet.
     *
     * @param manager Entry point to ApplicationInsightsManager.
     */
    public static void workbookManagedGet(
        com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) {
        manager
            .workbooks()
            .getByResourceGroupWithResponse(
                "my-resource-group", "deadb33f-5e0d-4064-8ebb-1a4ed0313eb2", null, Context.NONE);
    }

    /*
     * x-ms-original-file: specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbookGet.json
     */
    /**
     * Sample code: WorkbookGet.
     *
     * @param manager Entry point to ApplicationInsightsManager.
     */
    public static void workbookGet(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) {
        manager
            .workbooks()
            .getByResourceGroupWithResponse(
                "my-resource-group", "deadb33f-5e0d-4064-8ebb-1a4ed0313eb2", null, Context.NONE);
    }
}


text:
class JSON_API JSONWorker {
public:
    static json_string RemoveWhiteSpaceAndComments(const json_string & value_t, bool escapeQuotes) json_nothrow json_read_priority;
	static json_char * RemoveWhiteSpaceAndCommentsC(const json_string & value_t, bool escapeQuotes) json_nothrow json_read_priority;

    #ifdef JSON_READ_PRIORITY
	   static JSONNode parse(const json_string & json) json_throws(std::invalid_argument) json_read_priority;
	   static JSONNode parse_unformatted(const json_string & json) json_throws(std::invalid_argument) json_read_priority;

		static JSONNode _parse_unformatted(const json_char * json, const json_char * const end) json_throws(std::invalid_argument) json_read_priority;

		static json_char * RemoveWhiteSpace(const json_string & value_t, size_t & len, bool escapeQuotes) json_nothrow json_read_priority;

	   static void DoArray(const internalJSONNode * parent, const json_string & value_t) json_nothrow json_read_priority;
	   static void DoNode(const internalJSONNode * parent, const json_string & value_t) json_nothrow json_read_priority;

	   #ifdef JSON_LESS_MEMORY
		  #define NAME_ENCODED this, true
		  #define STRING_ENCODED this, false
		  static json_string FixString(const json_string & value_t, const internalJSONNode * flag, bool which) json_nothrow json_read_priority;
	   #else
		  #define NAME_ENCODED _name_encoded
		  #define STRING_ENCODED _string_encoded
		  static json_string FixString(const json_string & value_t, bool & flag) json_nothrow json_read_priority;
	   #endif
    #endif

    #if defined(JSON_READ_PRIORITY) || defined(JSON_STREAM)
		#if (JSON_READ_PRIORITY == HIGH) && (!(defined(JSON_LESS_MEMORY)))
			template<json_char ch>
			static size_t FindNextRelevant(const json_string & value_t, const size_t pos) json_nothrow json_read_priority;
		#else
			static size_t FindNextRelevant(json_char ch, const json_string & value_t, const size_t pos) json_nothrow json_read_priority;
		#endif
    #endif
    static void UnfixString(const json_string & value_t, bool flag, json_string & res) json_nothrow;
JSON_PRIVATE
    #ifdef JSON_READ_PRIORITY
	   static json_char Hex(const json_char * & pos) json_nothrow;
	   static json_uchar UTF8(const json_char * & pos, const json_char * const end) json_nothrow;
    #endif
    #ifdef JSON_ESCAPE_WRITES
	   static json_string toUTF8(json_uchar p) json_nothrow;
    #endif
    #ifdef JSON_UNICODE
	   static void UTF(const json_char * & pos, json_string & result, const json_char * const end) json_nothrow;
	   #ifdef JSON_ESCAPE_WRITES
		  static json_string toSurrogatePair(json_uchar pos) json_nothrow;
	   #endif
    #endif
    #ifdef JSON_READ_PRIORITY
	   static void SpecialChar(const json_char * & pos, const json_char * const end, json_string & res) json_nothrow;
	   static void NewNode(const internalJSONNode * parent, const json_string & name, const json_string & value, bool array) json_nothrow;
    #endif
private:
    JSONWorker(void);
};

#endif


text:
package com.flipkart.fdp.migration.distcp.codec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.security.authentication.client.AuthenticationException;

import com.flipkart.fdp.migration.distcp.core.MirrorDCMImpl.FileTuple;
import com.flipkart.fdp.migration.distcp.utils.MirrorUtils;

public class GenericHadoopCodec implements DCMCodec {

	private FileSystem fs = null;

	public GenericHadoopCodec(FileSystem fs) {

		this.fs = fs;
	}

	public OutputStream createOutputStream(Configuration conf, String path,
			boolean append) throws IOException {
		if (append)
			return fs.append(new Path(path));
		else
			return fs.create(new Path(path));
	}

	public InputStream createInputStream(Configuration conf, String path)
			throws IOException {

		return fs.open(new Path(path));

	}

	public boolean deleteSoureFile(String path) throws IOException {
		return fs.delete(new Path(path), false);
	}

	public boolean isSplitable() {

		return false;
	}

	public List<FileTuple> getInputPaths(String path,
			Collection<String> excludeList) throws Exception {

		return getInputPaths(Arrays.asList(new String[] { path }), excludeList);
	}

	public List<FileTuple> getInputPaths(Collection<String> paths,
			Collection<String> excludeList) throws Exception {

		System.out.println("A total of " + paths.size() + " paths to scan...");

		List<FileTuple> fileList = new ArrayList<FileTuple>();
		List<String> inputPaths = new ArrayList<String>();

		// Process regular expression based paths
		for (String path : paths) {

			System.out.println("Processing path: " + path);
			FileStatus[] stats = fs.globStatus(new Path(path));

			for (FileStatus fstat : stats) {
				if (fstat.isFile()) {
					fileList.add(new FileTuple(MirrorUtils.getSimplePath(fstat
							.getPath()), fstat.getLen(), fstat
							.getModificationTime()));
				} else {
					inputPaths.add(MirrorUtils.getSimplePath(fstat.getPath()));
				}
			}
		}

		if (inputPaths.size() > 0) {

			for (String path : inputPaths) {

				List<FileTuple> fstat = getFileStatusRecursive(new Path(path),
						excludeList);
				fileList.addAll(fstat);
			}
		}
		return fileList;
	}

	public List<FileTuple> getFileStatusRecursive(Path path,
			Collection<String> excludeList) throws MalformedURLException,
			IOException, AuthenticationException {

		List<FileTuple> response = new ArrayList<FileTuple>();

		FileStatus file = fs.getFileStatus(path);
		if (file != null && file.isFile()) {
			response.add(new FileTuple(
					MirrorUtils.getSimplePath(file.getPath()), file.getLen(),
					file.getModificationTime()));
			return response;
		}

		FileStatus[] fstats = fs.listStatus(path);

		if (fstats != null && fstats.length > 0) {

			for (FileStatus fstat : fstats) {

				if (fstat.isDirectory()
						&& !excludeList.contains(MirrorUtils
								.getSimplePath(fstat.getPath()))) {

					response.addAll(getFileStatusRecursive(fstat.getPath(),
							excludeList));
				} else {

					response.add(new FileTuple(MirrorUtils.getSimplePath(fstat
							.getPath()), fstat.getLen(), fstat
							.getModificationTime()));
				}
			}
		}
		return response;
	}

	@Override
	public boolean isExistsPath(String path) throws IOException {
		return fs.exists(new Path(path));
	}

	public void close() throws IOException {
		IOUtils.closeStream(fs);

	}
}


text:
package br.com.dbsoft.ui.component.li;

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.FacesRenderer;

import br.com.dbsoft.ui.component.DBSRenderer;
import br.com.dbsoft.ui.core.DBSFaces;

@FacesRenderer(componentFamily=DBSFaces.FAMILY, rendererType=DBSLi.RENDERER_TYPE)
public class DBSLiRenderer extends DBSRenderer {

	@Override
	public void encodeBegin(FacesContext pContext, UIComponent pComponent)
			throws IOException {
		if (!pComponent.isRendered()){return;}
		DBSLi xLi = (DBSLi) pComponent;
		ResponseWriter xWriter = pContext.getResponseWriter();
		String xClass = "";
		if (xLi.getStyleClass()!=null){
			xClass = xClass + xLi.getStyleClass() + " ";
		}
		String xClientId = xLi.getClientId(pContext);
		xWriter.startElement("li", xLi);
			if (shouldWriteIdAttribute(xLi)){
				DBSFaces.encodeAttribute(xWriter, "id", xClientId);
				DBSFaces.encodeAttribute(xWriter, "name", xClientId);
			}
			if (xClass!=""){
				DBSFaces.encodeAttribute(xWriter, "class", xClass);
			}
			DBSFaces.encodeAttribute(xWriter, "style", xLi.getStyle());
			DBSFaces.renderChildren(pContext, xLi);
	}

	@Override
	public void encodeEnd(FacesContext pContext, UIComponent pComponent) throws IOException{
		if (!pComponent.isRendered()){return;}
		ResponseWriter xWriter = pContext.getResponseWriter();
		xWriter.endElement("li");
	}
}


text:
#region Licence

#endregion

using System.CodeDom;

namespace WmcSoft.CodeBuilders.Policies
{
    public class AddPropertySetterRule : CodePolicyRule
    {

        public override void Apply(CodeCompileUnit codeCompileUnit, CodeTypeDeclaration codeTypeDeclaration, CodeTypeMember codeTypeMember)
        {
            var codeMemberProperty = codeTypeMember as CodeMemberProperty;
            if (codeTypeMember != null) {
                codeMemberProperty.HasSet = true;
            }
        }
    }
}


text:
var content = require('./content');
var queryComparator = require('./query-comparator');

var filterRequestHeader = function (req, ignoreHeaders) {
    return function (handler) {
        return content.matchesHeader(req, handler.request, ignoreHeaders);
    };
};

var filterRequestBody = function (req) {
    return function (handler) {
        return content.matchesBody(req, handler.request);
    };
};

var filterSchema = function (req) {
    return function (handler) {
        return content.matchesSchema(req, handler.request);
    };
};

exports.filterHandlers = function (req, handlers, ignoreHeaders) {
    if (handlers) {
        var filteredHandlers;

        handlers.sort(content.contentTypeComparator);

        var queryParams = req.query;
        if (Object.keys(queryParams).length === 0) {
            handlers.sort(queryComparator.noParamComparator);
        } else {
            queryComparator.countMatchingQueryParms(handlers, queryParams);
            handlers.sort(queryComparator.queryParameterComparator);
        }

        filteredHandlers = handlers.filter(filterRequestHeader(req, ignoreHeaders));

        var matchRequestBodyHandlers = filteredHandlers.filter(filterRequestBody(req));

        if (matchRequestBodyHandlers.length > 0) {
            return matchRequestBodyHandlers[0];
        }

        var matchSchemaHandlers = filteredHandlers.filter(filterSchema(req));

        if (matchSchemaHandlers.length > 0) {
            return matchSchemaHandlers[0];
        }
    }

    return null;
};


text: namespace chrono {}