text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

/**
 * EbsBlockDeviceType.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis2 version: 1.5.6  Built on : Aug 30, 2011 (10:01:01 CEST)
 */

                package com.amazon.ec2;

            /**
            *  EbsBlockDeviceType bean class
            */

        public  class EbsBlockDeviceType
        implements org.apache.axis2.databinding.ADBBean{
        /* This type was generated from the piece of schema that had
                name = EbsBlockDeviceType
                Namespace URI = http://ec2.amazonaws.com/doc/2012-08-15/
                Namespace Prefix = ns1
                */

        private static java.lang.String generatePrefix(java.lang.String namespace) {
            if(namespace.equals("http://ec2.amazonaws.com/doc/2012-08-15/")){
                return "ns1";
            }
            return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
        }

                        /**
                        * field for SnapshotId
                        */

                                    protected java.lang.String localSnapshotId ;

                           /*  This tracker boolean wil be used to detect whether the user called the set method
                          *   for this attribute. It will be used to determine whether to include this field
                           *   in the serialized XML
                           */
                           protected boolean localSnapshotIdTracker = false ;

                           /**
                           * Auto generated getter method
                           * @return java.lang.String
                           */
                           public  java.lang.String getSnapshotId(){
                               return localSnapshotId;
                           }

                            /**
                               * Auto generated setter method
                               * @param param SnapshotId
                               */
                               public void setSnapshotId(java.lang.String param){

                                       if (param != null){
                                          //update the setting tracker
                                          localSnapshotIdTracker = true;
                                       } else {
                                          localSnapshotIdTracker = false;

                                       }

                                            this.localSnapshotId=param;

                               }

                        /**
                        * field for VolumeSize
                        */

                                    protected int localVolumeSize ;

                           /*  This tracker boolean wil be used to detect whether the user called the set method
                          *   for this attribute. It will be used to determine whether to include this field
                           *   in the serialized XML
                           */
                           protected boolean localVolumeSizeTracker = false ;

                           /**
                           * Auto generated getter method
                           * @return int
                           */
                           public  int getVolumeSize(){
                               return localVolumeSize;
                           }

                            /**
                               * Auto generated setter method
                               * @param param VolumeSize
                               */
                               public void setVolumeSize(int param){

                                       // setting primitive attribute tracker to true

                                               if (param==java.lang.Integer.MIN_VALUE) {
                                           localVolumeSizeTracker = false;

                                       } else {
                                          localVolumeSizeTracker = true;
                                       }

                                            this.localVolumeSize=param;

                               }

                        /**
                        * field for DeleteOnTermination
                        */

                                    protected boolean localDeleteOnTermination ;

                           /*  This tracker boolean wil be used to detect whether the user called the set method
                          *   for this attribute. It will be used to determine whether to include this field
                           *   in the serialized XML
                           */
                           protected boolean localDeleteOnTerminationTracker = false ;

                           /**
                           * Auto generated getter method
                           * @return boolean
                           */
                           public  boolean getDeleteOnTermination(){
                               return localDeleteOnTermination;
                           }

                            /**
                               * Auto generated setter method
                               * @param param DeleteOnTermination
                               */
                               public void setDeleteOnTermination(boolean param){

                                       // setting primitive attribute tracker to true

                                               if (false) {
                                           localDeleteOnTerminationTracker = false;

                                       } else {
                                          localDeleteOnTerminationTracker = true;
                                       }

                                            this.localDeleteOnTermination=param;

                               }

                        /**
                        * field for VolumeType
                        */

                                    protected java.lang.String localVolumeType ;

                           /*  This tracker boolean wil be used to detect whether the user called the set method
                          *   for this attribute. It will be used to determine whether to include this field
                           *   in the serialized XML
                           */
                           protected boolean localVolumeTypeTracker = false ;

                           /**
                           * Auto generated getter method
                           * @return java.lang.String
                           */
                           public  java.lang.String getVolumeType(){
                               return localVolumeType;
                           }

                            /**
                               * Auto generated setter method
                               * @param param VolumeType
                               */
                               public void setVolumeType(java.lang.String param){

                                       if (param != null){
                                          //update the setting tracker
                                          localVolumeTypeTracker = true;
                                       } else {
                                          localVolumeTypeTracker = false;

                                       }

                                            this.localVolumeType=param;

                               }

                        /**
                        * field for Iops
                        */

                                    protected int localIops ;

                           /*  This tracker boolean wil be used to detect whether the user called the set method
                          *   for this attribute. It will be used to determine whether to include this field
                           *   in the serialized XML
                           */
                           protected boolean localIopsTracker = false ;

                           /**
                           * Auto generated getter method
                           * @return int
                           */
                           public  int getIops(){
                               return localIops;
                           }

                            /**
                               * Auto generated setter method
                               * @param param Iops
                               */
                               public void setIops(int param){

                                       // setting primitive attribute tracker to true

                                               if (param==java.lang.Integer.MIN_VALUE) {
                                           localIopsTracker = false;

                                       } else {
                                          localIopsTracker = true;
                                       }

                                            this.localIops=param;

                               }

     /**
     * isReaderMTOMAware
     * @return true if the reader supports MTOM
     */
   public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) {
        boolean isReaderMTOMAware = false;

        try{
          isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE));
        }catch(java.lang.IllegalArgumentException e){
          isReaderMTOMAware = false;
        }
        return isReaderMTOMAware;
   }

        /**
        *
        * @param parentQName
        * @param factory
        * @return org.apache.axiom.om.OMElement
        */
       public org.apache.axiom.om.OMElement getOMElement (
               final javax.xml.namespace.QName parentQName,
               final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{

               org.apache.axiom.om.OMDataSource dataSource =
                       new org.apache.axis2.databinding.ADBDataSource(this,parentQName){

                 public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
                       EbsBlockDeviceType.this.serialize(parentQName,factory,xmlWriter);
                 }
               };
               return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl(
               parentQName,factory,dataSource);

       }

         public void serialize(final javax.xml.namespace.QName parentQName,
                                       final org.apache.axiom.om.OMFactory factory,
                                       org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter)
                                throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
                           serialize(parentQName,factory,xmlWriter,false);
         }

         public void serialize(final javax.xml.namespace.QName parentQName,
                               final org.apache.axiom.om.OMFactory factory,
                               org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter,
                               boolean serializeType)
            throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{

                java.lang.String prefix = null;
                java.lang.String namespace = null;

                    prefix = parentQName.getPrefix();
                    namespace = parentQName.getNamespaceURI();

                    if ((namespace != null) && (namespace.trim().length() > 0)) {
                        java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
                        if (writerPrefix != null) {
                            xmlWriter.writeStartElement(namespace, parentQName.getLocalPart());
                        } else {
                            if (prefix == null) {
                                prefix = generatePrefix(namespace);
                            }

                            xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace);
                            xmlWriter.writeNamespace(prefix, namespace);
                            xmlWriter.setPrefix(prefix, namespace);
                        }
                    } else {
                        xmlWriter.writeStartElement(parentQName.getLocalPart());
                    }

                  if (serializeType){

                   java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://ec2.amazonaws.com/doc/2012-08-15/");
                   if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){
                       writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
                           namespacePrefix+":EbsBlockDeviceType",
                           xmlWriter);
                   } else {
                       writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
                           "EbsBlockDeviceType",
                           xmlWriter);
                   }

                   }
                if (localSnapshotIdTracker){
                                    namespace = "http://ec2.amazonaws.com/doc/2012-08-15/";
                                    if (! namespace.equals("")) {
                                        prefix = xmlWriter.getPrefix(namespace);

                                        if (prefix == null) {
                                            prefix = generatePrefix(namespace);

                                            xmlWriter.writeStartElement(prefix,"snapshotId", namespace);
                                            xmlWriter.writeNamespace(prefix, namespace);
                                            xmlWriter.setPrefix(prefix, namespace);

                                        } else {
                                            xmlWriter.writeStartElement(namespace,"snapshotId");
                                        }

                                    } else {
                                        xmlWriter.writeStartElement("snapshotId");
                                    }

                                          if (localSnapshotId==null){
                                              // write the nil attribute

                                                     throw new org.apache.axis2.databinding.ADBException("snapshotId cannot be null!!");

                                          }else{

                                                   xmlWriter.writeCharacters(localSnapshotId);

                                          }

                                   xmlWriter.writeEndElement();
                             } if (localVolumeSizeTracker){
                                    namespace = "http://ec2.amazonaws.com/doc/2012-08-15/";
                                    if (! namespace.equals("")) {
                                        prefix = xmlWriter.getPrefix(namespace);

                                        if (prefix == null) {
                                            prefix = generatePrefix(namespace);

                                            xmlWriter.writeStartElement(prefix,"volumeSize", namespace);
                                            xmlWriter.writeNamespace(prefix, namespace);
                                            xmlWriter.setPrefix(prefix, namespace);

                                        } else {
                                            xmlWriter.writeStartElement(namespace,"volumeSize");
                                        }

                                    } else {
                                        xmlWriter.writeStartElement("volumeSize");
                                    }

                                               if (localVolumeSize==java.lang.Integer.MIN_VALUE) {

                                                         throw new org.apache.axis2.databinding.ADBException("volumeSize cannot be null!!");

                                               } else {
                                                    xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localVolumeSize));
                                               }

                                   xmlWriter.writeEndElement();
                             } if (localDeleteOnTerminationTracker){
                                    namespace = "http://ec2.amazonaws.com/doc/2012-08-15/";
                                    if (! namespace.equals("")) {
                                        prefix = xmlWriter.getPrefix(namespace);

                                        if (prefix == null) {
                                            prefix = generatePrefix(namespace);

                                            xmlWriter.writeStartElement(prefix,"deleteOnTermination", namespace);
                                            xmlWriter.writeNamespace(prefix, namespace);
                                            xmlWriter.setPrefix(prefix, namespace);

                                        } else {
                                            xmlWriter.writeStartElement(namespace,"deleteOnTermination");
                                        }

                                    } else {
                                        xmlWriter.writeStartElement("deleteOnTermination");
                                    }

                                               if (false) {

                                                         throw new org.apache.axis2.databinding.ADBException("deleteOnTermination cannot be null!!");

                                               } else {
                                                    xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localDeleteOnTermination));
                                               }

                                   xmlWriter.writeEndElement();
                             } if (localVolumeTypeTracker){
                                    namespace = "http://ec2.amazonaws.com/doc/2012-08-15/";
                                    if (! namespace.equals("")) {
                                        prefix = xmlWriter.getPrefix(namespace);

                                        if (prefix == null) {
                                            prefix = generatePrefix(namespace);

                                            xmlWriter.writeStartElement(prefix,"volumeType", namespace);
                                            xmlWriter.writeNamespace(prefix, namespace);
                                            xmlWriter.setPrefix(prefix, namespace);

                                        } else {
                                            xmlWriter.writeStartElement(namespace,"volumeType");
                                        }

                                    } else {
                                        xmlWriter.writeStartElement("volumeType");
                                    }

                                          if (localVolumeType==null){
                                              // write the nil attribute

                                                     throw new org.apache.axis2.databinding.ADBException("volumeType cannot be null!!");

                                          }else{

                                                   xmlWriter.writeCharacters(localVolumeType);

                                          }

                                   xmlWriter.writeEndElement();
                             } if (localIopsTracker){
                                    namespace = "http://ec2.amazonaws.com/doc/2012-08-15/";
                                    if (! namespace.equals("")) {
                                        prefix = xmlWriter.getPrefix(namespace);

                                        if (prefix == null) {
                                            prefix = generatePrefix(namespace);

                                            xmlWriter.writeStartElement(prefix,"iops", namespace);
                                            xmlWriter.writeNamespace(prefix, namespace);
                                            xmlWriter.setPrefix(prefix, namespace);

                                        } else {
                                            xmlWriter.writeStartElement(namespace,"iops");
                                        }

                                    } else {
                                        xmlWriter.writeStartElement("iops");
                                    }

                                               if (localIops==java.lang.Integer.MIN_VALUE) {

                                                         throw new org.apache.axis2.databinding.ADBException("iops cannot be null!!");

                                               } else {
                                                    xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localIops));
                                               }

                                   xmlWriter.writeEndElement();
                             }
                    xmlWriter.writeEndElement();

        }

         /**
          * Util method to write an attribute with the ns prefix
          */
          private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,
                                      java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
              if (xmlWriter.getPrefix(namespace) == null) {
                       xmlWriter.writeNamespace(prefix, namespace);
                       xmlWriter.setPrefix(prefix, namespace);

              }

              xmlWriter.writeAttribute(namespace,attName,attValue);

         }

        /**
          * Util method to write an attribute without the ns prefix
          */
          private void writeAttribute(java.lang.String namespace,java.lang.String attName,
                                      java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
                if (namespace.equals(""))
              {
                  xmlWriter.writeAttribute(attName,attValue);
              }
              else
              {
                  registerPrefix(xmlWriter, namespace);
                  xmlWriter.writeAttribute(namespace,attName,attValue);
              }
          }

           /**
             * Util method to write an attribute without the ns prefix
             */
            private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName,
                                             javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {

                java.lang.String attributeNamespace = qname.getNamespaceURI();
                java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);
                if (attributePrefix == null) {
                    attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
                }
                java.lang.String attributeValue;
                if (attributePrefix.trim().length() > 0) {
                    attributeValue = attributePrefix + ":" + qname.getLocalPart();
                } else {
                    attributeValue = qname.getLocalPart();
                }

                if (namespace.equals("")) {
                    xmlWriter.writeAttribute(attName, attributeValue);
                } else {
                    registerPrefix(xmlWriter, namespace);
                    xmlWriter.writeAttribute(namespace, attName, attributeValue);
                }
            }
        /**
         *  method to handle Qnames
         */

        private void writeQName(javax.xml.namespace.QName qname,
                                javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
            java.lang.String namespaceURI = qname.getNamespaceURI();
            if (namespaceURI != null) {
                java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);
                if (prefix == null) {
                    prefix = generatePrefix(namespaceURI);
                    xmlWriter.writeNamespace(prefix, namespaceURI);
                    xmlWriter.setPrefix(prefix,namespaceURI);
                }

                if (prefix.trim().length() > 0){
                    xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
                } else {
                    // i.e this is the default namespace
                    xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
                }

            } else {
                xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
            }
        }

        private void writeQNames(javax.xml.namespace.QName[] qnames,
                                 javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {

            if (qnames != null) {
                // we have to store this data until last moment since it is not possible to write any
                // namespace data after writing the charactor data
                java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer();
                java.lang.String namespaceURI = null;
                java.lang.String prefix = null;

                for (int i = 0; i < qnames.length; i++) {
                    if (i > 0) {
                        stringToWrite.append(" ");
                    }
                    namespaceURI = qnames[i].getNamespaceURI();
                    if (namespaceURI != null) {
                        prefix = xmlWriter.getPrefix(namespaceURI);
                        if ((prefix == null) || (prefix.length() == 0)) {
                            prefix = generatePrefix(namespaceURI);
                            xmlWriter.writeNamespace(prefix, namespaceURI);
                            xmlWriter.setPrefix(prefix,namespaceURI);
                        }

                        if (prefix.trim().length() > 0){
                            stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
                        } else {
                            stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
                        }
                    } else {
                        stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
                    }
                }
                xmlWriter.writeCharacters(stringToWrite.toString());
            }

        }

         /**
         * Register a namespace prefix
         */
         private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
                java.lang.String prefix = xmlWriter.getPrefix(namespace);

                if (prefix == null) {
                    prefix = generatePrefix(namespace);

                    while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) {
                        prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
                    }

                    xmlWriter.writeNamespace(prefix, namespace);
                    xmlWriter.setPrefix(prefix, namespace);
                }

                return prefix;
            }

        /**
        * databinding method to get an XML representation of this object
        *
        */
        public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName)
                    throws org.apache.axis2.databinding.ADBException{

                 java.util.ArrayList elementList = new java.util.ArrayList();
                 java.util.ArrayList attribList = new java.util.ArrayList();

                 if (localSnapshotIdTracker){
                                      elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/",
                                                                      "snapshotId"));

                                        if (localSnapshotId != null){
                                            elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localSnapshotId));
                                        } else {
                                           throw new org.apache.axis2.databinding.ADBException("snapshotId cannot be null!!");
                                        }
                                    } if (localVolumeSizeTracker){
                                      elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/",
                                                                      "volumeSize"));

                                elementList.add(
                                   org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localVolumeSize));
                            } if (localDeleteOnTerminationTracker){
                                      elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/",
                                                                      "deleteOnTermination"));

                                elementList.add(
                                   org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localDeleteOnTermination));
                            } if (localVolumeTypeTracker){
                                      elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/",
                                                                      "volumeType"));

                                        if (localVolumeType != null){
                                            elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localVolumeType));
                                        } else {
                                           throw new org.apache.axis2.databinding.ADBException("volumeType cannot be null!!");
                                        }
                                    } if (localIopsTracker){
                                      elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/",
                                                                      "iops"));

                                elementList.add(
                                   org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localIops));
                            }

                return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray());

        }

     /**
      *  Factory class that keeps the parse method
      */
    public static class Factory{

        /**
        * static method to create the object
        * Precondition:  If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable
        *                If this object is not an element, it is a complex type and the reader is at the event just after the outer start element
        * Postcondition: If this object is an element, the reader is positioned at its end element
        *                If this object is a complex type, the reader is positioned at the end element of its outer element
        */
        public static EbsBlockDeviceType parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{
            EbsBlockDeviceType object =
                new EbsBlockDeviceType();

            int event;
            java.lang.String nillableValue = null;
            java.lang.String prefix ="";
            java.lang.String namespaceuri ="";
            try {

                while (!reader.isStartElement() && !reader.isEndElement())
                    reader.next();

                if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){
                  java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
                        "type");
                  if (fullTypeName!=null){
                    java.lang.String nsPrefix = null;
                    if (fullTypeName.indexOf(":") > -1){
                        nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":"));
                    }
                    nsPrefix = nsPrefix==null?"":nsPrefix;

                    java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1);

                            if (!"EbsBlockDeviceType".equals(type)){
                                //find namespace for the prefix
                                java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
                                return (EbsBlockDeviceType)com.amazon.ec2.ExtensionMapper.getTypeObject(
                                     nsUri,type,reader);
                              }

                  }

                }

                // Note all attributes that were handled. Used to differ normal attributes
                // from anyAttributes.
                java.util.Vector handledAttributes = new java.util.Vector();

                    reader.next();

                                    while (!reader.isStartElement() && !reader.isEndElement()) reader.next();

                                    if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","snapshotId").equals(reader.getName())){

                                    java.lang.String content = reader.getElementText();

                                              object.setSnapshotId(
                                                    org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));

                                        reader.next();

                              }  // End of if for expected property start element

                                    else {

                                    }

                                    while (!reader.isStartElement() && !reader.isEndElement()) reader.next();

                                    if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","volumeSize").equals(reader.getName())){

                                    java.lang.String content = reader.getElementText();

                                              object.setVolumeSize(
                                                    org.apache.axis2.databinding.utils.ConverterUtil.convertToInt(content));

                                        reader.next();

                              }  // End of if for expected property start element

                                    else {

                                               object.setVolumeSize(java.lang.Integer.MIN_VALUE);

                                    }

                                    while (!reader.isStartElement() && !reader.isEndElement()) reader.next();

                                    if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","deleteOnTermination").equals(reader.getName())){

                                    java.lang.String content = reader.getElementText();

                                              object.setDeleteOnTermination(
                                                    org.apache.axis2.databinding.utils.ConverterUtil.convertToBoolean(content));

                                        reader.next();

                              }  // End of if for expected property start element

                                    else {

                                    }

                                    while (!reader.isStartElement() && !reader.isEndElement()) reader.next();

                                    if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","volumeType").equals(reader.getName())){

                                    java.lang.String content = reader.getElementText();

                                              object.setVolumeType(
                                                    org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));

                                        reader.next();

                              }  // End of if for expected property start element

                                    else {

                                    }

                                    while (!reader.isStartElement() && !reader.isEndElement()) reader.next();

                                    if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","iops").equals(reader.getName())){

                                    java.lang.String content = reader.getElementText();

                                              object.setIops(
                                                    org.apache.axis2.databinding.utils.ConverterUtil.convertToInt(content));

                                        reader.next();

                              }  // End of if for expected property start element

                                    else {

                                               object.setIops(java.lang.Integer.MIN_VALUE);

                                    }

                            while (!reader.isStartElement() && !reader.isEndElement())
                                reader.next();

                                if (reader.isStartElement())
                                // A start element we are not expecting indicates a trailing invalid property
                                throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName());

            } catch (javax.xml.stream.XMLStreamException e) {
                throw new java.lang.Exception(e);
            }

            return object;
        }

        }//end of factory class

        }


