text:
'use strict';

const test = require('tape');
const Postman = require('../../fixtures/postman');

test('request header value assertion with empty request/response', (t) => {
  new Postman(t);

  t.doesNotThrow(() => {
    request.should.not.have.header('foo', undefined);
    request.should.not.have.header('foo', null);
    request.should.not.have.header('foo', 'zzzzz');

    response.should.not.have.header('foo', undefined);
    response.should.not.have.header('foo', null);
    response.should.not.have.header('foo', 'zzzzz');
  });

  t.throws(() =>
    request.should.have.header('foo', 'bar'),
  /expected header 'foo' to have value 'bar'/
  );

  t.throws(() =>
    request.should.have.header('foo', undefined),
  /expected header 'foo' to have value undefined but got '<header-not-set>'/
  );

  t.throws(() =>
    response.should.have.header('foo', 'bar'),
  /expected header 'foo' to have value 'bar'/
  );

  t.throws(() =>
    response.should.have.header('foo', undefined),
  /expected header 'foo' to have value undefined but got '<header-not-set>'/
  );

  t.end();
});

test('request header value assertion (pass)', (t) => {
  new Postman(t, {
    request: {
      headers: {
        foo: 'bar',
        'content-type': '',
        'X-Powered-By': 'my cool web server',
        'Set-Cookie': 'myCookie=hello',
      }
    }
  });

  t.doesNotThrow(() => {
    request.should.have.header('foo', 'bar');
    request.should.not.have.header('foo', 'zzzzz');

    request.should.have.header('Content-Type', '');
    request.should.not.have.header('Content-Type', undefined);
    request.should.not.have.header('Content-Type', null);

    expect(request).to.have.header('Set-Cookie', 'myCookie=hello');
    expect(request).not.to.have.header('Set-Cookie', 'someOtherCookie=goodbye');

    request.should.have.header('X-POWERED-BY', /^my (\w+ )+server$/);
    expect(request).not.to.have.header('x-powered-by', /^my awesome server$/);
  });

  t.end();
});

test('response header value assertion (pass)', (t) => {
  new Postman(t, {
    responseHeaders: {
      foo: 'bar',
      'content-type': '',
      'X-Powered-By': 'my cool web server',
      'Set-Cookie': 'myCookie=hello',
    }
  });

  t.doesNotThrow(() => {
    response.should.have.header('foo', 'bar');
    response.should.not.have.header('foo', 'zzzzz');

    response.should.have.header('Content-Type', '');
    response.should.not.have.header('Content-Type', undefined);
    response.should.not.have.header('Content-Type', null);

    expect(response).to.have.header('Set-Cookie', 'myCookie=hello');
    expect(response).not.to.have.header('Set-Cookie', 'someOtherCookie=goodbye');

    response.should.have.header('X-POWERED-BY', /^my (\w+ )+server$/);
    expect(response).not.to.have.header('x-powered-by', /^my awesome server$/);
  });

  t.end();
});

test('request header value assertion (fail)', (t) => {
  new Postman(t, {
    request: {
      headers: {
        foo: 'bar',
        'content-type': '',
        'X-Powered-By': 'my cool web server',
        'Set-Cookie': 'myCookie=hello',
      }
    }
  });

  t.throws(() =>
    request.should.not.have.header('foo', 'bar'),
  /expected header 'foo' to not have value 'bar'/
  );

  t.throws(() =>
    request.should.have.header('foo', 'zzzzz'),
  /expected header 'foo' to have value 'zzzzz'/
  );

  t.throws(() =>
    expect(request).not.to.have.header('Set-Cookie', 'myCookie=hello'),
  /expected header 'Set-Cookie' to not have value 'myCookie=hello'/
  );

  t.throws(() =>
    expect(request).to.have.header('Set-Cookie', 'someOtherCookie=goodbye'),
  /expected header 'Set-Cookie' to have value 'someOtherCookie=goodbye'/
  );

  t.throws(() =>
    request.should.not.have.header('X-POWERED-BY', /^my (\w+ )+server$/),
  /expected header 'X-POWERED-BY' to not match \/\^my \(\\w\+ \)\+server\$\//
  );

  t.throws(() =>
    expect(request).to.have.header('x-powered-by', /^my awesome server$/),
  /expected header 'x-powered-by' to match \/\^my awesome server\$\//
  );

  t.throws(() =>
    expect(request).to.have.header('xyz', /^some expression$/),
  /expected header 'xyz' to match \/\^some expression\$\/ but got '<header-not-set>'/
  );

  t.end();
});

test('response header value assertion (fail)', (t) => {
  new Postman(t, {
    responseHeaders: {
      foo: 'bar',
      'content-type': '',
      'X-Powered-By': 'my cool web server',
      'Set-Cookie': 'myCookie=hello',
    }
  });

  t.throws(() =>
    response.should.not.have.header('foo', 'bar'),
  /expected header 'foo' to not have value 'bar'/
  );

  t.throws(() =>
    response.should.have.header('foo', 'zzzzz'),
  /expected header 'foo' to have value 'zzzzz'/
  );

  t.throws(() =>
    expect(response).not.to.have.header('Set-Cookie', 'myCookie=hello'),
  /expected header 'Set-Cookie' to not have value 'myCookie=hello'/
  );

  t.throws(() =>
    expect(response).to.have.header('Set-Cookie', 'someOtherCookie=goodbye'),
  /expected header 'Set-Cookie' to have value 'someOtherCookie=goodbye'/
  );

  t.throws(() =>
    response.should.not.have.header('X-POWERED-BY', /^my (\w+ )+server$/),
  /expected header 'X-POWERED-BY' to not match \/\^my \(\\w\+ \)\+server\$\//
  );

  t.throws(() =>
    expect(response).to.have.header('x-powered-by', /^my awesome server$/),
  /expected header 'x-powered-by' to match \/\^my awesome server\$\//
  );

  t.throws(() =>
    expect(response).to.have.header('xyz', /^some expression$/),
  /expected header 'xyz' to match \/\^some expression\$\/ but got '<header-not-set>'/
  );

  t.end();
});


text:
package com.soteradefense.dga.hbse;

import com.soteradefense.dga.DGALoggingUtil;

import org.apache.giraph.bsp.CentralizedServiceWorker;
import org.apache.giraph.comm.WorkerClientRequestProcessor;
import org.apache.giraph.edge.Edge;
import org.apache.giraph.graph.AbstractComputation;
import org.apache.giraph.graph.GraphState;
import org.apache.giraph.graph.Vertex;
import org.apache.giraph.worker.WorkerGlobalCommUsage;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;

/**
 * Calculates Shortest paths, and accumulates pair dependency information.
 *

 * Use with SBMasterCompute to find an approximated set of vertices with highest
 * betweenness centrality.
 *

 * For background information on the approximation method see:
 * See "W. Chong, Efficient Extraction of High-Betweenness Vertices"
 *

 * For background information on the method of accumulation of pair dependencies and shortest path data see:
 * See "U. Brandes, A Faster Algorithm for Betweenness Centrality"
 */
public class HBSEComputation extends AbstractComputation<Text, VertexData, Text, PathData, PathData> {

    private static final Logger logger = LoggerFactory.getLogger(HBSEComputation.class);

    @Override
    public void initialize(GraphState graphState, WorkerClientRequestProcessor<Text, VertexData, Text> workerClientRequestProcessor, CentralizedServiceWorker<Text, VertexData, Text> graphTaskManager, WorkerGlobalCommUsage workerGlobalCommUsage) {
        super.initialize(graphState, workerClientRequestProcessor, graphTaskManager, workerGlobalCommUsage);
        DGALoggingUtil.setDGALogLevel(this.getConf());
    }

