text:
package com.esri.gpt.catalog.schema;
import com.esri.gpt.framework.jsf.MessageBroker;
import com.esri.gpt.framework.util.DateProxy;
import com.esri.gpt.framework.util.Val;
import com.esri.gpt.framework.xml.DomUtil;
import java.util.ArrayList;
import java.util.logging.Logger;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Content component associated with a metadata schema.
 *

 * The component is configured from a node with a schema configuration
 * XML document.
 *

 * Example:

 * <content select="/gmd:MD_Metadata/gmd:fileIdentifier/gco:CharacterString"/>
 */
public class Content extends Component {

  // class variables =============================================================

  /** Logger */
  private static Logger LOGGER = Logger.getLogger(Content.class.getName());

  /** GCO List node type = "gcoList" */
  public static final String NODETYPE_GCOLIST = "gcoList";

  /**
   * ISO code list value = "isoCodeListValue"
   *

   * This node type is represented by a duplication of an ISO code in
   * both a codeListValue attribute and the text node of the
   * attributes's parent element.
   */
  public static final String NODETYPE_ISOCODELISTVALUE = "isoCodeListValue";

  /** List node type = "list" */
  public static final String NODETYPE_LIST = "list";

  /** Single node type = "single" (this is the default) */
  public static final String NODETYPE_SINGLE = "single";

  /** Single node type = "single" (this is the default) */
  public static final String NODETYPE_PAIRRIGHTVALUE = "pairRightValue";

  /** Single node type = "single" (this is the default) */
  public static final String NODETYPE_PAIRLEFTVALUE = "pairLeftValue";

  // instance variables ==========================================================
  private Codes         _codes;
  private String        _delete = "";
  private boolean       _deleteIfEmpty = false;
  private boolean       _deleteParentIfEmpty = false;
  private ContentValues _multipleValues;
  private String        _nilReasonPath = "";
  private String        _nodeType = Content.NODETYPE_SINGLE;
  private String        _select = "";
  private ContentValue  _singleValue;
  private String        _update = "";
  private boolean       _useSelectForUpdate = false;

  // constructors ================================================================

  /** Default constructor. */
  public Content() {
    this(null);
  }

  /**
   * Construct by duplicating an existing object.
   * @param objectToDuplicate the object to duplicate
   */
  public Content(Content objectToDuplicate) {
    super(objectToDuplicate);
    if (objectToDuplicate == null) {
      setCodes(new Codes());
      setSingleValue(new ContentValue());
      setMultipleValues(new ContentValues());
    } else {
      setCodes(new Codes(objectToDuplicate.getCodes()));
      setNodeType(objectToDuplicate.getNodeType());
      setSingleValue(objectToDuplicate.getSingleValue().duplicate());
      setMultipleValues(new ContentValues(objectToDuplicate.getMultipleValues()));
      setSelect(objectToDuplicate.getSelect());
      setUpdate(objectToDuplicate.getUpdate());
      setDelete(objectToDuplicate.getDelete());
      setNilReasonPath(objectToDuplicate.getNilReasonPath());
      setUseSelectForUpdate(objectToDuplicate.getUseSelectForUpdate());
      setDeleteIfEmpty(objectToDuplicate.getDeleteIfEmpty());
      setDeleteParentIfEmpty(objectToDuplicate.getDeleteParentIfEmpty());
    }
  }

  // properties ==================================================================

  /**
   * Gets the codes for this parameter.
   * @return the value codes
   */
  public Codes getCodes() {
    return _codes;
  }
  /**
   * Sets the codes for this parameter.
   * @param codes the value codes
   */
  protected void setCodes(Codes codes) {
    _codes = codes;
    if (_codes == null) _codes = new Codes();
  }

  /**
   * Gets the XPath expression used to select nodes for deletion when an updated value is empty.
   * @return the delete expression
   */
  public String getDelete() {
    return _delete;
  }
  /**
   * Sets the XPath expression used to select nodes for deletion when an updated value is empty.
   * @param expression the delete expression
   */
  public void setDelete(String expression) {
    _delete = Val.chkStr(expression);
  }

  /**
   * Indicates if the node associated with the update expression should be
   * deleted if the updated value is empty.
   * @return true if the node should be deleted when the updated value is empty
   */
  public boolean getDeleteIfEmpty() {
    return _deleteIfEmpty;
  }
  /**
   * Indicates if the node(s) associated with the update expression should be
   * deleted if the updated value is empty.
   * @param deleteIfEmpty true if the node should be deleted when the updated value is empty
   */
  public void setDeleteIfEmpty(boolean deleteIfEmpty) {
    _deleteIfEmpty = deleteIfEmpty;
  }

  /**
   * Indicates if the parent node associated with the update expression should be
   * deleted if the updated value is empty.
   * @return true if the parent node should be deleted when the updated value is empty
   */
  public boolean getDeleteParentIfEmpty() {
    return _deleteParentIfEmpty;
  }
  /**
   * Indicates if the node(s) associated with the update expression should be deleted if the
   * updated value is empty.
   * @param deleteIfEmpty true if the node should be deleted when the updated value is empty
   */
  public void setDeleteParentIfEmpty(boolean deleteIfEmpty) {
    _deleteParentIfEmpty = deleteIfEmpty;
  }

  /**
   * Gets the multiple value list.
   * @return the multiple value list
   */
  public ContentValues getMultipleValues() {
    return _multipleValues;
  }
  /**
   * Sets the multiple value list
   * @param values the multiple value list
   */
  protected void setMultipleValues(ContentValues values) {
    _multipleValues = values;
    if (_multipleValues == null) _multipleValues = new ContentValues();
  }

  /**
   * Gets the XPath expression used to a ISO nil-reason attribute associated with this element.
   * @return the nil-reason expression
   */
  public String getNilReasonPath() {
    return _nilReasonPath;
  }
  /**
   * Sets the XPath expression used to a ISO nil-reason attribute associated with this element.
   * @param expression the nil-reason expression
   */
  public void setNilReasonPath(String expression) {
    _nilReasonPath = Val.chkStr(expression);
  }

  /**
   * Gets the node type.
   * @return the node type
   */
  public String getNodeType() {
    return _nodeType;
  }
  /**
   * Sets the node type.
   * @param type the node type
   */
  public void setNodeType(String type) {
    type = Val.chkStr(type);
    if (type.equals("")) {
      _nodeType = Content.NODETYPE_SINGLE;
    } else if (type.equalsIgnoreCase(Content.NODETYPE_GCOLIST)) {
      _nodeType = Content.NODETYPE_GCOLIST;
    } else if (type.equalsIgnoreCase(Content.NODETYPE_ISOCODELISTVALUE)) {
      _nodeType = Content.NODETYPE_ISOCODELISTVALUE;
    } else if (type.equalsIgnoreCase(Content.NODETYPE_LIST)) {
      _nodeType = Content.NODETYPE_LIST;
    } else if (type.equalsIgnoreCase(Content.NODETYPE_SINGLE)) {
      _nodeType = Content.NODETYPE_SINGLE;
    } else if (type.equalsIgnoreCase(Content.NODETYPE_PAIRLEFTVALUE)) {
      _nodeType = Content.NODETYPE_PAIRLEFTVALUE;
    } else if (type.equalsIgnoreCase(Content.NODETYPE_PAIRRIGHTVALUE)) {
      _nodeType = Content.NODETYPE_PAIRRIGHTVALUE;
    }else {
      _nodeType = Content.NODETYPE_SINGLE;
    }
  }

  /**
   * Gets the XPath selection expression.
   * @return the selection expression
   */
  public String getSelect() {
    return _select;
  }
  /**
   * Sets the XPath selection expression.
   * @param expression the selection expression
   */
  public void setSelect(String expression) {
    _select = Val.chkStr(expression);
  }

  /**
   * Gets the single value.
   * @return the single value
   */
  public ContentValue getSingleValue() {
    return _singleValue;
  }

  /**
   * Sets the single value.
   * @param value the single value
   */
  protected void setSingleValue(ContentValue value) {
    _singleValue = value;
    if (_singleValue == null) _singleValue = new ContentValue();
  }

  /**
   * Gets the XPath expression used to select nodes for update.
   * @return the update expression
   */
  public String getUpdate() {
    return _update;
  }
  /**
   * Sets the XPath expression used to select nodes for update.
   * @param expression the update expression
   */
  public void setUpdate(String expression) {
    _update = Val.chkStr(expression);
  }

  /**
   * Gets the status indicating if the selection expression should
   * be used for locating nodes during the update process.
   * @return true if the selection expression should be used for update
   */
  public boolean getUseSelectForUpdate() {
    return _useSelectForUpdate;
  }
  /**
   * Sets the status indicating if the selection expression should
   * be used for locating nodes during the update process.
   * @param useSelectForUpdate true if the selection expression
   *        should be used for update
   */
  public void setUseSelectForUpdate(boolean useSelectForUpdate) {
    _useSelectForUpdate = useSelectForUpdate;
  }

  // methods =====================================================================

  /**
   * Clears single and multiple values.
   */
  public void clearAllValues() {
    getSingleValue().clear();
    getMultipleValues().clear();
  }

  /**
   * Configures the object based upon a node loaded from a
   * schema configuration XML.
   *
The super.configure method should be invoked prior to any
   * sub-class configuration.
   *

   * The following attributes are configured:
   *
nodeType useSelectForUpdate deleteIfEmpty deleteParentIfEmpty select update delete nilReason
   *

   * The following child nodes are configured:
   *
codes
   * @param context the configuration context
   * @param node the configuration node
   * @param attributes the attributes of the configuration node
   */
  @Override
  public void configure(CfgContext context, Node node, NamedNodeMap attributes) {
    super.configure(context,node,attributes);

    // configure attributes
    setNodeType(DomUtil.getAttributeValue(attributes,"nodeType"));
    setSelect(DomUtil.getAttributeValue(attributes,"select"));
    setUpdate(DomUtil.getAttributeValue(attributes,"update"));
    setDelete(DomUtil.getAttributeValue(attributes,"delete"));
    setNilReasonPath(DomUtil.getAttributeValue(attributes,"nilReason"));
    setUseSelectForUpdate(Val.chkBool(
        DomUtil.getAttributeValue(attributes,"useSelectForUpdate"),false));
    setDeleteIfEmpty(Val.chkBool(
        DomUtil.getAttributeValue(attributes,"deleteIfEmpty"),false));
    setDeleteParentIfEmpty(Val.chkBool(
        DomUtil.getAttributeValue(attributes,"deleteParentIfEmpty"),false));

    // configure codes
    Node ndCodes = DomUtil.findFirst(node,"codes");
    if (ndCodes != null) {
      Node[] aryCodes = DomUtil.findChildren(ndCodes,"code");
      for (Node ndCode: aryCodes) {
        getCodes().add(context.getFactory().newCode(context,ndCode));
      }
    }

    // check to see if the selection expression should be used during
    // the update process
    if (getUseSelectForUpdate()) {
      setUpdate(getSelect());
    }
  }

  /**
   * Deletes nodes from a document based upon an XPath expression.
   * @param dom the metadata document template for the schema
   * @param xpath an XPath object configured with an appropriate
   *        Namespace context for the schema
   * @param expression the expression to use to delete the nodes
   * @throws XPathExpressionException if an expression fails
   * @throws SchemaException if the update fails
   */
  public static void deleteNodes(Document dom, XPath xpath, String expression)
    throws XPathExpressionException {
    expression = Val.chkStr(expression);
    if (expression.length() > 0) {
      NodeList nl = (NodeList)xpath.evaluate(expression,dom,XPathConstants.NODESET);
      for (int i=0;i<nl.getLength();i++) {
        Node node = nl.item(i);
        if (node.getParentNode() != null) {
          node.getParentNode().removeChild(node);
        }
      }
    }
  }

  /**
   * Produces a deep clone of the object.
   *
The duplication constructor is invoked.
   *
return new Content(this);
   */
  public Content duplicate() {
    return new Content(this);
  }