text:
package mil.nga.geopackage.user;

import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import mil.nga.geopackage.GeoPackageException;
import mil.nga.geopackage.db.GeoPackageDataType;

/**
 * User Row containing the values from a single cursor row
 *
 * @param <TColumn>
 *            column type
 * @param <TTable>
 *            table type
 *
 * @author osbornb
 */
public abstract class UserCoreRow<TColumn extends UserColumn, TTable extends UserTable<TColumn>> {

	/**
	 * User table
	 */
	protected final TTable table;

	/**
	 * User columns
	 */
	protected final UserColumns<TColumn> columns;

	/**
	 * Cursor column types of this row, based upon the data values
	 */
	protected final int[] columnTypes;

	/**
	 * Array of row values
	 */
	protected final Object[] values;

	/**
	 * Constructor
	 *
	 * @param table
	 *            table
	 * @param columns
	 *            columns
	 * @param columnTypes
	 *            column types
	 * @param values
	 *            values
	 * @since 3.5.0
	 */
	protected UserCoreRow(TTable table, UserColumns<TColumn> columns,
			int[] columnTypes, Object[] values) {
		this.table = table;
		this.columns = columns;
		this.columnTypes = columnTypes;
		this.values = values;
	}

	/**
	 * Constructor to create an empty row
	 *
	 * @param table
	 *            table
	 */
	protected UserCoreRow(TTable table) {
		this.table = table;
		this.columns = table.getUserColumns();
		// Default column types will all be 0 which is null
		// (Cursor.FIELD_TYPE_NULL)
		this.columnTypes = new int[table.columnCount()];
		this.values = new Object[table.columnCount()];
	}

