text:
/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library is distributed in the hope that it will be useful, but   *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA         *
 *   02110-1301  USA                                                       *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#ifndef TAGLIB_ASFTAG_H
#define TAGLIB_ASFTAG_H

#include "tag.h"
#include "tlist.h"
#include "tmap.h"
#include "taglib_export.h"
#include "asfattribute.h"

namespace TagLib {

  namespace ASF {

    typedef List<Attribute> AttributeList;
    typedef Map<String, AttributeList> AttributeListMap;

    class TAGLIB_EXPORT Tag : public TagLib::Tag {

      friend class File;

    public:

      Tag();

      virtual ~Tag();

      /*!
       * Returns the track name.
       */
      virtual String title() const;

      /*!
       * Returns the artist name.
       */
      virtual String artist() const;

      /*!
       * Returns the album name; if no album name is present in the tag
       * String::null will be returned.
       */
      virtual String album() const;

      /*!
       * Returns the track comment.
       */
      virtual String comment() const;

      /*!
       * Returns the genre name; if no genre is present in the tag String::null
       * will be returned.
       */
      virtual String genre() const;

      /*!
       * Returns the rating.
       */
      virtual String rating() const;

      /*!
       * Returns the genre name; if no genre is present in the tag String::null
       * will be returned.
       */
      virtual String copyright() const;

      /*!
       * Returns the year; if there is no year set, this will return 0.
       */
      virtual uint year() const;

      /*!
       * Returns the track number; if there is no track number set, this will
       * return 0.
       */
      virtual uint track() const;

      /*!
       * Sets the title to \a s.
       */
      virtual void setTitle(const String &s);

      /*!
       * Sets the artist to \a s.
       */
      virtual void setArtist(const String &s);

      /*!
       * Sets the album to \a s.  If \a s is String::null then this value will be
       * cleared.
       */
      virtual void setAlbum(const String &s);

      /*!
       * Sets the comment to \a s.
       */
      virtual void setComment(const String &s);

      /*!
       * Sets the rating to \a s.
       */
      virtual void setRating(const String &s);

      /*!
       * Sets the copyright to \a s.
       */
      virtual void setCopyright(const String &s);

      /*!
       * Sets the genre to \a s.
       */
      virtual void setGenre(const String &s);

      /*!
       * Sets the year to \a i.  If \a s is 0 then this value will be cleared.
       */
      virtual void setYear(uint i);

      /*!
       * Sets the track to \a i.  If \a s is 0 then this value will be cleared.
       */
      virtual void setTrack(uint i);

      /*!
       * Returns true if the tag does not contain any data.  This should be
       * reimplemented in subclasses that provide more than the basic tagging
       * abilities in this class.
       */
      virtual bool isEmpty() const;

      /*!
       * Returns a reference to the item list map.  This is an AttributeListMap of
       * all of the items in the tag.
       *
       * This is the most powerfull structure for accessing the items of the tag.
       */
      AttributeListMap &attributeListMap();

      /*!
       * Removes the \a key attribute from the tag
       */
      void removeItem(const String &name);

      /*!
       * Sets the \a key attribute to the value of \a attribute. If an attribute
       * with the \a key is already present, it will be replaced.
       */
      void setAttribute(const String &name, const Attribute &attribute);

      /*!
       * Sets the \a key attribute to the value of \a attribute. If an attribute
       * with the \a key is already present, it will be added to the list.
       */
      void addAttribute(const String &name, const Attribute &attribute);

      PropertyMap properties() const;
      void removeUnsupportedProperties(const StringList& properties);
      PropertyMap setProperties(const PropertyMap &properties);

    private:

      class TagPrivate;
      TagPrivate *d;
    };
  }
}
#endif


text:
package com.gearlles.ga.core.crossover;

import java.util.Random;

import com.gearlles.ga.core.Chromosome;

public class TwoPoint implements CrossoverInterface
{

    private static Random rand = new Random();

    public Chromosome[] mate(Chromosome dad, Chromosome mom)
    {
	// Convert the genes to arrays to make thing easier.
	double[] dadGene = dad.getGene();
	double[] momGene = mom.getGene();

	// Select a random pivot point for the mating
	int pivot1 = rand.nextInt(dadGene.length);
	int pivot2 = rand.nextInt(dadGene.length);

        int tmp;
        if (pivot1 > pivot2){
            tmp = pivot1;
            pivot1 = pivot2;
            pivot2 = tmp;
        }

	// Provide a container for the child gene data
	double[] child1 = new double[dadGene.length];
	double[] child2 = new double[dadGene.length];

	System.arraycopy(dadGene, 0, child1, 0, pivot1);
	System.arraycopy(momGene, pivot1, child1, pivot1, (pivot2 - pivot1));
	System.arraycopy(dadGene, pivot2, child1, pivot2, (dadGene.length - pivot2));

	System.arraycopy(momGene, 0, child2, 0, pivot1);
	System.arraycopy(dadGene, pivot1, child2, pivot1, (pivot2 - pivot1));
	System.arraycopy(momGene, pivot2, child2, pivot2, (dadGene.length - pivot2));

	return new Chromosome[] { new Chromosome(child1),
		new Chromosome(child2) };
    }

}

redpajama_set_name: RedPajamaGithub


text:
package org.onosproject.cli.net;

import org.apache.karaf.shell.commands.Option;
import org.onlab.packet.Ip6Address;
import org.onlab.packet.IpAddress;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.MacAddress;
import org.onlab.packet.TpPort;
import org.onlab.packet.VlanId;
import org.onlab.util.Bandwidth;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.net.EncapsulationType;
import org.onosproject.net.PortNumber;
import org.onosproject.net.ResourceGroup;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.intent.Constraint;
import org.onosproject.net.intent.Intent;
import org.onosproject.net.intent.Key;
import org.onosproject.net.intent.constraint.BandwidthConstraint;
import org.onosproject.net.intent.constraint.DomainConstraint;
import org.onosproject.net.intent.constraint.EncapsulationConstraint;
import org.onosproject.net.intent.constraint.HashedPathSelectionConstraint;
import org.onosproject.net.intent.constraint.PartialFailureConstraint;

import java.util.LinkedList;
import java.util.List;

import static com.google.common.base.Strings.isNullOrEmpty;
import static org.onosproject.net.flow.DefaultTrafficTreatment.builder;

/**
 * Base class for command line operations for connectivity based intents.
 */
public abstract class ConnectivityIntentCommand extends AbstractShellCommand {

    // Selectors
    @Option(name = "-s", aliases = "--ethSrc", description = "Source MAC Address",
            required = false, multiValued = false)
    private String srcMacString = null;

    @Option(name = "-d", aliases = "--ethDst", description = "Destination MAC Address",
            required = false, multiValued = false)
    private String dstMacString = null;

    @Option(name = "-t", aliases = "--ethType", description = "Ethernet Type",
            required = false, multiValued = false)
    private String ethTypeString = null;

    @Option(name = "-v", aliases = "--vlan", description = "VLAN ID",
            required = false, multiValued = false)
    private String vlanString = null;

    @Option(name = "--ipProto", description = "IP Protocol",
            required = false, multiValued = false)
    private String ipProtoString = null;

    @Option(name = "--ipSrc", description = "Source IP Prefix",
            required = false, multiValued = false)
    private String srcIpString = null;

    @Option(name = "--ipDst", description = "Destination IP Prefix",
            required = false, multiValued = false)
    private String dstIpString = null;

    @Option(name = "--fLabel", description = "IPv6 Flow Label",
            required = false, multiValued = false)
    private String fLabelString = null;

    @Option(name = "--icmp6Type", description = "ICMPv6 Type",
            required = false, multiValued = false)
    private String icmp6TypeString = null;

    @Option(name = "--icmp6Code", description = "ICMPv6 Code",
            required = false, multiValued = false)
    private String icmp6CodeString = null;

    @Option(name = "--ndTarget", description = "IPv6 Neighbor Discovery Target Address",
            required = false, multiValued = false)
    private String ndTargetString = null;

    @Option(name = "--ndSLL", description = "IPv6 Neighbor Discovery Source Link-Layer",
            required = false, multiValued = false)
    private String ndSllString = null;

    @Option(name = "--ndTLL", description = "IPv6 Neighbor Discovery Target Link-Layer",
            required = false, multiValued = false)
    private String ndTllString = null;

    @Option(name = "--tcpSrc", description = "Source TCP Port",
            required = false, multiValued = false)
    private String srcTcpString = null;

    @Option(name = "--tcpDst", description = "Destination TCP Port",
            required = false, multiValued = false)
    private String dstTcpString = null;

    @Option(name = "--extHdr", description = "IPv6 Extension Header Pseudo-field",
            required = false, multiValued = true)
    private List<String> extHdrStringList = null;

    @Option(name = "-a", aliases = "--appId", description = "Application Id",
            required = false, multiValued = false)
    private String appId = null;

    @Option(name = "-k", aliases = "--key", description = "Intent Key",
            required = false, multiValued = false)
    private String intentKey = null;

    // Treatments
    @Option(name = "--setEthSrc", description = "Rewrite Source MAC Address",
            required = false, multiValued = false)
    private String setEthSrcString = null;

    @Option(name = "--setEthDst", description = "Rewrite Destination MAC Address",
            required = false, multiValued = false)
    private String setEthDstString = null;

    @Option(name = "--setIpSrc", description = "Rewrite Source IP Address",
            required = false, multiValued = false)
    private String setIpSrcString = null;

    @Option(name = "--setIpDst", description = "Rewrite Destination IP Address",
            required = false, multiValued = false)
    private String setIpDstString = null;

    @Option(name = "--setVlan", description = "Rewrite VLAN ID",
            required = false, multiValued = false)
    private String setVlan = null;

    @Option(name = "--popVlan", description = "Pop VLAN Tag",
            required = false, multiValued = false)
    private boolean popVlan = false;

    @Option(name = "--pushVlan", description = "Push VLAN ID",
            required = false, multiValued = false)
    private String pushVlan = null;

    @Option(name = "--setQueue", description = "Set Queue ID (for OpenFlow 1.0, " +
            "also the port has to be specified, i.e., <port>/<queue>",
            required = false, multiValued = false)
    private String setQueue = null;

    // Priorities
    @Option(name = "-p", aliases = "--priority", description = "Priority",
            required = false, multiValued = false)
    private int priority = Intent.DEFAULT_INTENT_PRIORITY;