    /**
     * Works in two major stages which are repeated and coordinated
     * by the setting of a global state (set by the master compute class)
     *

     *

     *

     *
Stage 1:  Discover shortest paths, and shortest path counts for each source vertex in a globally set pivot batch to each node in the graph.

     *
Stage 2:  Accumulate pair dependencies.

     *

     */
    @Override
    public void compute(Vertex<Text, VertexData, Text> vertex, Iterable<PathData> messages) throws IOException {
        StringBuilder builder;
        long step = this.getSuperstep();
        String id = vertex.getId().toString();
        int updateCount = 0;
        State state = getCurrentGlobalState();

        if (step == 0) {
            vertex.setValue(new VertexData());
        }

        VertexData vertexValue = vertex.getValue();
        switch (state) {
            case PIVOT_SELECTION:
                logger.debug("Started the Pivot Selection Process.");
                if (!vertexValue.getWasPivotPoint() && isPossiblePivotPoint(id)) {
                    logger.debug("{} has been selected.", vertex.getId());
                    aggregate(HBSEMasterCompute.PIVOT_AGG, new PivotList(id));
                }
                break;
            // Start a shortest path phase
            // if this vertex is a source (pivot) send shortest path messages to neighbors
            case SHORTEST_PATH_START:
                if (isPivotPoint(id)) {
                    vertexValue.setWasPivotPoint(true);
                    logger.debug("Superstep: {} Start new shortest path computation. Source = {}", step, id);
                    for (Edge<Text, Text> edge : vertex.getEdges()) {
                        sendMessage(edge.getTargetVertexId(), PathData.getShortestPathMessage(id, id, getEdgeValue(edge.getValue().toString()), BigInteger.valueOf(1)));
                    }
                    vertexValue.addPathData(PathData.getShortestPathMessage(id, id, BigInteger.valueOf(0), BigInteger.valueOf(1L)));
                    this.aggregate(HBSEMasterCompute.UPDATE_COUNT_AGG, new IntWritable(1));
                }
                break;
            // continue a shortest path phase, continues until no shortest paths are updated.
            case SHORTEST_PATH_RUN:
                Map<String, ShortestPathList> updatedPathMap = new HashMap<String, ShortestPathList>();

                // process incoming messages
                for (PathData message : messages) {
                    ShortestPathList updatedPath = vertexValue.addPathData(message);
                    if (updatedPath != null) {
                        updatedPathMap.put(message.getSource(), updatedPath);
                    }
                }

                // send outgoing messages for each updated shortest path
                for (Entry<String, ShortestPathList> entry : updatedPathMap.entrySet()) {
                    ShortestPathList spl = entry.getValue();
                    String src = entry.getKey();
                    BigInteger numPaths = spl.getShortestPathCount();
                    updateCount++;
                    for (Edge<Text, Text> edge : vertex.getEdges()) {
                        BigInteger newDistance = spl.getDistance().add(getEdgeValue(edge.getValue().toString()));
                        this.sendMessage(edge.getTargetVertexId(), PathData.getShortestPathMessage(src, id, newDistance, numPaths));
                    }
                }

                this.aggregate(HBSEMasterCompute.UPDATE_COUNT_AGG, new IntWritable(updateCount));
                break;
            // Start of the dependency accumulation phase, each vertex must determine if it has any successors
            case PAIR_DEPENDENCY_PING_PREDECESSOR:
                builder = new StringBuilder();
                // for each shortest path send a message with that source.
                for (Entry<String, ShortestPathList> entry : vertexValue.getPathDataMap().entrySet()) {
                    String source = entry.getKey();
                    BigInteger distance = entry.getValue().getDistance();
                    if (distance.compareTo(BigInteger.ZERO) > 0) { // exclude this vertex
                        for (String pred : entry.getValue().getPredecessorPathCountMap().keySet()) {
                            this.sendMessage(new Text(pred), PathData.getPingMessage(source));
                            builder.append("(").append(pred).append(",").append(source).append("),");
                        }
                    }

                }
                if (builder.length() > 1) builder.deleteCharAt(builder.length() - 1);
                logger.trace("ID: {} Step: {} State: {} send messages (pred, source): {}", id, step, state, builder.toString());
                break;
            // process ping messages form PAIR_DEPENDENCY_PING_PREDECESSOR to determine if
            // this vertex has any successors
            // vertices with no successors will begin the pair dependency accumulation process.
            case PAIR_DEPENDENCY_FIND_SUCCESSORS:
                Set<String> successorExists = new HashSet<String>();

                for (PathData message : messages) {
                    String src = message.getSource();
                    successorExists.add(src);
                    vertexValue.addPartialDep(src, 0.0, 1);  // for every successor message ad one to the partial dep count
                }

                builder = new StringBuilder();
                Set<String> allPaths = vertexValue.getPathDataMap().keySet();
                allPaths.remove(vertex.getId().toString());
                Set<String> noSuccessor = new HashSet<String>();
                for (String src : allPaths) {
                    if (!successorExists.contains(src)) {
                        noSuccessor.add(src);
                        builder.append(src).append(",");
                    }
                }

                // for any sources that this vertex has no successors, start the dependency accumulation chain
                if (noSuccessor.size() > 0) {
                    for (String src : noSuccessor) {
                        ShortestPathList spl = vertexValue.getPathDataMap().get(src);
                        BigInteger numPaths = spl.getShortestPathCount();
                        double dep = 0;
                        for (String predecessor : spl.getPredecessorPathCountMap().keySet()) {
                            this.sendMessage(new Text(predecessor), PathData.getDependencyMessage(src, dep, numPaths));
                        }
                    }
                    noSuccessor.clear();
                }

                if (builder.length() > 1) builder.deleteCharAt(builder.length() - 1);
                logger.trace("ID: {} Step: {} State: {} set noSuccessor {}", id, step, state, builder);
                break;
            // continue the pair dependency phase until no updates are done / all dependencies are accumulated.
            case PAIR_DEPENDENCY_RUN:
                for (PathData message : messages) {
                    String src = message.getSource();

                    if (src.equals(id)) {
                        continue; // don't process paths for which you are the source
                    }

                    double successorDep = message.getDependency();
                    BigInteger successorNumPaths = message.getNumPaths();
                    BigInteger numPaths = vertexValue.getPathDataMap().get(src).getShortestPathCount();
                    double partialDep = (numPaths.doubleValue() / successorNumPaths.doubleValue()) * (1 + successorDep);
                    logger.debug("ID: {} Step: {} message [src:{} successorPaths:{} successorDep:{}] calculated [paths:{}, dep:{}]", id, step, src, successorNumPaths, successorDep, numPaths, partialDep);

                    // accumulate the dependency and subtract one successor
                    PartialDependency partialSum = vertexValue.addPartialDep(src, partialDep, -1);

                    // if the successor count reaches 0 pass this vertex dependency on to predecessors
                    if (partialSum.getSuccessors() == 0) {
                        ShortestPathList spl = vertexValue.getPathDataMap().get(src);
                        builder = new StringBuilder();
                        this.aggregate(HBSEMasterCompute.UPDATE_COUNT_AGG, new IntWritable(1));
                        for (String predecessor : spl.getPredecessorPathCountMap().keySet()) {
                            this.sendMessage(new Text(predecessor), PathData.getDependencyMessage(src, partialSum.getDependency(), numPaths));
                            builder.append(predecessor).append(",");
                        }
                        if (builder.length() > 1) builder.deleteCharAt(builder.length() - 1);
                        logger.debug("ID: {} Step: {} forwarding partial dep to predecessors ({}) [src: {}, paths:{}, dep:{}]", id, step, builder, src, numPaths, partialSum.getDependency());
                    }
                }
                break;
            // completed dependency accumulation. calculate current betweenness value and clear all other vertex data
            // to prepare for next stage (which will be SHORTEST_PATH_START or the computation will halt, based on high betweenness
            // set stability, as determined in the master compute class.
            case PAIR_DEPENDENCY_COMPLETE:
                double approxBetweenness = vertexValue.getApproxBetweenness();
                for (PartialDependency partialDependency : vertexValue.getPartialDependencyMap().values()) {
                    approxBetweenness += partialDependency.getDependency();
                }
                logger.debug("ID: {} has betweenness value of {}", vertex.getId(), approxBetweenness);
                vertexValue.setApproxBetweenness(approxBetweenness);
                vertexValue.getPartialDependencyMap().clear();
                vertexValue.getPathDataMap().clear();
                this.aggregate(HBSEMasterCompute.HIGH_BC_SET_AGG, getNewHighBetweennessList(id, approxBetweenness));
                break;
        }
    }

    /**
     * Parses the Edge Value from a string.
     *
     * @param s Edge value as a string
     * @return long edge value
     */
    private BigInteger getEdgeValue(String s) {
        long edgeValue;
        try {
            edgeValue = Long.parseLong(s);
        } catch (NumberFormatException ex) {
            edgeValue = 1;
        }
        return BigInteger.valueOf(edgeValue);
    }

    /**
     * Return the current global state
     *
     * @return State that stores the current global state
     */
    private State getCurrentGlobalState() {
        IntWritable stateInt = this.getAggregatedValue(HBSEMasterCompute.STATE_AGG);
        return State.values()[stateInt.get()];
    }

    /**
     * Get a new HighBetweennessList object, configured with the betweenness.set.maxSize option
     * from the job conf. If not set size will default to 1.
     *
     * @param id    Vertex Id
     * @param value Betweenness Value
     * @return an empty HighBetweennessList object.
     */
    public HighBetweennessList getNewHighBetweennessList(String id, double value) {
        int size;
        try {
            size = Integer.parseInt(getConf().get(HBSEConfigurationConstants.BETWEENNESS_SET_MAX_SIZE));
        } catch (NumberFormatException e) {
            logger.error("betweenness.set.maxSize must be set to a valid int.");
            throw e;
        }
        return new HighBetweennessList(size, id, value);
    }

    /**
     * Determines if a vertex can be a pivot point.
     *
     * @param id Vertex Id
     * @return True if it is a pivot point.
     */
    private boolean isPossiblePivotPoint(String id) {
        Random random = getRandomWithSeed(HBSEConfigurationConstants.PIVOT_BATCH_RANDOM_SEED);
        double percentageCutoff = (double) ((IntWritable) getAggregatedValue(HBSEMasterCompute.PIVOT_COUNT)).get() / getTotalNumVertices();
        double randomNumber = random.nextDouble();
        boolean isPivot = randomNumber < percentageCutoff;
        logger.debug("Selected as a possible pivot: {}", id);
        return isPivot;
    }

    private boolean isPivotPoint(String id) {
        PivotList pivots = getAggregatedValue(HBSEMasterCompute.PIVOT_AGG);
        logger.debug("Pivots have been selected for computation!  The count is {}", pivots.getPivots().size());
        return pivots.getPivots().contains(id);
    }