	/**
	 * Copy Constructor
	 *
	 * @param userCoreRow
	 *            user core row to copy
	 */
	protected UserCoreRow(UserCoreRow<TColumn, TTable> userCoreRow) {
		this.table = userCoreRow.table;
		this.columns = userCoreRow.columns;
		this.columnTypes = userCoreRow.columnTypes;
		this.values = new Object[userCoreRow.values.length];
		for (int i = 0; i < this.values.length; i++) {
			Object value = userCoreRow.values[i];
			if (value != null) {
				TColumn column = userCoreRow.getColumn(i);
				this.values[i] = copyValue(column, value);
			}
		}
	}

	/**
	 * Copy the value of the data type
	 *
	 * @param column
	 *            table column
	 * @param value
	 *            value
	 * @return copy value
	 */
	protected Object copyValue(TColumn column, Object value) {

		Object copyValue = value;

		switch (column.getDataType()) {

		case BLOB:
			if (value instanceof byte[]) {
				byte[] bytes = (byte[]) value;
				copyValue = Arrays.copyOf(bytes, bytes.length);
			} else {
				throw new GeoPackageException(
						"Unsupported copy value type. column: "
								+ column.getName() + ", value type: "
								+ value.getClass().getName() + ", data type: "
								+ column.getDataType());
			}
			break;
		case DATE:
		case DATETIME:
			if (value instanceof Date) {
				Date date = (Date) value;
				copyValue = new Date(date.getTime());
			} else if (!(value instanceof String)) {
				throw new GeoPackageException(
						"Unsupported copy value type. column: "
								+ column.getName() + ", value type: "
								+ value.getClass().getName() + ", data type: "
								+ column.getDataType());
			}
			break;
		default:

		}

		return copyValue;
	}

	/**
	 * Get the column count
	 *
	 * @return column count
	 */
	public int columnCount() {
		return columns.columnCount();
	}

	/**
	 * Get a Map
	 *
	 * @return a map
	 * @since 3.0.1
	 */
	public Set<Map.Entry<String, ColumnValue>> getAsMap() {
		Set<Map.Entry<String, ColumnValue>> result = new LinkedHashSet<>();
		for (int inx = 0; inx < columnCount(); inx++) {
			result.add(new AbstractMap.SimpleEntry<String, ColumnValue>(
					getColumnName(inx), new ColumnValue(getValue(inx))));
		}

		return result;
	}

	/**
	 * Get the column names
	 *
	 * @return column names
	 */
	public String[] getColumnNames() {
		return columns.getColumnNames();
	}

	/**
	 * Get the column name at the index
	 *
	 * @param index
	 *            index
	 * @return column name
	 */
	public String getColumnName(int index) {
		return columns.getColumnName(index);
	}

	/**
	 * Get the index of the column name
	 *
	 * @param columnName
	 *            column name
	 * @return column index
	 */
	public int getColumnIndex(String columnName) {
		return columns.getColumnIndex(columnName);
	}

	/**
	 * Get the value at the index
	 *
	 * @param index
	 *            index
	 * @return value
	 */
	public Object getValue(int index) {
		return values[index];
	}

	/**
	 * Get the value of the column name
	 *
	 * @param columnName
	 *            column name
	 * @return value
	 */
	public Object getValue(String columnName) {
		return values[columns.getColumnIndex(columnName)];
	}

	/**
	 * Get the value at the index as a string
	 *
	 * @param index
	 *            index
	 * @return value
	 * @since 3.2.0
	 */
	public String getValueString(int index) {
		String stringValue = null;
		Object value = getValue(index);
		if (value != null) {
			stringValue = value.toString();
		}
		return stringValue;
	}

	/**
	 * Get the value of the column name as a string
	 *
	 * @param columnName
	 *            column name
	 * @return value
	 * @since 3.2.0
	 */
	public String getValueString(String columnName) {
		return getValueString(columns.getColumnIndex(columnName));
	}

	/**
	 * Get the row values
	 *
	 * @return values
	 */
	public Object[] getValues() {
		return values;
	}

	/**
	 * Get the row column data types
	 *
	 * @return row column types
	 */
	public int[] getRowColumnTypes() {
		return columnTypes;
	}

	/**
	 * Get the Cursor column data type at the index
	 *
	 * @param index
	 *            index
	 * @return row column type
	 */
	public int getRowColumnType(int index) {
		return columnTypes[index];
	}

	/**
	 * Get the Cursor column data type of the column name
	 *
	 * @param columnName
	 *            column name
	 * @return row column type
	 */
	public int getRowColumnType(String columnName) {
		return columnTypes[columns.getColumnIndex(columnName)];
	}

	/**
	 * Get the table
	 *
	 * @return table
	 */
	public TTable getTable() {
		return table;
	}

	/**
	 * Get the columns
	 *
	 * @return columns
	 * @since 3.5.0
	 */
	public UserColumns<TColumn> getColumns() {
		return columns;
	}

	/**
	 * Get the column at the index
	 *
	 * @param index
	 *            index
	 * @return column
	 */
	public TColumn getColumn(int index) {
		return columns.getColumn(index);
	}

	/**
	 * Get the column of the column name
	 *
	 * @param columnName
	 *            column name
	 * @return column
	 */
	public TColumn getColumn(String columnName) {
		return columns.getColumn(columnName);
	}

	/**
	 * Check if the row has the column
	 *
	 * @param columnName
	 *            column name
	 * @return true if has the column
	 * @since 3.0.1
	 */
	public boolean hasColumn(String columnName) {
		return columns.hasColumn(columnName);
	}