    // Constraints
    @Option(name = "-b", aliases = "--bandwidth", description = "Bandwidth",
            required = false, multiValued = false)
    private String bandwidthString = null;

    @Option(name = "--partial", description = "Allow partial installation",
            required = false, multiValued = false)
    private boolean partial = false;

    @Option(name = "-e", aliases = "--encapsulation", description = "Encapsulation type",
            required = false, multiValued = false)
    private String encapsulationString = null;

    @Option(name = "--hashed", description = "Hashed path selection",
            required = false, multiValued = false)
    private boolean hashedPathSelection = false;

    @Option(name = "--domains", description = "Allow domain delegation",
            required = false, multiValued = false)
    private boolean domains = false;

    // Resource Group
    @Option(name = "-r", aliases = "--resourceGroup", description = "Resource Group Id",
            required = false, multiValued = false)
    private String resourceGroupId = null;

    /**
     * Constructs a traffic selector based on the command line arguments
     * presented to the command.
     * @return traffic selector
     */
    protected TrafficSelector buildTrafficSelector() {
        IpPrefix srcIpPrefix = null;
        IpPrefix dstIpPrefix = null;

        TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();

        if (!isNullOrEmpty(srcIpString)) {
            srcIpPrefix = IpPrefix.valueOf(srcIpString);
            if (srcIpPrefix.isIp4()) {
                selectorBuilder.matchIPSrc(srcIpPrefix);
            } else {
                selectorBuilder.matchIPv6Src(srcIpPrefix);
            }
        }

        if (!isNullOrEmpty(dstIpString)) {
            dstIpPrefix = IpPrefix.valueOf(dstIpString);
            if (dstIpPrefix.isIp4()) {
                selectorBuilder.matchIPDst(dstIpPrefix);
            } else {
                selectorBuilder.matchIPv6Dst(dstIpPrefix);
            }
        }

        if ((srcIpPrefix != null) && (dstIpPrefix != null) &&
            (srcIpPrefix.version() != dstIpPrefix.version())) {
            // ERROR: IP src/dst version mismatch
            throw new IllegalArgumentException(
                        "IP source and destination version mismatch");
        }

        //
        // Set the default EthType based on the IP version if the matching
        // source or destination IP prefixes.
        //
        Short ethType = null;
        if ((srcIpPrefix != null) && srcIpPrefix.isIp6()) {
            ethType = EthType.IPV6.value();
        }
        if ((dstIpPrefix != null) && dstIpPrefix.isIp6()) {
            ethType = EthType.IPV6.value();
        }
        if (!isNullOrEmpty(ethTypeString)) {
            ethType = EthType.parseFromString(ethTypeString);
        }
        if (ethType != null) {
            selectorBuilder.matchEthType(ethType);
        }
        if (!isNullOrEmpty(vlanString)) {
            selectorBuilder.matchVlanId(VlanId.vlanId(Short.parseShort(vlanString)));
        }
        if (!isNullOrEmpty(srcMacString)) {
            selectorBuilder.matchEthSrc(MacAddress.valueOf(srcMacString));
        }

        if (!isNullOrEmpty(dstMacString)) {
            selectorBuilder.matchEthDst(MacAddress.valueOf(dstMacString));
        }

        if (!isNullOrEmpty(ipProtoString)) {
            short ipProtoShort = IpProtocol.parseFromString(ipProtoString);
            selectorBuilder.matchIPProtocol((byte) ipProtoShort);
        }

        if (!isNullOrEmpty(fLabelString)) {
            selectorBuilder.matchIPv6FlowLabel(Integer.parseInt(fLabelString));
        }

        if (!isNullOrEmpty(icmp6TypeString)) {
            byte icmp6Type = Icmp6Type.parseFromString(icmp6TypeString);
            selectorBuilder.matchIcmpv6Type(icmp6Type);
        }

        if (!isNullOrEmpty(icmp6CodeString)) {
            byte icmp6Code = Icmp6Code.parseFromString(icmp6CodeString);
            selectorBuilder.matchIcmpv6Code(icmp6Code);
        }

        if (!isNullOrEmpty(ndTargetString)) {
            selectorBuilder.matchIPv6NDTargetAddress(Ip6Address.valueOf(ndTargetString));
        }

        if (!isNullOrEmpty(ndSllString)) {
            selectorBuilder.matchIPv6NDSourceLinkLayerAddress(MacAddress.valueOf(ndSllString));
        }

        if (!isNullOrEmpty(ndTllString)) {
            selectorBuilder.matchIPv6NDTargetLinkLayerAddress(MacAddress.valueOf(ndTllString));
        }

        if (!isNullOrEmpty(srcTcpString)) {
            selectorBuilder.matchTcpSrc(TpPort.tpPort(Integer.parseInt(srcTcpString)));
        }

        if (!isNullOrEmpty(dstTcpString)) {
            selectorBuilder.matchTcpDst(TpPort.tpPort(Integer.parseInt(dstTcpString)));
        }

        if (extHdrStringList != null) {
            short extHdr = 0;
            for (String extHdrString : extHdrStringList) {
                extHdr = (short) (extHdr | ExtHeader.parseFromString(extHdrString));
            }
            selectorBuilder.matchIPv6ExthdrFlags(extHdr);
        }

        return selectorBuilder.build();
    }

    /**
     * Generates a traffic treatment for this intent based on command line
     * arguments presented to the command.
     *
     * @return traffic treatment
     */
    protected TrafficTreatment buildTrafficTreatment() {
        final TrafficTreatment.Builder treatmentBuilder = builder();
        boolean emptyTreatment = true;

        if (!isNullOrEmpty(setEthSrcString)) {
            treatmentBuilder.setEthSrc(MacAddress.valueOf(setEthSrcString));
            emptyTreatment = false;
        }

        if (!isNullOrEmpty(setEthDstString)) {
            treatmentBuilder.setEthDst(MacAddress.valueOf(setEthDstString));
            emptyTreatment = false;
        }

        if (!isNullOrEmpty(setIpSrcString)) {
            treatmentBuilder.setIpSrc(IpAddress.valueOf(setIpSrcString));
            emptyTreatment = false;
        }

        if (!isNullOrEmpty(setIpDstString)) {
            treatmentBuilder.setIpDst(IpAddress.valueOf(setIpDstString));
            emptyTreatment = false;
        }
        if (!isNullOrEmpty(setVlan)) {
            treatmentBuilder.setVlanId(VlanId.vlanId(Short.parseShort(setVlan)));
            emptyTreatment = false;
        }
        if (popVlan) {
            treatmentBuilder.popVlan();
            emptyTreatment = false;
        }
        if (!isNullOrEmpty(pushVlan)) {
            treatmentBuilder.pushVlan();
            treatmentBuilder.setVlanId(VlanId.vlanId(Short.parseShort(pushVlan)));
            emptyTreatment = false;
        }
        if (!isNullOrEmpty(setQueue)) {
            // OpenFlow 1.0 notation (for ENQUEUE): <port>/<queue>
            if (setQueue.contains("/")) {
                String[] queueConfig = setQueue.split("/");
                PortNumber port = PortNumber.portNumber(Long.parseLong(queueConfig[0]));
                long queueId = Long.parseLong(queueConfig[1]);
                treatmentBuilder.setQueue(queueId, port);
            } else {
                treatmentBuilder.setQueue(Long.parseLong(setQueue));
            }
            emptyTreatment = false;
        }

        if (emptyTreatment) {
            return DefaultTrafficTreatment.emptyTreatment();
        } else {
            return treatmentBuilder.build();
        }
    }

    /**
     * Builds the constraint list for this command based on the command line
     * parameters.
     *
     * @return List of constraint objects describing the constraints requested
     */
    protected List<Constraint> buildConstraints() {
        final List<Constraint> constraints = new LinkedList<>();

        // Check for a bandwidth specification
        if (!isNullOrEmpty(bandwidthString)) {
            Bandwidth bandwidth;
            try {
                bandwidth = Bandwidth.bps(Long.parseLong(bandwidthString));
            // when the string can't be parsed as long, then try to parse as double
            } catch (NumberFormatException e) {
                bandwidth = Bandwidth.bps(Double.parseDouble(bandwidthString));
            }
            constraints.add(new BandwidthConstraint(bandwidth));
        }

        // Check for partial failure specification
        if (partial) {
            constraints.add(new PartialFailureConstraint());
        }

        // Check for encapsulation specification
        if (!isNullOrEmpty(encapsulationString)) {
            final EncapsulationType encapType = EncapsulationType.valueOf(encapsulationString);
            constraints.add(new EncapsulationConstraint(encapType));
        }

        // Check for hashed path selection
        if (hashedPathSelection) {
            constraints.add(new HashedPathSelectionConstraint());
        }

        // Check for domain processing
        if (domains) {
            constraints.add(DomainConstraint.domain());
        }
        return constraints;
    }

    @Override
    protected ApplicationId appId() {
        ApplicationId appIdForIntent;
        if (appId == null) {
            appIdForIntent = super.appId();
        } else {
            CoreService service = get(CoreService.class);
            appIdForIntent = service.getAppId(appId);
        }
        return appIdForIntent;
    }

    protected ResourceGroup resourceGroup() {
        if (resourceGroupId != null) {
            if (resourceGroupId.toLowerCase().startsWith("0x")) {
                return ResourceGroup.of(Long.parseUnsignedLong(resourceGroupId.substring(2), 16));
            } else {
                return ResourceGroup.of(Long.parseUnsignedLong(resourceGroupId));
            }
        } else {
            return null;
        }
    }

    /**
     * Creates a key for an intent based on command line arguments.  If a key
     * has been specified, it is returned.  If no key is specified, null
     * is returned.
     *
     * @return intent key if specified, null otherwise
     */
    protected Key key() {
        Key key = null;

        if (intentKey != null) {
            key = Key.of(intentKey, appId());
        }
        return key;
    }

    /**
     * Gets the priority to use for the intent.
     *
     * @return priority
     */
    protected int priority() {
        return priority;
    }
}