  /**
   * Appends property information for the component to a StringBuffer.
   *
The method is intended to support "FINEST" logging.
   *
super.echo should be invoked prior appending any local information.
   * @param sb the StringBuffer to use when appending information
   */
  @Override
  public void echo(StringBuffer sb) {
    super.echo(sb);
    sb.append(" nodeType=\"").append(getNodeType()).append("\"");
    sb.append(" useSelectForUpdate=\"").append(getUseSelectForUpdate()).append("\"");
    sb.append(" deleteIfEmpty=\"").append(getDeleteIfEmpty()).append("\"");
    sb.append(" deleteParentIfEmpty=\"").append(getDeleteParentIfEmpty()).append("\"");
    sb.append("\n select=\"").append(getSelect()).append("\"");
    sb.append("\n update=\"").append(getUpdate()).append("\"");
    sb.append("\n delete=\"").append(getDelete()).append("\"");
    if (this.getNilReasonPath().length() > 0) {
      sb.append("\n nilReason=\"").append(this.getNilReasonPath()).append("\"");
    }
    if ((getCodes().size() > 0)) {
      sb.append("\n").append(getCodes());
    }
    if (isSingleValue()) {
      sb.append("\n").append(getSingleValue());
    } else {
      sb.append("\n").append(getMultipleValues());
    }
  }

  /**
   * Evaluates the XPath select expression associated with a parameter.
   * @param dom the metadata document
   * @param xpath an XPath object configured with an appropriate
   *        Namespace context for the schema
   * @param parameter the associated parameter
   * @throws XPathExpressionException if an evaluation expression fails
   */
  public void evaluate(Document dom, XPath xpath, Parameter parameter)
    throws XPathExpressionException {
    clearAllValues();
    String sSelect = getSelect();
    LOGGER.finer("Evaluating xpath: "+sSelect);
    if (sSelect.length() > 0) {

      // evaluate single or multiple node values
      if (isSingleValue()) {
        String sValue = xpath.evaluate(sSelect,dom);
        getSingleValue().setValue(sValue);
      } else {
        ContentValues values = getMultipleValues();
        NodeList nl = (NodeList)xpath.evaluate(sSelect,dom,XPathConstants.NODESET);
        for (int i=0;i<nl.getLength();i++) {
          String sValue = nl.item(i).getTextContent();
          values.add(new ContentValue(sValue));
        }
      }
    }

    // check for an ISO nil-reason
    parameter.getValidation().setNilReasonValue("");
    String sNil = this.getNilReasonPath();
    if (sNil.length() > 0) {
      LOGGER.finer("Evaluating nilReason xpath: "+sNil);
      parameter.getValidation().setNilReasonValue(xpath.evaluate(sNil,dom));
    }
  }

  /**
   * Formats a value associated with a parameter.
   *

   * Currently, only Date type values are formatted.
   * @param parameter the associated parameter
   * @param value the value to format
   */
  public String formatValue(Parameter parameter, String value) {
    value = Val.chkStr(value);
    if (value.length() > 0) {
      if (parameter.getValidation().getValueType().equals(Validation.VALUETYPE_DATE)) {
        DateProxy dp = new DateProxy();
        dp.setDate(value);
        value = (dp.getDate());
      }
    }
    return value;
  }

  /**
   * Determines if the node type is of single value.
   * @return true if the node type is a single value type
   */
  public boolean isSingleValue() {
    return !getNodeType().equals(Content.NODETYPE_GCOLIST) &&
           !getNodeType().equals(Content.NODETYPE_LIST);
  }

  /**
   * Determines if the node value(s) is/are empty.
   * @return true if the node node value(s) is/are empty
   */
  public boolean isValueEmpty() {
    boolean bIsEmpty = true;
    if (isSingleValue()) {
      bIsEmpty = (getSingleValue().getValue().length() == 0);
    } else {
      for (ContentValue value: getMultipleValues()) {
        if (value.getValue().length() > 0) {
          bIsEmpty = false;
          break;
        }
      }
    }
    return bIsEmpty;
  }

  /**
   * Makes the display value for a parameter.
   *

   * The output component is suitable for display on the
   * metadata details page.
   * @param messageBroker the message broker
   * @param parameter the associated parameter
   * @return the UI input component
   */
  public String makeDisplayValue(MessageBroker messageBroker, Parameter parameter) {
    Codes codes = getCodes();
    if (isSingleValue()) {
      String sValue = formatValue(parameter,getSingleValue().getValue());
      sValue = codes.lookupDisplayValue(messageBroker,sValue);
      return sValue;
    } else {
      StringBuffer sb = new StringBuffer();
      String sDelimiter = ",";
      for (ContentValue value: getMultipleValues()) {
        String sValue = Val.chkStr(value.getValue());
        sValue = codes.lookupDisplayValue(messageBroker,sValue);
        if (sValue.length() > 0) {
          if (sb.length() > 0) {
            sb.append(sDelimiter).append(" ");
          }
          sb.append(sValue);
        }
      }
      return sb.toString();
    }
  }

  /**
   * Generates a String array of value(s) associated with the parameter.
   * @return the String array of values
   */
  public String[] toValueArray() {
    ArrayList<String> alValues = new ArrayList<String>();
    if (isSingleValue()) {
      alValues.add(getSingleValue().getValue());
    } else {
      for (ContentValue value: getMultipleValues()) {
        alValues.add(value.getValue());
      }
    }
    return alValues.toArray(new String[0]);
  }

  /**
   * Updates the metadata document based upon entered parameter value(s).
   *

   * @param dom the metadata document template for the schema
   * @param xpath an XPath object configured with an appropriate
   *        Namespace context for the schema
   * @param parameter the associated parameter
   * @throws XPathExpressionException if an expression fails
   * @throws SchemaException if the update fails
   */
  public void update(Document dom, XPath xpath, Parameter parameter)
    throws XPathExpressionException, SchemaException {

    // get the update expression, throw an exception if empty
    String sUpdate = getUpdate();
    LOGGER.finer("Updating xpath: "+sUpdate);
    if (sUpdate.length() == 0) {

    } else if (isSingleValue()) {

      // get the value to set, search for the node to update
      String sValue = getSingleValue().getValue();
      Node node = (Node)xpath.evaluate(sUpdate,dom,XPathConstants.NODE);

      // throw an exception if the node to update was not located
      // within the template
      if (node == null) {

      } else {

        // update the node
        if (node.getNodeType() == Node.ELEMENT_NODE) {

          if (getNodeType().equals(Content.NODETYPE_PAIRLEFTVALUE)) {
            String sTextContent = Val.chkStr(node.getTextContent());
            int spaceIndx = sTextContent.indexOf(' ');
            if((spaceIndx == -1) && (sTextContent.length()>0)){
              sValue = sValue + " " + sTextContent;
            }
          } else if(getNodeType().equals(Content.NODETYPE_PAIRRIGHTVALUE)){
            String sTextContent = Val.chkStr(node.getTextContent());
            int spaceIndx = sTextContent.indexOf(' ');
            if((spaceIndx == -1) && (sTextContent.length()>0)){
              sValue = sTextContent + " " + sValue;
            }
          }

          node.setTextContent(sValue);

        } else if (node.getNodeType() == Node.TEXT_NODE) {
          node.setNodeValue(sValue);
        } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
          node.setNodeValue(sValue);

          // for an ISO code list value
          //   attempt to set the text node of the parent element
          //   to the code value
          if (getNodeType().equals(Content.NODETYPE_ISOCODELISTVALUE)) {
            if (node instanceof Attr) {
              Attr attr = (Attr)node;
              if (attr.getOwnerElement() != null) {
                attr.getOwnerElement().setTextContent(sValue);
              }
            }
          }
        }

        // delete if required
        if (isValueEmpty() && getDeleteParentIfEmpty()) {
          if (node instanceof Attr) {
            Node ndToDelete = ((Attr)node).getOwnerElement();
            ndToDelete.getParentNode().removeChild(ndToDelete);
          } else {
            node.getParentNode().getParentNode().removeChild(node.getParentNode());
          }
        } else if (isValueEmpty() && getDeleteIfEmpty()) {
          if (node instanceof Attr) {
            ((Attr)node).getOwnerElement().removeAttributeNode((Attr)node);
          } else {
            node.getParentNode().removeChild(node);
          }
        }

      }

    } else {
      Node node = (Node)xpath.evaluate(sUpdate,dom,XPathConstants.NODE);

      // throw an exception if the node to update was not located
      // within the template
      if (node == null) {

      } else {

        Node ndToClone = node;
        if (node instanceof Attr) {
          Attr attr = (Attr)node;
          ndToClone = attr.getOwnerElement();
        } else if (getNodeType().equals(Content.NODETYPE_GCOLIST)) {
          ndToClone = node.getParentNode();
        }
        Node ndInsertBefore = ndToClone.getNextSibling();
        Node ndParent = ndToClone.getParentNode();
        ArrayList<String> alValues = new ArrayList<String>();
        int nCount = 0;
        for (ContentValue value: getMultipleValues()) {
          if (value.getValue().length() > 0) {
            nCount++;
            alValues.add(value.getValue());
            if (nCount > 1) {
              Node ndCloned = ndToClone.cloneNode(true);
              ndParent.insertBefore(ndCloned,ndInsertBefore);
            }
          }
        }
        NodeList nl = (NodeList)xpath.evaluate(sUpdate,dom,XPathConstants.NODESET);
        for (int i=0;i<nl.getLength();i++) {
          String sValue = "";
          if (i < alValues.size()) {
            sValue = alValues.get(i);
          }
          Node ndActive = nl.item(i);
          ndActive.setTextContent(sValue);
        }

        // delete if required
        if (isValueEmpty() && getDeleteParentIfEmpty()) {
          node.getParentNode().getParentNode().removeChild(node.getParentNode());
        } else if (isValueEmpty() && getDeleteIfEmpty()) {
          node.getParentNode().removeChild(node);
        }

      }

    }

    // delete if required
    if (isValueEmpty() && (getDelete().length() > 0)) {
      deleteNodes(dom,xpath,getDelete());
    }

  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res/group.cs242.beatblocks"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/gameIcon"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_margin="16dp"
        android:src="@mipmap/ic_launcher"
        android:layout_alignParentTop="true"/>

    <TextView
        android:id="@+id/score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:textAllCaps="true"
        android:textColor="#FFF"
        android:textStyle="bold"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="10dp"
        android:textSize="20dp"
        android:text="Score: 0"
        android:fontFamily="roboto"
        android:layout_below="@id/gameIcon"/>

    <TextView
        android:id="@+id/high_score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:textAllCaps="true"
        android:textColor="#FFF"
        android:textStyle="bold"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="10dp"
        android:textSize="20dp"
        android:fontFamily="roboto"
        android:layout_below="@id/score"/>

    <TextView
        android:id="@+id/misses"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:textAllCaps="true"
        android:textColor="#FFF"
        android:textStyle="bold"
        android:text="Misses: 0"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="10dp"
        android:textSize="20dp"
        android:fontFamily="roboto"
        android:layout_below="@id/high_score"/>

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textAllCaps="true"
        android:textColor="#FFF"
        android:textStyle="bold"
        android:layout_marginTop="15dp"
        android:textSize="25dp"
        android:fontFamily="roboto"
        android:layout_alignParentTop="true"/>

    <ImageButton
        android:id="@+id/pauseButton"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_margin="16dp"
        android:src="@mipmap/pause"
        android:layout_alignParentTop="true"/>

    <group.cs242.beatblocks.BeatBlockBoardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/beat_block_board_view"
        custom:width_of_screen="1080"
        custom:height_of_screen="1920"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"/>