    /**
     * Gets a Random Object With A possible Seed based on a Configuration.
     *
     * @param name Configuration Key
     * @return Random which is either seeded or not.
     */
    private Random getRandomWithSeed(String name) {
        Random random;
        String randomSeedStr = getConf().get(name);
        if (randomSeedStr == null) {
            random = new Random();
        } else {
            long seed = Long.parseLong(randomSeedStr);
            random = new Random(seed);
            logger.debug("Set random seed: {}", seed);
        }
        return random;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.bibssoftware.libraries.sncf.model.list;

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

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;

import com.bibssoftware.libraries.sncf.model.Proximity;

/**
 *
 * @author bibssoftware
 *
 */
public class ProximityList {

  @XmlAttribute(name="ProximityCount")
  public Integer count;

  @XmlElement(name="Proximity")
  public List<Proximity> proximities = new ArrayList<Proximity>();

  public void add(Proximity proximity) {
    this.proximities.add(proximity);
  }

}


text:
package Gamess.gamessGUI;

import java.awt.Color;

import javax.swing.text.AttributeSet;
import javax.swing.text.Element;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.Highlighter.HighlightPainter;

public class Cosmetics
{
	//Underliners
	private static final WavedUnderlinePen ERROR_UNDERLINE_PEN = new WavedUnderlinePen(Color.RED);
	private static final WavedUnderlinePen WARNING_UNDERLINE_PEN = new WavedUnderlinePen(Color.YELLOW);

	//Attributes
	public static final SimpleAttributeSet NORMAL_ATTRIBUTE = new SimpleAttributeSet();
	public static final SimpleAttributeSet GROUP_ATTRIBUTE = new SimpleAttributeSet();
	public static final SimpleAttributeSet COMMENTS_ATTRIBUTE = new SimpleAttributeSet();
	public static final SimpleAttributeSet KEYWORD_ATTRIBUTE = new SimpleAttributeSet();
	public static final SimpleAttributeSet ERROR_UNDERLINE = new SimpleAttributeSet();
	public static final SimpleAttributeSet WARNING_UNDERLINE = new SimpleAttributeSet();

	//Colors
	public static final Color NORMAL_ATTRIBUTE_COLOR = Color.BLACK;
	public static final Color GROUP_ATTRIBUTE_COLOR = Color.RED;
	public static final Color KEYWORD_ATTRIBUTE_COLOR = Color.BLUE;

	static
	{
		//Normal AttributeSet
		StyleConstants.setForeground(NORMAL_ATTRIBUTE, NORMAL_ATTRIBUTE_COLOR);
		StyleConstants.setBold(NORMAL_ATTRIBUTE, false);

		//Group AttributeSet
		//StyleConstants.setForeground(GROUP_ATTRIBUTE, Color.getHSBColor(4.83456203f,.67f,.44f));
		StyleConstants.setForeground(GROUP_ATTRIBUTE, GROUP_ATTRIBUTE_COLOR);
		StyleConstants.setBold(GROUP_ATTRIBUTE, true);

		//Comment AttributeSet
		StyleConstants.setForeground(COMMENTS_ATTRIBUTE, Color.getHSBColor(1.35f, .63f, .71f));
		StyleConstants.setBold(COMMENTS_ATTRIBUTE, false);

		//Keyword attribute
		StyleConstants.setForeground(KEYWORD_ATTRIBUTE, KEYWORD_ATTRIBUTE_COLOR);
		StyleConstants.setBold(KEYWORD_ATTRIBUTE, false);

		//Error Underline
		ERROR_UNDERLINE.addAttribute("UNDERLINEPEN", ERROR_UNDERLINE_PEN);

		//Warning Underline
		WARNING_UNDERLINE.addAttribute("UNDERLINEPEN", WARNING_UNDERLINE_PEN);
	}

	public static final SimpleAttributeSet getCustomAttribute(String key, Object value)
	{
		SimpleAttributeSet toolTipAttribute = new SimpleAttributeSet();
		toolTipAttribute.addAttribute(key, value);
		return toolTipAttribute;
	}

	public static final SimpleAttributeSet getCustomAttribute(String key, Object value, AttributeSet existingAttribute)
	{
		SimpleAttributeSet toolTipAttribute = getCustomAttribute(key, value);
		if(existingAttribute != null)
		{
			toolTipAttribute.setResolveParent(existingAttribute);
		}
		return toolTipAttribute;
	}

	public static final void setCharacterAttributes(int startOffset , int length , AttributeSet attribute, boolean replace)
	{
		StyledDocument styledDocument = GamessGUI.inputFilePane.getStyledDocument();
		Element element = null;
		element = styledDocument.getCharacterElement(startOffset);

		//Do not do anything if the element already contains the same attribute
		if(element.getAttributes().containsAttributes(attribute) && replace == false)
			return;
		styledDocument.setCharacterAttributes(startOffset, length, attribute, replace);
	}

	public static final void setParagraphAttributes(int startOffset , int length , AttributeSet attribute)
	{
		StyledDocument styledDocument = GamessGUI.inputFilePane.getStyledDocument();
		Element element = null;
		element = styledDocument.getParagraphElement(startOffset);
		//Do not do anything if the element already contains the same attribute
		if(element.getAttributes().containsAttributes(attribute))
			return;
		styledDocument.setParagraphAttributes(startOffset, length, attribute, true);
		setCharacterAttributes(startOffset, length, attribute, true);
	}

	public static final void setUnderline(int startOffset , int length , AttributeSet attribute)
	{
		StyledDocument styledDocument = GamessGUI.inputFilePane.getStyledDocument();
		styledDocument.setCharacterAttributes(startOffset, length, getCustomAttribute("UNDERLINE", (HighlightPainter)attribute.getAttribute("UNDERLINEPEN")), false);
	}

	public static final void setTooltip(int startOffset , int length , String tooltip)
	{
		StyledDocument styledDocument = GamessGUI.inputFilePane.getStyledDocument();
		styledDocument.setCharacterAttributes(startOffset, length, getCustomAttribute("TOOLTIP", tooltip), false);
	}

	public static final String getFormattedToolTip(String tooltip)
	{
		//previous value was #E6BE8A
		return "" + tooltip.replace("\n", "
") + "";
	}

	public static final String getInputFileToolTip(String tooltip)
	{
		return "" + tooltip.replace("\n", "
") + "";
	}

	public static final String getMenuToolTip(String tooltip)
	{
		return "" + tooltip.replace("\n", "
") + "";
	}
}


text:
require File.expand_path('../helper.rb', __FILE__)

class SlackTest < PapertrailServices::TestCase
  def test_logs
    svc = service(:logs, { :slack_url => "https://site.slack.com/services/hooks/incoming-webhook?token=aaaa" }, payload)

    http_stubs.post '/services/hooks/incoming-webhook' do |env|
      [200, {}, '']
    end

    svc.receive_logs
  end

  def test_long_logs
    long_payload = payload.dup
    long_payload[:events] *= 100

    svc = service(:logs, { :slack_url => "https://site.slack.com/services/hooks/incoming-webhook?token=aaaa" }, long_payload)

    http_stubs.post '/services/hooks/incoming-webhook' do |env|
      [200, {}, '']
    end

    svc.receive_logs
  end

  def test_build_attachments
    long_payload = payload.dup
    long_payload[:events] *= 100

    slack = Service::Slack.new
    attachment = slack.build_attachments(long_payload[:events])
    assert attachment[0][:text].length < 8000
    assert attachment[0][:fallback].length < 8000
  end

  def test_no_messages
    empty_payload = payload.dup
    empty_payload[:events] = []

    svc = service(:logs, { :slack_url => "https://site.slack.com/services/hooks/incoming-webhook?token=aaaa" }, empty_payload)

    post = false
    http_stubs.post '/services/hooks/incoming-webhook' do |env|
      post = true
      body = JSON(env[:body])

      assert !body.has_key?('attachments'), 'Expected no attachments without events'

      [200, {}, '']
    end

    svc.receive_logs

    assert post, 'Expected post to service webhook'
  end

  def test_dont_display_messages
    svc = service(:logs, { :dont_display_messages => 1, :slack_url => "https://site.slack.com/services/hooks/incoming-webhook?token=aaaa" }, payload)

    post = false
    http_stubs.post '/services/hooks/incoming-webhook' do |env|
      post = true
      body = JSON(env[:body])

      assert !body.has_key?('attachments'), 'Expected no attachments without events'

      [200, {}, '']
    end

    svc.receive_logs

    assert post, 'Expected post to service webhook'
  end

  def service(*args)
    super Service::Slack, *args
  end
end


text:
package libkb

const IsBrewBuild = false


text: CREATE EXTENSION pg_stat_statements;


text:
module Deas

  Error = Class.new(RuntimeError)
  ServerError = Class.new(Error)

  ServerRootError = Class.new(ServerError) do
    def message
      "server `root` not set but required"
    end
  end

  NoHandlerClassError = Class.new(Error) do
    def initialize(handler_class_name)
      super "Deas couldn't find the view handler '#{handler_class_name}'" \
            " - it doesn't exist or hasn't been required in yet."
    end
  end

  HandlerProxyNotFound = Class.new(Error)

  NotFound = Class.new(Error)

end


text:
from __future__ import unicode_literals

import collections

from spotify import utils

__all__ = ['AudioBufferStats', 'AudioFormat', 'Bitrate', 'SampleType']

class AudioBufferStats(
    collections.namedtuple('AudioBufferStats', ['samples', 'stutter'])
):

    """Stats about the application's audio buffers."""

    pass

@utils.make_enum('SP_BITRATE_', 'BITRATE_')
class Bitrate(utils.IntEnum):
    pass

@utils.make_enum('SP_SAMPLETYPE_')
class SampleType(utils.IntEnum):
    pass

class AudioFormat(object):

    """A Spotify audio format object.

    You'll never need to create an instance of this class yourself, but you'll
    get :class:`AudioFormat` objects as the ``audio_format`` argument to the
    :attr:`~spotify.SessionCallbacks.music_delivery` callback.
    """

    def __init__(self, sp_audioformat):
        self._sp_audioformat = sp_audioformat

    @property
    def sample_type(self):
        """The :class:`SampleType`, currently always
        :attr:`SampleType.INT16_NATIVE_ENDIAN`."""
        return SampleType(self._sp_audioformat.sample_type)

    @property
    def sample_rate(self):
        """The sample rate, typically 44100 Hz."""
        return self._sp_audioformat.sample_rate

    @property
    def channels(self):
        """The number of audio channels, typically 2."""
        return self._sp_audioformat.channels

    def frame_size(self):
        """The byte size of a single frame of this format."""
        if self.sample_type == SampleType.INT16_NATIVE_ENDIAN:
            return 2 * self.channels
        else:
            raise ValueError('Unknown sample type: %d', self.sample_type)


text:
# Recognize receipts

This sample demonstrates how to recognize and extract common fields from US receipts, using a pre-trained receipt model.

To get started you'll need a Cognitive Services resource or a Form Recognizer resource.  See [README][README] for prerequisites and instructions.

## Creating a `FormRecognizerClient`

To create a new `FormRecognizerClient` you need the endpoint and credentials from your resource. In the sample below you'll use a Form Recognizer API key credential by creating an `AzureKeyCredential` object, that if needed, will allow you to update the API key without creating a new client.

You can set `endpoint` and `apiKey` based on an environment variable, a configuration setting, or any way that works for your application.

```C# Snippet:CreateFormRecognizerClient
string endpoint = "<endpoint>";
string apiKey = "<apiKey>";
var credential = new AzureKeyCredential(apiKey);
var client = new FormRecognizerClient(new Uri(endpoint), credential);
```

## Recognize receipts from a URI

To recognize receipts from a URI, use the `StartRecognizeReceiptsFromUri` method. The returned value is a collection of `RecognizedReceipt` objects -- one for each page in the submitted document.

```C# Snippet:FormRecognizerSampleRecognizeReceiptFileFromUri
RecognizedReceiptCollection receipts = await client.StartRecognizeReceiptsFromUri(new Uri(receiptUri)).WaitForCompletionAsync();
foreach (var receipt in receipts)
{
    USReceipt usReceipt = receipt.AsUSReceipt();

    string merchantName = usReceipt.MerchantName?.Value ?? default;
    DateTime transactionDate = usReceipt.TransactionDate?.Value ?? default;
    IReadOnlyList<USReceiptItem> items = usReceipt.Items ?? default;
    float subtotal = usReceipt.Subtotal?.Value ?? default;
    float tax = usReceipt.Tax?.Value ?? default;
    float tip = usReceipt.Tip?.Value ?? default;
    float total = usReceipt.Total?.Value ?? default;

    Console.WriteLine($"Recognized USReceipt fields:");
    Console.WriteLine($"    Merchant Name: '{merchantName}', with confidence {usReceipt.MerchantName.Confidence}");
    Console.WriteLine($"    Transaction Date: '{transactionDate}', with confidence {usReceipt.TransactionDate.Confidence}");

    for (int i = 0; i < items.Count; i++)
    {
        USReceiptItem item = usReceipt.Items[i];
        Console.WriteLine($"    Item {i}:  Name: '{item.Name.Value}', Quantity: '{item.Quantity?.Value}', Price: '{item.Price?.Value}'");
        Console.WriteLine($"    TotalPrice: '{item.TotalPrice.Value}'");
    }

    Console.WriteLine($"    Subtotal: '{subtotal}', with confidence '{usReceipt.Subtotal.Confidence}'");
    Console.WriteLine($"    Tax: '{tax}', with confidence '{usReceipt.Tax.Confidence}'");
    Console.WriteLine($"    Tip: '{tip}', with confidence '{usReceipt.Tip?.Confidence ?? 0.0f}'");
    Console.WriteLine($"    Total: '{total}', with confidence '{usReceipt.Total.Confidence}'");
}
```

## Recognize receipts from a given file

To recognize receipts from a given file, use the `StartRecognizeReceipts` method. The returned value is a collection of `RecognizedReceipt` objects -- one for each page in the submitted document.

```C# Snippet:FormRecognizerRecognizeReceiptFromFile
using (FileStream stream = new FileStream(receiptPath, FileMode.Open))
{
    RecognizedReceiptCollection receipts = await client.StartRecognizeReceipts(stream).WaitForCompletionAsync();
    /*
     *
     */
}
```

To see the full example source files, see:

* [Recognize receipts from URI](https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/formrecognizer/Azure.AI.FormRecognizer/tests/samples/Sample2_RecognizeReceiptsFromUri.cs)
* [Recognize receipts from file](https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/formrecognizer/Azure.AI.FormRecognizer/tests/samples/Sample2_RecognizeReceiptsFromFile.cs)

[README]: https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/formrecognizer/Azure.AI.FormRecognizer#getting-started


text:
/*******************************************************************************
	File:		tns_param.h

	Content:	TNS parameters

*******************************************************************************/

/*
   TNS parameters
 */
#ifndef _TNS_PARAM_H
#define _TNS_PARAM_H

#include "tns.h"

typedef struct{
  Word32 samplingRate;
  Word16 maxBandLong;
  Word16 maxBandShort;
}TNS_MAX_TAB_ENTRY;

typedef struct{
    Word32 bitRateFrom;
    Word32 bitRateTo;
    const TNS_CONFIG_TABULATED *paramMono_Long;  /* contains TNS parameters */
    const TNS_CONFIG_TABULATED *paramMono_Short;
    const TNS_CONFIG_TABULATED *paramStereo_Long;
    const TNS_CONFIG_TABULATED *paramStereo_Short;
}TNS_INFO_TAB;

void GetTnsParam(TNS_CONFIG_TABULATED *tnsConfigTab,
                 Word32 bitRate, Word16 channels, Word16 blockType);

void GetTnsMaxBands(Word32 samplingRate, Word16 blockType, Word16* tnsMaxSfb);

#endif /* _TNS_PARAM_H */


text:
package rogel.io.fopl;

import java.util.HashMap;

/**
 * A Symbol is an object that represents. Everything expressed in FOPL is done in terms of
 * Symbols. In this implementation, Symbols follow the Herbrand interpretation and are merely
 * objects that represent String-based names. There is only one Symbol for any given name.
 *

 * The set of all Symbols that are declared during the execution of any FOPL program constitute
 * that program's domain of discourse.
 *
 * @author recardona
 * @see https://en.wikipedia.org/wiki/Herbrand_interpretation
 */
public final class Symbol {

    /**
     * The domain of discourse is the set of entities over which variables of interest in some
     * formal language may range. For Symbols, this domain captures every Symbol that has been
     * used during program execution.
     */
    private static HashMap<String, Symbol> symbolDomainOfDiscourse = new HashMap<String, Symbol>();

    /**
     * The number to use as a suffix for Symbols generated by the method
     * {@code Symbol.generateSymbol()}.
     */
    private static int generatedSymbolSuffix = 0;

    /** The String name this Symbol represents. */
    private String name;

    /**
     * Returns a Symbol with the given name. If no such Symbol exists, this method creates a new
     * one and adds it to the domain of discourse for future retrieval.
     *
     * @param name The name of the Symbol that is sought.
     * @return a Symbol with the given name.
     * @throws IllegalArgumentException if the Symbol name is null or empty.
     */
    public static Symbol get(String name) throws IllegalArgumentException {

        if((name == null) || (name.equals(""))) {
            throw new IllegalArgumentException("Attempted to get a Symbol without a name.");
        }

        if(Symbol.symbolDomainOfDiscourse.containsKey(name)) {
            return symbolDomainOfDiscourse.get(name);
        }

        Symbol newSymbol = new Symbol(name);
        Symbol.symbolDomainOfDiscourse.put(name, newSymbol);
        return newSymbol;
    }

    /**
     * Generates a new Symbol within the domain of discourse. The new Symbol is guaranteed to be
     * unique, and will be of the form {@code G{number}}, where {@code {number}} is an integer.
     *
     * @return the newly generated Symbol.
     */
    public static Symbol generateSymbol() {

        // Attempt to create an unused Symbol name.
        String generatedSymbolName = "G" + Symbol.generatedSymbolSuffix;

        // If that Symbol already exists, increment the counter and try again.
        while(Symbol.symbolDomainOfDiscourse.containsKey(generatedSymbolName)) {
            Symbol.generatedSymbolSuffix++;
            generatedSymbolName = "G" + Symbol.generatedSymbolSuffix;
        }

        // Return the new Symbol.
        return Symbol.get(generatedSymbolName);
    }

    /**
     * Generates a new Symbol within the domain of discourse. The new Symbol is guaranteed to be
     * unique, and will be of the form {@code {prefix}{number}}, where {@code {prefix}} is the
     * parameter String, and {@code {number}} is an integer.
     *
     * @param prefix The prefix of the Symbol to generate.
     * @return the newly generated Symbol.
     */
    public static Symbol generateSymbol(String prefix) {

        // Attempt to create an unused Symbol name.
        String generatedSymbolName = prefix + Symbol.generatedSymbolSuffix;

        // If that Symbol already exists, increment the counter and try again.
        while(Symbol.symbolDomainOfDiscourse.containsKey(generatedSymbolName)) {
            Symbol.generatedSymbolSuffix++;
            generatedSymbolName = prefix + Symbol.generatedSymbolSuffix;
        }

        // Return the new Symbol.
        return Symbol.get(generatedSymbolName);
    }

    /**
     * Constructs a Symbol of the given name.
     *
     * @param name The name of the symbol.
     */
    private Symbol(String name) {
        this.name = name;
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Object#clone()
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Symbol.clone() is not supported");
    }

    /**
     * Compares this Symbol to the parameter object. The result is true if and only if the argument
     * is another Symbol that represents the same sequence of characters as this object.
     *
     * @param obj The object to compare this Symbol against.
     * @return true if the given object represents a Symbol whose name is syntactically equivalent
     *     to this Symbol's name, false otherwise.
     */
    @Override
    public boolean equals(Object obj) {
        if( ! (obj instanceof Symbol)) {
            return false;
        }

        Symbol other = (Symbol) obj;
        return (this.name.equals(other.name));
    }

    /**
     * Returns a hash code for this Symbol. The hash code for a Symbol object is computed as the
     * hash of the sequence of characters the Symbol represents; i.e
     * {@code toString().hashCode()}.
     *
     * @return a hash code value for this object.
     */
    @Override
    public int hashCode() {
        return this.name.hashCode();
    }

    /**
     * Returns a String representation of this Symbol, which is simply the name that this object
     * represents.
     *
     * @return a String representation of this Symbol.
     */
    @Override
    public String toString() {
        return this.name;
    }
}


text:
using System;
class StringsAndObjects
{
    static void Main()
    {
        string a = "Hello";
        string b = "World";
        object c = a + " " + b;
        string objToString;
        Console.WriteLine(c);
        objToString = (string)c;
        Console.WriteLine(objToString);
    }
}


text:
import { route, template, DialogService, EventAggregator, NavigationService, StorageService, title, components } from "./../../../../src/index";
import * as Routes from "./../routes";
import { BasePageViewModel } from "./../base-page-view-model";
import { inject } from "@nivinjoseph/n-ject";
import "./dashboard-view.scss";
import { ScopedService } from "../../services/scoped-service";
import { BindingTestViewModel } from "../../components/binding-test/binding-test-view-model";
import { Delay, Duration, synchronize } from "@nivinjoseph/n-util";
// import { Delay } from "@nivinjoseph/n-util";

@components(BindingTestViewModel)
@template(require("./dashboard-view.html"))
@route(Routes.dashboard)
@title("Dashboard")
@inject("DialogService", "EventAggregator", "NavigationService", "StorageService", "ScopedService")
export class DashboardViewModel extends BasePageViewModel
{
    private readonly _dialogService: DialogService;
    // @ts-expect-error: not used atm
    private readonly _eventAggregator: EventAggregator;
    // @ts-expect-error: not used atm
    private readonly _navigationService: NavigationService;
    // @ts-expect-error: not used atm
    private readonly _storageService: StorageService;
    // @ts-expect-error: not used atm
    private readonly _scopedService: ScopedService;

    private readonly _message = "Dashboard view";
    private _score = 10;
    private _fooParentValue: string | null;
    // private _isActive = false;

    public get score(): number { return this._score; }

    public get message(): string { return this._message; }

    public get fooParentValue(): string | null { return this._fooParentValue; }
    public set fooParentValue(value: string | null)
    {
        console.log("setting", value);
        this._fooParentValue = value;
    }

    public constructor(dialogService: DialogService, evenAggregator: EventAggregator,
        navigationService: NavigationService, storageService: StorageService, scopedService: ScopedService)
    {
        super();

        this._dialogService = dialogService;
        this._eventAggregator = evenAggregator;
        this._navigationService = navigationService;
        this._storageService = storageService;
        this._scopedService = scopedService;

        // this._fooParentValue = "whatever";
        // this._fooParentValue = null as any;
        this._fooParentValue = null;
        // this._fooParentValue = 1 as any;

        this.executeOnDestroy(() => console.log("Destroying dashboard"));
    }

    @synchronize(Duration.fromMilliSeconds(1000))
    public increment(): void
    {
        // console.log(this);
        // console.log("isActive", this._isActive);

        // if (this._isActive === true)
        //     return;

        // try
        // {
        //     this._isActive = true;

        //     // do all the logic
        // }
        // finally
        // {
        //     this._isActive = false;
        // }

        // this._isActive = true;

        // await Delay.milliseconds(100);

        this._score++;

        this._dialogService.showWarningMessage("Score incremented");

        // this._dialogService.showLoadingScreen();
        // setTimeout(() => this._dialogService.hideLoadingScreen(), 5000);

        // this._dialogService.showErrorMessage("haha");

        // this._navigationService.navigate(Routes.updateTodo, { id: 5 });

        // this._isActive = false;
    }

    public async loading(): Promise<void>
    {
        console.log("loading clicked");
        this._dialogService.showLoadingScreen();

        await Delay.seconds(3);

        this._dialogService.hideLoadingScreen();
    }
}


text:
package bd;
import javax.persistence.Persistence;

//Precisamos apenas criar um EntityManagerFactory, que todas as tabelas mapeadas
//pelas entidades serão criadas ou atualizadas.

public class CriaTabelas {

	public static void main(String[] args) {
		Persistence.createEntityManagerFactory("CinemaJsfPU");
	}

}


text:
package cognitiveservices

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"encoding/json"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/to"
	"github.com/Azure/go-autorest/tracing"
	"net/http"
)

// The package's fully qualified name.
const fqdn = "github.com/Azure/azure-sdk-for-go/services/cognitiveservices/mgmt/2017-04-18/cognitiveservices"

// KeyName enumerates the values for key name.
type KeyName string

const (
	// Key1 ...
	Key1 KeyName = "Key1"
	// Key2 ...
	Key2 KeyName = "Key2"
)

// PossibleKeyNameValues returns an array of possible values for the KeyName const type.
func PossibleKeyNameValues() []KeyName {
	return []KeyName{Key1, Key2}
}

// NetworkRuleAction enumerates the values for network rule action.
type NetworkRuleAction string

const (
	// Allow ...
	Allow NetworkRuleAction = "Allow"
	// Deny ...
	Deny NetworkRuleAction = "Deny"
)

// PossibleNetworkRuleActionValues returns an array of possible values for the NetworkRuleAction const type.
func PossibleNetworkRuleActionValues() []NetworkRuleAction {
	return []NetworkRuleAction{Allow, Deny}
}

// ProvisioningState enumerates the values for provisioning state.
type ProvisioningState string

const (
	// Creating ...
	Creating ProvisioningState = "Creating"
	// Deleting ...
	Deleting ProvisioningState = "Deleting"
	// Failed ...
	Failed ProvisioningState = "Failed"
	// Moving ...
	Moving ProvisioningState = "Moving"
	// ResolvingDNS ...
	ResolvingDNS ProvisioningState = "ResolvingDNS"
	// Succeeded ...
	Succeeded ProvisioningState = "Succeeded"
)

// PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type.
func PossibleProvisioningStateValues() []ProvisioningState {
	return []ProvisioningState{Creating, Deleting, Failed, Moving, ResolvingDNS, Succeeded}
}

// QuotaUsageStatus enumerates the values for quota usage status.
type QuotaUsageStatus string

const (
	// Blocked ...
	Blocked QuotaUsageStatus = "Blocked"
	// Included ...
	Included QuotaUsageStatus = "Included"
	// InOverage ...
	InOverage QuotaUsageStatus = "InOverage"
	// Unknown ...
	Unknown QuotaUsageStatus = "Unknown"
)

// PossibleQuotaUsageStatusValues returns an array of possible values for the QuotaUsageStatus const type.
func PossibleQuotaUsageStatusValues() []QuotaUsageStatus {
	return []QuotaUsageStatus{Blocked, Included, InOverage, Unknown}
}

// ResourceSkuRestrictionsReasonCode enumerates the values for resource sku restrictions reason code.
type ResourceSkuRestrictionsReasonCode string

const (
	// NotAvailableForSubscription ...
	NotAvailableForSubscription ResourceSkuRestrictionsReasonCode = "NotAvailableForSubscription"
	// QuotaID ...
	QuotaID ResourceSkuRestrictionsReasonCode = "QuotaId"
)

// PossibleResourceSkuRestrictionsReasonCodeValues returns an array of possible values for the ResourceSkuRestrictionsReasonCode const type.
func PossibleResourceSkuRestrictionsReasonCodeValues() []ResourceSkuRestrictionsReasonCode {
	return []ResourceSkuRestrictionsReasonCode{NotAvailableForSubscription, QuotaID}
}

// ResourceSkuRestrictionsType enumerates the values for resource sku restrictions type.
type ResourceSkuRestrictionsType string

const (
	// Location ...
	Location ResourceSkuRestrictionsType = "Location"
	// Zone ...
	Zone ResourceSkuRestrictionsType = "Zone"
)

// PossibleResourceSkuRestrictionsTypeValues returns an array of possible values for the ResourceSkuRestrictionsType const type.
func PossibleResourceSkuRestrictionsTypeValues() []ResourceSkuRestrictionsType {
	return []ResourceSkuRestrictionsType{Location, Zone}
}

// SkuTier enumerates the values for sku tier.
type SkuTier string

const (
	// Free ...
	Free SkuTier = "Free"
	// Premium ...
	Premium SkuTier = "Premium"
	// Standard ...
	Standard SkuTier = "Standard"
)

// PossibleSkuTierValues returns an array of possible values for the SkuTier const type.
func PossibleSkuTierValues() []SkuTier {
	return []SkuTier{Free, Premium, Standard}
}

// UnitType enumerates the values for unit type.
type UnitType string

const (
	// Bytes ...
	Bytes UnitType = "Bytes"
	// BytesPerSecond ...
	BytesPerSecond UnitType = "BytesPerSecond"
	// Count ...
	Count UnitType = "Count"
	// CountPerSecond ...
	CountPerSecond UnitType = "CountPerSecond"
	// Milliseconds ...
	Milliseconds UnitType = "Milliseconds"
	// Percent ...
	Percent UnitType = "Percent"
	// Seconds ...
	Seconds UnitType = "Seconds"
)

// PossibleUnitTypeValues returns an array of possible values for the UnitType const type.
func PossibleUnitTypeValues() []UnitType {
	return []UnitType{Bytes, BytesPerSecond, Count, CountPerSecond, Milliseconds, Percent, Seconds}
}

// Account cognitive Services Account is an Azure resource representing the provisioned account, its type,
// location and SKU.
type Account struct {
	autorest.Response `json:"-"`
	// Etag - READ-ONLY; Entity Tag
	Etag *string `json:"etag,omitempty"`
	// ID - READ-ONLY; The id of the created account
	ID *string `json:"id,omitempty"`
	// Kind - The Kind of the resource.
	Kind *string `json:"kind,omitempty"`
	// Location - The location of the resource
	Location *string `json:"location,omitempty"`
	// Name - READ-ONLY; The name of the created account
	Name *string `json:"name,omitempty"`
	// Properties - Properties of Cognitive Services account.
	Properties *AccountProperties `json:"properties,omitempty"`
	// Sku - The SKU of Cognitive Services account.
	Sku *Sku `json:"sku,omitempty"`
	// Tags - Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters.
	Tags map[string]*string `json:"tags"`
	// Type - READ-ONLY; Resource type
	Type *string `json:"type,omitempty"`
}

// MarshalJSON is the custom marshaler for Account.
func (a Account) MarshalJSON() ([]byte, error) {
	objectMap := make(map[string]interface{})
	if a.Kind != nil {
		objectMap["kind"] = a.Kind
	}
	if a.Location != nil {
		objectMap["location"] = a.Location
	}
	if a.Properties != nil {
		objectMap["properties"] = a.Properties
	}
	if a.Sku != nil {
		objectMap["sku"] = a.Sku
	}
	if a.Tags != nil {
		objectMap["tags"] = a.Tags
	}
	return json.Marshal(objectMap)
}

// AccountAPIProperties the api properties for special APIs.
type AccountAPIProperties struct {
	// QnaRuntimeEndpoint - (QnAMaker Only) The runtime endpoint of QnAMaker.
	QnaRuntimeEndpoint *string `json:"qnaRuntimeEndpoint,omitempty"`
	// StatisticsEnabled - (Bing Search Only) The flag to enable statistics of Bing Search.
	StatisticsEnabled *bool `json:"statisticsEnabled,omitempty"`
	// EventHubConnectionString - (Personalization Only) The flag to enable statistics of Bing Search.
	EventHubConnectionString *string `json:"eventHubConnectionString,omitempty"`
	// StorageAccountConnectionString - (Personalization Only) The storage account connection string.
	StorageAccountConnectionString *string `json:"storageAccountConnectionString,omitempty"`
}

// AccountEnumerateSkusResult the list of cognitive services accounts operation response.
type AccountEnumerateSkusResult struct {
	autorest.Response `json:"-"`
	// Value - READ-ONLY; Gets the list of Cognitive Services accounts and their properties.
	Value *[]ResourceAndSku `json:"value,omitempty"`
}

// AccountKeys the access keys for the cognitive services account.
type AccountKeys struct {
	autorest.Response `json:"-"`
	// Key1 - Gets the value of key 1.
	Key1 *string `json:"key1,omitempty"`
	// Key2 - Gets the value of key 2.
	Key2 *string `json:"key2,omitempty"`
}

// AccountListResult the list of cognitive services accounts operation response.
type AccountListResult struct {
	autorest.Response `json:"-"`
	// NextLink - The link used to get the next page of accounts.
	NextLink *string `json:"nextLink,omitempty"`
	// Value - READ-ONLY; Gets the list of Cognitive Services accounts and their properties.
	Value *[]Account `json:"value,omitempty"`
}

// AccountListResultIterator provides access to a complete listing of Account values.
type AccountListResultIterator struct {
	i    int
	page AccountListResultPage
}

// NextWithContext advances to the next value.  If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *AccountListResultIterator) NextWithContext(ctx context.Context) (err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/AccountListResultIterator.NextWithContext")
		defer func() {
			sc := -1
			if iter.Response().Response.Response != nil {
				sc = iter.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	iter.i++
	if iter.i < len(iter.page.Values()) {
		return nil
	}
	err = iter.page.NextWithContext(ctx)
	if err != nil {
		iter.i--
		return err
	}
	iter.i = 0
	return nil
}

// Next advances to the next value.  If there was an error making
// the request the iterator does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (iter *AccountListResultIterator) Next() error {
	return iter.NextWithContext(context.Background())
}

// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter AccountListResultIterator) NotDone() bool {
	return iter.page.NotDone() && iter.i < len(iter.page.Values())
}

// Response returns the raw server response from the last page request.
func (iter AccountListResultIterator) Response() AccountListResult {
	return iter.page.Response()
}

// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter AccountListResultIterator) Value() Account {
	if !iter.page.NotDone() {
		return Account{}
	}
	return iter.page.Values()[iter.i]
}

// Creates a new instance of the AccountListResultIterator type.
func NewAccountListResultIterator(page AccountListResultPage) AccountListResultIterator {
	return AccountListResultIterator{page: page}
}

// IsEmpty returns true if the ListResult contains no values.
func (alr AccountListResult) IsEmpty() bool {
	return alr.Value == nil || len(*alr.Value) == 0
}

// accountListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (alr AccountListResult) accountListResultPreparer(ctx context.Context) (*http.Request, error) {
	if alr.NextLink == nil || len(to.String(alr.NextLink)) < 1 {
		return nil, nil
	}
	return autorest.Prepare((&http.Request{}).WithContext(ctx),
		autorest.AsJSON(),
		autorest.AsGet(),
		autorest.WithBaseURL(to.String(alr.NextLink)))
}

// AccountListResultPage contains a page of Account values.
type AccountListResultPage struct {
	fn  func(context.Context, AccountListResult) (AccountListResult, error)
	alr AccountListResult
}

// NextWithContext advances to the next page of values.  If there was an error making
// the request the page does not advance and the error is returned.
func (page *AccountListResultPage) NextWithContext(ctx context.Context) (err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/AccountListResultPage.NextWithContext")
		defer func() {
			sc := -1
			if page.Response().Response.Response != nil {
				sc = page.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	next, err := page.fn(ctx, page.alr)
	if err != nil {
		return err
	}
	page.alr = next
	return nil
}

// Next advances to the next page of values.  If there was an error making
// the request the page does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (page *AccountListResultPage) Next() error {
	return page.NextWithContext(context.Background())
}

// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page AccountListResultPage) NotDone() bool {
	return !page.alr.IsEmpty()
}

// Response returns the raw server response from the last page request.
func (page AccountListResultPage) Response() AccountListResult {
	return page.alr
}

// Values returns the slice of values for the current page or nil if there are no values.
func (page AccountListResultPage) Values() []Account {
	if page.alr.IsEmpty() {
		return nil
	}
	return *page.alr.Value
}

// Creates a new instance of the AccountListResultPage type.
func NewAccountListResultPage(getNextPage func(context.Context, AccountListResult) (AccountListResult, error)) AccountListResultPage {
	return AccountListResultPage{fn: getNextPage}
}

// AccountProperties properties of Cognitive Services account.
type AccountProperties struct {
	// ProvisioningState - READ-ONLY; Gets the status of the cognitive services account at the time the operation was called. Possible values include: 'Creating', 'ResolvingDNS', 'Moving', 'Deleting', 'Succeeded', 'Failed'
	ProvisioningState ProvisioningState `json:"provisioningState,omitempty"`
	// Endpoint - READ-ONLY; Endpoint of the created account.
	Endpoint *string `json:"endpoint,omitempty"`
	// InternalID - READ-ONLY; The internal identifier.
	InternalID *string `json:"internalId,omitempty"`
	// CustomSubDomainName - Optional subdomain name used for token-based authentication.
	CustomSubDomainName *string `json:"customSubDomainName,omitempty"`
	// NetworkAcls - A collection of rules governing the accessibility from specific network locations.
	NetworkAcls *NetworkRuleSet `json:"networkAcls,omitempty"`
	// APIProperties - The api properties for special APIs.
	APIProperties *AccountAPIProperties `json:"apiProperties,omitempty"`
}

// CheckDomainAvailabilityParameter check Domain availability parameter.
type CheckDomainAvailabilityParameter struct {
	// SubdomainName - The subdomain name to use.
	SubdomainName *string `json:"subdomainName,omitempty"`
	// Type - The Type of the resource.
	Type *string `json:"type,omitempty"`
}

// CheckDomainAvailabilityResult check Domain availability result.
type CheckDomainAvailabilityResult struct {
	autorest.Response `json:"-"`
	// IsSubdomainAvailable - Indicates the given SKU is available or not.
	IsSubdomainAvailable *bool `json:"isSubdomainAvailable,omitempty"`
	// Reason - Reason why the SKU is not available.
	Reason *string `json:"reason,omitempty"`
	// SubdomainName - The subdomain name to use.
	SubdomainName *string `json:"subdomainName,omitempty"`
	// Type - The Type of the resource.
	Type *string `json:"type,omitempty"`
}

// CheckSkuAvailabilityParameter check SKU availability parameter.
type CheckSkuAvailabilityParameter struct {
	// Skus - The SKU of the resource.
	Skus *[]string `json:"skus,omitempty"`
	// Kind - The Kind of the resource.
	Kind *string `json:"kind,omitempty"`
	// Type - The Type of the resource.
	Type *string `json:"type,omitempty"`
}

// CheckSkuAvailabilityResult check SKU availability result.
type CheckSkuAvailabilityResult struct {
	// Kind - The Kind of the resource.
	Kind *string `json:"kind,omitempty"`
	// Type - The Type of the resource.
	Type *string `json:"type,omitempty"`
	// SkuName - The SKU of Cognitive Services account.
	SkuName *string `json:"skuName,omitempty"`
	// SkuAvailable - Indicates the given SKU is available or not.
	SkuAvailable *bool `json:"skuAvailable,omitempty"`
	// Reason - Reason why the SKU is not available.
	Reason *string `json:"reason,omitempty"`
	// Message - Additional error message.
	Message *string `json:"message,omitempty"`
}

// CheckSkuAvailabilityResultList check SKU availability result list.
type CheckSkuAvailabilityResultList struct {
	autorest.Response `json:"-"`
	// Value - Check SKU availability result list.
	Value *[]CheckSkuAvailabilityResult `json:"value,omitempty"`
}

// Error cognitive Services error object.
type Error struct {
	// Error - The error body.
	Error *ErrorBody `json:"error,omitempty"`
}

// ErrorBody cognitive Services error body.
type ErrorBody struct {
	// Code - error code
	Code *string `json:"code,omitempty"`
	// Message - error message
	Message *string `json:"message,omitempty"`
}

// IPRule a rule governing the accessibility from a specific ip address or ip range.
type IPRule struct {
	// Value - An IPv4 address range in CIDR notation, such as '124.56.78.91' (simple IP address) or '124.56.78.0/24' (all addresses that start with 124.56.78).
	Value *string `json:"value,omitempty"`
}

// MetricName a metric name.
type MetricName struct {
	// Value - READ-ONLY; The name of the metric.
	Value *string `json:"value,omitempty"`
	// LocalizedValue - READ-ONLY; The friendly name of the metric.
	LocalizedValue *string `json:"localizedValue,omitempty"`
}

// NetworkRuleSet a set of rules governing the network accessibility.
type NetworkRuleSet struct {
	// DefaultAction - The default action when no rule from ipRules and from virtualNetworkRules match. This is only used after the bypass property has been evaluated. Possible values include: 'Allow', 'Deny'
	DefaultAction NetworkRuleAction `json:"defaultAction,omitempty"`
	// IPRules - The list of IP address rules.
	IPRules *[]IPRule `json:"ipRules,omitempty"`
	// VirtualNetworkRules - The list of virtual network rules.
	VirtualNetworkRules *[]VirtualNetworkRule `json:"virtualNetworkRules,omitempty"`
}

// OperationDisplayInfo the operation supported by Cognitive Services.
type OperationDisplayInfo struct {
	// Description - The description of the operation.
	Description *string `json:"description,omitempty"`
	// Operation - The action that users can perform, based on their permission level.
	Operation *string `json:"operation,omitempty"`
	// Provider - Service provider: Microsoft Cognitive Services.
	Provider *string `json:"provider,omitempty"`
	// Resource - Resource on which the operation is performed.
	Resource *string `json:"resource,omitempty"`
}

// OperationEntity the operation supported by Cognitive Services.
type OperationEntity struct {
	// Name - Operation name: {provider}/{resource}/{operation}.
	Name *string `json:"name,omitempty"`
	// Display - The operation supported by Cognitive Services.
	Display *OperationDisplayInfo `json:"display,omitempty"`
	// Origin - The origin of the operation.
	Origin *string `json:"origin,omitempty"`
	// Properties - Additional properties.
	Properties interface{} `json:"properties,omitempty"`
}

// OperationEntityListResult the list of cognitive services accounts operation response.
type OperationEntityListResult struct {
	autorest.Response `json:"-"`
	// NextLink - The link used to get the next page of operations.
	NextLink *string `json:"nextLink,omitempty"`
	// Value - The list of operations.
	Value *[]OperationEntity `json:"value,omitempty"`
}

// OperationEntityListResultIterator provides access to a complete listing of OperationEntity values.
type OperationEntityListResultIterator struct {
	i    int
	page OperationEntityListResultPage
}

// NextWithContext advances to the next value.  If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *OperationEntityListResultIterator) NextWithContext(ctx context.Context) (err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/OperationEntityListResultIterator.NextWithContext")
		defer func() {
			sc := -1
			if iter.Response().Response.Response != nil {
				sc = iter.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	iter.i++
	if iter.i < len(iter.page.Values()) {
		return nil
	}
	err = iter.page.NextWithContext(ctx)
	if err != nil {
		iter.i--
		return err
	}
	iter.i = 0
	return nil
}

// Next advances to the next value.  If there was an error making
// the request the iterator does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (iter *OperationEntityListResultIterator) Next() error {
	return iter.NextWithContext(context.Background())
}

// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter OperationEntityListResultIterator) NotDone() bool {
	return iter.page.NotDone() && iter.i < len(iter.page.Values())
}