text:
namespace Poco {

class Foundation_API DateTimeParser
	/// This class provides a method for parsing dates and times
	/// from strings. All parsing methods do their best to
	/// parse a meaningful result, even from malformed input
	/// strings.
	///
	/// The returned DateTime will always contain a time in the same
	/// timezone as the time in the string. Call DateTime::makeUTC()
	/// with the timeZoneDifferential returned by parse() to convert
	/// the DateTime to UTC.
	///
	/// Note: When parsing a time in 12-hour (AM/PM) format, the hour
	/// (%h) must be parsed before the AM/PM designator (%a, %A),
	/// otherwise the AM/PM designator will be ignored.
{
public:
	static void parse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential);
		/// Parses a date and time in the given format from the given string.
		/// Throws a SyntaxException if the string cannot be successfully parsed.
		/// Please see DateTimeFormatter::format() for a description of the format string.
		/// Class DateTimeFormat defines format strings for various standard date/time formats.

	static DateTime parse(const std::string& fmt, const std::string& str, int& timeZoneDifferential);
		/// Parses a date and time in the given format from the given string.
		/// Throws a SyntaxException if the string cannot be successfully parsed.
		/// Please see DateTimeFormatter::format() for a description of the format string.
		/// Class DateTimeFormat defines format strings for various standard date/time formats.

	static bool tryParse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential);
		/// Parses a date and time in the given format from the given string.
		/// Returns true if the string has been successfully parsed, false otherwise.
		/// Please see DateTimeFormatter::format() for a description of the format string.
		/// Class DateTimeFormat defines format strings for various standard date/time formats.

	static void parse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential);
		/// Parses a date and time from the given dateTime string. Before parsing, the method
		/// examines the dateTime string for a known date/time format.
		/// Throws a SyntaxException if the string cannot be successfully parsed.
		/// Please see DateTimeFormatter::format() for a description of the format string.
		/// Class DateTimeFormat defines format strings for various standard date/time formats.

	static DateTime parse(const std::string& str, int& timeZoneDifferential);
		/// Parses a date and time from the given dateTime string. Before parsing, the method
		/// examines the dateTime string for a known date/time format.
		/// Please see DateTimeFormatter::format() for a description of the format string.
		/// Class DateTimeFormat defines format strings for various standard date/time formats.

	static bool tryParse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential);
		/// Parses a date and time from the given dateTime string. Before parsing, the method
		/// examines the dateTime string for a known date/time format.
		/// Please see DateTimeFormatter::format() for a description of the format string.
		/// Class DateTimeFormat defines format strings for various standard date/time formats.

	static int parseMonth(std::string::const_iterator& it, const std::string::const_iterator& end);
		/// Tries to interpret the given range as a month name. The range must be at least
		/// three characters long.
		/// Returns the month number (1 .. 12) if the month name is valid. Otherwise throws
		/// a SyntaxException.

	static int parseDayOfWeek(std::string::const_iterator& it, const std::string::const_iterator& end);
		/// Tries to interpret the given range as a weekday name. The range must be at least
		/// three characters long.
		/// Returns the weekday number (0 .. 6, where 0 = Synday, 1 = Monday, etc.) if the
		/// weekday name is valid. Otherwise throws a SyntaxException.

protected:
	static int parseTZD(std::string::const_iterator& it, const std::string::const_iterator& end);
	static int parseAMPM(std::string::const_iterator& it, const std::string::const_iterator& end, int hour);
};

} // namespace Poco

#endif // Foundation_DateTimeParser_INCLUDED


text:
package com.smartsheet.api.internal.json;

import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.smartsheet.api.models.Cell;
import com.smartsheet.api.models.CellLink;

/**
 * If the class being serialized is a cell, pass along the default serializer along to the CellSerializer object.
 * We'll special case the linkInFromCell case but pass the rest along to the default serializer.
 */
public class CellSerializerModifier extends BeanSerializerModifier {
    @Override
    public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
        if (beanDesc.getBeanClass() == Cell.class) {
            return new CellSerializer((JsonSerializer<Object>) serializer);
        }
        else if (beanDesc.getBeanClass() == CellLink.class) {
            return new CellLinkSerializer((JsonSerializer<Object>) serializer);
        }
        return serializer;
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />

  <meta property="og:title" content=" App ·  Ila e Ricky" />
  <meta property="og:site_name" content="Ila e Ricky" />
  <meta property="og:url" content="http://ilaericky.it/tags/app/" />

  <meta property="og:type" content="website" />

  <title>
     App ·  Ila e Ricky
  </title>

  <meta name="description" content="Ci sposiamo il 25 Giugno 2016!" />

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

  <link rel="shortcut icon" href="http://ilaericky.it/images/favicon.ico">
  <link rel="apple-touch-icon" href="http://ilaericky.it/images/apple-touch-icon.png" />

  <link rel="stylesheet" type="text/css" href="http://ilaericky.it/css/screen.css" />
  <link rel="stylesheet" type="text/css" href="http://ilaericky.it/css/nav.css" />
  <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Annie+Use+Your+Telescope|Open+Sans:700,400|Inconsolata" />
  <link rel="stylesheet" type="text/css" href="http://ilaericky.it/css/normalize.css" />
  <link rel="stylesheet" type="text/css" href="http://ilaericky.it/css/component.css" />
  <link rel="stylesheet" type="text/css" href="http://ilaericky.it/css/custom-bars.css" />

    <meta name="generator" content="Hugo 0.15" />

    <link rel="canonical" href="http://ilaericky.it/tags/app/" />

Menu

        Close

            	Ila e Ricky

            	Info utili

            	Scrivici!

            	Verso la location

            	Lista viaggio

            	Save the date

            	App foto

          ☰Menu

App

	Page 1 of 1

App per le foto!

Eh, già, purtroppo non è un app Tiknil, ma speriamo funzioni lo stesso.

E’ un app per fare le foto e condividerle al nostro matrimonio!

Scaricatela, aggiungetevi come invitati e vediamo le foto di tutti!

Apple
Android

Codice dell’album: IT409acd26

Enjoy!

            Riccardo Tribbia e Ilaria Bariletti

        on

                #app,

                #foto,

        <time class="post-date" datetime="2016-06-14T16:46:04+02:00">
            14 Jun 2016
        </time>

	Page 1 of 1

Ila e Ricky

Proudly generated by HUGO, with Casper theme


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="resources/images/favicon.ico">
    <title>apiman :: tutorials & walkthroughs</title>

    <link href="resources/bootstrap-3.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="resources/patternfly-1.0.5/css/patternfly.min.css" rel="stylesheet">
    <link href="https://static.jboss.org/css/rhbar.css" media="screen" rel="stylesheet">
    <link href="resources/css/apiman-web.css?v=1.1.9.Final" rel="stylesheet">
    <link href="resources/css/apiman-web.responsive.css?v=1.1.9.Final" rel="stylesheet">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          apiman

Overview

Download

Roadmap

Blog

                Get Involved

                        Report a Bug

                        Chat on IRC

                        Twitter Feed

                        Mailing List

                        Contributors List

                Learn More

                        Tutorials & Walkthroughs

                        Installation Guide

                        User Guide

                        Developer Guide

                        Production Guide

                        API Manager REST Endpoints

                1.1.x

                        Latest Version

                        Version 1.1.x

              Note: You are viewing the (deprecated) project site for version 1.1.x of apiman.  This is an older version.  Did you want to see the latest version of apiman instead?

Tutorials & Walkthroughs

                  For your convenience we've produced a few tutorial/walkthrough videos.  The information in
                  the videos is duplicated in the project guides (see User, Developer, and Installation guides),
                  but if you prefer to learn visually then this might be the place for you!

apiman Concepts

Installing apiman

Using apiman

apiman plugins

Public Services

                                Copyright ©  Red Hat, Inc. All rights reserved.

                                apiman code is open source and released under Apache License, v2.0.

                                Open Source Disclosure


text:
<?php

namespace Knp\Snappy;

/**
 * Use this class to create a snapshot / thumbnail from a HTML page
 *
 * @package Snappy
 *
 * @author  Matthieu Bontemps <matthieu.bontemps@knplabs.com>
 * @author  Antoine Hérault <antoine.herault@knplabs.com>
 */
class Image extends AbstractGenerator
{
    /**
     * {@inheritDoc}
     */
    public function __construct($binary = null, array $options = array(), array $env = null)
    {
        $this->setDefaultExtension('jpg');

        parent::__construct($binary, $options, $env);
    }

    /**
     * {@inheritDoc}
     */
    protected function configure()
    {
        $this->addOptions(array(
            'allow'                        => null,    // Allow the file or files from the specified folder to be loaded (repeatable)
            'checkbox-checked-svg'         => null,    // Use this SVG file when rendering checked checkboxes
            'checked-svg'                  => null,    // Use this SVG file when rendering unchecked checkboxes
            'cookie'                       => array(), // Set an additional cookie (repeatable)
            'cookie-jar'                   => null,    // Read and write cookies from and to the supplied cookie jar file
            'crop-h'                       => null,    // Set height for croping
            'crop-w'                       => null,    // Set width for croping
            'crop-x'                       => null,    // Set x coordinate for croping (default 0)
            'crop-y'                       => null,    // Set y coordinate for croping (default 0)
            'custom-header'                => array(), // Set an additional HTTP header (repeatable)
            'custom-header-propagation'    => null,    // Add HTTP headers specified by --custom-header for each resource request.
            'no-custom-header-propagation' => null,    // Do not add HTTP headers specified by --custom-header for each resource request.
            'debug-javascript'             => null,    // Show javascript debugging output
            'no-debug-javascript'          => null,    // Do not show javascript debugging output (default)
            'encoding'                     => null,    // Set the default text encoding, for input
            'format'                       => $this->getDefaultExtension(),   // Output format
            'height'                       => null,    // Set screen height (default is calculated from page content) (default 0)
            'images'                       => null,    // Do load or print images (default)
            'no-images'                    => null,    // Do not load or print images
            'disable-javascript'           => null,    // Do not allow web pages to run javascript
            'enable-javascript'            => null,    // Do allow web pages to run javascript (default)
            'javascript-delay'             => null,    // Wait some milliseconds for javascript finish (default 200)
            'load-error-handling'          => null,    // Specify how to handle pages that fail to load: abort, ignore or skip (default abort)
            'disable-local-file-access'    => null,    // Do not allowed conversion of a local file to read in other local files, unless explecitily allowed with allow
            'enable-local-file-access'     => null,    // Allowed conversion of a local file to read in other local files. (default)
            'minimum-font-size'            => null,    // Minimum font size
            'password'                     => null,    // HTTP Authentication password
            'disable-plugins'              => null,    // Disable installed plugins (default)
            'enable-plugins'               => null,    // Enable installed plugins (plugins will likely not work)
            'post'                         => array(), // Add an additional post field
            'post-file'                    => array(), // Post an additional file
            'proxy'                        => null,    // Use a proxy
            'quality'                      => null,    // Output image quality (between 0 and 100) (default 94)
            'radiobutton-checked-svg'      => null,    // Use this SVG file when rendering checked radiobuttons
            'radiobutton-svg'              => null,    // Use this SVG file when rendering unchecked radiobuttons
            'run-script'                   => null,    // Run this additional javascript after the page is done loading (repeatable)
            'disable-smart-width'          => null,    // Use the specified width even if it is not large enough for the content
            'enable-smart-width'           => null,    // Extend --width to fit unbreakable content (default)
            'stop-slow-scripts'            => null,    // Stop slow running javascripts
            'no-stop-slow-scripts'         => null,    // Do not stop slow running javascripts (default)
            'transparent'                  => null,    // Make the background transparrent in pngs *
            'use-xserver'                  => null,    // Use the X server (some plugins and other stuff might not work without X11)
            'user-style-sheet'             => null,    // Specify a user style sheet, to load with every page
            'username'                     => null,    // HTTP Authentication username
            'width'                        => null,    // Set screen width (default is 1024)
            'window-status'                => null,    // Wait until window.status is equal to this string before rendering page
            'zoom'                         => null,    // Use this zoom factor (default 1)
        ));
    }
}


text:
"""
Pyrorp.py

Python implementation of the Remote Object Reference Protocol

"""

import socket
import time

sock = socket.socket()
#sock.setblocking(0)

try:
	sock.connect(("localhost",25565))
	sock.sendall(bytes("1+1000\r\n", 'utf-8'))
	print(sock.recv(1024))

finally:
	sock.close()


text:
module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'scope-enum': [2, 'always', ['common', 'universal', 'package', 'npm', 'circle', 'lint', 'packaging', 'changelog']]
  }
};