    <group.cs242.beatblocks.BeatMapView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/beat_map_view"
        custom:width_screen="1080"
        custom:height_screen="1920"
        android:layout_centerHorizontal="true"
        android:layout_above="@id/beat_block_board_view"
        android:layout_below="@id/high_score"/>

</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text:
Angular 2 Quickstart - Angular.io

https://angular.io/docs/ts/latest/quickstart.html

npm install
npm start


text:
<!doctype html>

<meta charset="utf-8">

<title>Il Budget è morto? (parte 1) / Menicucci & Associati</title>

<meta property="og:locale" content="it">
<meta property="og:site_name" content="Menicucci & Associati">
<meta property="og:title" content="Il Budget è morto? (parte 1)">

  <link rel="canonical" href="http://localhost:4000/il-budget-e-morto-parte-1/">
  <meta property="og:url" content="http://localhost:4000/il-budget-e-morto-parte-1/">

  <meta property="og:description" content="Jack Welch, uno dei manager più famosi del mondo, a capo della General Electric per lungo tempo, nel suo libro Winning ha scritto:"Fa perdere tempo, porta via energie e il piacere di lavorare. Nasconde le opportunità e impedisce la crescita. Tira fuori il peggio dell'azienda, ne nasconde le capacità e le livella nella mediocrità."Stiamo parlando del processo di BUDGET. Questo odiatissimo esercizio di definizione dei target, di assegnazione delle risorse e di incentivazione del personale, rappresenta il pilastro su cui la quasi totalità degli imprenditori e dei manager di PMI poggia l'operatività aziendale. Da un po' di tempo, però, alcune aziende, guidate da Steve Player, direttore del Beyond Budgeting Round Table (un network di aziende che conta oltre 50 associati, fra i quali Google, Unilever e Toyota), hanno cominciato a parlare di eliminare il budget dai processi aziendali.">

  <meta name="twitter:site" content="@bmenicucci">
  <meta name="twitter:title" content="Il Budget è morto? (parte 1)">
  <meta name="twitter:description" content="Jack Welch, uno dei manager più famosi del mondo, a capo della General Electric per lungo tempo, nel suo libro Winning ha scritto:"Fa perdere tempo, porta via energie e il piacere di lavorare. Nasconde le opportunità e impedisce la crescita. Tira fuori il peggio dell'azienda, ne nasconde le capacità e le livella nella mediocrità."Stiamo parlando del processo di BUDGET. Questo odiatissimo esercizio di definizione dei target, di assegnazione delle risorse e di incentivazione del personale, rappresenta il pilastro su cui la quasi totalità degli imprenditori e dei manager di PMI poggia l'operatività aziendale. Da un po' di tempo, però, alcune aziende, guidate da Steve Player, direttore del Beyond Budgeting Round Table (un network di aziende che conta oltre 50 associati, fra i quali Google, Unilever e Toyota), hanno cominciato a parlare di eliminare il budget dai processi aziendali.">
  <meta name="twitter:url" content="http://localhost:4000/il-budget-e-morto-parte-1/">

    <meta name="twitter:card" content="summary">

  <meta property="og:type" content="article">
  <meta property="article:published_time" content="2013-09-06T16:41:15+02:00">

    <link rel="next" href="http://localhost:4000/il-budget-e-morto-parte-2/" title="Il budget è morto? (parte 2)">

    <link rel="prev" href="http://localhost:4000/la-balanced-scorecard/" title="La Balanced Scorecard">

  <meta name="google-site-verification" content="3HSeLrF7fmpp6RjeU1e93TTBJpVnO0RK2wvo_n4CIZc" />

<link href="http://localhost:4000/feed.xml" type="application/atom+xml" rel="alternate" title="Menicucci & Associati Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="http://localhost:4000/assets/css/main.css">

<meta http-equiv="cleartype" content="on">

<link rel="icon" href="/favicon.png" >

        <button>

</button>

Menicucci & Associati

Chi Siamo

Consulenza

Formazione

Contatti

Blog

Privacy e politica dei Cookies

             <form role="search" method="get" action="/search/">
                 <input id="searchString" name="searchString"
                        placeholder="Cerca nel sito" type="text">
                 <input id="searchButton" name="googleSearchName" type="submit" value="Search">
             </form>

          Home
          <meta itemprop="position" content="1" />

        >>

Il Budget è morto? (parte 1)

Brunello Menicucci

Management Consultant CMC™

    <button class="btn btn--inverse">Follow</button>

 Lido di Camaiore, LU

 Email

 Twitter

 Google+

 LinkedIn

    <meta itemprop="headline" content="Il Budget è morto? (parte 1)">
    <meta itemprop="description" content="Jack Welch, uno dei manager più famosi del mondo, a capo della General Electric per lungo tempo, nel suo libro Winning ha scritto:"Fa perdere tempo, porta via energie e il piacere di lavorare. Nasconde le opportunità e impedisce la crescita. Tira fuori il peggio dell'azienda, ne nasconde le capacità e le livella nella mediocrità."Stiamo parlando del processo di BUDGET. Questo odiatissimo esercizio di definizione dei target, di assegnazione delle risorse e di incentivazione del personale, rappresenta il pilastro su cui la quasi totalità degli imprenditori e dei manager di PMI poggia l'operatività aziendale. Da un po' di tempo, però, alcune aziende, guidate da Steve Player, direttore del Beyond Budgeting Round Table (un network di aziende che conta oltre 50 associati, fra i quali Google, Unilever e Toyota), hanno cominciato a parlare di eliminare il budget dai processi aziendali.">
    <meta itemprop="datePublished" content="September 06, 2013">

Il Budget è morto? (parte 1)

	  3 minuti di lettura

Jack Welch, uno dei manager più famosi del mondo, a capo della General Electric per lungo tempo, nel suo libro Winning ha scritto:

"Fa perdere tempo, porta via energie e il piacere di lavorare. Nasconde le opportunità e impedisce la crescita. Tira fuori il peggio dell'azienda, ne nasconde le capacità e le livella nella mediocrità."

Stiamo parlando del processo di BUDGET. Questo odiatissimo esercizio di definizione dei target, di assegnazione delle risorse e di incentivazione del personale, rappresenta il pilastro su cui la quasi totalità degli imprenditori e dei manager di PMI poggia l'operatività aziendale. Da un po' di tempo, però, alcune aziende, guidate da Steve Player, direttore del Beyond Budgeting Round Table (un network di aziende che conta oltre 50 associati, fra i quali Google, Unilever e Toyota), hanno cominciato a parlare di eliminare il budget dai processi aziendali.

Perché? Le ragioni sono numerose;  intanto perché, rispetto al processo di budget, è difficile ottenere risposte rapide: tipicamente, se bisogna apportare qualche modifica, è necessario coinvolgere diverse persone, magari di reparti diversi, in svariate riunioni. Poi perché il budget, misurando le persone su target prefissati, toglie spazio alla creatività e all'iniziativa personale.

Lo stesso vale se consideriamo la relazione coi Clienti: siccome il budget, tipicamente, ha un orizzonte temporale di breve periodo, c'è il rischio che le persone si concentrino esclusivamente sul risultato da ottenere nell'immediato, perdendo di vista la relazione di lunga durata con i Clienti che, invece, dovrebbe essere il vero obiettivo.

Senza dimenticare che, siccome nel processo di budget le risorsa sono spesso allocate, i responsabili tenderanno a spendere fino all'ultimo centesimo dell'ammontare ricevuto in allocazione, per evitare riduzioni del budget di spesa nel periodo successivo. Inoltre bisogna considerare che il budget nasce, come strumento di pianificazione e di distribuzione delle risorse, in un periodo storico stabile e ben definito; esattamente il contrario di quello che è oggi il panorama economico, caratterizzato da mercati turbolenti e da un deciso cambiamento dei driver del valore: se ieri la creazione di valore era una conseguenza delle economie di scala, oggi i driver del valore sono l'innovazione (sia di prodotto che di processo), il time to market, cioè la capacità di arrivare per primi sul mercato, e con l'attitudine all'apprendimento e all'adattamento rispetto all'ambiente.

Ultimo non ultimo, mentre ieri la crescita era vincolata dalla disponibilità di capitale "tangibile", oggi le aziende, per crearsi un vantaggio competitivo che duri davvero nel tempo, devono privilegiare e fare affidamento su quelli che si chiamano "intangibles" ovvero il capitale umano, la proprietà intellettuale, la capacità di "fare brand" e di sfruttare la conoscenza (knowledge management), passando quindi a una gestione dei "processi", più che per funzioni.

Ecco che, a partire dalla fine del secolo scorso, per ovviare a questi limiti, sono state messe a punto nuove tecniche di budgeting (Zero Based Budgeting, Activity Based Budgeting etc.) le quali hanno contribuito sicuramente a migliorare la situazione, senza però portare a risultati davvero soddisfacenti.

Il Beyond Budgeting, nato nell'ambito degli studi del CAM-I (Consortium for Advanced Manufacturing - International) è un approccio di tipo deduttivo basato sulle esperienze concrete di alcuni pionieri, che nel 1998, a Londra, hanno costituito il Beyond Budgeting Round Table (BBRT) il quale ha analizzato il modus operandi di 13 aziende che operano completamente (o quasi) senza la stesura di budget.

Da questa osservazione nasce il modello, che si basa su 12 principi, suddivisi in due macro-aree:  i cambiamenti da apportare alla leadership cioè al modo di gestire, e i cambiamenti da apportare in termini di gestione dei processi.

E' interessante notare come questo modello sia applicato da aziende lontane geograficamente ma anche per settore e per dimensione, a dimostrazione che si tratta di un approccio realmente innovativo e largamente applicabile.

Che ne pensate? Nella vostra azienda il budget è fonte di problemi?
Lasciate un commento, e non perdete la seconda parte di questo Post!

 Ultimo aggiornamento: <time datetime="2013-09-06T16:41:15+02:00">September 06, 2013</time>

Condividi

   Twitter

   Facebook

   Google+

   LinkedIn

      Previous

      Next

Potrebbe interessarti anche:

        Strategie per il Cambiamento

	  1 minuti di lettura

L'ambiente intorno a noi si evolve a una velocità sempre maggiore. Mai come adesso il significato di quanto diceva Eraclito: "Non c'è niente di permanente, t...

        Controllo Di Gestione Fra Tradizione E Evoluzione

	  1 minuti di lettura

Un seminario gratuito di CNA e APCO sul Controllo di Gestione
It is not necessary to change. Survival is not mandatory. (W. Edwards Deming)
L'impresa, lo sap...

        Auguri per un 2016 strepitoso!

	  meno di 1 minuti di lettura

Auguri a tutti per un 2016 prosperoso e sereno!

        Pa Non Fa Rima Con Performance

	  2 minuti di lettura

Questa mattina, su un quotidiano, ho letto una notizia il cui titolo era:

Chi Siamo

Consulenza

Formazione

Contatti

Blog

Privacy e politica dei Cookies

Follow:

 Twitter

 Feed

© 2016 Brunello Menicucci. Powered by Jekyll & Minimal Mistakes.


text:
#include <functional>
#include <memory>

namespace Tools
{

template<class InputType = double, class OutputType = double>
class TableCalculator
{
public:
    TableCalculator(const std::function<OutputType(InputType)>& funct,
        InputType start, InputType end, InputType step);