// Response returns the raw server response from the last page request.
func (iter OperationEntityListResultIterator) Response() OperationEntityListResult {
	return iter.page.Response()
}

// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter OperationEntityListResultIterator) Value() OperationEntity {
	if !iter.page.NotDone() {
		return OperationEntity{}
	}
	return iter.page.Values()[iter.i]
}

// Creates a new instance of the OperationEntityListResultIterator type.
func NewOperationEntityListResultIterator(page OperationEntityListResultPage) OperationEntityListResultIterator {
	return OperationEntityListResultIterator{page: page}
}

// IsEmpty returns true if the ListResult contains no values.
func (oelr OperationEntityListResult) IsEmpty() bool {
	return oelr.Value == nil || len(*oelr.Value) == 0
}

// operationEntityListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (oelr OperationEntityListResult) operationEntityListResultPreparer(ctx context.Context) (*http.Request, error) {
	if oelr.NextLink == nil || len(to.String(oelr.NextLink)) < 1 {
		return nil, nil
	}
	return autorest.Prepare((&http.Request{}).WithContext(ctx),
		autorest.AsJSON(),
		autorest.AsGet(),
		autorest.WithBaseURL(to.String(oelr.NextLink)))
}

// OperationEntityListResultPage contains a page of OperationEntity values.
type OperationEntityListResultPage struct {
	fn   func(context.Context, OperationEntityListResult) (OperationEntityListResult, error)
	oelr OperationEntityListResult
}