text:
'use strict';

var fs = require('fs');
var path = require('path-posix');
var assign = require('object-assign');
var symlinkOrCopy = require('symlink-or-copy');
var Entry = require('./entry');
var logger = require('heimdalljs-logger')('fs-tree-diff:');
var util = require('./util');
var sortAndExpand = util.sortAndExpand;
var validateSortedUnique = util.validateSortedUnique;

var ARBITRARY_START_OF_TIME = 0;
var DEFAULT_DELEGATE = {
  unlink: function(inputPath, outputPath, relativePath) {
    fs.unlinkSync(outputPath);
  },
  rmdir: function(inputPath, outputPath, relativePath) {
    fs.rmdirSync(outputPath);
  },
  mkdir: function(inputPath, outputPath, relativePath) {
    fs.mkdirSync(outputPath);
  },
  change: function(inputPath, outputPath, relativePath) {
    // We no-op if the platform can symlink, because we assume the output path
    // is already linked via a prior create operation.
    if (symlinkOrCopy.canSymlink) {
      return;
    }

    fs.unlinkSync(outputPath);
    symlinkOrCopy.sync(inputPath, outputPath);
  },
  create: function(inputPath, outputPath, relativePath) {
    symlinkOrCopy.sync(inputPath, outputPath);
  }
};

module.exports = FSTree;

function FSTree(options) {
  options = options || {};

  var entries = options.entries || [];

  if (options.sortAndExpand) {
    sortAndExpand(entries);
  } else {
    validateSortedUnique(entries);
  }

  this.entries = entries;
}

FSTree.fromPaths = function(paths, options) {
  if (typeof options !== 'object') { options = {}; }

  var entries = paths.map(function(path) {
    return new Entry(path, 0, ARBITRARY_START_OF_TIME);
  });

  return new FSTree({
    entries: entries,
    sortAndExpand: options.sortAndExpand,
  });
};

FSTree.fromEntries = function(entries, options) {
  if (typeof options !== 'object') { options = {}; }

  return new FSTree({
    entries: entries,
    sortAndExpand: options.sortAndExpand,
  });
};

Object.defineProperty(FSTree.prototype, 'size', {
  get: function() {
    return this.entries.length;
  }
});

FSTree.prototype.addEntries = function(entries, options) {
  if (!Array.isArray(entries)) {
    throw new TypeError('entries must be an array');
  }
  if (options && options.sortAndExpand) {
    sortAndExpand(entries);
  } else {
    validateSortedUnique(entries);
  }
  var fromIndex = 0;
  var toIndex = 0;
  while (fromIndex < entries.length) {
    while (toIndex < this.entries.length &&
           this.entries[toIndex].relativePath < entries[fromIndex].relativePath) {
      toIndex++;
    }
    if (toIndex < this.entries.length &&
        this.entries[toIndex].relativePath === entries[fromIndex].relativePath) {
      this.entries.splice(toIndex, 1, entries[fromIndex++]);
    } else {
      this.entries.splice(toIndex++, 0, entries[fromIndex++]);
    }
  }
};

FSTree.prototype.addPaths = function(paths, options) {
  var entries = paths.map(function(path) {
    return new Entry(path, 0, ARBITRARY_START_OF_TIME);
  });

  this.addEntries(entries, options);
}

FSTree.prototype.forEach = function(fn, context) {
  this.entries.forEach(fn, context);
};

FSTree.prototype.calculatePatch = function(otherFSTree, isEqual) {
  if (arguments.length > 1 && typeof isEqual !== 'function') {
    throw new TypeError('calculatePatch\'s second argument must be a function');
  }

  if (typeof isEqual !== 'function') {
    isEqual = FSTree.defaultIsEqual;
  }

  var ours = this.entries;
  var theirs = otherFSTree.entries;
  var additions = [];

  var i = 0;
  var j = 0;

  var removals = [];

  var command;

  while (i < ours.length && j < theirs.length) {
    var x = ours[i];
    var y = theirs[j];

    if (x.relativePath < y.relativePath) {
      // ours
      i++;

      command = removeCommand(x);

      if (x.isDirectory()) {
        removals.push(command);
      } else {
        // pre-cleanup file removals should occure in-order, this ensures file
        // -> directory transforms work correctly
        additions.push(command);
      }

      // remove additions
    } else if (x.relativePath > y.relativePath) {
      // theirs
      j++;
      additions.push(addCommand(y));
    } else {
      if (!isEqual(x, y)) {
        command = updateCommand(y);

        if (x.isDirectory()) {
          removals.push(command);
        } else {
          additions.push(command);
        }
      }
      // both are the same
      i++; j++;
    }
  }

  // cleanup ours
  for (; i < ours.length; i++) {
    removals.push(removeCommand(ours[i]));
  }

  // cleanup theirs
  for (; j < theirs.length; j++) {
    additions.push(addCommand(theirs[j]));
  }

  // operations = removals (in reverse) then additions
  return removals.reverse().concat(additions);
};

FSTree.prototype.calculateAndApplyPatch = function(otherFSTree, input, output, delegate) {
  var patch = this.calculatePatch(otherFSTree);
  FSTree.applyPatch(input, output, patch, delegate);
};

FSTree.defaultIsEqual = function defaultIsEqual(entryA, entryB) {
  if (entryA.isDirectory() && entryB.isDirectory()) {
    // ignore directory changes by default
    return true;
  }

  var equal = entryA.size === entryB.size &&
       +entryA.mtime === +entryB.mtime &&
       entryA.mode === entryB.mode;

  if (!equal) {
    logger.info('invalidation reason: \nbefore %o\n entryB %o', entryA, entryB);
  }

  return equal;
};

FSTree.applyPatch = function(input, output, patch, _delegate) {
  var delegate = assign({}, DEFAULT_DELEGATE, _delegate);
  for (var i = 0; i < patch.length; i++) {
    applyOperation(input, output, patch[i], delegate);
  }
};

function applyOperation(input, output, operation, delegate) {
  var method = operation[0];
  var relativePath = operation[1];
  var inputPath = path.join(input, relativePath);
  var outputPath = path.join(output, relativePath);

  var delegateType = typeof delegate[method];
  if (delegateType === 'function') {
    delegate[method](inputPath, outputPath, relativePath);
  } else {
    throw new Error('Unable to apply patch operation: ' + method + '. The value of delegate.' + method + ' is of type ' + delegateType + ', and not a function. Check the `delegate` argument to `FSTree.prototype.applyPatch`.');
  }
}

function addCommand(entry) {
  return [entry.isDirectory() ? 'mkdir' : 'create', entry.relativePath, entry];
}

function removeCommand(entry) {
  return [entry.isDirectory() ? 'rmdir' : 'unlink', entry.relativePath, entry];
}

function updateCommand(entry) {
  return ['change', entry.relativePath, entry];
}


text:
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors.  All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package proto

/*
 * Routines for encoding data into the wire format for protocol buffers.
 */

import (
    "errors"
    "fmt"
    "reflect"
    "sort"
)

// RequiredNotSetError is the error returned if Marshal is called with
// a protocol buffer struct whose required fields have not
// all been initialized. It is also the error returned if Unmarshal is
// called with an encoded protocol buffer that does not include all the
// required fields.
//
// When printed, RequiredNotSetError reports the first unset required field in a
// message. If the field cannot be precisely determined, it is reported as
// "{Unknown}".
type RequiredNotSetError struct {
    field string
}

func (e *RequiredNotSetError) Error() string {
    return fmt.Sprintf("proto: required field %q not set", e.field)
}

var (
// errRepeatedHasNil is the error returned if Marshal is called with
// a struct with a repeated field containing a nil element.
    errRepeatedHasNil = errors.New("proto: repeated field has nil element")

// ErrNil is the error returned if Marshal is called with nil.
    ErrNil = errors.New("proto: Marshal called with nil")
)

// The fundamental encoders that put bytes on the wire.
// Those that take integer types all accept uint64 and are
// therefore of type valueEncoder.

const maxVarintBytes = 10 // maximum length of a varint

// EncodeVarint returns the varint encoding of x.
// This is the format for the
// int32, int64, uint32, uint64, bool, and enum
// protocol buffer types.
// Not used by the package itself, but helpful to clients
// wishing to use the same encoding.
func EncodeVarint(x uint64) []byte {
    var buf [maxVarintBytes]byte
    var n int
    for n = 0; x > 127; n++ {
        buf[n] = 0x80 | uint8(x & 0x7F)
        x >>= 7
    }
    buf[n] = uint8(x)
    n++
    return buf[0:n]
}