	/**
	 * Get the id value, which is the value of the primary key
	 *
	 * @return id
	 */
	public long getId() {
		long id;
		int index = getPkColumnIndex();
		if (index < 0) {
			StringBuilder error = new StringBuilder(
					"Id column does not exist in ");
			if (columns.isCustom()) {
				error.append("custom specified table columns. ");
			}
			error.append("table: " + columns.getTableName());
			if (columns.isCustom()) {
				error.append(", columns: " + columns.getColumnNames());
			}
			throw new GeoPackageException(error.toString());
		}
		Object objectValue = getValue(index);
		if (objectValue == null) {
			throw new GeoPackageException("Row Id was null. table: "
					+ columns.getTableName() + ", index: " + index + ", name: "
					+ getPkColumn().getName());
		}
		if (objectValue instanceof Number) {
			id = ((Number) objectValue).longValue();
		} else {
			throw new GeoPackageException("Row Id was not a number. table: "
					+ columns.getTableName() + ", index: " + index + ", name: "
					+ getPkColumn().getName() + ", value: " + objectValue);
		}

		return id;
	}

	/**
	 * Check if the row has an id column
	 *
	 * @return true if has an id column
	 * @since 3.0.1
	 */
	public boolean hasIdColumn() {
		return getPkColumnIndex() >= 0;
	}

	/**
	 * Check if the row has an id value
	 *
	 * @return true if has an id
	 * @since 2.0.0
	 */
	public boolean hasId() {
		boolean hasId = false;
		if (hasIdColumn()) {
			Object objectValue = getValue(getPkColumnIndex());
			hasId = objectValue != null && objectValue instanceof Number;
		}
		return hasId;
	}

	/**
	 * Get the primary key column index
	 *
	 * @return primary key column index
	 */
	public int getPkColumnIndex() {
		return columns.getPkColumnIndex();
	}

	/**
	 * Get the primary key column
	 *
	 * @return primary key column
	 */
	public TColumn getPkColumn() {
		return columns.getPkColumn();
	}

	/**
	 * Set the column value at the index
	 *
	 * @param index
	 *            index
	 * @param value
	 *            value
	 */
	public void setValue(int index, Object value) {
		if (index == columns.getPkColumnIndex() && !columns.isPkModifiable()) {
			throw new GeoPackageException(
					"Can not update the primary key of the row. Table Name: "
							+ table.getTableName() + ", Index: " + index
							+ ", Name: " + table.getPkColumnName());
		}
		values[index] = value;
	}

	/**
	 * Set the column value of the column name
	 *
	 * @param columnName
	 *            column name
	 * @param value
	 *            value
	 */
	public void setValue(String columnName, Object value) {
		setValue(getColumnIndex(columnName), value);
	}

	/**
	 * Set the id
	 *
	 * @param id
	 *            id value
	 * @since 4.0.0
	 */
	public void setId(long id) {
		setId(id, columns.isPkModifiable());
	}

	/**
	 * Set the id and optionally validate
	 *
	 * @param id
	 *            id value
	 * @param pkModifiable
	 *            primary key modifiable
	 */
	void setId(long id, boolean pkModifiable) {
		int index = getPkColumnIndex();
		if (index >= 0) {
			if (!pkModifiable) {
				throw new GeoPackageException(
						"Can not update the primary key of the row. Table Name: "
								+ table.getTableName() + ", Index: " + index
								+ ", Name: " + table.getPkColumnName());
			}
			values[index] = id;
		}
	}

	/**
	 * Clears the id so the row can be used as part of an insert or create
	 */
	public void resetId() {
		values[getPkColumnIndex()] = null;
	}

	/**
	 * Validate the value and its actual value types against the column data
	 * type class
	 *
	 * @param column
	 *            column
	 * @param value
	 *            value
	 * @param valueTypes
	 *            value types
	 */
	protected void validateValue(TColumn column, Object value,
			Class<?>... valueTypes) {

		if (columns.isValueValidation()) {

			GeoPackageDataType dataType = column.getDataType();
			if (dataType == null) {
				throw new GeoPackageException(
						"Column is missing a data type. Column: "
								+ column.getName() + ", Value: " + value
								+ ", Type: '" + column.getType()
								+ "', Actual Type: "
								+ valueTypes[0].getSimpleName());
			}

			Class<?> dataTypeClass = dataType.getClassType();

			boolean valid = false;
			for (Class<?> valueType : valueTypes) {
				if (valueType.equals(dataTypeClass)) {
					valid = true;
					break;
				}
			}

			if (!valid) {
				throw new GeoPackageException("Illegal value. Column: "
						+ column.getName() + ", Value: " + value
						+ ", Expected Type: " + dataTypeClass.getSimpleName()
						+ ", Actual Type: " + valueTypes[0].getSimpleName());
			}

		}

	}

}

redpajama_set_name: RedPajamaGithub


text:
package be.kwakeroni.parameters.definition.ext;

import be.kwakeroni.parameters.client.api.model.EntryType;
import be.kwakeroni.parameters.definition.api.ParameterGroupDefinition;

import java.util.function.Function;

/**
 * (C) 2017 Maarten Van Puymbroeck
 */
public interface DefinitionBuilder<GroupType extends EntryType> {

    public default ParameterGroupDefinition<GroupType> build(String name) {
        return this.build(name, Function.identity());
    }

    public default ParameterGroupDefinition<GroupType> build(String name, Function<DefinitionBuilderFinalizer, DefinitionBuilderFinalizer> finalizer) {
        return this.createPartialDefinition(name, finalizer);
    }

    public PartialDefinition<?, GroupType> createPartialDefinition(String name, Function<DefinitionBuilderFinalizer, DefinitionBuilderFinalizer> finalizer);

}


text:
package skadistats.clarity.analyzer.replay;

import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.IntegerBinding;
import skadistats.clarity.processor.runner.ControllableRunner;
import skadistats.clarity.source.Source;

import java.io.IOException;

public class PropertySupportRunner extends ControllableRunner {

    private IntegerBinding tick = Bindings.createIntegerBinding(this::getTick);
    private IntegerBinding lastTick = Bindings.createIntegerBinding(this::getLastTick);

    public PropertySupportRunner(Source source) throws IOException {
        super(source);
        source.notifyOnLastTickChanged(() -> Platform.runLater(this.lastTick::invalidate));
    }

    @Override
    protected void setTick(int tick) {
        super.setTick(tick);
        Platform.runLater(this.tick::invalidate);
    }

    public IntegerBinding tickProperty() {
        return tick;
    }

    public IntegerBinding lastTickProperty() {
        return lastTick;
    }

}


text:
//The MIT License (MIT)
//
//Copyright (c) 2014 Andrew Leap
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

#if DEBUG
//This will kick us into the save called default and set the first vessel active
[KSPAddon(KSPAddon.Startup.MainMenu, false)]
public class Debug_AutoLoadPersistentSaveOnStartup : MonoBehaviour
{
    //use this variable for first run to avoid the issue with when this is true and multiple addons use it
    public static bool first = true;
    public void Start()
    {
        //only do it on the first entry to the menu
        if (first)
        {
            first = false;
            HighLogic.SaveFolder = "default";
            Game game = GamePersistence.LoadGame("persistent", HighLogic.SaveFolder, true, false);

            if (game != null && game.flightState != null && game.compatible)
            {
                game.Start();
                /*Int32 FirstVessel;
                Boolean blnFoundVessel = false;
                for (FirstVessel = 0; FirstVessel < game.flightState.protoVessels.Count; FirstVessel++)
                {
                    //This logic finds the first non-asteroid vessel
                    if (game.flightState.protoVessels[FirstVessel].vesselType != VesselType.SpaceObject &&
                        game.flightState.protoVessels[FirstVessel].vesselType != VesselType.Unknown)
                    {
                        ////////////////////////////////////////////////////
                        //PUT ANY OTHER LOGIC YOU WANT IN HERE//
                        ////////////////////////////////////////////////////
                        blnFoundVessel = true;
                        break;
                    }
                }
                if (!blnFoundVessel)
                    FirstVessel = 0;
                FlightDriver.StartAndFocusVessel(game, FirstVessel);*/
            }

            //CheatOptions.InfiniteFuel = true;
        }
    }
}
#endif


text:
package bluetears.test07.active;

import java.io.IOException;

import charlotte.saber.htt.HttArtoria;
import charlotte.saber.htt.HttSaber;
import charlotte.saber.htt.HttSaberRequest;
import charlotte.saber.htt.HttSaberResponse;
import charlotte.saber.htt.HttSaberX;
import charlotte.tools.StringTools;

public class ActivePage implements HttSaber {
	@Override
	public HttSaberResponse doRequest(HttSaberRequest req) throws Exception, HttSaberX {
		HttSaberResponse res = HttArtoria.i().createResponse();

		res.getHeaderFields().put("Content-Type", "text/plain; charset=UTF-8");
		res.setBody(("x-alter: [" +
			req.getHeaderFields().get("x-alter")
			+ "]").getBytes(StringTools.CHARSET_UTF8));

		return res;
	}