    OutputType Get(InputType input);
private:
    InputType start;
    InputType end;
    InputType step;
    unordered_map<size_t, OutputType> table;
};

template<class InputType, class OutputType>
TableCalculator<InputType, OutputType>::TableCalculator(
    const std::function<OutputType(InputType)>& funct,
    InputType start, InputType end, InputType step)
    : start(start), end(end), step(step)
{
    size_t enumerator = 0;
    for (InputType iter = start; iter < end; iter += step)
    {
        table[enumerator++] = funct(iter);
    }
}

template<class InputType, class OutputType>
OutputType TableCalculator<InputType, OutputType>::Get(InputType input)
{
    if (input < start) {
        return table[0]; }
    else if (input >= end) {
        return table[table.size() - 1];
    } else {
        size_t index = static_cast<size_t>((input - start) / step);
        return table[index];
    }
}

}


text:
package predicates

import (
	"fmt"

	v1 "k8s.io/api/core/v1"
	storagev1beta1 "k8s.io/api/storage/v1beta1"
	"k8s.io/apimachinery/pkg/util/rand"
	utilfeature "k8s.io/apiserver/pkg/util/feature"
	corelisters "k8s.io/client-go/listers/core/v1"
	storagelisters "k8s.io/client-go/listers/storage/v1"
	v1beta1storagelisters "k8s.io/client-go/listers/storage/v1beta1"
	csitrans "k8s.io/csi-translation-lib"
	"k8s.io/klog"
	v1helper "k8s.io/kubernetes/pkg/apis/core/v1/helper"
	"k8s.io/kubernetes/pkg/features"
	schedulernodeinfo "k8s.io/kubernetes/pkg/scheduler/nodeinfo"
	volumeutil "k8s.io/kubernetes/pkg/volume/util"
)

// InTreeToCSITranslator contains methods required to check migratable status
// and perform translations from InTree PV's to CSI
type InTreeToCSITranslator interface {
	IsPVMigratable(pv *v1.PersistentVolume) bool
	IsMigratableIntreePluginByName(inTreePluginName string) bool
	GetInTreePluginNameFromSpec(pv *v1.PersistentVolume, vol *v1.Volume) (string, error)
	GetCSINameFromInTreeName(pluginName string) (string, error)
	TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)
}

// CSIMaxVolumeLimitChecker defines predicate needed for counting CSI volumes
type CSIMaxVolumeLimitChecker struct {
	csiNodeLister v1beta1storagelisters.CSINodeLister
	pvLister      corelisters.PersistentVolumeLister
	pvcLister     corelisters.PersistentVolumeClaimLister
	scLister      storagelisters.StorageClassLister

	randomVolumeIDPrefix string

	translator InTreeToCSITranslator
}

// NewCSIMaxVolumeLimitPredicate returns a predicate for counting CSI volumes
func NewCSIMaxVolumeLimitPredicate(
	csiNodeLister v1beta1storagelisters.CSINodeLister, pvLister corelisters.PersistentVolumeLister, pvcLister corelisters.PersistentVolumeClaimLister, scLister storagelisters.StorageClassLister) FitPredicate {
	c := &CSIMaxVolumeLimitChecker{
		csiNodeLister:        csiNodeLister,
		pvLister:             pvLister,
		pvcLister:            pvcLister,
		scLister:             scLister,
		randomVolumeIDPrefix: rand.String(32),
		translator:           csitrans.New(),
	}
	return c.attachableLimitPredicate
}

func getVolumeLimits(nodeInfo *schedulernodeinfo.NodeInfo, csiNode *storagev1beta1.CSINode) map[v1.ResourceName]int64 {
	// TODO: stop getting values from Node object in v1.18
	nodeVolumeLimits := nodeInfo.VolumeLimits()
	if csiNode != nil {
		for i := range csiNode.Spec.Drivers {
			d := csiNode.Spec.Drivers[i]
			if d.Allocatable != nil && d.Allocatable.Count != nil {
				// TODO: drop GetCSIAttachLimitKey once we don't get values from Node object (v1.18)
				k := v1.ResourceName(volumeutil.GetCSIAttachLimitKey(d.Name))
				nodeVolumeLimits[k] = int64(*d.Allocatable.Count)
			}
		}
	}
	return nodeVolumeLimits
}

func (c *CSIMaxVolumeLimitChecker) attachableLimitPredicate(
	pod *v1.Pod, meta PredicateMetadata, nodeInfo *schedulernodeinfo.NodeInfo) (bool, []PredicateFailureReason, error) {
	// If the new pod doesn't have any volume attached to it, the predicate will always be true
	if len(pod.Spec.Volumes) == 0 {
		return true, nil, nil
	}

	if !utilfeature.DefaultFeatureGate.Enabled(features.AttachVolumeLimit) {
		return true, nil, nil
	}

	node := nodeInfo.Node()
	if node == nil {
		return false, nil, fmt.Errorf("node not found")
	}

	// If CSINode doesn't exist, the predicate may read the limits from Node object
	csiNode, err := c.csiNodeLister.Get(node.Name)
	if err != nil {
		// TODO: return the error once CSINode is created by default (2 releases)
		klog.V(5).Infof("Could not get a CSINode object for the node: %v", err)
	}

	newVolumes := make(map[string]string)
	if err := c.filterAttachableVolumes(csiNode, pod.Spec.Volumes, pod.Namespace, newVolumes); err != nil {
		return false, nil, err
	}

	// If the pod doesn't have any new CSI volumes, the predicate will always be true
	if len(newVolumes) == 0 {
		return true, nil, nil
	}

	// If the node doesn't have volume limits, the predicate will always be true
	nodeVolumeLimits := getVolumeLimits(nodeInfo, csiNode)
	if len(nodeVolumeLimits) == 0 {
		return true, nil, nil
	}

	attachedVolumes := make(map[string]string)
	for _, existingPod := range nodeInfo.Pods() {
		if err := c.filterAttachableVolumes(csiNode, existingPod.Spec.Volumes, existingPod.Namespace, attachedVolumes); err != nil {
			return false, nil, err
		}
	}

	attachedVolumeCount := map[string]int{}
	for volumeUniqueName, volumeLimitKey := range attachedVolumes {
		if _, ok := newVolumes[volumeUniqueName]; ok {
			// Don't count single volume used in multiple pods more than once
			delete(newVolumes, volumeUniqueName)
		}
		attachedVolumeCount[volumeLimitKey]++
	}

	newVolumeCount := map[string]int{}
	for _, volumeLimitKey := range newVolumes {
		newVolumeCount[volumeLimitKey]++
	}

	for volumeLimitKey, count := range newVolumeCount {
		maxVolumeLimit, ok := nodeVolumeLimits[v1.ResourceName(volumeLimitKey)]
		if ok {
			currentVolumeCount := attachedVolumeCount[volumeLimitKey]
			if currentVolumeCount+count > int(maxVolumeLimit) {
				return false, []PredicateFailureReason{ErrMaxVolumeCountExceeded}, nil
			}
		}
	}

	return true, nil, nil
}

func (c *CSIMaxVolumeLimitChecker) filterAttachableVolumes(
	csiNode *storagev1beta1.CSINode, volumes []v1.Volume, namespace string, result map[string]string) error {
	for _, vol := range volumes {
		// CSI volumes can only be used as persistent volumes
		if vol.PersistentVolumeClaim == nil {
			continue
		}
		pvcName := vol.PersistentVolumeClaim.ClaimName

		if pvcName == "" {
			return fmt.Errorf("PersistentVolumeClaim had no name")
		}

		pvc, err := c.pvcLister.PersistentVolumeClaims(namespace).Get(pvcName)

		if err != nil {
			klog.V(5).Infof("Unable to look up PVC info for %s/%s", namespace, pvcName)
			continue
		}

		driverName, volumeHandle := c.getCSIDriverInfo(csiNode, pvc)
		if driverName == "" || volumeHandle == "" {
			klog.V(5).Infof("Could not find a CSI driver name or volume handle, not counting volume")
			continue
		}

		volumeUniqueName := fmt.Sprintf("%s/%s", driverName, volumeHandle)
		volumeLimitKey := volumeutil.GetCSIAttachLimitKey(driverName)
		result[volumeUniqueName] = volumeLimitKey
	}
	return nil
}

// getCSIDriverInfo returns the CSI driver name and volume ID of a given PVC.
// If the PVC is from a migrated in-tree plugin, this function will return
// the information of the CSI driver that the plugin has been migrated to.
func (c *CSIMaxVolumeLimitChecker) getCSIDriverInfo(csiNode *storagev1beta1.CSINode, pvc *v1.PersistentVolumeClaim) (string, string) {
	pvName := pvc.Spec.VolumeName
	namespace := pvc.Namespace
	pvcName := pvc.Name

	if pvName == "" {
		klog.V(5).Infof("Persistent volume had no name for claim %s/%s", namespace, pvcName)
		return c.getCSIDriverInfoFromSC(csiNode, pvc)
	}

	pv, err := c.pvLister.Get(pvName)
	if err != nil {
		klog.V(5).Infof("Unable to look up PV info for PVC %s/%s and PV %s", namespace, pvcName, pvName)
		// If we can't fetch PV associated with PVC, may be it got deleted
		// or PVC was prebound to a PVC that hasn't been created yet.
		// fallback to using StorageClass for volume counting
		return c.getCSIDriverInfoFromSC(csiNode, pvc)
	}

	csiSource := pv.Spec.PersistentVolumeSource.CSI
	if csiSource == nil {
		// We make a fast path for non-CSI volumes that aren't migratable
		if !c.translator.IsPVMigratable(pv) {
			return "", ""
		}

		pluginName, err := c.translator.GetInTreePluginNameFromSpec(pv, nil)
		if err != nil {
			klog.V(5).Infof("Unable to look up plugin name from PV spec: %v", err)
			return "", ""
		}

		if !isCSIMigrationOn(csiNode, pluginName) {
			klog.V(5).Infof("CSI Migration of plugin %s is not enabled", pluginName)
			return "", ""
		}

		csiPV, err := c.translator.TranslateInTreePVToCSI(pv)
		if err != nil {
			klog.V(5).Infof("Unable to translate in-tree volume to CSI: %v", err)
			return "", ""
		}

		if csiPV.Spec.PersistentVolumeSource.CSI == nil {
			klog.V(5).Infof("Unable to get a valid volume source for translated PV %s", pvName)
			return "", ""
		}

		csiSource = csiPV.Spec.PersistentVolumeSource.CSI
	}

	return csiSource.Driver, csiSource.VolumeHandle
}

// getCSIDriverInfoFromSC returns the CSI driver name and a random volume ID of a given PVC's StorageClass.
func (c *CSIMaxVolumeLimitChecker) getCSIDriverInfoFromSC(csiNode *storagev1beta1.CSINode, pvc *v1.PersistentVolumeClaim) (string, string) {
	namespace := pvc.Namespace
	pvcName := pvc.Name
	scName := v1helper.GetPersistentVolumeClaimClass(pvc)

	// If StorageClass is not set or not found, then PVC must be using immediate binding mode
	// and hence it must be bound before scheduling. So it is safe to not count it.
	if scName == "" {
		klog.V(5).Infof("PVC %s/%s has no StorageClass", namespace, pvcName)
		return "", ""
	}

	storageClass, err := c.scLister.Get(scName)
	if err != nil {
		klog.V(5).Infof("Could not get StorageClass for PVC %s/%s: %v", namespace, pvcName, err)
		return "", ""
	}

	// We use random prefix to avoid conflict with volume IDs. If PVC is bound during the execution of the
	// predicate and there is another pod on the same node that uses same volume, then we will overcount
	// the volume and consider both volumes as different.
	volumeHandle := fmt.Sprintf("%s-%s/%s", c.randomVolumeIDPrefix, namespace, pvcName)

	provisioner := storageClass.Provisioner
	if c.translator.IsMigratableIntreePluginByName(provisioner) {
		if !isCSIMigrationOn(csiNode, provisioner) {
			klog.V(5).Infof("CSI Migration of plugin %s is not enabled", provisioner)
			return "", ""
		}

		driverName, err := c.translator.GetCSINameFromInTreeName(provisioner)
		if err != nil {
			klog.V(5).Infof("Unable to look up driver name from plugin name: %v", err)
			return "", ""
		}
		return driverName, volumeHandle
	}

	return provisioner, volumeHandle
}


text:
'use strict'

const utils = require('./utils.js')

module.exports = {
  meta: {
    docs: {},
    schema: []
  },

  create: function (context) {
    return {
      CallExpression: function (node) {
        if (node.callee.type !== 'MemberExpression') return
        if (node.callee.property.name !== 'text') return

        if (utils.isjQuery(node)) {
          context.report({
            node: node,
            message: 'Prefer textContent to $.text'
          })
        }
      }
    }
  }
}


text:
module CustomTypes where
import Data.Array

data Color = Black | White
  deriving (Eq, Show)