// NextWithContext advances to the next page of values.  If there was an error making
// the request the page does not advance and the error is returned.
func (page *OperationEntityListResultPage) NextWithContext(ctx context.Context) (err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/OperationEntityListResultPage.NextWithContext")
		defer func() {
			sc := -1
			if page.Response().Response.Response != nil {
				sc = page.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	next, err := page.fn(ctx, page.oelr)
	if err != nil {
		return err
	}
	page.oelr = next
	return nil
}

// Next advances to the next page of values.  If there was an error making
// the request the page does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (page *OperationEntityListResultPage) Next() error {
	return page.NextWithContext(context.Background())
}

// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page OperationEntityListResultPage) NotDone() bool {
	return !page.oelr.IsEmpty()
}

// Response returns the raw server response from the last page request.
func (page OperationEntityListResultPage) Response() OperationEntityListResult {
	return page.oelr
}

// Values returns the slice of values for the current page or nil if there are no values.
func (page OperationEntityListResultPage) Values() []OperationEntity {
	if page.oelr.IsEmpty() {
		return nil
	}
	return *page.oelr.Value
}

// Creates a new instance of the OperationEntityListResultPage type.
func NewOperationEntityListResultPage(getNextPage func(context.Context, OperationEntityListResult) (OperationEntityListResult, error)) OperationEntityListResultPage {
	return OperationEntityListResultPage{fn: getNextPage}
}