// EncodeVarint writes a varint-encoded integer to the Buffer.
// This is the format for the
// int32, int64, uint32, uint64, bool, and enum
// protocol buffer types.
func (p *Buffer) EncodeVarint(x uint64) error {
    for x >= 1 << 7 {
        p.buf = append(p.buf, uint8(x & 0x7f | 0x80))
        x >>= 7
    }
    p.buf = append(p.buf, uint8(x))
    return nil
}

// SizeVarint returns the varint encoding size of an integer.
func SizeVarint(x uint64) int {
    return sizeVarint(x)
}

func sizeVarint(x uint64) (n int) {
    for {
        n++
        x >>= 7
        if x == 0 {
            break
        }
    }
    return n
}

// EncodeFixed64 writes a 64-bit integer to the Buffer.
// This is the format for the
// fixed64, sfixed64, and double protocol buffer types.
func (p *Buffer) EncodeFixed64(x uint64) error {
    p.buf = append(p.buf,
        uint8(x),
        uint8(x >> 8),
        uint8(x >> 16),
        uint8(x >> 24),
        uint8(x >> 32),
        uint8(x >> 40),
        uint8(x >> 48),
        uint8(x >> 56))
    return nil
}

func sizeFixed64(x uint64) int {
    return 8
}

// EncodeFixed32 writes a 32-bit integer to the Buffer.
// This is the format for the
// fixed32, sfixed32, and float protocol buffer types.
func (p *Buffer) EncodeFixed32(x uint64) error {
    p.buf = append(p.buf,
        uint8(x),
        uint8(x >> 8),
        uint8(x >> 16),
        uint8(x >> 24))
    return nil
}

func sizeFixed32(x uint64) int {
    return 4
}

// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
// to the Buffer.
// This is the format used for the sint64 protocol buffer type.
func (p *Buffer) EncodeZigzag64(x uint64) error {
    // use signed number to get arithmetic right shift.
    return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}

func sizeZigzag64(x uint64) int {
    return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}

// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
// to the Buffer.
// This is the format used for the sint32 protocol buffer type.
func (p *Buffer) EncodeZigzag32(x uint64) error {
    // use signed number to get arithmetic right shift.
    return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
}

func sizeZigzag32(x uint64) int {
    return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
}

// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
// This is the format used for the bytes protocol buffer
// type and for embedded messages.
func (p *Buffer) EncodeRawBytes(b []byte) error {
    p.EncodeVarint(uint64(len(b)))
    p.buf = append(p.buf, b...)
    return nil
}

func sizeRawBytes(b []byte) int {
    return sizeVarint(uint64(len(b))) +
    len(b)
}

// EncodeStringBytes writes an encoded string to the Buffer.
// This is the format used for the proto2 string type.
func (p *Buffer) EncodeStringBytes(s string) error {
    p.EncodeVarint(uint64(len(s)))
    p.buf = append(p.buf, s...)
    return nil
}

func sizeStringBytes(s string) int {
    return sizeVarint(uint64(len(s))) +
    len(s)
}

// Marshaler is the interface representing objects that can marshal themselves.
type Marshaler interface {
    Marshal() ([]byte, error)
}

// Marshal takes the protocol buffer
// and encodes it into the wire format, returning the data.
func Marshal(pb Message) ([]byte, error) {
    // Can the object marshal itself?
    if m, ok := pb.(Marshaler); ok {
        return m.Marshal()
    }
    p := NewBuffer(nil)
    err := p.Marshal(pb)
    var state errorState
    if err != nil && !state.shouldContinue(err, nil) {
        return nil, err
    }
    if p.buf == nil && err == nil {
        // Return a non-nil slice on success.
        return []byte{}, nil
    }
    return p.buf, err
}

// EncodeMessage writes the protocol buffer to the Buffer,
// prefixed by a varint-encoded length.
func (p *Buffer) EncodeMessage(pb Message) error {
    t, base, err := getbase(pb)
    if structPointer_IsNil(base) {
        return ErrNil
    }
    if err == nil {
        var state errorState
        err = p.enc_len_struct(GetProperties(t.Elem()), base, &state)
    }
    return err
}

// Marshal takes the protocol buffer
// and encodes it into the wire format, writing the result to the
// Buffer.
func (p *Buffer) Marshal(pb Message) error {
    // Can the object marshal itself?
    if m, ok := pb.(Marshaler); ok {
        data, err := m.Marshal()
        if err != nil {
            return err
        }
        p.buf = append(p.buf, data...)
        return nil
    }

    t, base, err := getbase(pb)
    if structPointer_IsNil(base) {
        return ErrNil
    }
    if err == nil {
        err = p.enc_struct(GetProperties(t.Elem()), base)
    }

    if collectStats {
        stats.Encode++
    }

    return err
}

// Size returns the encoded size of a protocol buffer.
func Size(pb Message) (n int) {
    // Can the object marshal itself?  If so, Size is slow.
    // TODO: add Size to Marshaler, or add a Sizer interface.
    if m, ok := pb.(Marshaler); ok {
        b, _ := m.Marshal()
        return len(b)
    }

    t, base, err := getbase(pb)
    if structPointer_IsNil(base) {
        return 0
    }
    if err == nil {
        n = size_struct(GetProperties(t.Elem()), base)
    }

    if collectStats {
        stats.Size++
    }

    return
}

// Individual type encoders.

// Encode a bool.
func (o *Buffer) enc_bool(p *Properties, base structPointer) error {
    v := *structPointer_Bool(base, p.field)
    if v == nil {
        return ErrNil
    }
    x := 0
    if *v {
        x = 1
    }
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, uint64(x))
    return nil
}

func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error {
    v := *structPointer_BoolVal(base, p.field)
    if !v {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, 1)
    return nil
}

func size_bool(p *Properties, base structPointer) int {
    v := *structPointer_Bool(base, p.field)
    if v == nil {
        return 0
    }
    return len(p.tagcode) + 1 // each bool takes exactly one byte
}

func size_proto3_bool(p *Properties, base structPointer) int {
    v := *structPointer_BoolVal(base, p.field)
    if !v && !p.oneof {
        return 0
    }
    return len(p.tagcode) + 1 // each bool takes exactly one byte
}

// Encode an int32.
func (o *Buffer) enc_int32(p *Properties, base structPointer) error {
    v := structPointer_Word32(base, p.field)
    if word32_IsNil(v) {
        return ErrNil
    }
    x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, uint64(x))
    return nil
}

func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error {
    v := structPointer_Word32Val(base, p.field)
    x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
    if x == 0 {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, uint64(x))
    return nil
}

func size_int32(p *Properties, base structPointer) (n int) {
    v := structPointer_Word32(base, p.field)
    if word32_IsNil(v) {
        return 0
    }
    x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
    n += len(p.tagcode)
    n += p.valSize(uint64(x))
    return
}

func size_proto3_int32(p *Properties, base structPointer) (n int) {
    v := structPointer_Word32Val(base, p.field)
    x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
    if x == 0 && !p.oneof {
        return 0
    }
    n += len(p.tagcode)
    n += p.valSize(uint64(x))
    return
}

// Encode a uint32.
// Exactly the same as int32, except for no sign extension.
func (o *Buffer) enc_uint32(p *Properties, base structPointer) error {
    v := structPointer_Word32(base, p.field)
    if word32_IsNil(v) {
        return ErrNil
    }
    x := word32_Get(v)
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, uint64(x))
    return nil
}

func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error {
    v := structPointer_Word32Val(base, p.field)
    x := word32Val_Get(v)
    if x == 0 {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, uint64(x))
    return nil
}

func size_uint32(p *Properties, base structPointer) (n int) {
    v := structPointer_Word32(base, p.field)
    if word32_IsNil(v) {
        return 0
    }
    x := word32_Get(v)
    n += len(p.tagcode)
    n += p.valSize(uint64(x))
    return
}

func size_proto3_uint32(p *Properties, base structPointer) (n int) {
    v := structPointer_Word32Val(base, p.field)
    x := word32Val_Get(v)
    if x == 0 && !p.oneof {
        return 0
    }
    n += len(p.tagcode)
    n += p.valSize(uint64(x))
    return
}

// Encode an int64.
func (o *Buffer) enc_int64(p *Properties, base structPointer) error {
    v := structPointer_Word64(base, p.field)
    if word64_IsNil(v) {
        return ErrNil
    }
    x := word64_Get(v)
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, x)
    return nil
}

func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error {
    v := structPointer_Word64Val(base, p.field)
    x := word64Val_Get(v)
    if x == 0 {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, x)
    return nil
}

func size_int64(p *Properties, base structPointer) (n int) {
    v := structPointer_Word64(base, p.field)
    if word64_IsNil(v) {
        return 0
    }
    x := word64_Get(v)
    n += len(p.tagcode)
    n += p.valSize(x)
    return
}

func size_proto3_int64(p *Properties, base structPointer) (n int) {
    v := structPointer_Word64Val(base, p.field)
    x := word64Val_Get(v)
    if x == 0 && !p.oneof {
        return 0
    }
    n += len(p.tagcode)
    n += p.valSize(x)
    return
}

// Encode a string.
func (o *Buffer) enc_string(p *Properties, base structPointer) error {
    v := *structPointer_String(base, p.field)
    if v == nil {
        return ErrNil
    }
    x := *v
    o.buf = append(o.buf, p.tagcode...)
    o.EncodeStringBytes(x)
    return nil
}