data Move = Pass | Play (Int, Int)
  deriving (Eq, Show)

data Tile = Mine | Opponent | Neutral
  deriving (Eq, Show)

-- data structure of the game tree nodes
data Node = Node Board Player Coordinates
  deriving (Eq, Show)

type Player = Tile
type Coordinates = (Int,Int)
type Board = Array Coordinates Tile
type State = Board


text:
<?php

namespace Test\LoginBundle\Entity;

use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="admin_roles")
 */
class Role implements RoleInterface
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nombre", type="string", length=255, nullable=true)
     */
    protected $name;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    public function getRole() {
        return $this->getName();
    }

    public function __toString() {
        return $this->getRole();
    }
}


text:
package org.apache.flink.runtime.query;

import org.apache.flink.api.common.JobID;
import org.apache.flink.queryablestate.KvStateID;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.state.KeyGroupRange;
import org.apache.flink.runtime.state.internal.InternalKvState;
import org.apache.flink.util.Preconditions;

import java.util.ArrayList;
import java.util.List;

/** A helper for KvState registrations of a single task. */
public class TaskKvStateRegistry {

    /** KvStateRegistry for KvState instance registrations. */
    private final KvStateRegistry registry;

    /** JobID of the task. */
    private final JobID jobId;

    /** JobVertexID of the task. */
    private final JobVertexID jobVertexId;

    /** List of all registered KvState instances of this task. */
    private final List<KvStateInfo> registeredKvStates = new ArrayList<>();

    TaskKvStateRegistry(KvStateRegistry registry, JobID jobId, JobVertexID jobVertexId) {
        this.registry = Preconditions.checkNotNull(registry, "KvStateRegistry");
        this.jobId = Preconditions.checkNotNull(jobId, "JobID");
        this.jobVertexId = Preconditions.checkNotNull(jobVertexId, "JobVertexID");
    }

    /**
     * Registers the KvState instance at the KvStateRegistry.
     *
     * @param keyGroupRange Key group range the KvState instance belongs to
     * @param registrationName The registration name (not necessarily the same as the KvState name
     *     defined in the state descriptor used to create the KvState instance)
     * @param kvState The
     */
    public void registerKvState(
            KeyGroupRange keyGroupRange,
            String registrationName,
            InternalKvState<?, ?, ?> kvState,
            ClassLoader userClassLoader) {
        KvStateID kvStateId =
                registry.registerKvState(
                        jobId,
                        jobVertexId,
                        keyGroupRange,
                        registrationName,
                        kvState,
                        userClassLoader);
        registeredKvStates.add(new KvStateInfo(keyGroupRange, registrationName, kvStateId));
    }

    /** Unregisters all registered KvState instances from the KvStateRegistry. */
    public void unregisterAll() {
        for (KvStateInfo kvState : registeredKvStates) {
            registry.unregisterKvState(
                    jobId,
                    jobVertexId,
                    kvState.keyGroupRange,
                    kvState.registrationName,
                    kvState.kvStateId);
        }
    }

    /** 3-tuple holding registered KvState meta data. */
    private static class KvStateInfo {

        private final KeyGroupRange keyGroupRange;

        private final String registrationName;

        private final KvStateID kvStateId;

        KvStateInfo(KeyGroupRange keyGroupRange, String registrationName, KvStateID kvStateId) {
            this.keyGroupRange = keyGroupRange;
            this.registrationName = registrationName;
            this.kvStateId = kvStateId;
        }
    }
}


text:
{% extends "base.html" %}
{% load url from future %}

{% block script %}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
{% endblock %}

{% block heading %}Login using any of the following methods{% endblock %}

{% block content %}

{% endblock %}


text:
package com.bitdubai.fermat_ccp_plugin.layer.network_service.crypto_transmission.developer.bitdubai.version_1.crypto_transmission_database.dao;

import com.bitdubai.fermat_api.layer.all_definition.enums.CryptoCurrency;
import com.bitdubai.fermat_api.layer.all_definition.exceptions.InvalidParameterException;
import com.bitdubai.fermat_api.layer.dmp_network_service.crypto_transmission.interfaces.structure.CryptoTransmissionMetadata;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFilterType;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantCreateDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantInsertRecordException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;
import com.bitdubai.fermat_ccp_api.layer.network_service.crypto_addresses.exceptions.PendingRequestNotFoundException;
import com.bitdubai.fermat_ccp_plugin.layer.network_service.crypto_transmission.developer.bitdubai.version_1.crypto_transmission_database.CryptoTransmissionNetworkServiceDatabaseConstants;
import com.bitdubai.fermat_ccp_plugin.layer.network_service.crypto_transmission.developer.bitdubai.version_1.crypto_transmission_database.CryptoTransmissionNetworkServiceDatabaseFactory;
import com.bitdubai.fermat_ccp_plugin.layer.network_service.crypto_transmission.developer.bitdubai.version_1.crypto_transmission_database.exceptions.CantInitializeCryptoTransmissionNetworkServiceDatabaseException;
import com.bitdubai.fermat_ccp_plugin.layer.network_service.crypto_transmission.developer.bitdubai.version_1.structure.crypto_transmission_structure.CryptoTransmissionMetadataRecord;

import java.util.List;
import java.util.UUID;

/**
 * Created by Matias Furszyfer on 2015.10.04..
 */
public class CryptoTransmissionMetadataDAO {

    private final PluginDatabaseSystem pluginDatabaseSystem;
    private final UUID pluginId            ;

    private Database database;

    public CryptoTransmissionMetadataDAO(final PluginDatabaseSystem pluginDatabaseSystem,
                                            final UUID                 pluginId            ) {

        this.pluginDatabaseSystem = pluginDatabaseSystem;
        this.pluginId             = pluginId            ;
    }

    public void initialize() throws CantInitializeCryptoTransmissionNetworkServiceDatabaseException {
        try {

            database = this.pluginDatabaseSystem.openDatabase(
                    this.pluginId,
                    this.pluginId.toString()
            );

        } catch (DatabaseNotFoundException e) {

            try {

                CryptoTransmissionNetworkServiceDatabaseFactory databaseFactory = new CryptoTransmissionNetworkServiceDatabaseFactory(pluginDatabaseSystem);
                database = databaseFactory.createDatabase(
                        pluginId,
                        pluginId.toString()
                );

            } catch (CantCreateDatabaseException f) {

                throw new CantInitializeCryptoTransmissionNetworkServiceDatabaseException(CantCreateDatabaseException.DEFAULT_MESSAGE, f, "", "There is a problem and i cannot create the database.");
            } catch (Exception z) {

                throw new CantInitializeCryptoTransmissionNetworkServiceDatabaseException(CantInitializeCryptoTransmissionNetworkServiceDatabaseException.DEFAULT_MESSAGE, z, "", "Generic Exception.");
            }

        } catch (CantOpenDatabaseException e) {

            throw new CantInitializeCryptoTransmissionNetworkServiceDatabaseException(CantOpenDatabaseException.DEFAULT_MESSAGE, e, "", "Exception not handled by the plugin, there is a problem and i cannot open the database.");
        } catch (Exception e) {

            throw new CantInitializeCryptoTransmissionNetworkServiceDatabaseException(CantInitializeCryptoTransmissionNetworkServiceDatabaseException.DEFAULT_MESSAGE, e, "", "Generic Exception.");
        }
    }

    public void saveCryptoTransmissionMetadata(CryptoTransmissionMetadata cryptoTransmissionMetadata) throws CantSaveCryptoTransmissionMetadatatException {

        try {

            DatabaseTable addressExchangeRequestTable = database.getTable(CryptoTransmissionNetworkServiceDatabaseConstants.COMPONENT_VERSIONS_DETAILS_TABLE_NAME);
            DatabaseTableRecord entityRecord = addressExchangeRequestTable.getEmptyRecord();

            entityRecord = buildDatabaseRecord(entityRecord, cryptoTransmissionMetadata);

            addressExchangeRequestTable.insertRecord(entityRecord);

        } catch (CantInsertRecordException e) {

            //throw new CantSaveCryptoTransmissionMetadatatException(e, "", "Exception not handled by the plugin, there is a problem in database and i cannot insert the record.");
        }
    }

    public CryptoTransmissionMetadata getPendingRequest(UUID transmissionId) throws CantGetCryptoTransmissionMetadataException,
            PendingRequestNotFoundException {

        if (transmissionId == null)
            //throw new CantGetCryptoTransmissionMetadataException(null,"", "requestId, can not be null");

        try {

            DatabaseTable metadataTable = database.getTable(CryptoTransmissionNetworkServiceDatabaseConstants.COMPONENT_VERSIONS_DETAILS_TABLE_NAME);

            metadataTable.setUUIDFilter(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_TRANSMISSION_ID_COLUMN_NAME, transmissionId, DatabaseFilterType.EQUAL);

            metadataTable.loadToMemory();

            List<DatabaseTableRecord> records = metadataTable.getRecords();

            if (!records.isEmpty())
                return buildCryptoTransmissionRecord(records.get(0));
            else
                throw new PendingRequestNotFoundException(null, "RequestID: "+transmissionId, "Can not find an address exchange request with the given request id.");

        } catch (CantLoadTableToMemoryException exception) {

            //throw new CantGetCryptoTransmissionMetadataException(exception, "", "Exception not handled by the plugin, there is a problem in database and i cannot load the table.");
        } catch (InvalidParameterException exception) {

            //throw new CantGetCryptoTransmissionMetadataException(exception, "", "Check the cause."                                                                                );
        }
        //TODO: cambiar esto con excepciones
        return null;
    }

    private CryptoTransmissionMetadata buildCryptoTransmissionRecord(DatabaseTableRecord record) throws InvalidParameterException {

        UUID   transactionId                       = record.getUUIDValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_TRANSMISSION_ID_COLUMN_NAME);
        UUID   requestId                  = record.getUUIDValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_REQUEST_ID_COLUMN_NAME);
        String cryptoCurrencyString    = record.getStringValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_CRYPTO_CURRENCY_COLUMN_NAME);
        long amount     = record.getLongValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_CRYPTO_AMOUNT_COLUMN_NAME);
        String sender     = record.getStringValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_SENDER_PUBLICK_KEY_COLUMN_NAME);
        String destination      = record.getStringValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_DESTINATION_PUBLIC_KEY_COLUMN_NAME);
        String associatedHash  = record.getStringValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_ASSOCIATED_CRYPTO_TRANSACTION_HASH_COLUMN_NAME);
        String description = record.getStringValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_PAYMENT_DESCRIPTION_COLUMN_NAME  );

        CryptoCurrency cryptoCurrency = CryptoCurrency                     .getByCode(cryptoCurrencyString              );
        return new CryptoTransmissionMetadataRecord(
                associatedHash,
                amount,
                cryptoCurrency,
                destination,
                description,
                requestId,
                sender,
                transactionId
        );
    }

    private DatabaseTableRecord buildDatabaseRecord(DatabaseTableRecord                                 record,
                                                    CryptoTransmissionMetadata cryptoTransmissionMetadata) {

        record.setUUIDValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_TRANSMISSION_ID_COLUMN_NAME, cryptoTransmissionMetadata.getTransmissionId());
        record.setUUIDValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_REQUEST_ID_COLUMN_NAME, cryptoTransmissionMetadata.getRequestId());
        record.setStringValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_CRYPTO_CURRENCY_COLUMN_NAME, cryptoTransmissionMetadata.getCryptoCurrency().getCode());
        record.setLongValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_CRYPTO_AMOUNT_COLUMN_NAME, cryptoTransmissionMetadata.getCryptoAmount());
        record.setStringValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_SENDER_PUBLICK_KEY_COLUMN_NAME, cryptoTransmissionMetadata.getSenderPublicKey());
        record.setStringValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_DESTINATION_PUBLIC_KEY_COLUMN_NAME , cryptoTransmissionMetadata.getDestinationPublicKey());
        record.setStringValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_ASSOCIATED_CRYPTO_TRANSACTION_HASH_COLUMN_NAME   , cryptoTransmissionMetadata.getAssociatedCryptoTransactionHash());
        record.setStringValue(CryptoTransmissionNetworkServiceDatabaseConstants.CRYPTO_TRANSMISSION_METADATA_PAYMENT_DESCRIPTION_COLUMN_NAME  , cryptoTransmissionMetadata.getPaymentDescription());
        return record;
    }

}