	@Override
	public void close() throws IOException {
		// noop
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>BitmapConverter</title>
<meta name="date" content="2014-04-07">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

Controller

Class BitmapConverter

java.lang.Object

Controller.BitmapConverter

All Implemented Interfaces:

com.google.gson.JsonDeserializer<Bitmap>, com.google.gson.JsonSerializer<Bitmap>

public class BitmapConverter
extends java.lang.Object
implements com.google.gson.JsonDeserializer<Bitmap>, com.google.gson.JsonSerializer<Bitmap>

use this class to convert Bitmap to Json, and vice-versa

Author:

yazhou

Constructor Summary

Constructors

Constructor and Description

BitmapConverter()

Method Summary

Methods

Modifier and Type
Method and Description

Bitmap
deserialize(com.google.gson.JsonElement arg0,
           java.lang.reflect.Type arg1,
           com.google.gson.JsonDeserializationContext arg2)

com.google.gson.JsonElement
serialize(Bitmap arg0,
         java.lang.reflect.Type arg1,
         com.google.gson.JsonSerializationContext arg2)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

BitmapConverter

public BitmapConverter()

Method Detail

serialize

public com.google.gson.JsonElement serialize(Bitmap arg0,
                                    java.lang.reflect.Type arg1,
                                    com.google.gson.JsonSerializationContext arg2)

Specified by:

serialize in interface com.google.gson.JsonSerializer<Bitmap>

deserialize

public Bitmap deserialize(com.google.gson.JsonElement arg0,
                 java.lang.reflect.Type arg1,
                 com.google.gson.JsonDeserializationContext arg2)
                   throws com.google.gson.JsonParseException

Specified by:

deserialize in interface com.google.gson.JsonDeserializer<Bitmap>

Throws:

com.google.gson.JsonParseException

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD


text:
from cio.backends import cache
from djedi.tests.base import DjediTest

class CacheTest(DjediTest):
    def test_set(self):
        uri = "i18n://sv-se@page/title.txt#1"
        content = "Title"

        self.assertIsNone(cache.get(uri))
        cache.set(uri, content)

        node = cache.get(uri)
        self.assertEqual(node["uri"], uri)
        self.assertEqual(node["content"], content)

        cache.delete(uri)
        self.assertIsNone(cache.get(uri))


text:
import {Timeline} from '@luma.gl/core';

function makeEvents(events, opts = {}) {
  return events.map((type, i) => makeEvent(type, opts, i));
}

function makeEvent(type, opts, seed) {
  const event = {
    type,
    handled: opts.handled,
    offsetCenter: {x: 100 + seed, y: 100 - seed},
    delta: -seed - 1,
    deltaX: seed / 2,
    deltaY: seed / 2,
    velocityX: seed / 2,
    velocityY: seed / 2,
    velocity: seed / 2,
    deltaTime: seed,
    scale: 1 + (seed + 1) * 0.1,
    rotation: (seed + 1) * 5,
    srcEvent: opts,
    preventDefault: () => {},
    stopPropagation: () => {
      event.handled = true;
    }
  };
  return event;
}

const BASE_PROPS = {
  x: 0,
  y: 0,
  width: 100,
  height: 100,
  scrollZoom: true,
  dragPan: true,
  dragRotate: true,
  doubleClickZoom: true,
  touchZoom: true,
  touchRotate: true,
  keyboard: true
};

const TEST_CASES = [
  {
    title: 'pan',
    props: {},
    events: () => makeEvents(['panstart', 'panmove', 'panend']),
    viewStateChanges: 3,
    interactionStates: 2 // isDragging, isPanning/isRotating
  },
  {
    title: 'pan#function key',
    props: {},
    events: () => makeEvents(['panstart', 'panmove', 'panend'], {metaKey: true}),
    viewStateChanges: 3,
    interactionStates: 2 // isDragging, isPanning/isRotating
  },
  {
    title: 'pan#out of bounds',
    props: {x: 200},
    events: () => makeEvents(['panstart', 'panmove', 'panend']),
    viewStateChanges: 0,
    interactionStates: 0
  },
  {
    title: 'pan#handled event',
    props: {},
    events: () => makeEvents(['panstart', 'panmove', 'panend'], {handled: true}),
    viewStateChanges: 0,
    interactionStates: 0
  },
  {
    title: 'pan#disabled',
    props: {dragPan: false, dragRotate: false},
    events: () => makeEvents(['panstart', 'panmove', 'panend']),
    viewStateChanges: 2,
    interactionStates: 1 // isDragging
  },
  {
    title: 'pan#function key#disabled',
    props: {dragPan: false, dragRotate: false},
    events: () => makeEvents(['panstart', 'panmove', 'panend'], {metaKey: true}),
    viewStateChanges: 2,
    interactionStates: 1 // isDragging
  },

  {
    title: 'pinch',
    props: {},
    events: () => makeEvents(['pinchstart', 'pinchmove', 'pinchend']),
    viewStateChanges: 3,
    interactionStates: 4 // isDragging, isPanning, isRotating, isZooming
  },
  {
    title: 'pinch#out of bounds',
    props: {x: 200},
    events: () => makeEvents(['pinchstart', 'pinchmove', 'pinchend']),
    viewStateChanges: 0,
    interactionStates: 0
  },
  {
    title: 'pinch#disabled',
    props: {touchZoom: false, touchRotate: false},
    events: () => makeEvents(['pinchstart', 'pinchmove', 'pinchend']),
    viewStateChanges: 2,
    interactionStates: 1 // isDragging
  },

  {
    title: 'tripan',
    props: {},
    events: () => makeEvents(['tripanstart', 'tripanmove', 'tripanend']),
    viewStateChanges: 3,
    interactionStates: 2 // isDragging, isRotating
  },
  {
    title: 'tripan#out of bounds',
    props: {x: 200},
    events: () => makeEvents(['tripanstart', 'tripanmove', 'tripanend']),
    viewStateChanges: 0,
    interactionStates: 0
  },
  {
    title: 'tripan#disabled',
    props: {touchRotate: false},
    events: () => makeEvents(['tripanstart', 'tripanmove', 'tripanend']),
    viewStateChanges: 2,
    interactionStates: 1 // isDragging
  },

  {
    title: 'wheel',
    props: {},
    events: () => makeEvents(['wheel']),
    viewStateChanges: 1,
    interactionStates: 2
  },
  {
    title: 'wheel#out of bounds',
    props: {x: 200},
    events: () => makeEvents(['wheel']),
    viewStateChanges: 0,
    interactionStates: 0
  },
  {
    title: 'wheel#disabled',
    props: {scrollZoom: false},
    events: () => makeEvents(['wheel']),
    viewStateChanges: 0,
    interactionStates: 0
  },

  {
    title: 'doubletap',
    props: {},
    events: () => makeEvents(['doubletap']),
    viewStateChanges: 1,
    interactionStates: 2
  },
  {
    title: 'doubletap#out of bounds',
    props: {x: 200},
    events: () => makeEvents(['doubletap']),
    viewStateChanges: 0,
    interactionStates: 0
  },
  {
    title: 'doubletap#disabled',
    props: {doubleClickZoom: false},
    events: () => makeEvents(['doubletap']),
    viewStateChanges: 0,
    interactionStates: 0
  },

  {
    title: 'keyboard',
    props: {},
    events: () =>
      makeEvents(['keydown'], {code: 'Minus'})
        .concat(makeEvents(['keydown'], {code: 'Minus', shiftKey: true}))
        .concat(makeEvents(['keydown'], {code: 'Equal'}))
        .concat(makeEvents(['keydown'], {code: 'Equal', shiftKey: true}))
        .concat(makeEvents(['keydown'], {code: 'ArrowLeft'}))
        .concat(makeEvents(['keydown'], {code: 'ArrowLeft', shiftKey: true}))
        .concat(makeEvents(['keydown'], {code: 'ArrowUp'}))
        .concat(makeEvents(['keydown'], {code: 'ArrowUp', shiftKey: true}))
        .concat(makeEvents(['keydown'], {code: 'ArrowRight'}))
        .concat(makeEvents(['keydown'], {code: 'ArrowRight', shiftKey: true}))
        .concat(makeEvents(['keydown'], {code: 'ArrowDown'}))
        .concat(makeEvents(['keydown'], {code: 'ArrowDown', shiftKey: true})),
    viewStateChanges: 12,
    interactionStates: 3
  },
  {
    title: 'keyboard#disabled',
    props: {keyboard: false},
    events: () => makeEvents(['keydown'], {code: 'Minus'}),
    viewStateChanges: 0,
    interactionStates: 0
  }
];

export default async function testController(t, ViewClass, defaultProps, blackList = []) {
  const timeline = new Timeline();
  const view = new ViewClass({controller: true});
  Object.assign(defaultProps, BASE_PROPS, view.controller, {
    timeline,
    makeViewport: viewState =>
      view.makeViewport({width: BASE_PROPS.width, height: BASE_PROPS.height, viewState})
  });
  const ControllerClass = defaultProps.type;
  const controller = new ControllerClass(defaultProps);

  for (const testCase of TEST_CASES) {
    if (blackList.includes(testCase.title)) {
      continue; // eslint-disable-line
    }
    await runTestCase(t, controller, testCase, defaultProps);
  }
}

async function runTestCase(t, controller, testCase, defaultProps) {
  let onViewStateChangeCalled = 0;
  const affectedStates = new Set();

  /* eslint-disable no-loop-func */
  controller.setProps(
    Object.assign(
      {
        onViewStateChange: ({viewState, interactionState}) => {
          if (!interactionState.inTransition) {
            onViewStateChangeCalled++;
          }
          controller.setProps(Object.assign({}, defaultProps, testCase.props, viewState));
        },
        onStateChange: state => {
          for (const key in state) {
            if (state[key] && key.startsWith('is')) {
              affectedStates.add(key);
            }
          }
        }
      },
      defaultProps,
      testCase.props
    )
  );
  for (const event of testCase.events()) {
    controller.handleEvent(event);
    await waitUntil(
      controller,
      () => !controller._eventStartBlocked && !controller._interactionState.inTransition
    );
  }
  t.is(onViewStateChangeCalled, testCase.viewStateChanges, `${testCase.title} onViewStateChange`);
  t.is(
    affectedStates.size,
    testCase.interactionStates,
    `${testCase.title} interaction state updated`
  );
}

function waitUntil(controller, verify) {
  const {timeline} = controller.controllerStateProps;
  return new Promise(resolve => {
    const check = () => {
      if (verify()) {
        resolve();
      } else {
        timeline.setTime(timeline.getTime() + 100);
        controller.updateTransition();
        /* global setTimeout */
        setTimeout(check, 10);
      }
    };
    check();
  });
}


text:
<?php

namespace Tale\Net\Ip;

use Tale\Net\AddressFamily,
    Tale\Net\Dns,
    Exception;

class Address
{

    private $_bytes;
    private $_family;

    public function __construct(array $bytes)
    {

        $this->_bytes = $bytes;

        switch (count($this->_bytes)) {
            case 4:
                $this->_family = AddressFamily::INET;
                break;
            case 16:
                $this->_family = AddressFamily::INET6;
                break;
            default:

                throw new Exception("Failed to construct IP address: Passed bytes dont count for any known AddressFamily. Try 4 (IPv4) or 16 (IPv6) bytes");
        }
    }

    public function getBytes()
    {

        return $this->_bytes;
    }

    public function getHexBytes()
    {

        return array_map(function ($byte) {

            return str_pad(dechex($byte), 2, '0', \STR_PAD_LEFT);
        }, $this->_bytes);
    }

    public function getFamily()
    {

        return $this->_family;
    }

    public function isIpv4()
    {

        return $this->_family === AddressFamily::INET;
    }

    public function isIpv6()
    {

        return $this->_family === AddressFamily::INET6;
    }

    public function getString()
    {

        return inet_ntop(implode(array_map('chr', $this->_bytes)));
    }

    public function getReverseHostName()
    {

        return Dns::getReverseHostName($this);
    }

    public function lookUp()
    {

        return Dns::lookUpReverse($this);
    }

    public function lookUpArray()
    {

        return iterator_to_array($this->lookUp());
    }

    public function lookUpFirst()
    {

        return Dns::lookUpReverseFirst($this);
    }

    public function lookUpHostName()
    {

        $first = $this->lookUpFirst();

        if (!$first)
            return null;

        return $first->getTargetHostName();
    }

    public function __toString()
    {

        return $this->getString();
    }

    public static function fromString($string)
    {

        $n = @inet_pton($string);

        if ($n === false)
            throw new Exception("Failed to convert string to IPAddress: $string is not a valid ip address of any kind");

        return new static(array_map('ord', str_split($n)));
    }

    public static function tryFromString($string)
    {

        $ip = null;
        try {

            $ip = self::fromString($string);
        } catch (\Exception $e) {

            return null;
        }

        return $ip;
    }

    public static function fromDomain($string, $v6 = false)
    {

        $ip = self::tryFromString($string);

        if ($ip)
            return $ip;

        $record = $v6 ? Dns::lookUpAaaaRecord($string) : Dns::lookUpARecord($string);

        if (!$record)
            throw new Exception("Failed to look up IP address for host $string. No matching records found");

        return $record->getAddress();
    }
}


text:
"""Trace allows the profiler to trace Python events."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import functools

from tensorflow.python.profiler.internal import _pywrap_traceme
from tensorflow.python.util.tf_export import tf_export

# This variable is modified by PythonHooks::Start/Stop() in C++. Such
# arrangement will reduce the number of calls through pybind11.
enabled = False

@tf_export('profiler.experimental.Trace', v1=[])
class Trace(object):
  """Context manager that generates a trace event in the profiler.

  A trace event will start when entering the context, and stop and save the
  result to the profiler when exiting the context. Open TensorBoard Profile tab
  and choose trace viewer to view the trace event in the timeline.

  Trace events are created only when the profiler is enabled. More information
  on how to use the profiler can be found at
  https://tensorflow.org/guide/profiler

  Example usage:
  ```python
  tf.profiler.experimental.start('logdir')
  for step in range(num_steps):
    # Creates a trace event for each training step with the step number.
    with tf.profiler.experimental.Trace("Train", step_num=step):
      train_fn()
  tf.profiler.experimental.stop()
  ```
  """

  def __init__(self, name, **kwargs):
    """Creates a trace event in the profiler.

    Args:
      name: The name of the trace event.
      **kwargs: Keyword arguments added to the trace event.
                Both the key and value are of types that
                can be converted to strings, which will be
                interpreted by the profiler according to the
                traceme name.

      Example usage:

      ```python

        tf.profiler.experimental.start('logdir')
        for step in range(num_steps):
          # Creates a trace event for each training step with the
          # step number.
          with tf.profiler.experimental.Trace("Train", step_num=step):
            train_fn()
        tf.profiler.experimental.stop()

      ```
      The example above uses the keyword argument "step_num" to specify the
      training step being traced.
    """
    if enabled:
      # Creating _pywrap_traceme.TraceMe starts the clock.
      self._traceme = _pywrap_traceme.TraceMe(name, **kwargs)
    else:
      self._traceme = None

  def __enter__(self):
    # Starting the TraceMe clock here would require an extra Python->C++ call.
    return self

  def set_metadata(self, **kwargs):
    """Sets metadata in this trace event.

    Args:
      **kwargs: metadata in key-value pairs.

    This method enables setting metadata in a trace event after it is
    created.

    Example usage:

    ```python

      def call(function):
        with tf.profiler.experimental.Trace("call",
             function_name=function.name) as tm:
          binary, in_cache = jit_compile(function)
          tm.set_metadata(in_cache=in_cache)
          execute(binary)

    ```
    In this example, we want to trace how much time spent on
    calling a function, which includes compilation and execution.
    The compilation can be either getting a cached copy of the
    binary or actually generating the binary, which is indicated
    by the boolean "in_cache" returned by jit_compile(). We need
    to use set_metadata() to pass in_cache because we did not know
    the in_cache value when the trace was created (and we cannot
    create the trace after jit_compile(), because we want
    to measure the entire duration of call()).
    """
    if self._traceme and kwargs:
      self._traceme.SetMetadata(**kwargs)

  def __exit__(self, exc_type, exc_val, exc_tb):
    if self._traceme:
      self._traceme.Stop()

def trace_wrapper(trace_name, **trace_kwargs):
  """Decorator alternative to `with Trace(): ...`.  It's faster.

  Args:
    trace_name: The name of the trace event.
    **trace_kwargs: Keyword arguments added to the trace event. Both the key and
      value are of types that can be converted to strings, which will be
      interpreted by the profiler according to the traceme name.

  Returns:
    A decorator that can wrap a function and apply `Trace` scope if needed.

  Example usage:
    ```python

    @trace_wrapper('trace_name')
    def func(x, y, z):
      pass  # code to execute and apply `Trace` if needed.

    # Equivalent to
    # with Trace('trace_name'):
    #   func(1, 2, 3)
    func(1, 2, 3)
    ```
  """

  def inner_wrapper(func):

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
      if enabled:
        with Trace(trace_name, **trace_kwargs):
          return func(*args, **kwargs)
      return func(*args, **kwargs)

    return wrapped

  return inner_wrapper


text:
function [ points ] = intersectUnitVectorHyperSphere( n )
    % intersectUnitVectorHyperSphere. Return intersection points between a unit hyper sphere and its axis.
    %   For additional details please see https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
    %
    %   [ points ] = intersectUnitVectorHyperSphere( n )
    %
    %   INPUT
    %       n - space dimension.
    %
    %   OUTPUT
    %       points - intersection points between a unit hyper sphere and its axis
    %
    % unit sphere. for 3D: [x_center y_center z_center  R]
    sphere = [zeros(n), ones(n, 1)];

    % unit vectors. for 3D: [x0 y0 z0  dx dy dz]
    line = [zeros(n), eye(n)];

    points = intersectLineHyperSphere(line, sphere, n);
end


text:
namespace FlaUI.Core
{
    public interface ITextRange2 : ITextRange
    {
        void ShowContextMenu();
    }
}


text:
package koodi.domain;

import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;

@Entity
public class QuestionSeries extends BaseModel {

    @NotBlank(message = "Otsikko ei saa olla tyhjä")
    private String title;

    @NotNull(message = "Järjestys vaaditaan")
    private Integer orderNumber;

    @OneToMany(fetch = FetchType.EAGER)
    private List<Achievement> achievements;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setOrderNumber(Integer orderNumber) {
        this.orderNumber = orderNumber;
    }

    public Integer getOrderNumber() {
        return orderNumber;
    }

    public List<Achievement> getAchievements() {
        return achievements;
    }

    public void setAchievements(List<Achievement> achievements) {
        this.achievements = achievements;
    }

}


text:
from jsonobject import *

class RequestLog(JsonObject):
    type = 'request'
    id = StringProperty()
    method = StringProperty()
    path = StringProperty()
    params = DictProperty()
    size = IntegerProperty()
    time = FloatProperty()
    timestamp = FloatProperty()
    traceback = StringProperty()

class ResponseLog(JsonObject):
    type = 'response'
    id = StringProperty()
    path = StringProperty()
    method = StringProperty()
    size = IntegerProperty()
    time = FloatProperty()


text:
Add Product

### Actor
Product Approver

### Bounded Context
Catalog

### Summary
Adds a product to the product catalog so that a user can search
for it and it can be added to a cart, rented, purchased and shipped.

### Input

| Name        | Description                              |
| ----------- | ---------------------------------------- |
| Name        | The name of the product to add.          |
| Description | An optional description for the product. |

### Output
Returns the ID of the added product.

### Rules
1. A product with the same name does not already exist.
2. The user must be an employee.

### Post Conditions
1. A product with the name and description is added to the product catalog.
2. The product can be found in product search.
3. The response comes back in less than .5 seconds.
4. The Product Added Event is raised.

### Usage Index
.01n


text:
int main(int argc, const char * argv[]) {
unsigned long int hexdouble;
double a;
sscanf(argv[1], "%lX", &hexdouble);
a = *(double*)(&hexdouble);
double b;
sscanf(argv[2], "%lX", &hexdouble);
b = *(double*)(&hexdouble);
double c;
sscanf(argv[3], "%lX", &hexdouble);
c = *(double*)(&hexdouble);
double d;
sscanf(argv[4], "%lX", &hexdouble);
d = *(double*)(&hexdouble);
double result = gsl_sf_ellint_RJ(a, b, c, d,GSL_PREC_DOUBLE);
//printf("%.15f\n", result);
VALGRIND_PRINT_ERROR("result", &result);
return 0;
}


text: Ubuntu 14.04 base image


text:
import { ListStateOrchestrator } from '../list-state.rxstate';
import { ListSearchModel } from './search.model';
import { ListSearchSetSearchTextAction } from './set-search-text.action';
import { ListSearchSetFunctionsAction } from './set-functions.action';
import { ListSearchSetFieldSelectorsAction } from './set-field-selectors.action';
import { ListSearchSetOptionsAction } from './set-options.action';

export class ListSearchOrchestrator extends ListStateOrchestrator<ListSearchModel> {
  constructor() {
    super();

    this
      .register(ListSearchSetSearchTextAction, this.setSearchText)
      .register(ListSearchSetFunctionsAction, this.setFunctions)
      .register(ListSearchSetFieldSelectorsAction, this.setFieldSelectors)
      .register(ListSearchSetOptionsAction, this.setOptions);
  }

  private setSearchText(
    state: ListSearchModel,
    action: ListSearchSetSearchTextAction): ListSearchModel {
    return new ListSearchModel(
      Object.assign({}, state, { searchText: action.searchText ? action.searchText : '' })
    );
  }

  private setFunctions(
    state: ListSearchModel,
    action: ListSearchSetFunctionsAction): ListSearchModel {
    return new ListSearchModel(Object.assign({}, state, { functions: [...action.functions] }));
  }

  private setFieldSelectors(
    state: ListSearchModel,
    action: ListSearchSetFieldSelectorsAction): ListSearchModel {
    return new ListSearchModel(
      Object.assign({}, state, { fieldSelectors: [...action.fieldSelectors] })
    );
  }

  private setOptions(state: ListSearchModel, action: ListSearchSetOptionsAction) {
    let result = state;

    if (action.searchTextAction) {
      result = this.setSearchText(result, action.searchTextAction);
    }

    if (action.setFieldSelectorsAction) {
      result = this.setFieldSelectors(result, action.setFieldSelectorsAction);
    }

    if (action.setFunctionsAction) {
      result = this.setFunctions(result, action.setFunctionsAction);
    }

    return result;
  }
}


text:
"""Tests for sequence_generator."""

# internal imports

import tensorflow as tf

from magenta.music import sequence_generator
from magenta.protobuf import generator_pb2

class TestSequenceGenerator(sequence_generator.BaseSequenceGenerator):

  def __init__(self, checkpoint=None, bundle=None):
    details = generator_pb2.GeneratorDetails(
        id='test_generator',
        description='Test Generator')

    super(TestSequenceGenerator, self).__init__(details, checkpoint, bundle)

  def _initialize_with_checkpoint(self, checkpoint_file):
    pass

  def _initialize_with_checkpoint_and_metagraph(self, checkpoint_file,
                                                metagraph_file):
    pass

  def _close(self):
    pass

  def _generate(self):
    pass

  def _write_checkpoint_with_metagraph(self, checkpoint_file):
    pass

class SequenceGeneratorTest(tf.test.TestCase):

  def testSpecifyEitherCheckPointOrBundle(self):
    bundle = generator_pb2.GeneratorBundle(
        generator_details=generator_pb2.GeneratorDetails(
            id='test_generator'),
        checkpoint_file=['foo.ckpt'],
        metagraph_file='foo.ckpt.meta')

    with self.assertRaises(sequence_generator.SequenceGeneratorException):
      TestSequenceGenerator(checkpoint='foo.ckpt', bundle=bundle)
    with self.assertRaises(sequence_generator.SequenceGeneratorException):
      TestSequenceGenerator(checkpoint=None, bundle=None)

    TestSequenceGenerator(checkpoint='foo.ckpt')
    TestSequenceGenerator(bundle=bundle)

  def testUseMatchingGeneratorId(self):
    bundle = generator_pb2.GeneratorBundle(
        generator_details=generator_pb2.GeneratorDetails(
            id='test_generator'),
        checkpoint_file=['foo.ckpt'],
        metagraph_file='foo.ckpt.meta')

    TestSequenceGenerator(bundle=bundle)

    bundle.generator_details.id = 'blarg'

    with self.assertRaises(sequence_generator.SequenceGeneratorException):
      TestSequenceGenerator(bundle=bundle)

  def testGetBundleDetails(self):
    # Test with non-bundle generator.
    seq_gen = TestSequenceGenerator(checkpoint='foo.ckpt')
    self.assertEquals(None, seq_gen.bundle_details)

    # Test with bundle-based generator.
    bundle_details = generator_pb2.GeneratorBundle.BundleDetails(
        description='bundle of joy')
    bundle = generator_pb2.GeneratorBundle(
        generator_details=generator_pb2.GeneratorDetails(
            id='test_generator'),
        bundle_details=bundle_details,
        checkpoint_file=['foo.ckpt'],
        metagraph_file='foo.ckpt.meta')
    seq_gen = TestSequenceGenerator(bundle=bundle)
    self.assertEquals(bundle_details, seq_gen.bundle_details)

if __name__ == '__main__':
  tf.test.main()


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

/**
 * @fileoverview Unit test for the Translation tab active mode service.
 */

// TODO(#7222): Remove the following block of unnnecessary imports once
// the code corresponding to the spec is upgraded to Angular 8.
import { UpgradedServices } from 'services/UpgradedServices';
// ^^^ This block is to be removed.

require(
  'pages/exploration-editor-page/translation-tab/services/' +
  'translation-tab-active-mode.service.ts');

describe('Translation tab active mode service', function() {
  beforeEach(angular.mock.module('oppia'));
  beforeEach(angular.mock.module('oppia', function($provide) {
    var ugs = new UpgradedServices();
    for (let [key, value] of Object.entries(ugs.getUpgradedServices())) {
      $provide.value(key, value);
    }
  }));
  var ttams = null;

  beforeEach(angular.mock.inject(function($injector) {
    ttams = $injector.get('TranslationTabActiveModeService');
  }));

  it('should correctly activate translation mode', function() {
    expect(ttams.isTranslationModeActive()).toBeFalsy();
    ttams.activateTranslationMode();
    expect(ttams.isTranslationModeActive()).toBeTruthy();
  });

  it('should correctly activate voiceover mode', function() {
    expect(ttams.isVoiceoverModeActive()).toBeFalsy();
    ttams.activateVoiceoverMode();
    expect(ttams.isVoiceoverModeActive()).toBeTruthy();
  });

  it('should correctly report the active mode', function() {
    expect(ttams.isVoiceoverModeActive()).toBeFalsy();
    expect(ttams.isTranslationModeActive()).toBeFalsy();

    ttams.activateVoiceoverMode();

    expect(ttams.isVoiceoverModeActive()).toBeTruthy();
    expect(ttams.isTranslationModeActive()).toBeFalsy();

    ttams.activateTranslationMode();

    expect(ttams.isVoiceoverModeActive()).toBeFalsy();
    expect(ttams.isTranslationModeActive()).toBeTruthy();
  });
});


text:
function validateName(){
  var MName =document.getElementById("MYname").value;
  document.getElementById("MYname").setAttribute("class", "");

  if (MName.length<3)
  {
    document.getElementById("MYname").setAttribute("class", "error");

    alert("Must contain min 3 letters");
    return false;
  }

  return true;
}

function validateMail(){
  var MMail = document.getElementById("mail").value;
  document.getElementById("mail").setAttribute("class","");
  //funkcia koiato proveriava validnostta na id="MYname"
//funkcia koiato vrashta true pri validni danni i vrrashta false pri nevalidni danni
function validateName(){
  var MName =document.getElementById("MYname").value;
  document.getElementById("MYname").setAttribute("class", "");

  if (MName.length<3)
  {
    document.getElementById("MYname").setAttribute("class", "error");

    alert("Must contain min 3 letters");
    return false;
  }

  return true;
}

function validateMail(){
  var MMail = document.getElementById("mail").value;
  document.getElementById("mail").setAttribute("class","");
  var n = MMail.search(/[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+/i);
if (n!==0){
   document.getElementById("mail").setAttribute("class", "error");
   alert("Must contain numbers, letters, @, dots and dash");
   return false;
}

  return true;
}
//Malki, Glavni bukvi, cifri, dolna cherta do 8 simvola

function validateUser(){
  var MUser = document.getElementById("username").value;
  document.getElementById("username").setAttribute("class","");
  var u=MUser.search(/[a-zA-Z0-9_]{3,8}/i);

  if (u!==0){
     document.getElementById("username").setAttribute("class", "error");
     alert("Must contain numbers, letters, dash");
     return false;
  }

  return true;
}

// parolata da e pone 8 simvola, pone 1 malka, pone 1 golqma bukva i pone 1 cifra

function validatePass1(){
  document.getElementById("PSW1").setAttribute("class","");
  document.getElementById("PSW2").setAttribute("class","");
  var Pass1 = document.getElementById("PSW1").value;
  var Pass2=document.getElementById("PSW2").value;
  if(Pass1!==Pass2){
    document.getElementById("PSW1").setAttribute("class", "error");
    document.getElementById("PSW2").setAttribute("class", "error");

    alert("ERROR:Pass1 is not identical whit Pass2");
    return false;
  }

if (Pass1.search(/[a-z]+/g)===-1||
    Pass1.search(/[A-Z]+/g)===-1||
    Pass1.search(/[0-9]+/g)===-1||
    Pass1.search(/[a-zA-Z0-9]{8,}/g)===-1){
   document.getElementById("PSW1").setAttribute("class", "error");
    document.getElementById("PSW2").setAttribute("class", "error");
   alert("ERROR!! Invalid password");
   return false;
}

  document.getElementById("demo").innerHTML = "The regstration is valid!";

  return true;

}

function myFunction() {
  var valName=validateName();
  if (valName===false)
    {
      return;
    }

  var valMail=validateMail();
  if (valMail===false)
    {
      return;
    }

  var valUser=validateUser();
  if(valUser===false){
    return;
  }
  var valP1=validatePass1();
  if (valP1===false)
    {
      return;
    }

}


text:
/* { dg-do run } */
/* { dg-options "-O0" } */

extern void abort (void);
extern void exit (int);

/* Check that out-of-bounds case warnings work in the case that the
   testing expression is promoted.  */
int
foo1 (unsigned char i)
{
  switch (i)
    {
    case -1:   /* { dg-warning "case label value is less than minimum value for type" } */
      return 1;
    case 256:  /* { dg-warning "case label value exceeds maximum value for type" } */
      return 2;
    default:
      return 3;
    }
}

/* Like above, but for case ranges that need to be satured.  */
int
foo2 (unsigned char i)
{
  switch (i)
    {
    case -1 ... 1:   /* { dg-warning "lower value in case label range less than minimum value for type" } */
      return 1;
    case 254 ... 256:  /* { dg-warning "upper value in case label range exceeds maximum value for type" } */
      return 2;
    default:
      return 3;
    }
}

int
main (void)
{
  if (foo1 (10) != 3)
    abort ();
  if (foo2 (10) != 3)
    abort ();
  exit (0);
}


text:
<!DOCTYPE HTML>

    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>PhoneGap</title>

    <link rel="stylesheet" type="text/css" category="android" href="../dojo/dojox/mobile/themes/android/android.css"/>
    <link rel="stylesheet" href="../dojo/dojox/mobile/themes/buttons.css" type="text/css"/>
    <link rel="stylesheet" href="../dojo/dojox/mobile/themes/domButtons.css" type="text/css"/>

Notifications

Select action below.

Action

Beep

Vibrate

Alert Dialog

Confirm Dialog

FIX: Prompt Dialog

Spinner Dialog

Progress Dialog


text:
package org.mini2Dx.minibus.messagedata.primitives;

import org.mini2Dx.minibus.MessageData;
import org.mini2Dx.minibus.pool.MessageDataPool;
import org.mini2Dx.minibus.pool.OptionallyPooledMessageData;
import org.mini2Dx.minibus.pool.PooledMessageData;

/**
 * Utility implementation of {@link MessageData} for sending short array values
 */
public class ShortArrayMessageData extends OptionallyPooledMessageData {
	private short [] value;

	public ShortArrayMessageData(short [] value) {
		super();
		this.value = value;
	}

	public ShortArrayMessageData(MessageDataPool<PooledMessageData> pool) {
		super(pool);
	}

	public short [] getValue() {
		return value;
	}

	public void setValue(short[] value) {
		this.value = value;
	}
}


text:
class Hash
  def except(*delete_keys)
    remaining_keys = keys - delete_keys
    Hash[remaining_keys.zip(values_at(*remaining_keys))]
  end
end


text:
This is the introduction ^[Also, here is a footnote]. Here you can write what
your document will be about. This is the best thing ever [@Meyer2000
@Codishetal2000].

## Math

Here is inline math \(1+1=2\) and a math block:

\[
\theta = 0
\quad \Rightarrow \quad
\sin^{2}\theta = 0
\]{#eq:math-example}

## Code

Here is a code block

```{#lst:code-example .ruby .numberLines caption="Ruby code example"}
array = %w(1 2 3)
squared = array.map{|n| n*n}
puts squared
```

## Image

Here is a figure

![Ginger the Cat by Henry Riley](images/cat.jpg){#fig:cat}

## Table

Create tables with captions like so:

| a | b | c |
|---|---|---|
| 1 | 2 | 3 |
| 4 | 5 | 6 |{#tbl:table-example}

: Example table

## Crossreferencing

You can also reference math [@eq:math-example], code [@lst:code-example],
figures [@fig:cat].

## Lists

_References_ is by default added in the `references.md` file. However you can
also add a lists of figures, tables and/or listings.

\listoffigures

\listoftables

\listoflistings


text:
__author__="Sergey Karakovskiy, sergey at idsia fullstop ch"
__date__ ="$May 2, 2009 7:54:12 PM$"

class MarioAgent:
#    class MarioAgent(Agent):
    """ An agent is an entity capable of producing actions, based on previous observations.
        Generally it will also learn from experience. It can interact directly with a Task.
    """

    def integrateObservation(self, obs):
        raise "Not implemented"

    def getAction(self):
        raise "Not implemented"

    def giveReward(self, reward):
        pass

    def _getName(self):
        if self._name is None:
            self._name = self.__class__.__name__
        return self._name

    def _setName(self, newname):
        """Change name to newname. Uniqueness is not guaranteed anymore."""
        self._name = newname

    _name = None
    name = property(_getName, _setName)

    def __repr__(self):
        """ The default representation of a named object is its name. """
        return "<%s '%s'>" % (self.__class__.__name__, self.name)

    def newEpisode(self):
        pass


text:
var hbs             = require('express-hbs'),
    _               = require('lodash'),
    api             = require('../api'),
    config          = require('../config'),
    filters         = require('../filters'),
    template        = require('./template'),
    body_class;

body_class = function (options) {
    var classes = [],
        context = options.data.root.context,
        post = this.post,
        tags = this.post && this.post.tags ? this.post.tags : this.tags || [],
        page = this.post && this.post.page ? this.post.page : this.page || false;

    if (post) {
        // To be removed from pages by #2597 when we're ready to deprecate this
        // i.e. this should be if (_.contains(context, 'post') && post) { ... }
        classes.push('post-template');
    }

    if (_.contains(context, 'home')) {
        classes.push('home-template');
    } else if (_.contains(context, 'page') && page) {
        classes.push('page-template');
        // To be removed by #2597 when we're ready to deprecate this
        classes.push('page');
    } else if (_.contains(context, 'tag') && this.tag) {
        classes.push('tag-template');
        classes.push('tag-' + this.tag.slug);
    } else if (_.contains(context, 'author') && this.author) {
        classes.push('author-template');
        classes.push('author-' + this.author.slug);
    } else if (_.contains(context, 'private')) {
        classes.push('private-template');
    }

    if (tags) {
        classes = classes.concat(tags.map(function (tag) { return 'tag-' + tag.slug; }));
    }

    if (_.contains(context, 'paged')) {
        classes.push('paged');
        // To be removed from pages by #2597 when we're ready to deprecate this
        classes.push('archive-template');
    }

    return api.settings.read({context: {internal: true}, key: 'activeTheme'}).then(function (response) {
        var activeTheme = response.settings[0],
            paths = config.paths.availableThemes[activeTheme.value],
            view;

        if (post && page) {
            view = template.getThemeViewForPost(paths, post).split('-');

            if (view[0] === 'page' && view.length > 1) {
                classes.push(view.join('-'));
                // To be removed by #2597 when we're ready to deprecate this
                view.splice(1, 0, 'template');
                classes.push(view.join('-'));
            }
        }

        return filters.doFilter('body_class', classes).then(function (classes) {
            var classString = _.reduce(classes, function (memo, item) { return memo + ' ' + item; }, '');
            return new hbs.handlebars.SafeString(classString.trim());
        });
    });
};

module.exports = body_class;