// RegenerateKeyParameters regenerate key parameters.
type RegenerateKeyParameters struct {
	// KeyName - key name to generate (Key1|Key2). Possible values include: 'Key1', 'Key2'
	KeyName KeyName `json:"keyName,omitempty"`
}

// ResourceAndSku cognitive Services resource type and SKU.
type ResourceAndSku struct {
	// ResourceType - Resource Namespace and Type
	ResourceType *string `json:"resourceType,omitempty"`
	// Sku - The SKU of Cognitive Services account.
	Sku *Sku `json:"sku,omitempty"`
}

// ResourceSku describes an available Cognitive Services SKU.
type ResourceSku struct {
	// ResourceType - READ-ONLY; The type of resource the SKU applies to.
	ResourceType *string `json:"resourceType,omitempty"`
	// Name - READ-ONLY; The name of SKU.
	Name *string `json:"name,omitempty"`
	// Tier - READ-ONLY; Specifies the tier of Cognitive Services account.
	Tier *string `json:"tier,omitempty"`
	// Kind - READ-ONLY; The Kind of resources that are supported in this SKU.
	Kind *string `json:"kind,omitempty"`
	// Locations - READ-ONLY; The set of locations that the SKU is available.
	Locations *[]string `json:"locations,omitempty"`
	// Restrictions - READ-ONLY; The restrictions because of which SKU cannot be used. This is empty if there are no restrictions.
	Restrictions *[]ResourceSkuRestrictions `json:"restrictions,omitempty"`
}

// ResourceSkuRestrictionInfo ...
type ResourceSkuRestrictionInfo struct {
	// Locations - READ-ONLY; Locations where the SKU is restricted
	Locations *[]string `json:"locations,omitempty"`
	// Zones - READ-ONLY; List of availability zones where the SKU is restricted.
	Zones *[]string `json:"zones,omitempty"`
}

// ResourceSkuRestrictions describes restrictions of a SKU.
type ResourceSkuRestrictions struct {
	// Type - READ-ONLY; The type of restrictions. Possible values include: 'Location', 'Zone'
	Type ResourceSkuRestrictionsType `json:"type,omitempty"`
	// Values - READ-ONLY; The value of restrictions. If the restriction type is set to location. This would be different locations where the SKU is restricted.
	Values *[]string `json:"values,omitempty"`
	// RestrictionInfo - READ-ONLY; The information about the restriction where the SKU cannot be used.
	RestrictionInfo *ResourceSkuRestrictionInfo `json:"restrictionInfo,omitempty"`
	// ReasonCode - READ-ONLY; The reason for restriction. Possible values include: 'QuotaID', 'NotAvailableForSubscription'
	ReasonCode ResourceSkuRestrictionsReasonCode `json:"reasonCode,omitempty"`
}

// ResourceSkusResult the Get Skus operation response.
type ResourceSkusResult struct {
	autorest.Response `json:"-"`
	// Value - The list of skus available for the subscription.
	Value *[]ResourceSku `json:"value,omitempty"`
	// NextLink - The uri to fetch the next page of Skus.
	NextLink *string `json:"nextLink,omitempty"`
}

// ResourceSkusResultIterator provides access to a complete listing of ResourceSku values.
type ResourceSkusResultIterator struct {
	i    int
	page ResourceSkusResultPage
}

// NextWithContext advances to the next value.  If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *ResourceSkusResultIterator) NextWithContext(ctx context.Context) (err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ResourceSkusResultIterator.NextWithContext")
		defer func() {
			sc := -1
			if iter.Response().Response.Response != nil {
				sc = iter.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	iter.i++
	if iter.i < len(iter.page.Values()) {
		return nil
	}
	err = iter.page.NextWithContext(ctx)
	if err != nil {
		iter.i--
		return err
	}
	iter.i = 0
	return nil
}

// Next advances to the next value.  If there was an error making
// the request the iterator does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (iter *ResourceSkusResultIterator) Next() error {
	return iter.NextWithContext(context.Background())
}

// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter ResourceSkusResultIterator) NotDone() bool {
	return iter.page.NotDone() && iter.i < len(iter.page.Values())
}

// Response returns the raw server response from the last page request.
func (iter ResourceSkusResultIterator) Response() ResourceSkusResult {
	return iter.page.Response()
}

// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter ResourceSkusResultIterator) Value() ResourceSku {
	if !iter.page.NotDone() {
		return ResourceSku{}
	}
	return iter.page.Values()[iter.i]
}

// Creates a new instance of the ResourceSkusResultIterator type.
func NewResourceSkusResultIterator(page ResourceSkusResultPage) ResourceSkusResultIterator {
	return ResourceSkusResultIterator{page: page}
}