text:
package hu.belicza.andras.mpq.model;

/**
 *

 * The User Data before the header of the MPQ archives.
 *

 *
 *

 * The second version of the MoPaQ format, first used in Burning Crusade, features a mechanism to store some amount of data outside the archive proper, though
 * the reason for this mechanism is not known. This is implemented by means of a shunt block that precedes the archive itself. The format of this block is as
 * follows (see below):
 *

 *
 *

 * When Storm encounters this block in its search for the archive header, it saves the location of the shunt block and resumes its search for the archive header
 * at the offset specified in the shunt.

 *

 * Blizzard-generated archives place the shunt at the beginning of the file, and begin the archive itself at the next 512-byte boundary after the end of the
 * shunt block.
 *

 *
 *

 * Source: The_MoPaQ_Archive_Format
 *

 *
 * @author Andras Belicza
 */
public class UserData {

	/**
	 * The magic value indicating User Data section in valid MPQ archives. Indicates that this is a shunt block. ASCII "MPQ" 1Bh.
	 */
	public static final byte[] MPQ_MAGIC_EXT = new byte[] { 'M', 'P', 'Q', 0x1B };

	/**
	 * The number of bytes that have been allocated in this archive for user data. This does not need to be the exact size of the data itself, but merely the
	 * maximum amount of data which may be stored in this archive.
	 */
	public int                 userDataSize;

	/** The offset in the file at which to continue the search for the archive header. */
	public int                 archiveHeaderOffset;

	/** The block to store user data in. It has userDataSize bytes. */
	public byte[]              userData;

	/**
	 * Checks and returns if the specified magic is a valid MPQ_EXT magic.
	 *
	 * @param magic magic to be checked
	 * @return true if the specified magic is valid; false otherwise
	 */
	public static boolean isMpqMagicExt( final byte[] magic ) {
		if ( magic.length != MPQ_MAGIC_EXT.length )
			return false;

		for ( int i = 0; i < MPQ_MAGIC_EXT.length; i++ )
			if ( MPQ_MAGIC_EXT[ i ] != magic[ i ] )
				return false;

		return true;
	}

}


text:
/**
 * SECTION:gstglutils
 * @title: GstGLUtils
 * @short_description: some miscellaneous utilities for OpenGL
 * @see_also: #GstGLContext
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h>

#include <gst/gst.h>
#include <glib/gprintf.h>

#include "gl.h"
#include "gstglutils.h"
#include "gstglutils_private.h"

#if GST_GL_HAVE_WINDOW_X11
#include <gst/gl/x11/gstgldisplay_x11.h>
#endif
#if GST_GL_HAVE_WINDOW_WAYLAND
#include <gst/gl/wayland/gstgldisplay_wayland.h>
#endif

#define USING_OPENGL(context) (gst_gl_context_check_gl_version (context, GST_GL_API_OPENGL, 1, 0))
#define USING_OPENGL3(context) (gst_gl_context_check_gl_version (context, GST_GL_API_OPENGL3, 3, 1))
#define USING_GLES(context) (gst_gl_context_check_gl_version (context, GST_GL_API_GLES, 1, 0))
#define USING_GLES2(context) (gst_gl_context_check_gl_version (context, GST_GL_API_GLES2, 2, 0))
#define USING_GLES3(context) (gst_gl_context_check_gl_version (context, GST_GL_API_GLES2, 3, 0))

#ifndef GST_DISABLE_GST_DEBUG
GST_DEBUG_CATEGORY_STATIC (gst_gl_utils_debug);
static GstDebugCategory *
_init_gl_utils_debug_category (void)
{
  static volatile gsize _init = 0;

  if (g_once_init_enter (&_init)) {
    GST_DEBUG_CATEGORY_INIT (gst_gl_utils_debug, "glutils", 0,
        "OpenGL Utilities");
    g_once_init_leave (&_init, 1);
  }

  return gst_gl_utils_debug;
}

#define GST_CAT_DEFAULT _init_gl_utils_debug_category()
#endif

static gboolean
gst_gl_display_found (GstElement * element, GstGLDisplay * display)
{
  if (display) {
    GST_LOG_OBJECT (element, "already have a display (%p)", display);
    return TRUE;
  }

  return FALSE;
}

GST_DEBUG_CATEGORY_STATIC (GST_CAT_CONTEXT);

static void
_init_context_debug (void)
{
#ifndef GST_DISABLE_GST_DEBUG
  static volatile gsize _init = 0;

  if (g_once_init_enter (&_init)) {
    GST_DEBUG_CATEGORY_GET (GST_CAT_CONTEXT, "GST_CONTEXT");
    g_once_init_leave (&_init, 1);
  }
#endif
}

static gboolean
pad_query (const GValue * item, GValue * value, gpointer user_data)
{
  GstPad *pad = g_value_get_object (item);
  GstQuery *query = user_data;
  gboolean res;

  _init_context_debug ();

  res = gst_pad_peer_query (pad, query);

  if (res) {
    g_value_set_boolean (value, TRUE);
    return FALSE;
  }

  GST_CAT_INFO_OBJECT (GST_CAT_CONTEXT, pad, "pad peer query failed");
  return TRUE;
}

gboolean
gst_gl_run_query (GstElement * element, GstQuery * query,
    GstPadDirection direction)
{
  GstIterator *it;
  GstIteratorFoldFunction func = pad_query;
  GValue res = { 0 };

  g_value_init (&res, G_TYPE_BOOLEAN);
  g_value_set_boolean (&res, FALSE);

  /* Ask neighbor */
  if (direction == GST_PAD_SRC)
    it = gst_element_iterate_src_pads (element);
  else
    it = gst_element_iterate_sink_pads (element);

  while (gst_iterator_fold (it, func, &res, query) == GST_ITERATOR_RESYNC)
    gst_iterator_resync (it);

  gst_iterator_free (it);

  return g_value_get_boolean (&res);
}

static void
_gst_context_query (GstElement * element, const gchar * display_type)
{
  GstQuery *query;
  GstContext *ctxt;

  _init_context_debug ();

  /*  2a) Query downstream with GST_QUERY_CONTEXT for the context and
   *      check if downstream already has a context of the specific type
   *  2b) Query upstream as above.
   */
  query = gst_query_new_context (display_type);
  if (gst_gl_run_query (element, query, GST_PAD_SRC)) {
    gst_query_parse_context (query, &ctxt);
    GST_CAT_INFO_OBJECT (GST_CAT_CONTEXT, element,
        "found context (%p) in downstream query", ctxt);
    gst_element_set_context (element, ctxt);
  } else if (gst_gl_run_query (element, query, GST_PAD_SINK)) {
    gst_query_parse_context (query, &ctxt);
    GST_CAT_INFO_OBJECT (GST_CAT_CONTEXT, element,
        "found context (%p) in upstream query", ctxt);
    gst_element_set_context (element, ctxt);
  } else {
    /* 3) Post a GST_MESSAGE_NEED_CONTEXT message on the bus with
     *    the required context type and afterwards check if a
     *    usable context was set now as in 1). The message could
     *    be handled by the parent bins of the element and the
     *    application.
     */
    GstMessage *msg;

    GST_CAT_INFO_OBJECT (GST_CAT_CONTEXT, element,
        "posting need context message");
    msg = gst_message_new_need_context (GST_OBJECT_CAST (element),
        display_type);
    gst_element_post_message (element, msg);
  }

  /*
   * Whomever responds to the need-context message performs a
   * GstElement::set_context() with the required context in which the element
   * is required to update the display_ptr or call gst_gl_handle_set_context().
   */

  gst_query_unref (query);
}

static void
gst_gl_display_context_query (GstElement * element, GstGLDisplay ** display_ptr)
{
  _gst_context_query (element, GST_GL_DISPLAY_CONTEXT_TYPE);
  if (*display_ptr)
    return;

#if GST_GL_HAVE_WINDOW_X11
  _gst_context_query (element, "gst.x11.display.handle");
  if (*display_ptr)
    return;
#endif

#if GST_GL_HAVE_WINDOW_WAYLAND
  _gst_context_query (element, "GstWaylandDisplayHandleContextType");
  if (*display_ptr)
    return;
#endif
}

static void
gst_gl_context_query (GstElement * element)
{
  _gst_context_query (element, "gst.gl.app_context");
}

/*  4) Create a context by itself and post a GST_MESSAGE_HAVE_CONTEXT
 *     message.
 */
void
gst_gl_element_propagate_display_context (GstElement * element,
    GstGLDisplay * display)
{
  GstContext *context;
  GstMessage *msg;

  if (!display) {
    GST_ERROR_OBJECT (element, "Could not get GL display connection");
    return;
  }

  _init_context_debug ();

  context = gst_context_new (GST_GL_DISPLAY_CONTEXT_TYPE, TRUE);
  gst_context_set_gl_display (context, display);

  gst_element_set_context (element, context);

  GST_CAT_INFO_OBJECT (GST_CAT_CONTEXT, element,
      "posting have context (%p) message with display (%p)", context, display);
  msg = gst_message_new_have_context (GST_OBJECT_CAST (element), context);
  gst_element_post_message (GST_ELEMENT_CAST (element), msg);
}

/**
 * gst_gl_ensure_element_data:
 * @element: the #GstElement running the query
 * @display_ptr: (inout): the resulting #GstGLDisplay
 * @other_context_ptr: (inout): the resulting #GstGLContext
 *
 * Perform the steps necessary for retrieving a #GstGLDisplay and (optionally)
 * an application provided #GstGLContext from the surrounding elements or from
 * the application using the #GstContext mechanism.
 *
 * If the contents of @display_ptr or @other_context_ptr are not %NULL, then no
 * #GstContext query is necessary for #GstGLDisplay or #GstGLContext retrieval
 * or is performed.
 *
 * This performs #GstContext queries (if necessary) for a winsys display
 * connection with %GST_GL_DISPLAY_CONTEXT_TYPE, "gst.x11.display.handle", and
 * "GstWaylandDisplayHandleContextType" stopping after the first successful
 * retrieval.
 *
 * This also performs a #GstContext query (if necessary) for an optional
 * application provided #GstGLContext using the name "gst.gl.app_context".
 * The returned #GstGLContext will be shared with a GStreamer created OpenGL context.
 *
 * Returns: whether a #GstGLDisplay exists in @display_ptr
 */
gboolean
gst_gl_ensure_element_data (gpointer element, GstGLDisplay ** display_ptr,
    GstGLContext ** other_context_ptr)
{
  GstGLDisplay *display;

  g_return_val_if_fail (element != NULL, FALSE);
  g_return_val_if_fail (display_ptr != NULL, FALSE);
  g_return_val_if_fail (other_context_ptr != NULL, FALSE);

  /*  1) Check if the element already has a context of the specific
   *     type.
   */
  display = *display_ptr;
  if (gst_gl_display_found (element, display))
    goto done;

  gst_gl_display_context_query (element, display_ptr);

  /* Neighbour found and it updated the display */
  if (gst_gl_display_found (element, *display_ptr))
    goto get_gl_context;

  /* If no neighboor, or application not interested, use system default */
  display = gst_gl_display_new ();

  *display_ptr = display;

  gst_gl_element_propagate_display_context (element, display);

get_gl_context:
  if (*other_context_ptr)
    goto done;

  gst_gl_context_query (element);

done:
  return *display_ptr != NULL;
}