func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error {
    v := *structPointer_StringVal(base, p.field)
    if v == "" {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    o.EncodeStringBytes(v)
    return nil
}

func size_string(p *Properties, base structPointer) (n int) {
    v := *structPointer_String(base, p.field)
    if v == nil {
        return 0
    }
    x := *v
    n += len(p.tagcode)
    n += sizeStringBytes(x)
    return
}

func size_proto3_string(p *Properties, base structPointer) (n int) {
    v := *structPointer_StringVal(base, p.field)
    if v == "" && !p.oneof {
        return 0
    }
    n += len(p.tagcode)
    n += sizeStringBytes(v)
    return
}

// All protocol buffer fields are nillable, but be careful.
func isNil(v reflect.Value) bool {
    switch v.Kind() {
    case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
        return v.IsNil()
    }
    return false
}

// Encode a message struct.
func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error {
    var state errorState
    structp := structPointer_GetStructPointer(base, p.field)
    if structPointer_IsNil(structp) {
        return ErrNil
    }

    // Can the object marshal itself?
    if p.isMarshaler {
        m := structPointer_Interface(structp, p.stype).(Marshaler)
        data, err := m.Marshal()
        if err != nil && !state.shouldContinue(err, nil) {
            return err
        }
        o.buf = append(o.buf, p.tagcode...)
        o.EncodeRawBytes(data)
        return state.err
    }

    o.buf = append(o.buf, p.tagcode...)
    return o.enc_len_struct(p.sprop, structp, &state)
}

func size_struct_message(p *Properties, base structPointer) int {
    structp := structPointer_GetStructPointer(base, p.field)
    if structPointer_IsNil(structp) {
        return 0
    }

    // Can the object marshal itself?
    if p.isMarshaler {
        m := structPointer_Interface(structp, p.stype).(Marshaler)
        data, _ := m.Marshal()
        n0 := len(p.tagcode)
        n1 := sizeRawBytes(data)
        return n0 + n1
    }

    n0 := len(p.tagcode)
    n1 := size_struct(p.sprop, structp)
    n2 := sizeVarint(uint64(n1)) // size of encoded length
    return n0 + n1 + n2
}

// Encode a group struct.
func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error {
    var state errorState
    b := structPointer_GetStructPointer(base, p.field)
    if structPointer_IsNil(b) {
        return ErrNil
    }

    o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
    err := o.enc_struct(p.sprop, b)
    if err != nil && !state.shouldContinue(err, nil) {
        return err
    }
    o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
    return state.err
}

func size_struct_group(p *Properties, base structPointer) (n int) {
    b := structPointer_GetStructPointer(base, p.field)
    if structPointer_IsNil(b) {
        return 0
    }

    n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup))
    n += size_struct(p.sprop, b)
    n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup))
    return
}

// Encode a slice of bools ([]bool).
func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error {
    s := *structPointer_BoolSlice(base, p.field)
    l := len(s)
    if l == 0 {
        return ErrNil
    }
    for _, x := range s {
        o.buf = append(o.buf, p.tagcode...)
        v := uint64(0)
        if x {
            v = 1
        }
        p.valEnc(o, v)
    }
    return nil
}

func size_slice_bool(p *Properties, base structPointer) int {
    s := *structPointer_BoolSlice(base, p.field)
    l := len(s)
    if l == 0 {
        return 0
    }
    return l * (len(p.tagcode) + 1) // each bool takes exactly one byte
}

// Encode a slice of bools ([]bool) in packed format.
func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error {
    s := *structPointer_BoolSlice(base, p.field)
    l := len(s)
    if l == 0 {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    o.EncodeVarint(uint64(l)) // each bool takes exactly one byte
    for _, x := range s {
        v := uint64(0)
        if x {
            v = 1
        }
        p.valEnc(o, v)
    }
    return nil
}

func size_slice_packed_bool(p *Properties, base structPointer) (n int) {
    s := *structPointer_BoolSlice(base, p.field)
    l := len(s)
    if l == 0 {
        return 0
    }
    n += len(p.tagcode)
    n += sizeVarint(uint64(l))
    n += l // each bool takes exactly one byte
    return
}

// Encode a slice of bytes ([]byte).
func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error {
    s := *structPointer_Bytes(base, p.field)
    if s == nil {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    o.EncodeRawBytes(s)
    return nil
}

func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error {
    s := *structPointer_Bytes(base, p.field)
    if len(s) == 0 {
        return ErrNil
    }
    o.buf = append(o.buf, p.tagcode...)
    o.EncodeRawBytes(s)
    return nil
}

func size_slice_byte(p *Properties, base structPointer) (n int) {
    s := *structPointer_Bytes(base, p.field)
    if s == nil && !p.oneof {
        return 0
    }
    n += len(p.tagcode)
    n += sizeRawBytes(s)
    return
}

func size_proto3_slice_byte(p *Properties, base structPointer) (n int) {
    s := *structPointer_Bytes(base, p.field)
    if len(s) == 0 && !p.oneof {
        return 0
    }
    n += len(p.tagcode)
    n += sizeRawBytes(s)
    return
}

// Encode a slice of int32s ([]int32).
func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return ErrNil
    }
    for i := 0; i < l; i++ {
        o.buf = append(o.buf, p.tagcode...)
        x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
        p.valEnc(o, uint64(x))
    }
    return nil
}

func size_slice_int32(p *Properties, base structPointer) (n int) {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return 0
    }
    for i := 0; i < l; i++ {
        n += len(p.tagcode)
        x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
        n += p.valSize(uint64(x))
    }
    return
}

// Encode a slice of int32s ([]int32) in packed format.
func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return ErrNil
    }
    // TODO: Reuse a Buffer.
    buf := NewBuffer(nil)
    for i := 0; i < l; i++ {
        x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
        p.valEnc(buf, uint64(x))
    }

    o.buf = append(o.buf, p.tagcode...)
    o.EncodeVarint(uint64(len(buf.buf)))
    o.buf = append(o.buf, buf.buf...)
    return nil
}

func size_slice_packed_int32(p *Properties, base structPointer) (n int) {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return 0
    }
    var bufSize int
    for i := 0; i < l; i++ {
        x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
        bufSize += p.valSize(uint64(x))
    }

    n += len(p.tagcode)
    n += sizeVarint(uint64(bufSize))
    n += bufSize
    return
}

// Encode a slice of uint32s ([]uint32).
// Exactly the same as int32, except for no sign extension.
func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return ErrNil
    }
    for i := 0; i < l; i++ {
        o.buf = append(o.buf, p.tagcode...)
        x := s.Index(i)
        p.valEnc(o, uint64(x))
    }
    return nil
}

func size_slice_uint32(p *Properties, base structPointer) (n int) {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return 0
    }
    for i := 0; i < l; i++ {
        n += len(p.tagcode)
        x := s.Index(i)
        n += p.valSize(uint64(x))
    }
    return
}

// Encode a slice of uint32s ([]uint32) in packed format.
// Exactly the same as int32, except for no sign extension.
func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return ErrNil
    }
    // TODO: Reuse a Buffer.
    buf := NewBuffer(nil)
    for i := 0; i < l; i++ {
        p.valEnc(buf, uint64(s.Index(i)))
    }

    o.buf = append(o.buf, p.tagcode...)
    o.EncodeVarint(uint64(len(buf.buf)))
    o.buf = append(o.buf, buf.buf...)
    return nil
}

func size_slice_packed_uint32(p *Properties, base structPointer) (n int) {
    s := structPointer_Word32Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return 0
    }
    var bufSize int
    for i := 0; i < l; i++ {
        bufSize += p.valSize(uint64(s.Index(i)))
    }

    n += len(p.tagcode)
    n += sizeVarint(uint64(bufSize))
    n += bufSize
    return
}

// Encode a slice of int64s ([]int64).
func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error {
    s := structPointer_Word64Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return ErrNil
    }
    for i := 0; i < l; i++ {
        o.buf = append(o.buf, p.tagcode...)
        p.valEnc(o, s.Index(i))
    }
    return nil
}

func size_slice_int64(p *Properties, base structPointer) (n int) {
    s := structPointer_Word64Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return 0
    }
    for i := 0; i < l; i++ {
        n += len(p.tagcode)
        n += p.valSize(s.Index(i))
    }
    return
}

// Encode a slice of int64s ([]int64) in packed format.
func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error {
    s := structPointer_Word64Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return ErrNil
    }
    // TODO: Reuse a Buffer.
    buf := NewBuffer(nil)
    for i := 0; i < l; i++ {
        p.valEnc(buf, s.Index(i))
    }

    o.buf = append(o.buf, p.tagcode...)
    o.EncodeVarint(uint64(len(buf.buf)))
    o.buf = append(o.buf, buf.buf...)
    return nil
}

func size_slice_packed_int64(p *Properties, base structPointer) (n int) {
    s := structPointer_Word64Slice(base, p.field)
    l := s.Len()
    if l == 0 {
        return 0
    }
    var bufSize int
    for i := 0; i < l; i++ {
        bufSize += p.valSize(s.Index(i))
    }

    n += len(p.tagcode)
    n += sizeVarint(uint64(bufSize))
    n += bufSize
    return
}

// Encode a slice of slice of bytes ([][]byte).
func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error {
    ss := *structPointer_BytesSlice(base, p.field)
    l := len(ss)
    if l == 0 {
        return ErrNil
    }
    for i := 0; i < l; i++ {
        o.buf = append(o.buf, p.tagcode...)
        o.EncodeRawBytes(ss[i])
    }
    return nil
}

func size_slice_slice_byte(p *Properties, base structPointer) (n int) {
    ss := *structPointer_BytesSlice(base, p.field)
    l := len(ss)
    if l == 0 {
        return 0
    }
    n += l * len(p.tagcode)
    for i := 0; i < l; i++ {
        n += sizeRawBytes(ss[i])
    }
    return
}

// Encode a slice of strings ([]string).
func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error {
    ss := *structPointer_StringSlice(base, p.field)
    l := len(ss)
    for i := 0; i < l; i++ {
        o.buf = append(o.buf, p.tagcode...)
        o.EncodeStringBytes(ss[i])
    }
    return nil
}

func size_slice_string(p *Properties, base structPointer) (n int) {
    ss := *structPointer_StringSlice(base, p.field)
    l := len(ss)
    n += l * len(p.tagcode)
    for i := 0; i < l; i++ {
        n += sizeStringBytes(ss[i])
    }
    return
}

// Encode a slice of message structs ([]*struct).
func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error {
    var state errorState
    s := structPointer_StructPointerSlice(base, p.field)
    l := s.Len()

    for i := 0; i < l; i++ {
        structp := s.Index(i)
        if structPointer_IsNil(structp) {
            return errRepeatedHasNil
        }

        // Can the object marshal itself?
        if p.isMarshaler {
            m := structPointer_Interface(structp, p.stype).(Marshaler)
            data, err := m.Marshal()
            if err != nil && !state.shouldContinue(err, nil) {
                return err
            }
            o.buf = append(o.buf, p.tagcode...)
            o.EncodeRawBytes(data)
            continue
        }

        o.buf = append(o.buf, p.tagcode...)
        err := o.enc_len_struct(p.sprop, structp, &state)
        if err != nil && !state.shouldContinue(err, nil) {
            if err == ErrNil {
                return errRepeatedHasNil
            }
            return err
        }
    }
    return state.err
}