// IsEmpty returns true if the ListResult contains no values.
func (rsr ResourceSkusResult) IsEmpty() bool {
	return rsr.Value == nil || len(*rsr.Value) == 0
}

// resourceSkusResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (rsr ResourceSkusResult) resourceSkusResultPreparer(ctx context.Context) (*http.Request, error) {
	if rsr.NextLink == nil || len(to.String(rsr.NextLink)) < 1 {
		return nil, nil
	}
	return autorest.Prepare((&http.Request{}).WithContext(ctx),
		autorest.AsJSON(),
		autorest.AsGet(),
		autorest.WithBaseURL(to.String(rsr.NextLink)))
}

// ResourceSkusResultPage contains a page of ResourceSku values.
type ResourceSkusResultPage struct {
	fn  func(context.Context, ResourceSkusResult) (ResourceSkusResult, error)
	rsr ResourceSkusResult
}

// NextWithContext advances to the next page of values.  If there was an error making
// the request the page does not advance and the error is returned.
func (page *ResourceSkusResultPage) NextWithContext(ctx context.Context) (err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ResourceSkusResultPage.NextWithContext")
		defer func() {
			sc := -1
			if page.Response().Response.Response != nil {
				sc = page.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	next, err := page.fn(ctx, page.rsr)
	if err != nil {
		return err
	}
	page.rsr = next
	return nil
}

// Next advances to the next page of values.  If there was an error making
// the request the page does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (page *ResourceSkusResultPage) Next() error {
	return page.NextWithContext(context.Background())
}

// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page ResourceSkusResultPage) NotDone() bool {
	return !page.rsr.IsEmpty()
}

// Response returns the raw server response from the last page request.
func (page ResourceSkusResultPage) Response() ResourceSkusResult {
	return page.rsr
}

// Values returns the slice of values for the current page or nil if there are no values.
func (page ResourceSkusResultPage) Values() []ResourceSku {
	if page.rsr.IsEmpty() {
		return nil
	}
	return *page.rsr.Value
}

// Creates a new instance of the ResourceSkusResultPage type.
func NewResourceSkusResultPage(getNextPage func(context.Context, ResourceSkusResult) (ResourceSkusResult, error)) ResourceSkusResultPage {
	return ResourceSkusResultPage{fn: getNextPage}
}

// Sku the SKU of the cognitive services account.
type Sku struct {
	// Name - Gets or sets the sku name. Required for account creation, optional for update.
	Name *string `json:"name,omitempty"`
	// Tier - READ-ONLY; Gets the sku tier. This is based on the SKU name. Possible values include: 'Free', 'Standard', 'Premium'
	Tier SkuTier `json:"tier,omitempty"`
}

// Usage the usage data for a usage request.
type Usage struct {
	// Unit - The unit of the metric. Possible values include: 'Count', 'Bytes', 'Seconds', 'Percent', 'CountPerSecond', 'BytesPerSecond', 'Milliseconds'
	Unit UnitType `json:"unit,omitempty"`
	// Name - READ-ONLY; The name information for the metric.
	Name *MetricName `json:"name,omitempty"`
	// QuotaPeriod - READ-ONLY; The quota period used to summarize the usage values.
	QuotaPeriod *string `json:"quotaPeriod,omitempty"`
	// Limit - READ-ONLY; Maximum value for this metric.
	Limit *float64 `json:"limit,omitempty"`
	// CurrentValue - READ-ONLY; Current value for this metric.
	CurrentValue *float64 `json:"currentValue,omitempty"`
	// NextResetTime - READ-ONLY; Next reset time for current quota.
	NextResetTime *string `json:"nextResetTime,omitempty"`
	// Status - Cognitive Services account quota usage status. Possible values include: 'Included', 'Blocked', 'InOverage', 'Unknown'
	Status QuotaUsageStatus `json:"status,omitempty"`
}

// UsagesResult the response to a list usage request.
type UsagesResult struct {
	autorest.Response `json:"-"`
	// Value - READ-ONLY; The list of usages for Cognitive Service account.
	Value *[]Usage `json:"value,omitempty"`
}

// VirtualNetworkRule a rule governing the accessibility from a specific virtual network.
type VirtualNetworkRule struct {
	// ID - Full resource id of a vnet subnet, such as '/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1'.
	ID *string `json:"id,omitempty"`
	// State - Gets the state of virtual network rule.
	State *string `json:"state,omitempty"`
	// IgnoreMissingVnetServiceEndpoint - Ignore missing vnet service endpoint or not.
	IgnoreMissingVnetServiceEndpoint *bool `json:"ignoreMissingVnetServiceEndpoint,omitempty"`
}


text:
package main

import (
	"fmt"
	"io"
	//"net/mail"
	"os"
	"path"
	"strings"

	"github.com/cention-sany/go.enmime"
	"github.com/cention-sany/net/mail"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Fprintln(os.Stderr, "Missing filename argument")
		os.Exit(1)
	}

	reader, err := os.Open(os.Args[1])
	if err != nil {
		fmt.Fprintln(os.Stderr, "Failed to open file:", err)
		os.Exit(1)
	}

	basename := path.Base(os.Args[1])
	if err = dump(reader, basename); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func dump(reader io.Reader, name string) error {
	// Read email using Go's net/mail
	msg, err := mail.ReadMessage(reader)
	if err != nil {
		return fmt.Errorf("During mail.ReadMessage: %v", err)
	}

	// Parse message body with enmime
	mime, err := enmime.ParseMIMEBody(msg)
	if err != nil {
		return fmt.Errorf("During enmime.ParseMIMEBody: %v", err)
	}

	h1(name)
	h2("Header")
	for k := range msg.Header {
		switch strings.ToLower(k) {
		case "from", "to", "bcc", "subject":
			continue
		}
		fmt.Printf("%v: %v  \n", k, mime.GetHeader(k))
	}

	h2("Envelope")
	for _, hkey := range enmime.AddressHeaders {
		addrlist, err := mime.AddressList(hkey)
		if err != nil {
			if err == mail.ErrHeaderNotPresent {
				continue
			}
			panic(err)
		}
		fmt.Println("### " + hkey)
		for _, addr := range addrlist {
			fmt.Printf("%v <%v>\n", addr.Name, addr.Address)
		}
	}

	fmt.Printf("### Subject\n %v\n", mime.GetHeader("Subject"))

	h2("Body Text")
	fmt.Println(mime.Text)
	fmt.Println()

	h2("Body HTML")
	fmt.Println(mime.HTML)
	fmt.Println()

	h2("Attachment List")
	for _, a := range mime.Attachments {
		fmt.Printf("- %v (%v)\n", a.FileName(), a.ContentType())
	}
	fmt.Println()

	h2("MIME Part Tree")
	if mime.Root == nil {
		fmt.Println("Message was not MIME encoded")
	} else {
		printPart(mime.Root, "    ")
	}

	return nil
}

func h1(content string) {
	bar := strings.Repeat("-", len(content))
	fmt.Printf("#%v\n%v\n\n", content, bar)
}

func h2(content string) {
	fmt.Printf("##%v\n", content)
}

// printPart pretty prints the MIMEPart tree
func printPart(p enmime.MIMEPart, indent string) {
	sibling := p.NextSibling()
	child := p.FirstChild()

	// Compute indent strings
	myindent := indent + "`-- "
	childindent := indent + "    "
	if sibling != nil {
		myindent = indent + "|-- "
		childindent = indent + "|   "
	}
	if p.Parent() == nil {
		// Root shouldn't be decorated, has no siblings
		myindent = indent
		childindent = indent
	}

	// Format and print this node
	ctype := "MISSING TYPE"
	if p.ContentType() != "" {
		ctype = p.ContentType()
	}
	disposition := ""
	if p.Disposition() != "" {
		disposition = ", disposition: " + p.Disposition()
	}
	filename := ""
	if p.FileName() != "" {
		filename = ", filename: \"" + p.FileName() + "\""
	}
	fmt.Printf("%s%s%s%s\n", myindent, ctype, disposition, filename)

	// Recurse
	if child != nil {
		printPart(child, childindent)
	}
	if sibling != nil {
		printPart(sibling, indent)
	}
}