/**
 * gst_gl_handle_set_context:
 * @element: a #GstElement
 * @context: a #GstContext
 * @display: (inout) (transfer full): location of a #GstGLDisplay
 * @other_context: (inout) (transfer full): location of a #GstGLContext
 *
 * Helper function for implementing #GstElementClass.set_context() in
 * OpenGL capable elements.
 *
 * Retrieve's the #GstGLDisplay or #GstGLContext in @context and places the
 * result in @display or @other_context respectively.
 *
 * Returns: whether the @display or @other_context could be set successfully
 */
gboolean
gst_gl_handle_set_context (GstElement * element, GstContext * context,
    GstGLDisplay ** display, GstGLContext ** other_context)
{
  GstGLDisplay *display_replacement = NULL;
  GstGLContext *context_replacement = NULL;
  const gchar *context_type;

  g_return_val_if_fail (display != NULL, FALSE);
  g_return_val_if_fail (other_context != NULL, FALSE);

  if (!context)
    return FALSE;

  context_type = gst_context_get_context_type (context);

  if (g_strcmp0 (context_type, GST_GL_DISPLAY_CONTEXT_TYPE) == 0) {
    if (!gst_context_get_gl_display (context, &display_replacement)) {
      GST_WARNING_OBJECT (element, "Failed to get display from context");
      return FALSE;
    }
  }
#if GST_GL_HAVE_WINDOW_X11
  else if (g_strcmp0 (context_type, "gst.x11.display.handle") == 0) {
    const GstStructure *s;
    Display *display;

    s = gst_context_get_structure (context);
    if (gst_structure_get (s, "display", G_TYPE_POINTER, &display, NULL))
      display_replacement =
          (GstGLDisplay *) gst_gl_display_x11_new_with_display (display);
  }
#endif
#if GST_GL_HAVE_WINDOW_WAYLAND
  else if (g_strcmp0 (context_type, "GstWaylandDisplayHandleContextType") == 0) {
    const GstStructure *s;
    struct wl_display *display;

    s = gst_context_get_structure (context);
    if (gst_structure_get (s, "display", G_TYPE_POINTER, &display, NULL))
      display_replacement =
          (GstGLDisplay *) gst_gl_display_wayland_new_with_display (display);
  }
#endif
  else if (g_strcmp0 (context_type, "gst.gl.app_context") == 0) {
    const GstStructure *s = gst_context_get_structure (context);
    GstGLDisplay *context_display;
    GstGLDisplay *element_display;

    if (gst_structure_get (s, "context", GST_TYPE_GL_CONTEXT,
            &context_replacement, NULL)) {
      context_display = gst_gl_context_get_display (context_replacement);
      element_display = display_replacement ? display_replacement : *display;
      if (element_display
          && (gst_gl_display_get_handle_type (element_display) &
              gst_gl_display_get_handle_type (context_display)) == 0) {
        GST_ELEMENT_WARNING (element, LIBRARY, SETTINGS, ("%s",
                "Cannot set a GL context with a different display type"), ("%s",
                "Cannot set a GL context with a different display type"));
        gst_object_unref (context_replacement);
        context_replacement = NULL;
      }
      gst_object_unref (context_display);
    }
  }

  if (display_replacement) {
    GstGLDisplay *old = *display;
    *display = display_replacement;

    if (old)
      gst_object_unref (old);
  }

  if (context_replacement) {
    GstGLContext *old = *other_context;
    *other_context = context_replacement;

    if (old)
      gst_object_unref (old);
  }

  return TRUE;
}

/**
 * gst_gl_handle_context_query:
 * @element: a #GstElement
 * @query: a #GstQuery of type %GST_QUERY_CONTEXT
 * @display: (transfer none) (nullable): a #GstGLDisplay
 * @context: (transfer none) (nullable): a #GstGLContext
 * @other_context: (transfer none) (nullable): application provided #GstGLContext
 *
 * Returns: Whether the @query was successfully responded to from the passed
 *          @display, @context, and @other_context.
 */
gboolean
gst_gl_handle_context_query (GstElement * element, GstQuery * query,
    GstGLDisplay * display, GstGLContext * gl_context,
    GstGLContext * other_context)
{
  const gchar *context_type;
  GstContext *context, *old_context;

  g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
  g_return_val_if_fail (GST_IS_QUERY (query), FALSE);
  g_return_val_if_fail (display == NULL || GST_IS_GL_DISPLAY (display), FALSE);
  g_return_val_if_fail (gl_context == NULL
      || GST_IS_GL_CONTEXT (gl_context), FALSE);
  g_return_val_if_fail (other_context == NULL
      || GST_IS_GL_CONTEXT (other_context), FALSE);

  GST_LOG_OBJECT (element, "handle context query %" GST_PTR_FORMAT, query);
  gst_query_parse_context_type (query, &context_type);

  if (display && g_strcmp0 (context_type, GST_GL_DISPLAY_CONTEXT_TYPE) == 0) {
    gst_query_parse_context (query, &old_context);

    if (old_context)
      context = gst_context_copy (old_context);
    else
      context = gst_context_new (GST_GL_DISPLAY_CONTEXT_TYPE, TRUE);

    gst_context_set_gl_display (context, display);
    gst_query_set_context (query, context);
    gst_context_unref (context);
    GST_DEBUG_OBJECT (element, "successfully set %" GST_PTR_FORMAT
        " on %" GST_PTR_FORMAT, display, query);

    return TRUE;
  }
#if GST_GL_HAVE_WINDOW_X11
  else if (display && g_strcmp0 (context_type, "gst.x11.display.handle") == 0) {
    GstStructure *s;

    gst_query_parse_context (query, &old_context);

    if (old_context)
      context = gst_context_copy (old_context);
    else
      context = gst_context_new ("gst.x11.display.handle", TRUE);

    if (gst_gl_display_get_handle_type (display) & GST_GL_DISPLAY_TYPE_X11) {
      Display *x11_display = (Display *) gst_gl_display_get_handle (display);

      if (x11_display) {
        s = gst_context_writable_structure (context);
        gst_structure_set (s, "display", G_TYPE_POINTER, x11_display, NULL);

        gst_query_set_context (query, context);
        gst_context_unref (context);

        GST_DEBUG_OBJECT (element, "successfully set x11 display %p (from %"
            GST_PTR_FORMAT ") on %" GST_PTR_FORMAT, x11_display, display,
            query);

        return TRUE;
      }
    }
  }
#endif
#if GST_GL_HAVE_WINDOW_WAYLAND
  else if (display
      && g_strcmp0 (context_type, "GstWaylandDisplayHandleContextType") == 0) {
    GstStructure *s;

    gst_query_parse_context (query, &old_context);

    if (old_context)
      context = gst_context_copy (old_context);
    else
      context = gst_context_new ("GstWaylandDisplayHandleContextType", TRUE);

    if (gst_gl_display_get_handle_type (display) & GST_GL_DISPLAY_TYPE_WAYLAND) {
      struct wl_display *wayland_display =
          (struct wl_display *) gst_gl_display_get_handle (display);

      if (wayland_display) {
        s = gst_context_writable_structure (context);
        gst_structure_set (s, "display", G_TYPE_POINTER, wayland_display, NULL);

        gst_query_set_context (query, context);
        gst_context_unref (context);

        GST_DEBUG_OBJECT (element, "successfully set wayland display %p (from %"
            GST_PTR_FORMAT ") on %" GST_PTR_FORMAT, wayland_display, display,
            query);

        return TRUE;
      }
    }
  }
#endif
  else if (other_context && g_strcmp0 (context_type, "gst.gl.app_context") == 0) {
    GstStructure *s;

    gst_query_parse_context (query, &old_context);

    if (old_context)
      context = gst_context_copy (old_context);
    else
      context = gst_context_new ("gst.gl.app_context", TRUE);

    s = gst_context_writable_structure (context);
    gst_structure_set (s, "context", GST_TYPE_GL_CONTEXT, other_context, NULL);
    gst_query_set_context (query, context);
    gst_context_unref (context);

    GST_DEBUG_OBJECT (element, "successfully set application GL context %"
        GST_PTR_FORMAT " on %" GST_PTR_FORMAT, other_context, query);

    return TRUE;
  } else if (gl_context
      && g_strcmp0 (context_type, "gst.gl.local_context") == 0) {
    GstStructure *s;

    gst_query_parse_context (query, &old_context);

    if (old_context)
      context = gst_context_copy (old_context);
    else
      context = gst_context_new ("gst.gl.local_context", TRUE);

    s = gst_context_writable_structure (context);
    gst_structure_set (s, "context", GST_TYPE_GL_CONTEXT, gl_context, NULL);
    gst_query_set_context (query, context);
    gst_context_unref (context);

    GST_DEBUG_OBJECT (element, "successfully set GL context %"
        GST_PTR_FORMAT " on %" GST_PTR_FORMAT, gl_context, query);

    return TRUE;
  }

  return FALSE;
}

/**
 * gst_gl_query_local_gl_context:
 * @element: a #GstElement to query from
 * @direction: the #GstPadDirection to query
 * @context_ptr: (inout): location containing the current and/or resulting
 *                      #GstGLContext
 *
 * Performs a GST_QUERY_CONTEXT query of type "gst.gl.local_context" on all
 * #GstPads in @element of @direction for the local OpenGL context used by
 * GStreamer elements.
 *
 * Returns: whether @context_ptr contains a #GstGLContext
 */
gboolean
gst_gl_query_local_gl_context (GstElement * element, GstPadDirection direction,
    GstGLContext ** context_ptr)
{
  GstQuery *query;
  GstContext *context;
  const GstStructure *s;

  g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
  g_return_val_if_fail (context_ptr != NULL, FALSE);

  if (*context_ptr)
    return TRUE;

  query = gst_query_new_context ("gst.gl.local_context");
  if (gst_gl_run_query (GST_ELEMENT (element), query, direction)) {
    gst_query_parse_context (query, &context);
    if (context) {
      s = gst_context_get_structure (context);
      gst_structure_get (s, "context", GST_TYPE_GL_CONTEXT, context_ptr, NULL);
    }
  }

  gst_query_unref (query);

  return *context_ptr != NULL;
}

/**
 * gst_gl_get_plane_data_size:
 * @info: a #GstVideoInfo
 * @align: a #GstVideoAlignment or %NULL
 * @plane: plane number in @info to retrieve the data size of
 *
 * Retrieve the size in bytes of a video plane of data with a certain alignment
 */
gsize
gst_gl_get_plane_data_size (GstVideoInfo * info, GstVideoAlignment * align,
    guint plane)
{
  gint padded_height;
  gsize plane_size;

  padded_height = info->height;

  if (align)
    padded_height += align->padding_top + align->padding_bottom;

  padded_height =
      GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (info->finfo, plane, padded_height);

  plane_size = GST_VIDEO_INFO_PLANE_STRIDE (info, plane) * padded_height;

  return plane_size;
}

/**
 * gst_gl_get_plane_start:
 * @info: a #GstVideoInfo
 * @valign: a #GstVideoAlignment or %NULL
 * @plane: plane number in @info to retrieve the data size of
 *
 * Returns: difference between the supposed start of the plane from the @info
 *          and where the data from the previous plane ends.
 */
gsize
gst_gl_get_plane_start (GstVideoInfo * info, GstVideoAlignment * valign,
    guint plane)
{
  gsize plane_start;
  gint i;

  /* find the start of the plane data including padding */
  plane_start = 0;
  for (i = 0; i < plane; i++) {
    plane_start += gst_gl_get_plane_data_size (info, valign, i);
  }

  /* offset between the plane data start and where the video frame starts */
  return (GST_VIDEO_INFO_PLANE_OFFSET (info, plane)) - plane_start;
}

/**
 * gst_gl_value_get_texture_target_mask:
 * @value: an initialized #GValue of type G_TYPE_STRING
 *
 * See gst_gl_value_set_texture_target_from_mask() for what entails a mask
 *
 * Returns: the mask of #GstGLTextureTarget's in @value
 */