func size_slice_struct_message(p *Properties, base structPointer) (n int) {
    s := structPointer_StructPointerSlice(base, p.field)
    l := s.Len()
    n += l * len(p.tagcode)
    for i := 0; i < l; i++ {
        structp := s.Index(i)
        if structPointer_IsNil(structp) {
            return // return the size up to this point
        }

        // Can the object marshal itself?
        if p.isMarshaler {
            m := structPointer_Interface(structp, p.stype).(Marshaler)
            data, _ := m.Marshal()
            n += len(p.tagcode)
            n += sizeRawBytes(data)
            continue
        }

        n0 := size_struct(p.sprop, structp)
        n1 := sizeVarint(uint64(n0)) // size of encoded length
        n += n0 + n1
    }
    return
}

// Encode a slice of group structs ([]*struct).
func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error {
    var state errorState
    s := structPointer_StructPointerSlice(base, p.field)
    l := s.Len()

    for i := 0; i < l; i++ {
        b := s.Index(i)
        if structPointer_IsNil(b) {
            return errRepeatedHasNil
        }

        o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))

        err := o.enc_struct(p.sprop, b)

        if err != nil && !state.shouldContinue(err, nil) {
            if err == ErrNil {
                return errRepeatedHasNil
            }
            return err
        }

        o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
    }
    return state.err
}

func size_slice_struct_group(p *Properties, base structPointer) (n int) {
    s := structPointer_StructPointerSlice(base, p.field)
    l := s.Len()

    n += l * sizeVarint(uint64((p.Tag << 3) | WireStartGroup))
    n += l * sizeVarint(uint64((p.Tag << 3) | WireEndGroup))
    for i := 0; i < l; i++ {
        b := s.Index(i)
        if structPointer_IsNil(b) {
            return // return size up to this point
        }

        n += size_struct(p.sprop, b)
    }
    return
}

// Encode an extension map.
func (o *Buffer) enc_map(p *Properties, base structPointer) error {
    v := *structPointer_ExtMap(base, p.field)
    if err := encodeExtensionMap(v); err != nil {
        return err
    }
    // Fast-path for common cases: zero or one extensions.
    if len(v) <= 1 {
        for _, e := range v {
            o.buf = append(o.buf, e.enc...)
        }
        return nil
    }

    // Sort keys to provide a deterministic encoding.
    keys := make([]int, 0, len(v))
    for k := range v {
        keys = append(keys, int(k))
    }
    sort.Ints(keys)

    for _, k := range keys {
        o.buf = append(o.buf, v[int32(k)].enc...)
    }
    return nil
}

func size_map(p *Properties, base structPointer) int {
    v := *structPointer_ExtMap(base, p.field)
    return sizeExtensionMap(v)
}

// Encode a map field.
func (o *Buffer) enc_new_map(p *Properties, base structPointer) error {
    var state errorState // XXX: or do we need to plumb this through?

    /*
            A map defined as
                    map<key_type, value_type> map_field = N;
            is encoded in the same way as
                    message MapFieldEntry {
                            key_type key = 1;
                            value_type value = 2;
                    }
                    repeated MapFieldEntry map_field = N;
    */

    v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V
    if v.Len() == 0 {
        return nil
    }

    keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)

    enc := func() error {
        if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil {
            return err
        }
        if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil {
            return err
        }
        return nil
    }

    // Don't sort map keys. It is not required by the spec, and C++ doesn't do it.
    for _, key := range v.MapKeys() {
        val := v.MapIndex(key)

        // The only illegal map entry values are nil message pointers.
        if val.Kind() == reflect.Ptr && val.IsNil() {
            return errors.New("proto: map has nil element")
        }

        keycopy.Set(key)
        valcopy.Set(val)

        o.buf = append(o.buf, p.tagcode...)
        if err := o.enc_len_thing(enc, &state); err != nil {
            return err
        }
    }
    return nil
}

func size_new_map(p *Properties, base structPointer) int {
    v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V

    keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)

    n := 0
    for _, key := range v.MapKeys() {
        val := v.MapIndex(key)
        keycopy.Set(key)
        valcopy.Set(val)

        // Tag codes for key and val are the responsibility of the sub-sizer.
        keysize := p.mkeyprop.size(p.mkeyprop, keybase)
        valsize := p.mvalprop.size(p.mvalprop, valbase)
        entry := keysize + valsize
        // Add on tag code and length of map entry itself.
        n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry
    }
    return n
}

// mapEncodeScratch returns a new reflect.Value matching the map's value type,
// and a structPointer suitable for passing to an encoder or sizer.
func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) {
    // Prepare addressable doubly-indirect placeholders for the key and value types.
    // This is needed because the element-type encoders expect **T, but the map iteration produces T.

    keycopy = reflect.New(mapType.Key()).Elem()                 // addressable K
    keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K
    keyptr.Set(keycopy.Addr())                                  //
    keybase = toStructPointer(keyptr.Addr())                    // **K

    // Value types are more varied and require special handling.
    switch mapType.Elem().Kind() {
    case reflect.Slice:
        // []byte
        var dummy []byte
        valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte
        valbase = toStructPointer(valcopy.Addr())
    case reflect.Ptr:
        // message; the generated field type is map[K]*Msg (so V is *Msg),
        // so we only need one level of indirection.
        valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
        valbase = toStructPointer(valcopy.Addr())
    default:
        // everything else
        valcopy = reflect.New(mapType.Elem()).Elem()                // addressable V
        valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V
        valptr.Set(valcopy.Addr())                                  //
        valbase = toStructPointer(valptr.Addr())                    // **V
    }
    return
}

// Encode a struct.
func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error {
    var state errorState
    // Encode fields in tag order so that decoders may use optimizations
    // that depend on the ordering.
    // https://developers.google.com/protocol-buffers/docs/encoding#order
    for _, i := range prop.order {
        p := prop.Prop[i]
        if p.enc != nil {
            err := p.enc(o, p, base)
            if err != nil {
                if err == ErrNil {
                    if p.Required && state.err == nil {
                        state.err = &RequiredNotSetError{p.Name}
                    }
                } else if err == errRepeatedHasNil {
                    // Give more context to nil values in repeated fields.
                    return errors.New("repeated field " + p.OrigName + " has nil element")
                } else if !state.shouldContinue(err, p) {
                    return err
                }
            }
        }
    }

    // Do oneof fields.
    if prop.oneofMarshaler != nil {
        m := structPointer_Interface(base, prop.stype).(Message)
        if err := prop.oneofMarshaler(m, o); err != nil {
            return err
        }
    }

    // Add unrecognized fields at the end.
    if prop.unrecField.IsValid() {
        v := *structPointer_Bytes(base, prop.unrecField)
        if len(v) > 0 {
            o.buf = append(o.buf, v...)
        }
    }

    return state.err
}

func size_struct(prop *StructProperties, base structPointer) (n int) {
    for _, i := range prop.order {
        p := prop.Prop[i]
        if p.size != nil {
            n += p.size(p, base)
        }
    }

    // Add unrecognized fields at the end.
    if prop.unrecField.IsValid() {
        v := *structPointer_Bytes(base, prop.unrecField)
        n += len(v)
    }

    // Factor in any oneof fields.
    if prop.oneofSizer != nil {
        m := structPointer_Interface(base, prop.stype).(Message)
        n += prop.oneofSizer(m)
    }

    return
}

var zeroes [20]byte // longer than any conceivable sizeVarint

// Encode a struct, preceded by its encoded length (as a varint).
func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error {
    return o.enc_len_thing(func() error {
        return o.enc_struct(prop, base)
    }, state)
}

// Encode something, preceded by its encoded length (as a varint).
func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error {
    iLen := len(o.buf)
    o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length
    iMsg := len(o.buf)
    err := enc()
    if err != nil && !state.shouldContinue(err, nil) {
        return err
    }
    lMsg := len(o.buf) - iMsg
    lLen := sizeVarint(uint64(lMsg))
    switch x := lLen - (iMsg - iLen); {
    case x > 0: // actual length is x bytes larger than the space we reserved
        // Move msg x bytes right.
        o.buf = append(o.buf, zeroes[:x]...)
        copy(o.buf[iMsg + x:], o.buf[iMsg:iMsg + lMsg])
    case x < 0: // actual length is x bytes smaller than the space we reserved
        // Move msg x bytes left.
        copy(o.buf[iMsg + x:], o.buf[iMsg:iMsg + lMsg])
        o.buf = o.buf[:len(o.buf) + x] // x is negative
    }
    // Encode the length in the reserved space.
    o.buf = o.buf[:iLen]
    o.EncodeVarint(uint64(lMsg))
    o.buf = o.buf[:len(o.buf) + lMsg]
    return state.err
}

// errorState maintains the first error that occurs and updates that error
// with additional context.
type errorState struct {
    err error
}

// shouldContinue reports whether encoding should continue upon encountering the
// given error. If the error is RequiredNotSetError, shouldContinue returns true
// and, if this is the first appearance of that error, remembers it for future
// reporting.
//
// If prop is not nil, it may update any error with additional context about the
// field with the error.
func (s *errorState) shouldContinue(err error, prop *Properties) bool {
    // Ignore unset required fields.
    reqNotSet, ok := err.(*RequiredNotSetError)
    if !ok {
        return false
    }
    if s.err == nil {
        if prop != nil {
            err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field}
        }
        s.err = err
    }
    return true
}


text:
package com.syntax.manage;

import com.syntax.code.StyledTextBody;
import com.syntax.ui.SyntaxTextArea;

/**
 * Support basic operations in {@link SyntaxTextArea SyntaxTextArea}
 */