text:
package com.amazonaws.services.codecommit.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.codecommit.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * GetMergeConflictsRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class GetMergeConflictsRequestMarshaller {

    private static final MarshallingInfo<String> REPOSITORYNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("repositoryName").build();
    private static final MarshallingInfo<String> DESTINATIONCOMMITSPECIFIER_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("destinationCommitSpecifier").build();
    private static final MarshallingInfo<String> SOURCECOMMITSPECIFIER_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("sourceCommitSpecifier").build();
    private static final MarshallingInfo<String> MERGEOPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("mergeOption").build();
    private static final MarshallingInfo<String> CONFLICTDETAILLEVEL_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("conflictDetailLevel").build();
    private static final MarshallingInfo<Integer> MAXCONFLICTFILES_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("maxConflictFiles").build();
    private static final MarshallingInfo<String> CONFLICTRESOLUTIONSTRATEGY_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("conflictResolutionStrategy").build();
    private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("nextToken").build();

    private static final GetMergeConflictsRequestMarshaller instance = new GetMergeConflictsRequestMarshaller();

    public static GetMergeConflictsRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(GetMergeConflictsRequest getMergeConflictsRequest, ProtocolMarshaller protocolMarshaller) {

        if (getMergeConflictsRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(getMergeConflictsRequest.getRepositoryName(), REPOSITORYNAME_BINDING);
            protocolMarshaller.marshall(getMergeConflictsRequest.getDestinationCommitSpecifier(), DESTINATIONCOMMITSPECIFIER_BINDING);
            protocolMarshaller.marshall(getMergeConflictsRequest.getSourceCommitSpecifier(), SOURCECOMMITSPECIFIER_BINDING);
            protocolMarshaller.marshall(getMergeConflictsRequest.getMergeOption(), MERGEOPTION_BINDING);
            protocolMarshaller.marshall(getMergeConflictsRequest.getConflictDetailLevel(), CONFLICTDETAILLEVEL_BINDING);
            protocolMarshaller.marshall(getMergeConflictsRequest.getMaxConflictFiles(), MAXCONFLICTFILES_BINDING);
            protocolMarshaller.marshall(getMergeConflictsRequest.getConflictResolutionStrategy(), CONFLICTRESOLUTIONSTRATEGY_BINDING);
            protocolMarshaller.marshall(getMergeConflictsRequest.getNextToken(), NEXTTOKEN_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
var fs = require('fs'),
    child_process = require('child_process'),
    mkdirp = require('mkdirp'),
    uuid = require('node-uuid');

/**
 * TODO finish this
 */
function CacheStore() {

}

CacheStore.prototype = {
  get: function(id) {
    return null;
  },

  put: function(id, asset) {

  },

  post: function(asset) {

  },

  delete: function(id) {

  },

  setup: function() {
    this.id = uuid.v4();

    this.root = '/mnt/' + this.id;

    mkdirp.sync(this.root);

    child_process.exec('mount -t tmpfs -o size=20m tmpfs ' + this.root);
  },

  tearDown: function() {
    child_process.exec('umount ' + this.root);

    child_process.exec('rm ' + this.root);
  }
};

module.exports = CacheStore;


text:
package org.apache.hadoop.fs.s3a;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.util.AwsHostNameUtils;
import org.assertj.core.api.Assertions;
import org.junit.Test;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.s3a.statistics.impl.EmptyS3AStatisticsContext;

import static org.apache.hadoop.fs.s3a.Constants.AWS_REGION;
import static org.apache.hadoop.fs.s3a.Constants.AWS_S3_CENTRAL_REGION;
import static org.apache.hadoop.fs.s3a.Constants.DEFAULT_ENDPOINT;
import static org.apache.hadoop.fs.s3a.impl.InternalConstants.AWS_REGION_SYSPROP;
import static org.apache.hadoop.test.LambdaTestUtils.intercept;

/**
 * Test to check correctness of S3A endpoint regions in
 * {@link DefaultS3ClientFactory}.
 */
public class ITestS3AEndpointRegion extends AbstractS3ATestBase {

  private static final String AWS_REGION_TEST = "test-region";
  private static final String AWS_ENDPOINT_TEST = "test-endpoint";
  private static final String AWS_ENDPOINT_TEST_WITH_REGION =
      "test-endpoint.some-region.amazonaws.com";
  public static final String MARS_NORTH_2 = "mars-north-2";

  /**
   * Test to verify that setting a region with the config would bypass the
   * construction of region from endpoint.
   */
  @Test
  public void testWithRegionConfig() {
    getFileSystem().getConf().set(AWS_REGION, AWS_REGION_TEST);

    //Creating an endpoint config with a custom endpoint.
    AwsClientBuilder.EndpointConfiguration epr = createEpr(AWS_ENDPOINT_TEST,
        getFileSystem().getConf().getTrimmed(AWS_REGION));
    //Checking if setting region config bypasses the endpoint region.
    Assertions.assertThat(epr.getSigningRegion())
        .describedAs("There is a region mismatch")
        .isEqualTo(getFileSystem().getConf().get(AWS_REGION));
  }

  /**
   * Test to verify that not setting the region config, would lead to using
   * endpoint to construct the region.
   */
  @Test
  public void testWithoutRegionConfig() {
    getFileSystem().getConf().unset(AWS_REGION);

    //Creating an endpoint config with a custom endpoint containing a region.
    AwsClientBuilder.EndpointConfiguration eprRandom =
        createEpr(AWS_ENDPOINT_TEST_WITH_REGION,
            getFileSystem().getConf().getTrimmed(AWS_REGION));
    String regionFromEndpoint =
        AwsHostNameUtils
            .parseRegionFromAwsPartitionPattern(AWS_ENDPOINT_TEST_WITH_REGION);
    //Checking if not setting region config leads to constructing the region
    // from endpoint.
    Assertions.assertThat(eprRandom.getSigningRegion())
        .describedAs("There is a region mismatch")
        .isNotEqualTo(getFileSystem().getConf().get(AWS_REGION))
        .isEqualTo(regionFromEndpoint);
  }

  /**
   * Method to create EndpointConfiguration using an endpoint.
   *
   * @param endpoint the endpoint to be used for EndpointConfiguration creation.
   * @return an instance of EndpointConfiguration.
   */
  private AwsClientBuilder.EndpointConfiguration createEpr(String endpoint,
      String awsRegion) {
    return DefaultS3ClientFactory.createEndpointConfiguration(endpoint,
        new ClientConfiguration(), awsRegion);
  }

  @Test
  public void testInvalidRegionDefaultEndpoint() throws Throwable {
    describe("Create a client with an invalid region and the default endpoint");
    Configuration conf = getConfiguration();
    // we are making a big assumption about the timetable for AWS
    // region rollout.
    // if this test ever fails because this region now exists
    // -congratulations!
    conf.set(AWS_REGION, MARS_NORTH_2);
    createMarsNorth2Client(conf);
  }

  @Test
  public void testUnsetRegionDefaultEndpoint() throws Throwable {
    describe("Create a client with no region and the default endpoint");
    Configuration conf = getConfiguration();
    conf.unset(AWS_REGION);
    createS3Client(conf, DEFAULT_ENDPOINT, AWS_S3_CENTRAL_REGION);
  }

  /**
   * By setting the system property {@code "aws.region"} we can
   * guarantee that the SDK region resolution chain will always succeed
   * (and fast).
   * Clearly there is no validation of the region during the build process.
   */
  @Test
  public void testBlankRegionTriggersSDKResolution() throws Throwable {
    describe("Create a client with a blank region and the default endpoint."
        + " This will trigger the SDK Resolution chain");
    Configuration conf = getConfiguration();
    conf.set(AWS_REGION, "");
    System.setProperty(AWS_REGION_SYSPROP, MARS_NORTH_2);
    try {
      createMarsNorth2Client(conf);
    } finally {
      System.clearProperty(AWS_REGION_SYSPROP);
    }
  }

  /**
   * Create an S3 client bonded to an invalid region;
   * verify that calling {@code getRegion()} triggers
   * a failure.
   * @param conf configuration to use in the building.
   */
  private void createMarsNorth2Client(Configuration conf) throws Exception {
    AmazonS3 client = createS3Client(conf, DEFAULT_ENDPOINT, MARS_NORTH_2);
    intercept(IllegalArgumentException.class, MARS_NORTH_2, client::getRegion);
  }

  /**
   * Create an S3 client with the given conf and endpoint.
   * The region name must then match that of the expected
   * value.
   * @param conf configuration to use.
   * @param endpoint endpoint.
   * @param expectedRegion expected region
   * @return the client.
   * @throws URISyntaxException parse problems.
   * @throws IOException IO problems
   */
  @SuppressWarnings("deprecation")
  private AmazonS3 createS3Client(Configuration conf,
      String endpoint,
      String expectedRegion)
      throws URISyntaxException, IOException {

    DefaultS3ClientFactory factory
        = new DefaultS3ClientFactory();
    factory.setConf(conf);
    S3ClientFactory.S3ClientCreationParameters parameters
        = new S3ClientFactory.S3ClientCreationParameters()
        .withCredentialSet(new AnonymousAWSCredentialsProvider())
        .withPathUri(new URI("s3a://localhost/"))
        .withEndpoint(endpoint)
        .withMetrics(new EmptyS3AStatisticsContext()
            .newStatisticsFromAwsSdk());
    AmazonS3 client = factory.createS3Client(
        new URI("s3a://localhost/"),
        parameters);
    Assertions.assertThat(client.getRegionName())
        .describedAs("Client region name")
        .isEqualTo(expectedRegion);
    return client;
  }
}


text:
declare module "*.html" {
	var __a__: string;
	export default __a__;
}


text:
#ifndef SPINE_IKCONSTRAINTDATA_H_
#define SPINE_IKCONSTRAINTDATA_H_

#include <spine/dll.h>
#include <spine/BoneData.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef struct spIkConstraintData {
	const char* const name;
	int order;
	int /*boolean*/ skinRequired;
	int bonesCount;
	spBoneData** bones;

	spBoneData* target;
	int bendDirection;
	int /*boolean*/ compress;
	int /*boolean*/ stretch;
	int /*boolean*/ uniform;
	float mix;
	float softness;

#ifdef __cplusplus
	spIkConstraintData() :
		name(0),
		order(0),
		skinRequired(0),
		bonesCount(0),
		bones(0),
		target(0),
		bendDirection(0),
		compress(0),
		stretch(0),
		uniform(0),
		mix(0),
		softness(0) {
	}
#endif
} spIkConstraintData;

SP_API spIkConstraintData* spIkConstraintData_create (const char* name);
SP_API void spIkConstraintData_dispose (spIkConstraintData* self);

#ifdef SPINE_SHORT_NAMES
typedef spIkConstraintData IkConstraintData;
#define IkConstraintData_create(...) spIkConstraintData_create(__VA_ARGS__)
#define IkConstraintData_dispose(...) spIkConstraintData_dispose(__VA_ARGS__)
#endif

#ifdef __cplusplus
}
#endif

#endif /* SPINE_IKCONSTRAINTDATA_H_ */


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="stylesheet" href="/sass/main.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<link rel="alternate" type="application/rss+xml" title="RSS Feed for dmacleod.ca" href="https://dmacleod.ca/ra/index.xml" />

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

      </button>
      Readers' Advisory blog

About this blog

Browse by topics

Contact

Publications

Overclocked by Cory Doctorow

<time datetime='2017-03-27T00:00:00Z' itemprop="datePublished">March 27, 2017</time> • Donna MacLeod

About the book

Author:

Title: Overclocked : Stories of the future present

Publication: New York : Thunder’s Mouth Press, 2007. ISBN 9781560259817.

DAISY audio format narrated by Lloyd James, Nicola Barber, R. C. Bray, Fiona Hardingham, Jeffrey Kafer, Jim Meskimen and Emily Woo Zeller.
CELA library call number DA52551. 285 pages in the print edition; 13 hrs., 14 mins. as a recorded book.

About the story

I love the way Cory Doctorow explores the present through the lens of potential futures and alternate realities. He holds strong opinions on many issues, and puts his money where his mouth is: you have to respect someone like that.

This is his second collection of stories, published long ago in 2007.

These stories are not always easy to read, as his themes can and do get quite heavy and dark at times. But his work is characterised, I would say, by inventiveness and a solid, logical construction that make them seem both realistic and inevitable. Or, at least, evitable if we get off our collective butts and help out now. I personally find his approach to social-justice and technology to be very compelling.

This collection of short stories sort of exemplifies what I mean.

Each one is preceded by an introduction by the author, and each story is read by a different narrator. This lends a real dynamic range to the audiobook, and helps you transition from one story to another if you read them consecutively. Myself, I have to stop at the end of each story (or book) that I read and walk with it for a while, to transition between them. When reading short stories or novellas, I often switch to another of the several concurrent books that I am reading. That’s one reason I don’t review more of them!

This books contains the following stories, many of which have won prestigious awards which I will not mention here:

Printcrime (2006) is set in a city where countries who are determined to collect their copyright royalties are at war with those whose economy is based on royalty-free 3D printing.

When Sysadmins Ruled the Earth (2006) is an apocalyptic story set in Toronto. It is terrible and sad and hopeful.

Anda’s Game (2005), a takeoff on Ender’s Game by Oroson Scott Card, follows a young gamer into a world where skill and exploitation of oppressed labourers become all too real. Not only does it portray strong young female protagonists, it shows how personal decisions can add up to something important.

I, Robot (2005) is a philosophical and religious examination of one robot’s internal life after the Singularity.

I, Rowboat (2006) is also a philosophical and religious examination of one robot’s internal life after the Singularity. This time, that robot is a rowboat. I love this story.

After the Siege (2007?) follows a young girl as her city becomes embroiled in a war. She does what she must. It’s a hard read, but a good one.

About the author

Cory Doctorow is an active proponent of DRM-free publishing, and makes his writing available on his website. Please consider supporting him as a writer, by either buying one of his books or by donating one of his books to an institution (library, school, shelter, etc.) of your choice. He sometimes releases his newer work in a series of podcasts, and is active on many political fronts. He also makes numerous speaking appearances.

The best place to find his writing and podcasts is his website, CrapHound.com.

If you like his writing and appreciate insightful current-affairs writing, he is also a regular contributor to Boing Boing, a group blog that covers a wide range of issues and topics, and which also has a podcast section.

Recommended?

Recommended.

« Les yeux jaunes des crocodiles de Katherine Pancol

The Cherry Cola book club by Ashton Lee »

Recent articles

On hiatus for a while  August 11, 2018

Last ballad by Wiley Cash  March 31, 2018

Itsuka by Joy Kogawa  March 25, 2018

A discovery of witches by Deborah E. Harkness (All souls trilogy)  March 18, 2018

The back of the turtle by Thomas King  March 3, 2018

Six degrés de liberté de Nicolas Dickner  February 24, 2018

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License by Donna MacLeod.