GstGLTextureTarget
gst_gl_value_get_texture_target_mask (const GValue * targets)
{
  guint new_targets = 0;

  g_return_val_if_fail (targets != NULL, GST_GL_TEXTURE_TARGET_NONE);

  if (G_TYPE_CHECK_VALUE_TYPE (targets, G_TYPE_STRING)) {
    GstGLTextureTarget target;
    const gchar *str;

    str = g_value_get_string (targets);
    target = gst_gl_texture_target_from_string (str);

    if (target)
      new_targets |= 1 << target;
  } else if (G_TYPE_CHECK_VALUE_TYPE (targets, GST_TYPE_LIST)) {
    gint j, m;

    m = gst_value_list_get_size (targets);
    for (j = 0; j < m; j++) {
      const GValue *val = gst_value_list_get_value (targets, j);
      GstGLTextureTarget target;
      const gchar *str;

      str = g_value_get_string (val);
      target = gst_gl_texture_target_from_string (str);
      if (target)
        new_targets |= 1 << target;
    }
  }

  return new_targets;
}

/**
 * gst_gl_value_set_texture_target:
 * @value: an initialized #GValue of type G_TYPE_STRING
 * @target: a #GstGLTextureTarget's
 *
 * Returns: whether the @target could be set on @value
 */
gboolean
gst_gl_value_set_texture_target (GValue * value, GstGLTextureTarget target)
{
  g_return_val_if_fail (value != NULL, FALSE);
  g_return_val_if_fail (target != GST_GL_TEXTURE_TARGET_NONE, FALSE);

  if (target == GST_GL_TEXTURE_TARGET_2D) {
    g_value_set_static_string (value, GST_GL_TEXTURE_TARGET_2D_STR);
  } else if (target == GST_GL_TEXTURE_TARGET_RECTANGLE) {
    g_value_set_static_string (value, GST_GL_TEXTURE_TARGET_RECTANGLE_STR);
  } else if (target == GST_GL_TEXTURE_TARGET_EXTERNAL_OES) {
    g_value_set_static_string (value, GST_GL_TEXTURE_TARGET_EXTERNAL_OES_STR);
  } else {
    return FALSE;
  }

  return TRUE;
}

static guint64
_gst_gl_log2_int64 (guint64 value)
{
  guint64 ret = 0;

  while (value >>= 1)
    ret++;

  return ret;
}

/**
 * gst_gl_value_set_texture_target_from_mask:
 * @value: an uninitialized #GValue
 * @target_mask: a bitwise mask of #GstGLTextureTarget's
 *
 * A mask is a bitwise OR of (1 << target) where target is a valid
 * #GstGLTextureTarget
 *
 * Returns: whether the @target_mask could be set on @value
 */
gboolean
gst_gl_value_set_texture_target_from_mask (GValue * value,
    GstGLTextureTarget target_mask)
{
  g_return_val_if_fail (value != NULL, FALSE);
  g_return_val_if_fail (target_mask != GST_GL_TEXTURE_TARGET_NONE, FALSE);

  if ((target_mask & (target_mask - 1)) == 0) {
    /* only one texture target set */
    g_value_init (value, G_TYPE_STRING);
    return gst_gl_value_set_texture_target (value,
        _gst_gl_log2_int64 (target_mask));
  } else {
    GValue item = G_VALUE_INIT;
    gboolean ret = FALSE;

    g_value_init (value, GST_TYPE_LIST);
    g_value_init (&item, G_TYPE_STRING);
    if (target_mask & (1 << GST_GL_TEXTURE_TARGET_2D)) {
      gst_gl_value_set_texture_target (&item, GST_GL_TEXTURE_TARGET_2D);
      gst_value_list_append_value (value, &item);
      ret = TRUE;
    }
    if (target_mask & (1 << GST_GL_TEXTURE_TARGET_RECTANGLE)) {
      gst_gl_value_set_texture_target (&item, GST_GL_TEXTURE_TARGET_RECTANGLE);
      gst_value_list_append_value (value, &item);
      ret = TRUE;
    }
    if (target_mask & (1 << GST_GL_TEXTURE_TARGET_EXTERNAL_OES)) {
      gst_gl_value_set_texture_target (&item,
          GST_GL_TEXTURE_TARGET_EXTERNAL_OES);
      gst_value_list_append_value (value, &item);
      ret = TRUE;
    }

    g_value_unset (&item);
    return ret;
  }
}

static const gfloat identity_matrix[] = {
  1.0, 0.0, 0.0, 0.0,
  0.0, 1.0, 0.0, 0.0,
  0.0, 0.0, 1.0, 0.0,
  0.0, 0.0, 0.0, 1.0,
};

static const gfloat from_ndc_matrix[] = {
  0.5, 0.0, 0.0, 0.0,
  0.0, 0.5, 0.0, 0.0,
  0.0, 0.0, 0.5, 0.0,
  0.5, 0.5, 0.5, 1.0,
};

static const gfloat to_ndc_matrix[] = {
  2.0, 0.0, 0.0, 0.0,
  0.0, 2.0, 0.0, 0.0,
  0.0, 0.0, 2.0, 0.0,
  -1.0, -1.0, -1.0, 1.0,
};

/* multiplies two 4x4 matrices, @a X @b, and stores the result in @result
 * https://en.wikipedia.org/wiki/Matrix_multiplication
 */
static void
gst_gl_multiply_matrix4 (const gfloat * a, const gfloat * b, gfloat * result)
{
  int i, j, k;
  gfloat tmp[16] = { 0.0f };

  if (!a || !b || !result)
    return;
  for (i = 0; i < 4; i++) {     /* column */
    for (j = 0; j < 4; j++) {   /* row */
      for (k = 0; k < 4; k++) {
        tmp[j + (i * 4)] += a[k + (i * 4)] * b[j + (k * 4)];
      }
    }
  }

  for (i = 0; i < 16; i++)
    result[i] = tmp[i];
}

/*
 * gst_gl_get_affine_transformation_meta_as_ndc:
 * @meta: (nullable): a #GstVideoAffineTransformationMeta
 * @matrix: (out): result of the 4x4 matrix
 *
 * Retrieves the stored 4x4 affine transformation matrix stored in @meta in
 * NDC coordinates. if @meta is NULL, an identity matrix is returned.
 *
 * NDC is a left-handed coordinate sytem
 * - x - [-1, 1] - +ve X moves right
 * - y - [-1, 1] - +ve Y moves up
 * - z - [-1, 1] - +ve Z moves into
 */
void
gst_gl_get_affine_transformation_meta_as_ndc (GstVideoAffineTransformationMeta *
    meta, gfloat * matrix)
{
  if (!meta) {
    int i;

    for (i = 0; i < 16; i++) {
      matrix[i] = identity_matrix[i];
    }
  } else {
    float tmp[16];

    /* change of basis multiplications */
    gst_gl_multiply_matrix4 (from_ndc_matrix, meta->matrix, tmp);
    gst_gl_multiply_matrix4 (tmp, to_ndc_matrix, matrix);
  }
}

void gst_gl_set_affine_transformation_meta_from_ndc
    (GstVideoAffineTransformationMeta * meta, const gfloat * matrix)
{
  float tmp[16];

  g_return_if_fail (meta != NULL);

  /* change of basis multiplications */
  gst_gl_multiply_matrix4 (to_ndc_matrix, matrix, tmp);
  gst_gl_multiply_matrix4 (tmp, from_ndc_matrix, meta->matrix);
}


text:
package org.aktin.broker.client.run;

import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.List;

import org.aktin.broker.client.BrokerClientImpl;
import org.aktin.broker.client.auth.HttpApiKeyAuth;
import org.aktin.broker.xml.RequestInfo;

/**
 * Fetch requests.
 * @author R.W.Majeed
 *
 */
public class ListRequests {

	/**
	 * Fetch requests.
	 * @param args command line arguments. First two are required: Broker URL and API key.
	 * @throws IOException IO Error
	 */
	public static void main(String[] args) throws IOException{
		String apiKey = args[1];
		String brokerUrl = args[0];
		BrokerClientImpl client = new BrokerClientImpl(URI.create(brokerUrl));
		client.setClientAuthenticator(HttpApiKeyAuth.newBearer(apiKey));
		System.out.println("Connecting to broker "+brokerUrl);
		List<RequestInfo> rl = client.listMyRequests();
		System.out.println("Number of requests "+rl.size());
		for( RequestInfo i : rl ){
			System.out.println("Request #"+i.getId());
			System.out.println("\ttargeted="+i.targeted);
			System.out.println("\tpublished="+i.published);
			System.out.println("\ttypes="+Arrays.toString(i.types));
			System.out.println();
		}
	}
}


text:
module Homeflow
  module API
   class Location < Resource

    is_resource :locations

    #returns a search object pre build withe the correct place id
    def properties
      Property.where(:place => {:id => place_id})
    end

    def self.find_by_county_id_and_location_id(county_id, location_id)
      Request.run_for(Homeflow::API::ResourceIdentifier.new("/counties/#{county_id}/locations/#{location_id}"))
    end

    def self.find_by_country_id_and_county_id_and_location_id(country_id, county_id, location_id)
      Request.run_for(Homeflow::API::ResourceIdentifier.new("/countries/#{country_id}/counties/#{county_id}/locations/#{location_id}"))
    end

   end
 end
end


text:
<?php declare(strict_types=1);

namespace PHPUnit\Framework\Constraint;

use function array_map;
use function array_values;
use function count;

/**
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise for PHPUnit
 */
abstract class BinaryOperator extends Operator
{
    /**
     * @var Constraint[]
     */
    private $constraints = [];

    public static function fromConstraints(Constraint ...$constraints): self
    {
        $constraint = new static;

        $constraint->constraints = $constraints;

        return $constraint;
    }

    /**
     * @param mixed[] $constraints
     */
    public function setConstraints(array $constraints): void
    {
        $this->constraints = array_map(function ($constraint): Constraint {
            return $this->checkConstraint($constraint);
        }, array_values($constraints));
    }

    /**
     * Returns the number of operands (constraints).
     */
    final public function arity(): int
    {
        return count($this->constraints);
    }

    /**
     * Returns a string representation of the constraint.
     */
    public function toString(): string
    {
        $reduced = $this->reduce();

        if ($reduced !== $this) {
            return $reduced->toString();
        }

        $text = '';

        foreach ($this->constraints as $key => $constraint) {
            $constraint = $constraint->reduce();

            $text .= $this->constraintToString($constraint, $key);
        }

        return $text;
    }

    /**
     * Counts the number of constraint elements.
     */
    public function count(): int
    {
        $count = 0;

        foreach ($this->constraints as $constraint) {
            $count += count($constraint);
        }

        return $count;
    }

    /**
     * Returns the nested constraints.
     */
    final protected function constraints(): array
    {
        return $this->constraints;
    }

    /**
     * Returns true if the $constraint needs to be wrapped with braces.
     */
    final protected function constraintNeedsParentheses(Constraint $constraint): bool
    {
        return $this->arity() > 1 && parent::constraintNeedsParentheses($constraint);
    }

    /**
     * Reduces the sub-expression starting at $this by skipping degenerate
     * sub-expression and returns first descendant constraint that starts
     * a non-reducible sub-expression.
     *
     * See Constraint::reduce() for more.
     */
    protected function reduce(): Constraint
    {
        if ($this->arity() === 1 && $this->constraints[0] instanceof Operator) {
            return $this->constraints[0]->reduce();
        }

        return parent::reduce();
    }

    /**
     * Returns string representation of given operand in context of this operator.
     *
     * @param Constraint $constraint operand constraint
     * @param int        $position   position of $constraint in this expression
     */
    private function constraintToString(Constraint $constraint, int $position): string
    {
        $prefix = '';

        if ($position > 0) {
            $prefix = (' ' . $this->operator() . ' ');
        }

        if ($this->constraintNeedsParentheses($constraint)) {
            return $prefix . '( ' . $constraint->toString() . ' )';
        }

        $string = $constraint->toStringInContext($this, $position);

        if ($string === '') {
            $string = $constraint->toString();
        }

        return $prefix . $string;
    }
}