public class SyntaxDocumentTool {
    private SyntaxTextArea textArea;
    private SyntaxManager mSyntaxManager;
    /**
     * Construct tool and install tool in specified TextArea
     *
     * @param textArea specified textArea
     * @param mSyntaxManager provide default AttributeSet
     */
    public SyntaxDocumentTool(SyntaxTextArea textArea, SyntaxManager mSyntaxManager) {
        this.textArea = textArea;
        this.mSyntaxManager = mSyntaxManager;
    }
    /**
     * Find the begin index of line where position p at, suppose that p is an caret which
     * is located in the gap between character
     *
     * @param p the imaginary caret position, 0 ≤ p ≤ {@link StyledTextBody#length() length()}
     * @return begin index of line
     * @throws SyntaxException if p out of rang
     */
    public int lineBegin(int p) throws SyntaxException {
        synchronized(textArea) {
            char txt[] = textArea.getStyledTextBody().getText().toCharArray();
            if(p > textArea.getStyledTextBody().getText().length() || p < 0)
                throw new SyntaxException("Index out of text area " + p);
            if(p == txt.length)
                p--;
            for(int index = txt[p]=='\n' ? p - 1: p ; index >= 0; index--)
                if(txt[index] == '\n')
                    return index + 1;
            return 0;
        }
    }
    /**
     * Find the end index of line where position p at, suppose that p is an caret which
     * is located in the gap between character
     *
     * @param p the imaginary caret position, 0 ≤ p ≤ {@link StyledTextBody#length() length()}
     * @return end index of line
     * @throws SyntaxException if p out of rang
     */
    public int lineEnd(int p) throws SyntaxException {
        synchronized(textArea) {
            char txt[] = textArea.getStyledTextBody().getText().toCharArray();
            if(p > textArea.getStyledTextBody().getText().length() || p < 0)
                throw new SyntaxException("Index out of text area " + p);
            if(p == txt.length)
                p--;
            int textLength = txt.length;
            for(int index = p; index < textLength; index++)
                if(txt[index] == '\n')
                    return index - 1;
            return textLength - 1;
        }
    }
    /**
     * Check whether two imaginary caret positions are in same line
     *
     * @param p0 imaginary caret positions
     * @param p1 imaginary caret positions
     * @return true if two position in the same line
     * @throws SyntaxException if p0 or p1 out of rang
     */
    public boolean inSameLine(int p0, int p1) throws SyntaxException {
        return lineBegin(p0) == lineBegin(p1);
    }
    /**
     * Add a tab in front of line where position p at
     *
     * @param p specified line
     * @throws SyntaxException if p out of rang
     */
    public void addFrontTab(int p) throws SyntaxException {
        synchronized(textArea) {
            int begin = lineBegin(p);
            StyledTextBody textBody = textArea.getStyledTextBody();
            textBody.insertStyledText(begin, "\t", mSyntaxManager.getAttributeSet());
        }
    }
    /**
     * Remove a tab in front of line where position p at
     *
     * @param p sepcified line
     * @return the number of character that removed
     * @throws SyntaxException if p out of rang
     */
    public int removeFrontTab(int p) throws SyntaxException {
        synchronized(textArea) {
            int begin = lineBegin(p);
            int tabs[] = countFrontTab(p);
            if(tabs[0] == 0)
                return -1;
            else {
                char txt[] = textArea.getStyledTextBody().getText().toCharArray();
                StyledTextBody textBody = textArea.getStyledTextBody();
                if(tabs[1] != 0) {      // remove 1 tab
                    while(txt[begin] != '\t')
                        begin++;
                    textBody.removeStyledText(begin, 1);
                    return 1;
                } else {                // remove 4 spaces
                    textBody.removeStyledText(begin, Math.min(4, tabs[2]));
                    return Math.min(4, tabs[2]);
                }
            }
        }
    }
    /**
     * Count the number of prefix tabs at line where position p at
     *
     * @param p specified line
     * @return 3 information in array, [number of tabs, number of preifx tab '\t', number of prefix space ' ']
     * @throws SyntaxException if p out of rang
     */
    public int[] countFrontTab(int p) throws SyntaxException {
        synchronized(textArea) {
            if(p >= textArea.getStyledTextBody().getText().length() || p < 0)
                throw new SyntaxException("Index out of text area " + p);
            char txt[] = textArea.getStyledTextBody().getText().toCharArray();
            int index = lineEnd(p);
            int tabs = 0;
            int spaces = 0;
            while(index >= 0 && txt[index] != '\n') {
                if(txt[index] == '\t' || txt[index] == ' ') {
                    if(txt[index] == '\t')
                        tabs++;
                    else
                        spaces++;
                } else {
                    tabs = 0;
                    spaces = 0;
                }
                index--;
            }
            int ret[] = {tabs + spaces/4 + ((spaces%4 != 0) ? 1 : 0), tabs, spaces};
            return ret;
        }
    }
}


text:
package com.databricks.spark.avro

import org.apache.hadoop.mapreduce.TaskAttemptContext
import org.apache.spark.sql.sources.{OutputWriter, OutputWriterFactory}
import org.apache.spark.sql.types.StructType

private[avro] class AvroOutputWriterFactory(schema: StructType,
    recordName: String,
    recordNamespace: String) extends OutputWriterFactory {

  override def newInstance(path: String,
      dataSchema: StructType,
      context: TaskAttemptContext): OutputWriter =
    new AvroOutputWriter(path, context, schema, recordName, recordNamespace)
}


text:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <SwitchPreference
        android:defaultValue="false"
        android:key="preference_auto_export_enabled"
        android:title="@string/settings_auto_export_enable_checkbox" />
    <ListPreference
        android:entries="@array/settings_export_frequency_value_names"
        android:entryValues="@array/settings_export_frequency_values"
        android:key="preference_auto_export_frequency"
        android:title="@string/settings_auto_export_interval_list" />
    <PreferenceCategory android:title="@string/settings_category_auto_export_path_subdir">
        <SwitchPreference
            android:key="preference_auto_export_use_different_path"
            android:summary="@string/settings_auto_export_different_path_switch_summary"
            android:title="@string/settings_auto_export_different_path_switch" />
        <Preference
            android:key="preference_auto_export_path"
            android:title="@string/settings_auto_export_different_path" />
        <SwitchPreference
            android:key="preference_auto_export_use_different_structure"
            android:summary="@string/settings_auto_export_different_structure_switch_summary"
            android:title="@string/settings_auto_export_different_structure_switch" />
        <EditTextPreference
            android:defaultValue="@string/settings_export_structure_alba_default_value"
            android:dialogMessage="@string/settings_export_subdirectory_structure_dialog_message"
            android:dialogTitle="@string/settings_auto_export_different_structure_dialog_title"
            android:hint="@string/settings_export_structure_alba_default_value"
            android:key="preference_auto_export_structure"
            android:summary="@string/settings_export_subdirectory_structure_album_example"
            android:title="@string/settings_auto_export_different_structure" />
    </PreferenceCategory>
    <PreferenceCategory android:title="@string/settings_category_auto_export_conditions">
        <CheckBoxPreference
            android:key="preference_auto_export_require_charging"
            android:title="@string/settings_auto_export_require_charging_checkbox" />
        <CheckBoxPreference
            android:key="preference_auto_export_require_unmetered"
            android:title="@string/settings_auto_export_require_unmetered_checkbox" />
    </PreferenceCategory>
</PreferenceScreen>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>14.4. sha — SHA-1 message digest algorithm — Pythonista Documentation</title>
    <link rel="stylesheet" href="../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Pythonista Documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Pythonista Documentation" href="../index.html" />
    <link rel="up" title="14. Cryptographic Services" href="crypto.html" />
    <link rel="next" title="15. Generic Operating System Services" href="allos.html" />
    <link rel="prev" title="14.3. md5 — MD5 message digest algorithm" href="md5.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          modules |

          next |

          previous |

Pythonista Documentation »

The Python Standard Library »

14. Cryptographic Services »

14.4. <tt class="xref py py-mod docutils literal">sha</tt> — SHA-1 message digest algorithm¶

Deprecated since version 2.5: Use the <tt class="xref py py-mod docutils literal">hashlib</tt> module instead.

This module implements the interface to NIST’s secure hash  algorithm, known as
SHA-1.  SHA-1 is an improved version of the original SHA hash algorithm.  It is
used in the same way as the <tt class="xref py py-mod docutils literal">md5</tt> module: use <tt class="xref py py-func docutils literal">new()</tt> to create an sha
object, then feed this object with arbitrary strings using the <tt class="xref py py-meth docutils literal">update()</tt>
method, and at any point you can ask it for the digest of the
concatenation of the strings fed to it so far.  SHA-1 digests are 160 bits
instead of MD5’s 128 bits.

<tt class="descclassname">sha.</tt><tt class="descname">new</tt><big>(</big>[string]<big>)</big>¶

Return a new sha object.  If string is present, the method call
<tt class="docutils literal">update(string)</tt> is made.

The following values are provided as constants in the module and as attributes
of the sha objects returned by <tt class="xref py py-func docutils literal">new()</tt>:

<tt class="descclassname">sha.</tt><tt class="descname">blocksize</tt>¶

Size of the blocks fed into the hash function; this is always <tt class="docutils literal">1</tt>.  This size
is used to allow an arbitrary string to be hashed.

<tt class="descclassname">sha.</tt><tt class="descname">digest_size</tt>¶

The size of the resulting digest in bytes.  This is always <tt class="docutils literal">20</tt>.

An sha object has the same methods as md5 objects:

<tt class="descclassname">sha.</tt><tt class="descname">update</tt><big>(</big>arg<big>)</big>¶

Update the sha object with the string arg.  Repeated calls are equivalent to a
single call with the concatenation of all the arguments: <tt class="docutils literal">m.update(a);
m.update(b)</tt> is equivalent to <tt class="docutils literal">m.update(a+b)</tt>.

<tt class="descclassname">sha.</tt><tt class="descname">digest</tt><big>(</big><big>)</big>¶

Return the digest of the strings passed to the <tt class="xref py py-meth docutils literal">update()</tt> method so far.
This is a 20-byte string which may contain non-ASCII characters, including null
bytes.

<tt class="descclassname">sha.</tt><tt class="descname">hexdigest</tt><big>(</big><big>)</big>¶

Like <tt class="xref py py-meth docutils literal">digest()</tt> except the digest is returned as a string of length 40,
containing only hexadecimal digits.  This may  be used to exchange the value
safely in email or other non-binary environments.

<tt class="descclassname">sha.</tt><tt class="descname">copy</tt><big>(</big><big>)</big>¶

Return a copy (“clone”) of the sha object.  This can be used to efficiently
compute the digests of strings that share a common initial substring.

See also

Secure Hash Standard

The Secure Hash Algorithm is defined by NIST document FIPS PUB 180-2: Secure
Hash Standard,
published in August 2002.

Cryptographic Toolkit (Secure Hashing)

Links from NIST to various information on secure hashing.

    © Copyright 1990-2016, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.0.7.


text:
require 'spec_helper'

describe Viglink do

  let(:client) { Viglink::Client.new }

  it "configures with an API_KEY" do
    pending "I'm using the actual key"
    client.api_key.should eq 'your-api-key'
  end

  it "points to the REST API URL" do
    client.api_url.should eq 'http://catalog.viglink.com'
  end

end