text:
class ShouldaRenderJsonObjectMatcher
  attr_reader :options, :context, :root, :keys, :response, :failure_message, :negative_failure_message

  def initialize(root, options = {})
    @options = options
    # Coercing types root: Symbol, keys: Array of Symbols
    @root = root.to_s
    @keys = {
      required: massage_options(:required),
      forbidden: massage_options(:forbidden),
    }
  end

  def description
    "render JSON Hash/Object for #{@root}"
  end

  def matches?(controller)
    @response = controller.response
    matches_content_type? &&
      matches_root? &&
      has_required_keys? &&
      has_no_forbidden_keys?
  rescue JSON::ParserError
    set_failure_message "Response body was not a valid JSON string"
    false
  end

private

  def matches_content_type?
    content_type = response.content_type
    set_failure_message "Expected content type to be 'application/json' but was '#{content_type}' instead"
    set_negative_failure_message "Expected content type not to be '#{content_type}'"
    content_type == 'application/json'
  end

  def root_matches_expected_type?
    matches_root? ? root_is_expected_type? : false
  end

  def matches_root?
    klass = json[root].class
    set_failure_message "Expected root level node '#{root}' as Hash/Object but it was not found [class was #{klass}]"
    set_negative_failure_message "Did not expect to contain root level node '#{root}' but it was present as #{klass}"
    json.has_key?(root) && json[root].is_a?(expected_root_class)
  end

  def has_required_keys?
    return true unless keys[:required]
    set_failure_message "Expected child nodes for #{format_keys(missing_keys)} but there were none"
    set_negative_failure_message "Expected no child nodes for #{format_keys(missing_keys)} but they were present"
    missing_keys.empty?
  end

  def has_no_forbidden_keys?
    return true unless keys[:forbidden]
    set_failure_message "Expected no child nodes for #{format_keys(forbidden_keys)} but they were present"
    # Negative failure here makes no sense since they are expected to not be present
    forbidden_keys.empty?
  end

  def missing_keys
    @missing_keys ||= keys[:required].reject{|key| present?(key)}
  end

  def forbidden_keys
    @forbidden_keys ||= keys[:forbidden].select{|key| present?(key)}
  end

  def set_negative_failure_message(message)
    @negative_failure_message = message
  end

  def set_failure_message(message)
    @failure_message = message
  end

  def format_keys(keys)
    keys.map{|key| "'#{key}'"}.join(', ')
  end

  def json
    @json ||= JSON.parse(response.body)
  end

  def expected_root_class
    Hash
  end

  def massage_options(key)
    [options[key]].flatten.compact.map(&:to_s)
  end

  def present?(key)
    json[root].has_key?(key)
  end
end


text:
<?php

namespace PhpOffice\PhpPowerpoint\Writer\PowerPoint2007;

use PhpOffice\PhpPowerpoint\PhpPowerpoint;
use PhpOffice\PhpPowerpoint\Shape\Chart\Legend;
use PhpOffice\PhpPowerpoint\Shape\Chart\PlotArea;
use PhpOffice\PhpPowerpoint\Shape\Chart\Title;
use PhpOffice\PhpPowerpoint\Shape\Chart\Type\Bar3D;
use PhpOffice\PhpPowerpoint\Shape\Chart\Type\Line;
use PhpOffice\PhpPowerpoint\Shape\Chart\Type\Pie3D;
use PhpOffice\PhpPowerpoint\Shape\Chart\Type\Scatter;
use PhpOffice\PhpPowerpoint\Shape\Chart as ShapeChart;
use PhpOffice\PhpPowerpoint\Shared\Drawing as SharedDrawing;
use PhpOffice\PhpPowerpoint\Shared\XMLWriter;
use PhpOffice\PhpPowerpoint\Style\Border;

/**
 * \PhpOffice\PhpPowerpoint\Writer\PowerPoint2007\Chart
 */
class Chart extends Slide
{
    /**
     * Write chart to XML format
     *
     * @param  \PhpOffice\PhpPowerpoint\Shape\Chart $chart
     * @return string                    XML Output
     * @throws \Exception
     */
    public function writeChart(ShapeChart $chart = null)
    {
        // Check slide
        if (is_null($chart)) {
            throw new \Exception("Invalid \PhpOffice\PhpPowerpoint\Shape\Chart object passed.");
        }

        // Create XML writer
        $objWriter = $this->getXMLWriter();

        // XML header
        $objWriter->startDocument('1.0', 'UTF-8', 'yes');

        // c:chartSpace
        $objWriter->startElement('c:chartSpace');
        $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
        $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
        $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');

        // c:date1904
        $objWriter->startElement('c:date1904');
        $objWriter->writeAttribute('val', '1');
        $objWriter->endElement();

        // c:lang
        $objWriter->startElement('c:lang');
        $objWriter->writeAttribute('val', 'en-US');
        $objWriter->endElement();

        // c:chart
        $objWriter->startElement('c:chart');

        // Title?
        if ($chart->getTitle()->isVisible()) {
            // Write title
            $this->writeTitle($objWriter, $chart->getTitle());
        }

        // c:autoTitleDeleted
        $objWriter->startElement('c:autoTitleDeleted');
        $objWriter->writeAttribute('val', '0');
        $objWriter->endElement();

        // c:view3D
        $objWriter->startElement('c:view3D');

        // c:rotX
        $objWriter->startElement('c:rotX');
        $objWriter->writeAttribute('val', $chart->getView3D()->getRotationX());
        $objWriter->endElement();

        // c:hPercent
        $objWriter->startElement('c:hPercent');
        $objWriter->writeAttribute('val', $chart->getView3D()->getHeightPercent());
        $objWriter->endElement();

        // c:rotY
        $objWriter->startElement('c:rotY');
        $objWriter->writeAttribute('val', $chart->getView3D()->getRotationY());
        $objWriter->endElement();

        // c:depthPercent
        $objWriter->startElement('c:depthPercent');
        $objWriter->writeAttribute('val', $chart->getView3D()->getDepthPercent());
        $objWriter->endElement();

        // c:rAngAx
        $objWriter->startElement('c:rAngAx');
        $objWriter->writeAttribute('val', $chart->getView3D()->hasRightAngleAxes() ? '1' : '0');
        $objWriter->endElement();

        // c:perspective
        $objWriter->startElement('c:perspective');
        $objWriter->writeAttribute('val', $chart->getView3D()->getPerspective());
        $objWriter->endElement();

        $objWriter->endElement();

        // Write plot area
        $this->writePlotArea($objWriter, $chart->getPlotArea(), $chart);

        // Legend?
        if ($chart->getLegend()->isVisible()) {
            // Write legend
            $this->writeLegend($objWriter, $chart->getLegend());
        }

        // c:plotVisOnly
        $objWriter->startElement('c:plotVisOnly');
        $objWriter->writeAttribute('val', '1');
        $objWriter->endElement();

        $objWriter->endElement();

        // c:spPr
        $objWriter->startElement('c:spPr');

        // Fill
        $this->writeFill($objWriter, $chart->getFill());

        // Border
        if ($chart->getBorder()->getLineStyle() != Border::LINE_NONE) {
            $this->writeBorder($objWriter, $chart->getBorder(), '');
        }

        // Shadow
        if ($chart->getShadow()->isVisible()) {
            // a:effectLst
            $objWriter->startElement('a:effectLst');

            // a:outerShdw
            $objWriter->startElement('a:outerShdw');
            $objWriter->writeAttribute('blurRad', SharedDrawing::pixelsToEmu($chart->getShadow()->getBlurRadius()));
            $objWriter->writeAttribute('dist', SharedDrawing::pixelsToEmu($chart->getShadow()->getDistance()));
            $objWriter->writeAttribute('dir', SharedDrawing::degreesToAngle($chart->getShadow()->getDirection()));
            $objWriter->writeAttribute('algn', $chart->getShadow()->getAlignment());
            $objWriter->writeAttribute('rotWithShape', '0');

            // a:srgbClr
            $objWriter->startElement('a:srgbClr');
            $objWriter->writeAttribute('val', $chart->getShadow()->getColor()->getRGB());

            // a:alpha
            $objWriter->startElement('a:alpha');
            $objWriter->writeAttribute('val', $chart->getShadow()->getAlpha() * 1000);
            $objWriter->endElement();

            $objWriter->endElement();

            $objWriter->endElement();

            $objWriter->endElement();
        }

        $objWriter->endElement();

        // External data?
        if ($chart->hasIncludedSpreadsheet()) {
            // c:externalData
            $objWriter->startElement('c:externalData');
            $objWriter->writeAttribute('r:id', 'rId1');

            // c:autoUpdate
            $objWriter->startElement('c:autoUpdate');
            $objWriter->writeAttribute('val', '0');
            $objWriter->endElement();

            $objWriter->endElement();
        }

        $objWriter->endElement();

        // Return
        return $objWriter->getData();
    }

    /**
     * Write chart to XML format
     *
     * @param  PHPPowerPoint             $presentation
     * @param  \PhpOffice\PhpPowerpoint\Shape\Chart $chart
     * @param  string                    $tempName
     * @return string                    String output
     * @throws \Exception
     */
    public function writeSpreadsheet(PHPPowerPoint $presentation, $chart, $tempName)
    {
        // Need output?
        if (!$chart->hasIncludedSpreadsheet()) {
            throw new \Exception('No spreadsheet output is required for the given chart.');
        }

        // Verify PHPExcel
        if (!class_exists('PHPExcel')) {
            throw new \Exception('PHPExcel has not been loaded. Include PHPExcel.php in your script, e.g. require_once \'PHPExcel.php\'.');
        }

        // Create new spreadsheet
        $workbook = new PHPExcel();

        // Set properties
        $title = $chart->getTitle()->getText();
        if (strlen($title) == 0) {
            $title = 'Chart';
        }
        $workbook->getProperties()->setCreator($presentation->getProperties()->getCreator())->setLastModifiedBy($presentation->getProperties()->getLastModifiedBy())->setTitle($title);

        // Add chart data
        $sheet = $workbook->setActiveSheetIndex(0);
        $sheet->setTitle('Sheet1');

        // Write series
        $seriesIndex = 0;
        foreach ($chart->getPlotArea()->getType()->getData() as $series) {
            // Title
            $sheet->setCellValueByColumnAndRow(1 + $seriesIndex, 1, $series->getTitle());

            // X-axis
            $axisXData = array_keys($series->getValues());
            for ($i = 0; $i < count($axisXData); $i++) {
                $sheet->setCellValueByColumnAndRow(0, $i + 2, $axisXData[$i]);
            }

            // Y-axis
            $axisYData = array_values($series->getValues());
            for ($i = 0; $i < count($axisYData); $i++) {
                $sheet->setCellValueByColumnAndRow(1 + $seriesIndex, $i + 2, $axisYData[$i]);
            }

            ++$seriesIndex;
        }

        // Save to string
        $writer = PHPExcel_IOFactory::createWriter($workbook, 'Excel2007');
        $writer->save($tempName);

        // Load file in memory
        $returnValue = file_get_contents($tempName);
        @unlink($tempName);

        return $returnValue;
    }

    /**
     * Write element with value attribute
     *
     * @param \PhpOffice\PhpPowerpoint\Shared\XMLWriter $objWriter   XML Writer
     * @param string                         $elementName
     * @param string                         $value
     */
    protected function writeElementWithValAttribute($objWriter, $elementName, $value)
    {
        $objWriter->startElement($elementName);
        $objWriter->writeAttribute('val', $value);
        $objWriter->endElement();
    }

    /**
     * Write single value or reference
     *
     * @param \PhpOffice\PhpPowerpoint\Shared\XMLWriter $objWriter   XML Writer
     * @param boolean                        $isReference
     * @param mixed                          $value
     * @param string                         $reference
     */
    protected function writeSingleValueOrReference($objWriter, $isReference, $value, $reference)
    {
        if (!$isReference) {
            // Value
            $objWriter->writeElement('c:v', $value);
        } else {
            // Reference and cache
            $objWriter->startElement('c:strRef');
            $objWriter->writeElement('c:f', $reference);
            $objWriter->startElement('c:strCache');
            $objWriter->startElement('c:ptCount');
            $objWriter->writeAttribute('val', '1');
            $objWriter->endElement();

            $objWriter->startElement('c:pt');
            $objWriter->writeAttribute('idx', '0');
            $objWriter->writeElement('c:v', $value);
            $objWriter->endElement();
            $objWriter->endElement();
            $objWriter->endElement();
        }
    }

    /**
     * Write series value or reference
     *
     * @param \PhpOffice\PhpPowerpoint\Shared\XMLWriter $objWriter   XML Writer
     * @param boolean                        $isReference
     * @param mixed                          $values
     * @param string                         $reference
     */
    protected function writeMultipleValuesOrReference($objWriter, $isReference, $values, $reference)
    {
        // c:strLit / c:numLit
        // c:strRef / c:numRef
        $referenceType = ($isReference ? 'Ref' : 'Lit');
        if (is_int($values[0]) || is_float($values[0])) {
            $dataType = 'num';
        } else {
            $dataType = 'str';
        }
        $objWriter->startElement('c:' . $dataType . $referenceType);

        if (!$isReference) {
            // Value

            // c:ptCount
            $objWriter->startElement('c:ptCount');
            $objWriter->writeAttribute('val', count($values));
            $objWriter->endElement();

            // Add points
            for ($i = 0; $i < count($values); $i++) {
                // c:pt
                $objWriter->startElement('c:pt');
                $objWriter->writeAttribute('idx', $i);
                $objWriter->writeElement('c:v', $values[$i]);
                $objWriter->endElement();
            }
        } else {
            // Reference
            $objWriter->writeElement('c:f', $reference);
            $objWriter->startElement('c:' . $dataType . 'Cache');

            // c:ptCount
            $objWriter->startElement('c:ptCount');
            $objWriter->writeAttribute('val', count($values));
            $objWriter->endElement();

            // Add points
            for ($i = 0; $i < count($values); $i++) {
                // c:pt
                $objWriter->startElement('c:pt');
                $objWriter->writeAttribute('idx', $i);
                $objWriter->writeElement('c:v', $values[$i]);
                $objWriter->endElement();
            }

            $objWriter->endElement();
        }

        $objWriter->endElement();
    }

    /**
     * Write Title
     *
     * @param  \PhpOffice\PhpPowerpoint\Shared\XMLWriter  $objWriter XML Writer
     * @param  \PhpOffice\PhpPowerpoint\Shape\Chart\Title $subject
     * @throws \Exception
     */
    protected function writeTitle(XMLWriter $objWriter, Title $subject)
    {
        // c:title
        $objWriter->startElement('c:title');

        // c:tx
        $objWriter->startElement('c:tx');

        // c:rich
        $objWriter->startElement('c:rich');

        // a:bodyPr
        $objWriter->writeElement('a:bodyPr', null);

        // a:lstStyle
        $objWriter->writeElement('a:lstStyle', null);

        // a:p
        $objWriter->startElement('a:p');

        // a:pPr
        $objWriter->startElement('a:pPr');
        $objWriter->writeAttribute('algn', $subject->getAlignment()->getHorizontal());
        $objWriter->writeAttribute('fontAlgn', $subject->getAlignment()->getVertical());
        $objWriter->writeAttribute('marL', SharedDrawing::pixelsToEmu($subject->getAlignment()->getMarginLeft()));
        $objWriter->writeAttribute('marR', SharedDrawing::pixelsToEmu($subject->getAlignment()->getMarginRight()));
        $objWriter->writeAttribute('indent', SharedDrawing::pixelsToEmu($subject->getAlignment()->getIndent()));
        $objWriter->writeAttribute('lvl', $subject->getAlignment()->getLevel());

        // a:defRPr
        $objWriter->writeElement('a:defRPr', null);

        $objWriter->endElement();

        // a:r
        $objWriter->startElement('a:r');

        // a:rPr
        $objWriter->startElement('a:rPr');
        $objWriter->writeAttribute('lang', 'en-US');
        $objWriter->writeAttribute('dirty', '0');

        $objWriter->writeAttribute('b', ($subject->getFont()->isBold() ? 'true' : 'false'));
        $objWriter->writeAttribute('i', ($subject->getFont()->isItalic() ? 'true' : 'false'));
        $objWriter->writeAttribute('strike', ($subject->getFont()->isStrikethrough() ? 'sngStrike' : 'noStrike'));
        $objWriter->writeAttribute('sz', ($subject->getFont()->getSize() * 100));
        $objWriter->writeAttribute('u', $subject->getFont()->getUnderline());

        if ($subject->getFont()->isSuperScript() || $subject->getFont()->isSubScript()) {
            if ($subject->getFont()->isSuperScript()) {
                $objWriter->writeAttribute('baseline', '30000');
            } elseif ($subject->getFont()->isSubScript()) {
                $objWriter->writeAttribute('baseline', '-25000');
            }
        }

        // Font - a:solidFill
        $objWriter->startElement('a:solidFill');

        // a:srgbClr
        $objWriter->startElement('a:srgbClr');
        $objWriter->writeAttribute('val', $subject->getFont()->getColor()->getRGB());
        $objWriter->endElement();

        $objWriter->endElement();

        // Font - a:latin
        $objWriter->startElement('a:latin');
        $objWriter->writeAttribute('typeface', $subject->getFont()->getName());
        $objWriter->endElement();

        $objWriter->endElement();

        // a:t
        $objWriter->writeElement('a:t', $subject->getText());

        $objWriter->endElement();

        // a:endParaRPr
        $objWriter->startElement('a:endParaRPr');
        $objWriter->writeAttribute('lang', 'en-US');
        $objWriter->writeAttribute('dirty', '0');
        $objWriter->endElement();

        $objWriter->endElement();

        $objWriter->endElement();

        $objWriter->endElement();

        // Write layout
        $this->writeLayout($objWriter, $subject);

        // c:overlay
        $objWriter->startElement('c:overlay');
        $objWriter->writeAttribute('val', '0');
        $objWriter->endElement();

        $objWriter->endElement();
    }

    /**
     * Write Plot Area
     *
     * @param  \PhpOffice\PhpPowerpoint\Shared\XMLWriter     $objWriter XML Writer
     * @param  \PhpOffice\PhpPowerpoint\Shape\Chart\PlotArea $subject
     * @param  \PhpOffice\PhpPowerpoint\Shape\Chart          $chart
     * @throws \Exception
     */
    protected function writePlotArea(XMLWriter $objWriter, PlotArea $subject, ShapeChart $chart)
    {
        // c:plotArea
        $objWriter->startElement('c:plotArea');

        // Write layout
        $this->writeLayout($objWriter, $subject);

        // Write chart
        $chartType = $subject->getType();
        if ($chartType instanceof Bar3D) {
            $this->writeTypeBar3D($objWriter, $chartType, $chart->hasIncludedSpreadsheet());
        } elseif ($chartType instanceof Pie3D) {
            $this->writeTypePie3D($objWriter, $chartType, $chart->hasIncludedSpreadsheet());
        } elseif ($chartType instanceof Line) {
            $this->writeTypeLine($objWriter, $chartType, $chart->hasIncludedSpreadsheet());
        } elseif ($chartType instanceof Scatter) {
            $this->writeTypeScatter($objWriter, $chartType, $chart->hasIncludedSpreadsheet());
        } else {
            throw new \Exception('The chart type provided could not be rendered.');
        }

        // Write X axis?
        if ($chartType->hasAxisX()) {
            // c:catAx (Axis X)
            $objWriter->startElement('c:catAx');

            // c:axId
            $objWriter->startElement('c:axId');
            $objWriter->writeAttribute('val', '52743552');
            $objWriter->endElement();

            // c:scaling
            $objWriter->startElement('c:scaling');

            // c:orientation
            $objWriter->startElement('c:orientation');
            $objWriter->writeAttribute('val', 'minMax');
            $objWriter->endElement();

            $objWriter->endElement();

            // c:axPos
            $objWriter->startElement('c:axPos');
            $objWriter->writeAttribute('val', 'b');
            $objWriter->endElement();

            // c:numFmt
            $objWriter->startElement('c:numFmt');
            $objWriter->writeAttribute('formatCode', $subject->getAxisX()->getFormatCode());
            $objWriter->writeAttribute('sourceLinked', '0');
            $objWriter->endElement();

            // c:majorTickMark
            $objWriter->startElement('c:majorTickMark');
            $objWriter->writeAttribute('val', 'none');
            $objWriter->endElement();

            // c:tickLblPos
            $objWriter->startElement('c:tickLblPos');
            $objWriter->writeAttribute('val', 'nextTo');
            $objWriter->endElement();

            // c:txPr
            $objWriter->startElement('c:txPr');

            // a:bodyPr
            $objWriter->writeElement('a:bodyPr', null);

            // a:lstStyle
            $objWriter->writeElement('a:lstStyle', null);

            // a:p
            $objWriter->startElement('a:p');

            // a:pPr
            $objWriter->startElement('a:pPr');

            // a:defRPr
            $objWriter->writeElement('a:defRPr', null);

            $objWriter->endElement();

            // a:r
            $objWriter->startElement('a:r');

            // a:rPr
            $objWriter->startElement('a:rPr');
            $objWriter->writeAttribute('lang', 'en-US');
            $objWriter->writeAttribute('dirty', '0');
            $objWriter->endElement();

            // a:t
            $objWriter->writeElement('a:t', $subject->getAxisX()->getTitle());

            $objWriter->endElement();

            // a:endParaRPr
            $objWriter->startElement('a:endParaRPr');
            $objWriter->writeAttribute('lang', 'en-US');
            $objWriter->writeAttribute('dirty', '0');
            $objWriter->endElement();

            $objWriter->endElement();

            $objWriter->endElement();

            // c:crossAx
            $objWriter->startElement('c:crossAx');
            $objWriter->writeAttribute('val', '52749440');
            $objWriter->endElement();

            // c:crosses
            $objWriter->startElement('c:crosses');
            $objWriter->writeAttribute('val', 'autoZero');
            $objWriter->endElement();

            // c:lblAlgn
            $objWriter->startElement('c:lblAlgn');
            $objWriter->writeAttribute('val', 'ctr');
            $objWriter->endElement();

            // c:lblOffset
            $objWriter->startElement('c:lblOffset');
            $objWriter->writeAttribute('val', '100');
            $objWriter->endElement();

            $objWriter->endElement();
        }

        // Write Y axis?
        if ($chartType->hasAxisY()) {
            // c:valAx (Axis Y)
            $objWriter->startElement('c:valAx');

            // c:axId
            $objWriter->startElement('c:axId');
            $objWriter->writeAttribute('val', '52749440');
            $objWriter->endElement();

            // c:scaling
            $objWriter->startElement('c:scaling');

            // c:orientation
            $objWriter->startElement('c:orientation');
            $objWriter->writeAttribute('val', 'minMax');
            $objWriter->endElement();

            $objWriter->endElement();

            // c:axPos
            $objWriter->startElement('c:axPos');
            $objWriter->writeAttribute('val', 'l');
            $objWriter->endElement();

            // c:numFmt
            $objWriter->startElement('c:numFmt');
            $objWriter->writeAttribute('formatCode', $subject->getAxisY()->getFormatCode());
            $objWriter->writeAttribute('sourceLinked', '0');
            $objWriter->endElement();

            // c:majorGridlines
            //$objWriter->startElement('c:majorGridlines');
            //$objWriter->endElement();

            // c:majorTickMark
            $objWriter->startElement('c:majorTickMark');
            $objWriter->writeAttribute('val', 'none');
            $objWriter->endElement();

            // c:tickLblPos
            $objWriter->startElement('c:tickLblPos');
            $objWriter->writeAttribute('val', 'nextTo');
            $objWriter->endElement();

            // c:txPr
            $objWriter->startElement('c:txPr');

            // a:bodyPr
            $objWriter->writeElement('a:bodyPr', null);

            // a:lstStyle
            $objWriter->writeElement('a:lstStyle', null);

            // a:p
            $objWriter->startElement('a:p');

            // a:pPr
            $objWriter->startElement('a:pPr');

            // a:defRPr
            $objWriter->writeElement('a:defRPr', null);

            $objWriter->endElement();

            // a:r
            $objWriter->startElement('a:r');

            // a:rPr
            $objWriter->startElement('a:rPr');
            $objWriter->writeAttribute('lang', 'en-US');
            $objWriter->writeAttribute('dirty', '0');
            $objWriter->endElement();

            // a:t
            $objWriter->writeElement('a:t', $subject->getAxisY()->getTitle());

            $objWriter->endElement();

            // a:endParaRPr
            $objWriter->startElement('a:endParaRPr');
            $objWriter->writeAttribute('lang', 'en-US');
            $objWriter->writeAttribute('dirty', '0');
            $objWriter->endElement();

            $objWriter->endElement();

            $objWriter->endElement();

            // c:crossAx
            $objWriter->startElement('c:crossAx');
            $objWriter->writeAttribute('val', '52743552');
            $objWriter->endElement();

            // c:crosses
            $objWriter->startElement('c:crosses');
            $objWriter->writeAttribute('val', 'autoZero');
            $objWriter->endElement();

            // c:crossBetween
            $objWriter->startElement('c:crossBetween');
            $objWriter->writeAttribute('val', 'between');
            $objWriter->endElement();

            $objWriter->endElement();
        }

        $objWriter->endElement();
    }

    /**
     * Write Legend
     *
     * @param  \PhpOffice\PhpPowerpoint\Shared\XMLWriter   $objWriter XML Writer
     * @param  \PhpOffice\PhpPowerpoint\Shape\Chart\Legend $subject
     * @throws \Exception
     */
    protected function writeLegend(XMLWriter $objWriter, Legend $subject)
    {
        // c:legend
        $objWriter->startElement('c:legend');

        // c:legendPos
        $objWriter->startElement('c:legendPos');
        $objWriter->writeAttribute('val', $subject->getPosition());
        $objWriter->endElement();

        // Write layout
        $this->writeLayout($objWriter, $subject);

        // c:overlay
        $objWriter->startElement('c:overlay');
        $objWriter->writeAttribute('val', '0');
        $objWriter->endElement();

        // c:spPr
        $objWriter->startElement('c:spPr');

        // Fill
        $this->writeFill($objWriter, $subject->getFill());

        // Border
        if ($subject->getBorder()->getLineStyle() != Border::LINE_NONE) {
            $this->writeBorder($objWriter, $subject->getBorder(), '');
        }

        $objWriter->endElement();

        // c:txPr
        $objWriter->startElement('c:txPr');

        // a:bodyPr
        $objWriter->writeElement('a:bodyPr', null);

        // a:lstStyle
        $objWriter->writeElement('a:lstStyle', null);

        // a:p
        $objWriter->startElement('a:p');

        // a:pPr
        $objWriter->startElement('a:pPr');
        $objWriter->writeAttribute('algn', $subject->getAlignment()->getHorizontal());
        $objWriter->writeAttribute('fontAlgn', $subject->getAlignment()->getVertical());
        $objWriter->writeAttribute('marL', SharedDrawing::pixelsToEmu($subject->getAlignment()->getMarginLeft()));
        $objWriter->writeAttribute('marR', SharedDrawing::pixelsToEmu($subject->getAlignment()->getMarginRight()));
        $objWriter->writeAttribute('indent', SharedDrawing::pixelsToEmu($subject->getAlignment()->getIndent()));
        $objWriter->writeAttribute('lvl', $subject->getAlignment()->getLevel());

        // a:defRPr
        $objWriter->startElement('a:defRPr');

        $objWriter->writeAttribute('b', ($subject->getFont()->isBold() ? 'true' : 'false'));
        $objWriter->writeAttribute('i', ($subject->getFont()->isItalic() ? 'true' : 'false'));
        $objWriter->writeAttribute('strike', ($subject->getFont()->isStrikethrough() ? 'sngStrike' : 'noStrike'));
        $objWriter->writeAttribute('sz', ($subject->getFont()->getSize() * 100));
        $objWriter->writeAttribute('u', $subject->getFont()->getUnderline());

        if ($subject->getFont()->isSuperScript() || $subject->getFont()->isSubScript()) {
            if ($subject->getFont()->isSuperScript()) {
                $objWriter->writeAttribute('baseline', '30000');
            } elseif ($subject->getFont()->isSubScript()) {
                $objWriter->writeAttribute('baseline', '-25000');
            }
        }

        // Font - a:solidFill
        $objWriter->startElement('a:solidFill');

        // a:srgbClr
        $objWriter->startElement('a:srgbClr');
        $objWriter->writeAttribute('val', $subject->getFont()->getColor()->getRGB());
        $objWriter->endElement();

        $objWriter->endElement();

        // Font - a:latin
        $objWriter->startElement('a:latin');
        $objWriter->writeAttribute('typeface', $subject->getFont()->getName());
        $objWriter->endElement();

        $objWriter->endElement();

        $objWriter->endElement();

        // a:endParaRPr
        $objWriter->startElement('a:endParaRPr');
        $objWriter->writeAttribute('lang', 'en-US');
        $objWriter->writeAttribute('dirty', '0');
        $objWriter->endElement();

        $objWriter->endElement();

        $objWriter->endElement();

        $objWriter->endElement();
    }

    /**
     * Write Layout
     *
     * @param  \PhpOffice\PhpPowerpoint\Shared\XMLWriter $objWriter XML Writer
     * @param  mixed                          $subject
     * @throws \Exception
     */
    protected function writeLayout(XMLWriter $objWriter, $subject)
    {
        // c:layout
        $objWriter->startElement('c:layout');

        // c:manualLayout
        $objWriter->startElement('c:manualLayout');
        // c:xMode
        $objWriter->startElement('c:xMode');
        $objWriter->writeAttribute('val', 'edge');
        $objWriter->endElement();

        // c:yMode
        $objWriter->startElement('c:yMode');
        $objWriter->writeAttribute('val', 'edge');
        $objWriter->endElement();

        if ($subject->getOffsetX() != 0) {
            // c:x
            $objWriter->startElement('c:x');
            $objWriter->writeAttribute('val', $subject->getOffsetX());
            $objWriter->endElement();
        }

        if ($subject->getOffsetY() != 0) {
            // c:y
            $objWriter->startElement('c:y');
            $objWriter->writeAttribute('val', $subject->getOffsetY());
            $objWriter->endElement();
        }

        if ($subject->getWidth() != 0) {
            // c:w
            $objWriter->startElement('c:w');
            $objWriter->writeAttribute('val', $subject->getWidth());
            $objWriter->endElement();
        }

        if ($subject->getHeight() != 0) {
            // c:h
            $objWriter->startElement('c:h');
            $objWriter->writeAttribute('val', $subject->getHeight());
            $objWriter->endElement();
        }

        $objWriter->endElement();
        $objWriter->endElement();
    }

    /**
     * Write Type Bar3D
     *
     * @param  \PhpOffice\PhpPowerpoint\Shared\XMLWriter       $objWriter    XML Writer
     * @param  \PhpOffice\PhpPowerpoint\Shape\Chart\Type\Bar3D $subject
     * @param  boolean                              $includeSheet
     * @throws \Exception
     */
    protected function writeTypeBar3D(XMLWriter $objWriter, Bar3D $subject, $includeSheet = false)
    {
        // c:bar3DChart
        $objWriter->startElement('c:bar3DChart');

        // c:barDir
        $objWriter->startElement('c:barDir');
        $objWriter->writeAttribute('val', 'col');
        $objWriter->endElement();

        // c:grouping
        $objWriter->startElement('c:grouping');
        $objWriter->writeAttribute('val', 'clustered');
        $objWriter->endElement();

        // Write series
        $seriesIndex = 0;
        foreach ($subject->getData() as $series) {
            // c:ser
            $objWriter->startElement('c:ser');

            // c:idx
            $objWriter->startElement('c:idx');
            $objWriter->writeAttribute('val', $seriesIndex);
            $objWriter->endElement();

            // c:order
            $objWriter->startElement('c:order');
            $objWriter->writeAttribute('val', $seriesIndex);
            $objWriter->endElement();

            // c:tx
            $objWriter->startElement('c:tx');
            $coords = ($includeSheet ? 'Sheet1!$' . PHPExcel_Cell::stringFromColumnIndex(1 + $seriesIndex) . '$1' : '');
            $this->writeSingleValueOrReference($objWriter, $includeSheet, $series->getTitle(), $coords);
            $objWriter->endElement();

            // Fills for points?
            $dataPointFills = $series->getDataPointFills();
            foreach ($dataPointFills as $key => $value) {
                // c:dPt
                $objWriter->startElement('c:dPt');

                // c:idx
                $this->writeElementWithValAttribute($objWriter, 'c:idx', $key);

                // c:spPr
                $objWriter->startElement('c:spPr');

                // Write fill
                $this->writeFill($objWriter, $value);

                $objWriter->endElement();

                $objWriter->endElement();
            }

            // c:dLbls
            $objWriter->startElement('c:dLbls');

            // c:txPr
            $objWriter->startElement('c:txPr');

            // a:bodyPr
            $objWriter->writeElement('a:bodyPr', null);

            // a:lstStyle
            $objWriter->writeElement('a:lstStyle', null);

            // a:p
            $objWriter->startElement('a:p');

            // a:pPr
            $objWriter->startElement('a:pPr');

            // a:defRPr
            $objWriter->startElement('a:defRPr');

            $objWriter->writeAttribute('b', ($series->getFont()->isBold() ? 'true' : 'false'));
            $objWriter->writeAttribute('i', ($series->getFont()->isItalic() ? 'true' : 'false'));
            $objWriter->writeAttribute('strike', ($series->getFont()->isStrikethrough() ? 'sngStrike' : 'noStrike'));
            $objWriter->writeAttribute('sz', ($series->getFont()->getSize() * 100));
            $objWriter->writeAttribute('u', $series->getFont()->getUnderline());

            if ($series->getFont()->isSuperScript() || $series->getFont()->isSubScript()) {
                if ($series->getFont()->isSuperScript()) {
                    $objWriter->writeAttribute('baseline', '30000');
                } elseif ($series->getFont()->isSubScript()) {
                    $objWriter->writeAttribute('baseline', '-25000');
                }
            }

            // Font - a:solidFill
            $objWriter->startElement('a:solidFill');

            // a:srgbClr
            $objWriter->startElement('a:srgbClr');
            $objWriter->writeAttribute('val', $series->getFont()->getColor()->getRGB());
            $objWriter->endElement();

            $objWriter->endElement();

            // Font - a:latin
            $objWriter->startElement('a:latin');
            $objWriter->writeAttribute('typeface', $series->getFont()->getName());
            $objWriter->endElement();

            $objWriter->endElement();

            $objWriter->endElement();

            // a:endParaRPr
            $objWriter->startElement('a:endParaRPr');
            $objWriter->writeAttribute('lang', 'en-US');
            $objWriter->writeAttribute('dirty', '0');
            $objWriter->endElement();

            $objWriter->endElement();

            $objWriter->endElement();

            // c:showVal
            $this->writeElementWithValAttribute($objWriter, 'c:showVal', $series->hasShowValue() ? '1' : '0');

            // c:showCatName
            $this->writeElementWithValAttribute($objWriter, 'c:showCatName', $series->hasShowCategoryName() ? '1' : '0');

            // c:showSerName
            $this->writeElementWithValAttribute($objWriter, 'c:showSerName', $series->hasShowSeriesName() ? '1' : '0');

            // c:showPercent
            $this->writeElementWithValAttribute($objWriter, 'c:showPercent', $series->hasShowPercentage() ? '1' : '0');

            // c:showLeaderLines
            $this->writeElementWithValAttribute($objWriter, 'c:showLeaderLines', $series->hasShowLeaderLines() ? '1' : '0');

            $objWriter->endElement();

            // c:spPr
            $objWriter->startElement('c:spPr');

            // Write fill
            $this->writeFill($objWriter, $series->getFill());

            $objWriter->endElement();

            // Write X axis data
            $axisXData = array_keys($series->getValues());

            // c:cat
            $objWriter->startElement('c:cat');
            $this->writeMultipleValuesOrReference($objWriter, $includeSheet, $axisXData, 'Sheet1!$A$2:$A$' . (1 + count($axisXData)));
            $objWriter->endElement();

            // Write Y axis data
            $axisYData = array_values($series->getValues());

            // c:val
            $objWriter->startElement('c:val');
            $coords = ($includeSheet ? 'Sheet1!$' . PHPExcel_Cell::stringFromColumnIndex($seriesIndex + 1) . '$2:$' . PHPExcel_Cell::stringFromColumnIndex($seriesIndex + 1) . '$' . (1 + count($axisYData)) : '');
            $this->writeMultipleValuesOrReference($objWriter, $includeSheet, $axisYData, $coords);
            $objWriter->endElement();

            $objWriter->endElement();

            ++$seriesIndex;
        }

        // c:gapWidth
        $objWriter->startElement('c:gapWidth');
        $objWriter->writeAttribute('val', '75');
        $objWriter->endElement();

        // c:shape
        $objWriter->startElement('c:shape');
        $objWriter->writeAttribute('val', 'box');
        $objWriter->endElement();

        // c:axId
        $objWriter->startElement('c:axId');
        $objWriter->writeAttribute('val', '52743552');
        $objWriter->endElement();

        // c:axId
        $objWriter->startElement('c:axId');
        $objWriter->writeAttribute('val', '52749440');
        $objWriter->endElement();

        // c:axId
        $objWriter->startElement('c:axId');
        $objWriter->writeAttribute('val', '0');
        $objWriter->endElement();

        $objWriter->endElement();
    }

    /**
     * Write Type Pie3D
     *
     * @param  \PhpOffice\PhpPowerpoint\Shared\XMLWriter       $objWriter    XML Writer
     * @param  \PhpOffice\PhpPowerpoint\Shape\Chart\Type\Pie3D $subject
     * @param  boolean                              $includeSheet
     * @throws \Exception
     */
    protected function writeTypePie3D(XMLWriter $objWriter, Pie3D $subject, $includeSheet = false)
    {
        // c:pie3DChart
        $objWriter->startElement('c:pie3DChart');

        // c:varyColors
        $objWriter->startElement('c:varyColors');
        $objWriter->writeAttribute('val', '1');
        $objWriter->endElement();

        // Write series
        $seriesIndex = 0;
        foreach ($subject->getData() as $series) {
            // c:ser
            $objWriter->startElement('c:ser');

            // c:idx
            $objWriter->startElement('c:idx');
            $objWriter->writeAttribute('val', $seriesIndex);
            $objWriter->endElement();

            // c:order
            $objWriter->startElement('c:order');
            $objWriter->writeAttribute('val', $seriesIndex);
            $objWriter->endElement();

            // c:tx
            $objWriter->startElement('c:tx');
            $coords = ($includeSheet ? 'Sheet1!$' . PHPExcel_Cell::stringFromColumnIndex(1 + $seriesIndex) . '$1' : '');
            $this->writeSingleValueOrReference($objWriter, $includeSheet, $series->getTitle(), $coords);
            $objWriter->endElement();

            // c:explosion
            $objWriter->startElement('c:explosion');
            $objWriter->writeAttribute('val', '20');
            $objWriter->endElement();

            // Fills for points?
            $dataPointFills = $series->getDataPointFills();
            foreach ($dataPointFills as $key => $value) {
                // c:dPt
                $objWriter->startElement('c:dPt');

                // c:idx
                $this->writeElementWithValAttribute($objWriter, 'c:idx', $key);

                // c:spPr
                $objWriter->startElement('c:spPr');

                // Write fill
                $this->writeFill($objWriter, $value);

                $objWriter->endElement();

                $objWriter->endElement();
            }

            // c:dLbls
            $objWriter->startElement('c:dLbls');

            // c:txPr
            $objWriter->startElement('c:txPr');

            // a:bodyPr
            $objWriter->writeElement('a:bodyPr', null);

            // a:lstStyle
            $objWriter->writeElement('a:lstStyle', null);

            // a:p
            $objWriter->startElement('a:p');

            // a:pPr
            $objWriter->startElement('a:pPr');

            // a:defRPr
            $objWriter->startElement('a:defRPr');

            $objWriter->writeAttribute('b', ($series->getFont()->isBold() ? 'true' : 'false'));
            $objWriter->writeAttribute('i', ($series->getFont()->isItalic() ? 'true' : 'false'));
            $objWriter->writeAttribute('strike', ($series->getFont()->isStrikethrough() ? 'sngStrike' : 'noStrike'));
            $objWriter->writeAttribute('sz', ($series->getFont()->getSize() * 100));
            $objWriter->writeAttribute('u', $series->getFont()->getUnderline());

            if ($series->getFont()->isSuperScript() || $series->getFont()->isSubScript()) {
                if ($series->getFont()->isSuperScript()) {
                    $objWriter->writeAttribute('baseline', '30000');
                } elseif ($series->getFont()->isSubScript()) {
                    $objWriter->writeAttribute('baseline', '-25000');
                }
            }

            // Font - a:solidFill
            $objWriter->startElement('a:solidFill');

            // a:srgbClr
            $objWriter->startElement('a:srgbClr');
            $objWriter->writeAttribute('val', $series->getFont()->getColor()->getRGB());
            $objWriter->endElement();

            $objWriter->endElement();

            // Font - a:latin
            $objWriter->startElement('a:latin');
            $objWriter->writeAttribute('typeface', $series->getFont()->getName());
            $objWriter->endElement();

            $objWriter->endElement();

            $objWriter->endElement();

            // a:endParaRPr
            $objWriter->startElement('a:endParaRPr');
            $objWriter->writeAttribute('lang', 'en-US');
            $objWriter->writeAttribute('dirty', '0');
            $objWriter->endElement();

            $objWriter->endElement();

            $objWriter->endElement();

            // c:dLblPos
            $this->writeElementWithValAttribute($objWriter, 'c:dLblPos', $series->getLabelPosition());

            // c:showVal
            $this->writeElementWithValAttribute($objWriter, 'c:showVal', $series->hasShowValue() ? '1' : '0');

            // c:showCatName
            $this->writeElementWithValAttribute($objWriter, 'c:showCatName', $series->hasShowCategoryName() ? '1' : '0');

            // c:showSerName
            $this->writeElementWithValAttribute($objWriter, 'c:showSerName', $series->hasShowSeriesName() ? '1' : '0');

            // c:showPercent
            $this->writeElementWithValAttribute($objWriter, 'c:showPercent', $series->hasShowPercentage() ? '1' : '0');

            // c:showLeaderLines
            $this->writeElementWithValAttribute($objWriter, 'c:showLeaderLines', $series->hasShowLeaderLines() ? '1' : '0');

            $objWriter->endElement();

            // Write X axis data
            $axisXData = array_keys($series->getValues());

            // c:cat
            $objWriter->startElement('c:cat');
            $this->writeMultipleValuesOrReference($objWriter, $includeSheet, $axisXData, 'Sheet1!$A$2:$A$' . (1 + count($axisXData)));
            $objWriter->endElement();

            // Write Y axis data
            $axisYData = array_values($series->getValues());

            // c:val
            $objWriter->startElement('c:val');
            $coords = ($includeSheet ? 'Sheet1!$' . PHPExcel_Cell::stringFromColumnIndex($seriesIndex + 1) . '$2:$' . PHPExcel_Cell::stringFromColumnIndex($seriesIndex + 1) . '$' . (1 + count($axisYData)) : '');
            $this->writeMultipleValuesOrReference($objWriter, $includeSheet, $axisYData, $coords);
            $objWriter->endElement();

            $objWriter->endElement();

            ++$seriesIndex;
        }

        $objWriter->endElement();
    }

    /**
     * Write Type Line
     *
     * @param  \PhpOffice\PhpPowerpoint\Shared\XMLWriter      $objWriter    XML Writer
     * @param  \PhpOffice\PhpPowerpoint\Shape\Chart\Type\Line $subject
     * @param  boolean                             $includeSheet
     * @throws \Exception
     */
    protected function writeTypeLine(XMLWriter $objWriter, Line $subject, $includeSheet = false)
    {
        // c:lineChart
        $objWriter->startElement('c:lineChart');

        // c:grouping
        $objWriter->startElement('c:grouping');
        $objWriter->writeAttribute('val', 'standard');
        $objWriter->endElement();

        // c:varyColors
        $objWriter->startElement('c:varyColors');
        $objWriter->writeAttribute('val', '0');
        $objWriter->endElement();

        // Write series
        $seriesIndex = 0;
        foreach ($subject->getData() as $series) {
            // c:ser
            $objWriter->startElement('c:ser');

            // c:idx
            $objWriter->startElement('c:idx');
            $objWriter->writeAttribute('val', $seriesIndex);
            $objWriter->endElement();

            // c:order
            $objWriter->startElement('c:order');
            $objWriter->writeAttribute('val', $seriesIndex);
            $objWriter->endElement();

            // c:tx
            $objWriter->startElement('c:tx');
            $coords = ($includeSheet ? 'Sheet1!$' . PHPExcel_Cell::stringFromColumnIndex(1 + $seriesIndex) . '$1' : '');
            $this->writeSingleValueOrReference($objWriter, $includeSheet, $series->getTitle(), $coords);
            $objWriter->endElement();

            // c:dLbls
            $objWriter->startElement('c:dLbls');

            // c:txPr
            $objWriter->startElement('c:txPr');

            // a:bodyPr
            $objWriter->writeElement('a:bodyPr', null);

            // a:lstStyle
            $objWriter->writeElement('a:lstStyle', null);

            // a:p
            $objWriter->startElement('a:p');

            // a:pPr
            $objWriter->startElement('a:pPr');

            // a:defRPr
            $objWriter->startElement('a:defRPr');

            $objWriter->writeAttribute('b', ($series->getFont()->isBold() ? 'true' : 'false'));
            $objWriter->writeAttribute('i', ($series->getFont()->isItalic() ? 'true' : 'false'));
            $objWriter->writeAttribute('strike', ($series->getFont()->isStrikethrough() ? 'sngStrike' : 'noStrike'));
            $objWriter->writeAttribute('sz', ($series->getFont()->getSize() * 100));
            $objWriter->writeAttribute('u', $series->getFont()->getUnderline());

            if ($series->getFont()->isSuperScript() || $series->getFont()->isSubScript()) {
                if ($series->getFont()->isSuperScript()) {
                    $objWriter->writeAttribute('baseline', '30000');
                } elseif ($series->getFont()->isSubScript()) {
                    $objWriter->writeAttribute('baseline', '-25000');
                }
            }

            // Font - a:solidFill
            $objWriter->startElement('a:solidFill');

            // a:srgbClr
            $objWriter->startElement('a:srgbClr');
            $objWriter->writeAttribute('val', $series->getFont()->getColor()->getRGB());
            $objWriter->endElement();

            $objWriter->endElement();

            // Font - a:latin
            $objWriter->startElement('a:latin');
            $objWriter->writeAttribute('typeface', $series->getFont()->getName());
            $objWriter->endElement();

            $objWriter->endElement();

            $objWriter->endElement();

            // a:endParaRPr
            $objWriter->startElement('a:endParaRPr');
            $objWriter->writeAttribute('lang', 'en-US');
            $objWriter->writeAttribute('dirty', '0');
            $objWriter->endElement();

            $objWriter->endElement();

            $objWriter->endElement();

            // c:showVal
            $this->writeElementWithValAttribute($objWriter, 'c:showVal', $series->hasShowValue() ? '1' : '0');

            // c:showCatName
            $this->writeElementWithValAttribute($objWriter, 'c:showCatName', $series->hasShowCategoryName() ? '1' : '0');

            // c:showSerName
            $this->writeElementWithValAttribute($objWriter, 'c:showSerName', $series->hasShowSeriesName() ? '1' : '0');

            // c:showPercent
            $this->writeElementWithValAttribute($objWriter, 'c:showPercent', $series->hasShowPercentage() ? '1' : '0');

            // c:showLeaderLines
            $this->writeElementWithValAttribute($objWriter, 'c:showLeaderLines', $series->hasShowLeaderLines() ? '1' : '0');

            $objWriter->endElement();

            // c:spPr
            $objWriter->startElement('c:spPr');

            // Write fill
            $this->writeFill($objWriter, $series->getFill());

            $objWriter->endElement();

            // Write X axis data
            $axisXData = array_keys($series->getValues());

            // c:cat
            $objWriter->startElement('c:cat');
            $this->writeMultipleValuesOrReference($objWriter, $includeSheet, $axisXData, 'Sheet1!$A$2:$A$' . (1 + count($axisXData)));
            $objWriter->endElement();

            // Write Y axis data
            $axisYData = array_values($series->getValues());

            // c:val
            $objWriter->startElement('c:val');
            $coords = ($includeSheet ? 'Sheet1!$' . PHPExcel_Cell::stringFromColumnIndex($seriesIndex + 1) . '$2:$' . PHPExcel_Cell::stringFromColumnIndex($seriesIndex + 1) . '$' . (1 + count($axisYData)) : '');
            $this->writeMultipleValuesOrReference($objWriter, $includeSheet, $axisYData, $coords);
            $objWriter->endElement();

            $objWriter->endElement();

            ++$seriesIndex;
        }

        // c:marker
        $objWriter->startElement('c:marker');
        $objWriter->writeAttribute('val', '1');
        $objWriter->endElement();

        // c:smooth
        $objWriter->startElement('c:smooth');
        $objWriter->writeAttribute('val', '0');
        $objWriter->endElement();

        // c:axId
        $objWriter->startElement('c:axId');
        $objWriter->writeAttribute('val', '52743552');
        $objWriter->endElement();

        // c:axId
        $objWriter->startElement('c:axId');
        $objWriter->writeAttribute('val', '52749440');
        $objWriter->endElement();

        // c:axId
        $objWriter->startElement('c:axId');
        $objWriter->writeAttribute('val', '0');
        $objWriter->endElement();

        $objWriter->endElement();
    }

    /**
     * Write Type Scatter
     *
     * @param  \PhpOffice\PhpPowerpoint\Shared\XMLWriter         $objWriter    XML Writer
     * @param  \PhpOffice\PhpPowerpoint\Shape\Chart\Type\Scatter $subject
     * @param  boolean                                $includeSheet
     * @throws \Exception
     */
    protected function writeTypeScatter(XMLWriter $objWriter, Scatter $subject, $includeSheet = false)
    {
        // c:scatterChart
        $objWriter->startElement('c:scatterChart');

        // c:scatterStyle
        $objWriter->startElement('c:scatterStyle');
        $objWriter->writeAttribute('val', 'lineMarker');
        $objWriter->endElement();

        // c:varyColors
        $objWriter->startElement('c:varyColors');
        $objWriter->writeAttribute('val', '0');
        $objWriter->endElement();

        // Write series
        $seriesIndex = 0;
        foreach ($subject->getData() as $series) {
            // c:ser
            $objWriter->startElement('c:ser');

            // c:idx
            $objWriter->startElement('c:idx');
            $objWriter->writeAttribute('val', $seriesIndex);
            $objWriter->endElement();

            // c:order
            $objWriter->startElement('c:order');
            $objWriter->writeAttribute('val', $seriesIndex);
            $objWriter->endElement();

            // c:tx
            $objWriter->startElement('c:tx');
            $coords = ($includeSheet ? 'Sheet1!$' . PHPExcel_Cell::stringFromColumnIndex(1 + $seriesIndex) . '$1' : '');
            $this->writeSingleValueOrReference($objWriter, $includeSheet, $series->getTitle(), $coords);
            $objWriter->endElement();

            // c:marker
            $objWriter->startElement('c:marker');

            // c:marker
            $objWriter->startElement('c:symbol');
            $objWriter->writeAttribute('val', 'none'); // Marker style
            //$objWriter->writeAttribute('size', '7'); // Marker size
            $objWriter->endElement();

            $objWriter->endElement();

            // c:dLbls
            $objWriter->startElement('c:dLbls');

            // c:txPr
            $objWriter->startElement('c:txPr');

            // a:bodyPr
            $objWriter->writeElement('a:bodyPr', null);

            // a:lstStyle
            $objWriter->writeElement('a:lstStyle', null);

            // a:p
            $objWriter->startElement('a:p');

            // a:pPr
            $objWriter->startElement('a:pPr');

            // a:defRPr
            $objWriter->startElement('a:defRPr');

            $objWriter->writeAttribute('b', ($series->getFont()->isBold() ? 'true' : 'false'));
            $objWriter->writeAttribute('i', ($series->getFont()->isItalic() ? 'true' : 'false'));
            $objWriter->writeAttribute('strike', ($series->getFont()->isStrikethrough() ? 'sngStrike' : 'noStrike'));
            $objWriter->writeAttribute('sz', ($series->getFont()->getSize() * 100));
            $objWriter->writeAttribute('u', $series->getFont()->getUnderline());

            if ($series->getFont()->isSuperScript() || $series->getFont()->isSubScript()) {
                if ($series->getFont()->isSuperScript()) {
                    $objWriter->writeAttribute('baseline', '30000');
                } elseif ($series->getFont()->isSubScript()) {
                    $objWriter->writeAttribute('baseline', '-25000');
                }
            }

            // Font - a:solidFill
            $objWriter->startElement('a:solidFill');

            // a:srgbClr
            $objWriter->startElement('a:srgbClr');
            $objWriter->writeAttribute('val', $series->getFont()->getColor()->getRGB());
            $objWriter->endElement();

            $objWriter->endElement();

            // Font - a:latin
            $objWriter->startElement('a:latin');
            $objWriter->writeAttribute('typeface', $series->getFont()->getName());
            $objWriter->endElement();

            $objWriter->endElement();

            $objWriter->endElement();

            // a:endParaRPr
            $objWriter->startElement('a:endParaRPr');
            $objWriter->writeAttribute('lang', 'en-US');
            $objWriter->writeAttribute('dirty', '0');
            $objWriter->endElement();

            $objWriter->endElement();

            $objWriter->endElement();

            // c:showLegendKey
            $this->writeElementWithValAttribute($objWriter, 'c:showLegendKey', '0');

            // c:showVal
            $this->writeElementWithValAttribute($objWriter, 'c:showVal', $series->hasShowValue() ? '1' : '0');

            // c:showCatName
            $this->writeElementWithValAttribute($objWriter, 'c:showCatName', $series->hasShowCategoryName() ? '1' : '0');

            // c:showSerName
            $this->writeElementWithValAttribute($objWriter, 'c:showSerName', $series->hasShowSeriesName() ? '1' : '0');

            // c:showPercent
            $this->writeElementWithValAttribute($objWriter, 'c:showPercent', $series->hasShowPercentage() ? '1' : '0');

            // c:showLeaderLines
            $this->writeElementWithValAttribute($objWriter, 'c:showLeaderLines', $series->hasShowLeaderLines() ? '1' : '0');

            $objWriter->endElement();
            /*
            // c:spPr
            $objWriter->startElement('c:spPr');

            // Write fill
            $this->writeFill($objWriter, $series->getFill());

            $objWriter->endElement();
            */
            // Write X axis data
            $axisXData = array_keys($series->getValues());

            // c:xVal
            $objWriter->startElement('c:xVal');
            $this->writeMultipleValuesOrReference($objWriter, $includeSheet, $axisXData, 'Sheet1!$A$2:$A$' . (1 + count($axisXData)));
            $objWriter->endElement();

            // Write Y axis data
            $axisYData = array_values($series->getValues());

            // c:yVal
            $objWriter->startElement('c:yVal');
            $coords = ($includeSheet ? 'Sheet1!$' . PHPExcel_Cell::stringFromColumnIndex($seriesIndex + 1) . '$2:$' . PHPExcel_Cell::stringFromColumnIndex($seriesIndex + 1) . '$' . (1 + count($axisYData)) : '');
            $this->writeMultipleValuesOrReference($objWriter, $includeSheet, $axisYData, $coords);
            $objWriter->endElement();

            // c:smooth
            $objWriter->startElement('c:smooth');
            $objWriter->writeAttribute('val', '0');
            $objWriter->endElement();

            $objWriter->endElement();

            ++$seriesIndex;
        }

        // c:axId
        $objWriter->startElement('c:axId');
        $objWriter->writeAttribute('val', '52743552');
        $objWriter->endElement();

        // c:axId
        $objWriter->startElement('c:axId');
        $objWriter->writeAttribute('val', '52749440');
        $objWriter->endElement();

        $objWriter->endElement();
    }
}

redpajama_set_name: RedPajamaGithub


text:
 /**
  * @file px4io_serial.cpp
  *
  * Serial interface for PX4IO
  */

/* XXX trim includes */
#include <px4_config.h>

#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
#include <debug.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>

#include <arch/board/board.h>

/* XXX might be able to prune these */
#include <nuttx/arch.h>
#include <chip.h>
#include <up_internal.h>
#include <up_arch.h>

#include <debug.h>

#include <drivers/device/device.h>
#include <drivers/drv_hrt.h>
#include <board_config.h>

#include <systemlib/perf_counter.h>

#include <modules/px4iofirmware/protocol.h>

#ifdef PX4IO_SERIAL_BASE

device::Device	*PX4IO_serial_interface();

/* serial register accessors */
#define REG(_x)		(*(volatile uint32_t *)(PX4IO_SERIAL_BASE + _x))
#define rSR		REG(STM32_USART_SR_OFFSET)
#define rDR		REG(STM32_USART_DR_OFFSET)
#define rBRR		REG(STM32_USART_BRR_OFFSET)
#define rCR1		REG(STM32_USART_CR1_OFFSET)
#define rCR2		REG(STM32_USART_CR2_OFFSET)
#define rCR3		REG(STM32_USART_CR3_OFFSET)
#define rGTPR		REG(STM32_USART_GTPR_OFFSET)

class PX4IO_serial : public device::Device
{
public:
	PX4IO_serial();
	virtual ~PX4IO_serial();

	virtual int	init();
	virtual int	read(unsigned offset, void *data, unsigned count = 1);
	virtual int	write(unsigned address, void *data, unsigned count = 1);
	virtual int	ioctl(unsigned operation, unsigned &arg);

private:
	/*
	 * XXX tune this value
	 *
	 * At 1.5Mbps each register takes 13.3µs, and we always transfer a full packet.
	 * Packet overhead is 26µs for the four-byte header.
	 *
	 * 32 registers = 451µs
	 *
	 * Maybe we can just send smaller packets (e.g. 8 regs) and loop for larger (less common)
	 * transfers? Could cause issues with any regs expecting to be written atomically...
	 */
	static IOPacket		_dma_buffer;		// XXX static to ensure DMA-able memory

	DMA_HANDLE		_tx_dma;
	DMA_HANDLE		_rx_dma;

	/** saved DMA status */
	static const unsigned	_dma_status_inactive = 0x80000000;	// low bits overlap DMA_STATUS_* values
	static const unsigned	_dma_status_waiting  = 0x00000000;
	volatile unsigned	_rx_dma_status;

	/** bus-ownership lock */
	sem_t			_bus_semaphore;

	/** client-waiting lock/signal */
	sem_t			_completion_semaphore;

	/**
	 * Start the transaction with IO and wait for it to complete.
	 */
	int			_wait_complete();

	/**
	 * DMA completion handler.
	 */
	static void		_dma_callback(DMA_HANDLE handle, uint8_t status, void *arg);
	void			_do_rx_dma_callback(unsigned status);

	/**
	 * Serial interrupt handler.
	 */
	static int		_interrupt(int vector, void *context);
	void			_do_interrupt();

	/**
	 * Cancel any DMA in progress with an error.
	 */
	void			_abort_dma();

	/**
	 * Performance counters.
	 */
	perf_counter_t		_pc_txns;
	perf_counter_t		_pc_dmasetup;
	perf_counter_t		_pc_retries;
	perf_counter_t		_pc_timeouts;
	perf_counter_t		_pc_crcerrs;
	perf_counter_t		_pc_dmaerrs;
	perf_counter_t		_pc_protoerrs;
	perf_counter_t		_pc_uerrs;
	perf_counter_t		_pc_idle;
	perf_counter_t		_pc_badidle;

	/* do not allow top copying this class */
	PX4IO_serial(PX4IO_serial &);
	PX4IO_serial& operator = (const PX4IO_serial &);

};

IOPacket PX4IO_serial::_dma_buffer;
static PX4IO_serial *g_interface;

device::Device
*PX4IO_serial_interface()
{
	return new PX4IO_serial();
}

PX4IO_serial::PX4IO_serial() :
	Device("PX4IO_serial"),
	_tx_dma(nullptr),
	_rx_dma(nullptr),
	_rx_dma_status(_dma_status_inactive),
	_bus_semaphore(SEM_INITIALIZER(0)),
	_completion_semaphore(SEM_INITIALIZER(0)),
	_pc_txns(perf_alloc(PC_ELAPSED, "io_txns     ")),
	_pc_dmasetup(perf_alloc(PC_ELAPSED,	"io_dmasetup ")),
	_pc_retries(perf_alloc(PC_COUNT,	"io_retries  ")),
	_pc_timeouts(perf_alloc(PC_COUNT,	"io_timeouts ")),
	_pc_crcerrs(perf_alloc(PC_COUNT,	"io_crcerrs  ")),
	_pc_dmaerrs(perf_alloc(PC_COUNT,	"io_dmaerrs  ")),
	_pc_protoerrs(perf_alloc(PC_COUNT,	"io_protoerrs")),
	_pc_uerrs(perf_alloc(PC_COUNT,		"io_uarterrs ")),
	_pc_idle(perf_alloc(PC_COUNT,		"io_idle     ")),
	_pc_badidle(perf_alloc(PC_COUNT,	"io_badidle  "))
{
	g_interface = this;
}

PX4IO_serial::~PX4IO_serial()
{
	if (_tx_dma != nullptr) {
		stm32_dmastop(_tx_dma);
		stm32_dmafree(_tx_dma);
	}
	if (_rx_dma != nullptr) {
		stm32_dmastop(_rx_dma);
		stm32_dmafree(_rx_dma);
	}

	/* reset the UART */
	rCR1 = 0;
	rCR2 = 0;
	rCR3 = 0;

	/* detach our interrupt handler */
	up_disable_irq(PX4IO_SERIAL_VECTOR);
	irq_detach(PX4IO_SERIAL_VECTOR);

	/* restore the GPIOs */
	stm32_unconfiggpio(PX4IO_SERIAL_TX_GPIO);
	stm32_unconfiggpio(PX4IO_SERIAL_RX_GPIO);

	/* and kill our semaphores */
	sem_destroy(&_completion_semaphore);
	sem_destroy(&_bus_semaphore);

	perf_free(_pc_txns);
	perf_free(_pc_dmasetup);
	perf_free(_pc_retries);
	perf_free(_pc_timeouts);
	perf_free(_pc_crcerrs);
	perf_free(_pc_dmaerrs);
	perf_free(_pc_protoerrs);
	perf_free(_pc_uerrs);
	perf_free(_pc_idle);
	perf_free(_pc_badidle);

	if (g_interface == this)
		g_interface = nullptr;
}

int
PX4IO_serial::init()
{

	/* allocate DMA */
	_tx_dma = stm32_dmachannel(PX4IO_SERIAL_TX_DMAMAP);
	_rx_dma = stm32_dmachannel(PX4IO_SERIAL_RX_DMAMAP);
	if ((_tx_dma == nullptr) || (_rx_dma == nullptr)) {
		return -1;
	}

	/* configure pins for serial use */
	stm32_configgpio(PX4IO_SERIAL_TX_GPIO);
	stm32_configgpio(PX4IO_SERIAL_RX_GPIO);

	/* reset & configure the UART */
	rCR1 = 0;
	rCR2 = 0;
	rCR3 = 0;

	/* eat any existing interrupt status */
	(void)rSR;
	(void)rDR;

	/* configure line speed */
	uint32_t usartdiv32 = PX4IO_SERIAL_CLOCK / (PX4IO_SERIAL_BITRATE / 2);
	uint32_t mantissa = usartdiv32 >> 5;
	uint32_t fraction = (usartdiv32 - (mantissa << 5) + 1) >> 1;
	rBRR = (mantissa << USART_BRR_MANT_SHIFT) | (fraction << USART_BRR_FRAC_SHIFT);

	/* attach serial interrupt handler */
	irq_attach(PX4IO_SERIAL_VECTOR, _interrupt);
	up_enable_irq(PX4IO_SERIAL_VECTOR);

	/* enable UART in DMA mode, enable error and line idle interrupts */
	rCR3 = USART_CR3_EIE;

	rCR1 = USART_CR1_RE | USART_CR1_TE | USART_CR1_UE | USART_CR1_IDLEIE;

	/* create semaphores */
	sem_init(&_completion_semaphore, 0, 0);
	sem_init(&_bus_semaphore, 0, 1);

	/* XXX this could try talking to IO */

	return 0;
}

int
PX4IO_serial::ioctl(unsigned operation, unsigned &arg)
{

	switch (operation) {

	case 1:		/* XXX magic number - test operation */
		switch (arg) {
		case 0:
			lowsyslog("test 0\n");

			/* kill DMA, this is a PIO test */
			stm32_dmastop(_tx_dma);
			stm32_dmastop(_rx_dma);
			rCR3 &= ~(USART_CR3_DMAR | USART_CR3_DMAT);

			for (;;) {
				while (!(rSR & USART_SR_TXE))
					;
				rDR = 0x55;
			}
			return 0;

		case 1:
			{
				unsigned fails = 0;
				for (unsigned count = 0;; count++) {
					uint16_t value = count & 0xffff;

					if (write((PX4IO_PAGE_TEST << 8) | PX4IO_P_TEST_LED, &value, 1) != 0)
						fails++;

					if (count >= 5000) {
						lowsyslog("==== test 1 : %u failures ====\n", fails);
						perf_print_counter(_pc_txns);
						perf_print_counter(_pc_dmasetup);
						perf_print_counter(_pc_retries);
						perf_print_counter(_pc_timeouts);
						perf_print_counter(_pc_crcerrs);
						perf_print_counter(_pc_dmaerrs);
						perf_print_counter(_pc_protoerrs);
						perf_print_counter(_pc_uerrs);
						perf_print_counter(_pc_idle);
						perf_print_counter(_pc_badidle);
						count = 0;
					}
				}
				return 0;
			}
		case 2:
			lowsyslog("test 2\n");
			return 0;
		}
	default:
		break;
	}

	return -1;
}

int
PX4IO_serial::write(unsigned address, void *data, unsigned count)
{
	uint8_t page = address >> 8;
	uint8_t offset = address & 0xff;
	const uint16_t *values = reinterpret_cast<const uint16_t *>(data);

	if (count > PKT_MAX_REGS)
		return -EINVAL;

	sem_wait(&_bus_semaphore);

	int result;
	for (unsigned retries = 0; retries < 3; retries++) {

		_dma_buffer.count_code = count | PKT_CODE_WRITE;
		_dma_buffer.page = page;
		_dma_buffer.offset = offset;
		memcpy((void *)&_dma_buffer.regs[0], (void *)values, (2 * count));
		for (unsigned i = count; i < PKT_MAX_REGS; i++)
			_dma_buffer.regs[i] = 0x55aa;

		/* XXX implement check byte */

		/* start the transaction and wait for it to complete */
		result = _wait_complete();

		/* successful transaction? */
		if (result == OK) {

			/* check result in packet */
			if (PKT_CODE(_dma_buffer) == PKT_CODE_ERROR) {

				/* IO didn't like it - no point retrying */
				result = -EINVAL;
				perf_count(_pc_protoerrs);
			}

			break;
		}
		perf_count(_pc_retries);
	}

	sem_post(&_bus_semaphore);

	if (result == OK)
		result = count;
	return result;
}

int
PX4IO_serial::read(unsigned address, void *data, unsigned count)
{
	uint8_t page = address >> 8;
	uint8_t offset = address & 0xff;
	uint16_t *values = reinterpret_cast<uint16_t *>(data);

	if (count > PKT_MAX_REGS)
		return -EINVAL;

	sem_wait(&_bus_semaphore);

	int result;
	for (unsigned retries = 0; retries < 3; retries++) {

		_dma_buffer.count_code = count | PKT_CODE_READ;
		_dma_buffer.page = page;
		_dma_buffer.offset = offset;

		/* start the transaction and wait for it to complete */
		result = _wait_complete();

		/* successful transaction? */
		if (result == OK) {

			/* check result in packet */
			if (PKT_CODE(_dma_buffer) == PKT_CODE_ERROR) {

				/* IO didn't like it - no point retrying */
				result = -EINVAL;
				perf_count(_pc_protoerrs);

			/* compare the received count with the expected count */
			} else if (PKT_COUNT(_dma_buffer) != count) {

				/* IO returned the wrong number of registers - no point retrying */
				result = -EIO;
				perf_count(_pc_protoerrs);

			/* successful read */
			} else {

				/* copy back the result */
				memcpy(values, &_dma_buffer.regs[0], (2 * count));
			}

			break;
		}
		perf_count(_pc_retries);
	}

	sem_post(&_bus_semaphore);

	if (result == OK)
		result = count;
	return result;
}

int
PX4IO_serial::_wait_complete()
{
	/* clear any lingering error status */
	(void)rSR;
	(void)rDR;

	/* start RX DMA */
	perf_begin(_pc_txns);
	perf_begin(_pc_dmasetup);

	/* DMA setup time ~3µs */
	_rx_dma_status = _dma_status_waiting;

	/*
	 * Note that we enable circular buffer mode as a workaround for
	 * there being no API to disable the DMA FIFO. We need direct mode
	 * because otherwise when the line idle interrupt fires there
	 * will be packet bytes still in the DMA FIFO, and we will assume
	 * that the idle was spurious.
	 *
	 * XXX this should be fixed with a NuttX change.
	 */
	stm32_dmasetup(
		_rx_dma,
		PX4IO_SERIAL_BASE + STM32_USART_DR_OFFSET,
		reinterpret_cast<uint32_t>(&_dma_buffer),
		sizeof(_dma_buffer),
		DMA_SCR_CIRC		|	/* XXX see note above */
		DMA_SCR_DIR_P2M		|
		DMA_SCR_MINC		|
		DMA_SCR_PSIZE_8BITS	|
		DMA_SCR_MSIZE_8BITS	|
		DMA_SCR_PBURST_SINGLE	|
		DMA_SCR_MBURST_SINGLE);
	stm32_dmastart(_rx_dma, _dma_callback, this, false);
	rCR3 |= USART_CR3_DMAR;

	/* start TX DMA - no callback if we also expect a reply */
	/* DMA setup time ~3µs */
	_dma_buffer.crc = 0;
	_dma_buffer.crc = crc_packet(&_dma_buffer);
	stm32_dmasetup(
		_tx_dma,
		PX4IO_SERIAL_BASE + STM32_USART_DR_OFFSET,
		reinterpret_cast<uint32_t>(&_dma_buffer),
		PKT_SIZE(_dma_buffer),
		DMA_SCR_DIR_M2P		|
		DMA_SCR_MINC		|
		DMA_SCR_PSIZE_8BITS	|
		DMA_SCR_MSIZE_8BITS	|
		DMA_SCR_PBURST_SINGLE	|
		DMA_SCR_MBURST_SINGLE);
	stm32_dmastart(_tx_dma, nullptr, nullptr, false);
	//rCR1 &= ~USART_CR1_TE;
	//rCR1 |= USART_CR1_TE;
	rCR3 |= USART_CR3_DMAT;

	perf_end(_pc_dmasetup);

	/* compute the deadline for a 10ms timeout */
	struct timespec abstime;
	clock_gettime(CLOCK_REALTIME, &abstime);
	abstime.tv_nsec += 10*1000*1000;
	if (abstime.tv_nsec >= 1000*1000*1000) {
		abstime.tv_sec++;
		abstime.tv_nsec -= 1000*1000*1000;
	}

	/* wait for the transaction to complete - 64 bytes @ 1.5Mbps ~426µs */
	int ret;
	for (;;) {
		ret = sem_timedwait(&_completion_semaphore, &abstime);

		if (ret == OK) {
			/* check for DMA errors */
			if (_rx_dma_status & DMA_STATUS_TEIF) {
				perf_count(_pc_dmaerrs);
				ret = -EIO;
				break;
			}

			/* check packet CRC - corrupt packet errors mean IO receive CRC error */
			uint8_t crc = _dma_buffer.crc;
			_dma_buffer.crc = 0;
			if ((crc != crc_packet(&_dma_buffer)) | (PKT_CODE(_dma_buffer) == PKT_CODE_CORRUPT)) {
				perf_count(_pc_crcerrs);
				ret = -EIO;
				break;
			}

			/* successful txn (may still be reporting an error) */
			break;
		}

		if (errno == ETIMEDOUT) {
			/* something has broken - clear out any partial DMA state and reconfigure */
			_abort_dma();
			perf_count(_pc_timeouts);
			perf_cancel(_pc_txns);		/* don't count this as a transaction */
			break;
		}

		/* we might? see this for EINTR */
		lowsyslog("unexpected ret %d/%d\n", ret, errno);
	}

	/* reset DMA status */
	_rx_dma_status = _dma_status_inactive;

	/* update counters */
	perf_end(_pc_txns);

	return ret;
}

void
PX4IO_serial::_dma_callback(DMA_HANDLE handle, uint8_t status, void *arg)
{
	if (arg != nullptr) {
		PX4IO_serial *ps = reinterpret_cast<PX4IO_serial *>(arg);

		ps->_do_rx_dma_callback(status);
	}
}

void
PX4IO_serial::_do_rx_dma_callback(unsigned status)
{
	/* on completion of a reply, wake the waiter */
	if (_rx_dma_status == _dma_status_waiting) {

		/* check for packet overrun - this will occur after DMA completes */
		uint32_t sr = rSR;
		if (sr & (USART_SR_ORE | USART_SR_RXNE)) {
			(void)rDR;
			status = DMA_STATUS_TEIF;
		}

		/* save RX status */
		_rx_dma_status = status;

		/* disable UART DMA */
		rCR3 &= ~(USART_CR3_DMAT | USART_CR3_DMAR);

		/* complete now */
		sem_post(&_completion_semaphore);
	}
}

int
PX4IO_serial::_interrupt(int irq, void *context)
{
	if (g_interface != nullptr)
		g_interface->_do_interrupt();
	return 0;
}

void
PX4IO_serial::_do_interrupt()
{
	uint32_t sr = rSR;	/* get UART status register */
	(void)rDR;		/* read DR to clear status */

	if (sr & (USART_SR_ORE |	/* overrun error - packet was too big for DMA or DMA was too slow */
		USART_SR_NE |		/* noise error - we have lost a byte due to noise */
		USART_SR_FE)) {		/* framing error - start/stop bit lost or line break */

		/*
		 * If we are in the process of listening for something, these are all fatal;
		 * abort the DMA with an error.
		 */
		if (_rx_dma_status == _dma_status_waiting) {
			_abort_dma();

			perf_count(_pc_uerrs);
			/* complete DMA as though in error */
			_do_rx_dma_callback(DMA_STATUS_TEIF);

			return;
		}

		/* XXX we might want to use FE / line break as an out-of-band handshake ... handle it here */

		/* don't attempt to handle IDLE if it's set - things went bad */
		return;
	}

	if (sr & USART_SR_IDLE) {

		/* if there is DMA reception going on, this is a short packet */
		if (_rx_dma_status == _dma_status_waiting) {

			/* verify that the received packet is complete */
			size_t length = sizeof(_dma_buffer) - stm32_dmaresidual(_rx_dma);
			if ((length < 1) || (length < PKT_SIZE(_dma_buffer))) {
				perf_count(_pc_badidle);

				/* stop the receive DMA */
				stm32_dmastop(_rx_dma);

				/* complete the short reception */
				_do_rx_dma_callback(DMA_STATUS_TEIF);
				return;
			}

			perf_count(_pc_idle);

			/* stop the receive DMA */
			stm32_dmastop(_rx_dma);

			/* complete the short reception */
			_do_rx_dma_callback(DMA_STATUS_TCIF);
		}
	}
}

void
PX4IO_serial::_abort_dma()
{
	/* disable UART DMA */
	rCR3 &= ~(USART_CR3_DMAT | USART_CR3_DMAR);
	(void)rSR;
	(void)rDR;
	(void)rDR;

	/* stop DMA */
	stm32_dmastop(_tx_dma);
	stm32_dmastop(_rx_dma);
}

#endif /* PX4IO_SERIAL_BASE */


text:
<EWS-SimpleMessage version="2.0">
    <Authentication>
        <username>me</username>
        <token>password</token>
    </Authentication>

    <Alert>
        <Analyzer id="MSTest3"/>
        <CreateTime tz="+0200">2015-09-09 16:39:21</CreateTime>
        <Source category="ipv4" port="" protocol="tcp">192.168.1.1</Source>
        <Target category="ipv4" port="80" protocol="tcp">1.2.3.4</Target>
        <Request type="url">/cgi-bin/.br/style.css</Request>
        <Request type="raw">R0VUIC9jZ2ktYmluLy5ici9zdHlsZS5jc3MgSFRUUC8xLjENCkFjY2VwdDogdGV4dC9jc3MsKi8q
            O3E9MC4xLCovKg0KQWNjZXB0LUVuY29kaW5nOiBnemlwLGRlZmxhdGUNCkNvbm5lY3Rpb246IEtl
            ZXAtYWxpdmUNCkZyb206IGdvb2dsZWJvdChhdClnb29nbGVib3QuY29tDQpIb3N0OiB3d3cud2Vi
            bWFpbGhvdXNlLmRlDQpSZWZlcmVyOiBodHRwOi8vd3d3LndlYm1haWxob3VzZS5kZS9jZ2ktYmlu
            Ly5ici9wYXRoLnBocA0KVXNlci1BZ2VudDogTW96aWxsYS81LjAgKGNvbXBhdGlibGU7IEdvb2ds
            ZWJvdC8yLjE7ICtodHRwOi8vd3d3Lmdvb2dsZS5jb20vYm90Lmh0bWwp
        </Request>
        <Request type="description">WebHoneypot : Glastopf v3.1</Request>
        <AdditionalData meaning="host" type="string">www.webe.de</AdditionalData>
        <AdditionalData meaning="sqliteid" type="integer">3688</AdditionalData>
    </Alert>

    <Alert>
        <Analyzer id="4711"/>
        <CreateTime tz="+0200">2009-10-02 16:52:30</CreateTime>
        <Source category="ipv4" port="80" protocol="tcp">192.168.1.1</Source>
        <Target category="ipv4" port="80" protocol="tcp">1111</Target>
        <Request type="URL" text="">/SQLINJECTION_TEST/../</Request>
        <Request type="raw" text="">RDATA</Request>
        <Classification origin="vendor-specific" ident="sip-01" text="ModSecurity"/>
        <AdditionalData type="string" meaning="httpmethod">GET</AdditionalData>
        <AdditionalData type="string" meaning="host">HOST</AdditionalData>
    </Alert>
</EWS-SimpleMessage>


text:
<?xml version="1.0" encoding="UTF-8"?>
<component>
	<content-type>/component/component-catalog-item-price</content-type>	<display-template>/templates/web/components/catalog-item/catalog-item-price.ftl</display-template>
	<merge-strategy>inherit-levels</merge-strategy>
	<objectGroupId>881d</objectGroupId>
	<objectId>881dd6fb-568e-57b2-6444-336f08586e2f</objectId>
	<file-name>best-fit.xml</file-name>
	<folder-name/>
	<internal-name>Best Fit</internal-name>
	<titleText_t>Best Fit</titleText_t>
	<price_t>550</price_t>
	<buttonText_t>Sign Up Now</buttonText_t>
	<displayButton_b>true</displayButton_b>
	<services_o>	<item>	<key>/site/components/items/service//10-yoga-courses.xml</key>
	<value>10 Yoga Courses</value>
	<include>/site/components/items/service//10-yoga-courses.xml</include>
	<disableFlattening>false</disableFlattening>
	</item>	<item>	<key>/site/components/items/service/gym-services.xml</key>
	<value>GYM Services</value>
	<include>/site/components/items/service/gym-services.xml</include>
	<disableFlattening>false</disableFlattening>
	</item>	<item>	<key>/site/components/items/service//two-general-trainer.xml</key>
	<value>Two General Trainers</value>
	<include>/site/components/items/service//two-general-trainer.xml</include>
	<disableFlattening>false</disableFlattening>
	</item>	<item>	<key>/site/components/items/service//20-thai-massages.xml</key>
	<value>20 Thai Massages</value>
	<include>/site/components/items/service//20-thai-massages.xml</include>
	<disableFlattening>false</disableFlattening>
	</item>	<item>	<key>/site/components/items/service//25-aerobics.xml</key>
	<value>25 Aerobics</value>
	<include>/site/components/items/service//25-aerobics.xml</include>
	<disableFlattening>false</disableFlattening>
	</item></services_o>
	<createdDate>2017-5-30T20:38:16.000Z</createdDate>
	<createdDate_dt>2017-5-30T20:38:16.000Z</createdDate_dt>
	<lastModifiedDate>2017-7-7T16:55:20.000Z</lastModifiedDate>
	<lastModifiedDate_dt>2017-7-7T16:55:20.000Z</lastModifiedDate_dt>
	<buttonUrl_s>#newsletter</buttonUrl_s>
</component>


text:
import test from 'ava';

var OpenDKIM = require('../../');
var Messages = require('../fixtures/messages');

var messages = new Messages();

test('test message with bad timestamp (future)', async t => {
  try {
    var opendkim = new OpenDKIM();

    opendkim.query_method('DKIM_QUERY_FILE');
    opendkim.query_info('../fixtures/testkeys');

    await opendkim.verify({id: undefined});
    await opendkim.chunk({
      message: messages.bad_timestamp_future,
      length: messages.bad_timestamp_future.length
    });
    await opendkim.chunk_end();
    t.fail();
  } catch (err) {
    t.is(err.message, 'Unable to verify');
  }
});


text:
package org.radeox.filter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.radeox.api.engine.context.InitialRenderContext;
import org.radeox.api.engine.context.RenderContext;
import org.radeox.engine.context.BaseInitialRenderContext;
import org.radeox.filter.context.FilterContext;

/*
 * FilterPipe is a collection of Filters which are applied one by one to an
 * input to generate output @author stephan @team sonicteam
 *
 * @version $Id: FilterPipe.java 309395 2014-05-09 21:21:54Z enietzel@anisakai.com $
 */

public class FilterPipe
{
	private static Log log = LogFactory.getLog(FilterPipe.class);

	public final static String FIRST_IN_PIPE = "all";

	public final static String LAST_IN_PIPE = "none";

	public final static String[] EMPTY_BEFORE = new String[] {};

	public final static String[] NO_REPLACES = new String[] {};

	public final static String[] FIRST_BEFORE = new String[] { FIRST_IN_PIPE };

	private InitialRenderContext initialContext;

	private List filterList = null;

	private static Object[] noArguments = new Object[] {};

	public FilterPipe()
	{
		this(new BaseInitialRenderContext());
	}

	public FilterPipe(InitialRenderContext context)
	{
		filterList = new ArrayList();
		initialContext = context;
	}

	public void init()
	{
		Iterator iterator = new ArrayList(filterList).iterator();
		while (iterator.hasNext())
		{
			Filter filter = (Filter) iterator.next();
			String[] replaces = filter.replaces();
			for (int i = 0; i < replaces.length; i++)
			{
				String replace = replaces[i];
				removeFilter(replace);
			}
		}
	}

	public void removeFilter(String filterClass)
	{
		Iterator iterator = filterList.iterator();
		while (iterator.hasNext())
		{
			Filter filter = (Filter) iterator.next();
			if (filter.getClass().getName().equals(filterClass))
			{
				iterator.remove();
			}
		}
	}

	/**
	 * Add a filter to the pipe
	 *
	 * @param filter
	 *        Filter to add
	 */
	public void addFilter(Filter filter)
	{
		filter.setInitialContext(initialContext);

		int minIndex = Integer.MAX_VALUE;
		String[] before = filter.before();
		for (int i = 0; i < before.length; i++)
		{
			String s = before[i];
			int index = index(filterList, s);
			if (index < minIndex)
			{
				minIndex = index;
			}
		}
		if (minIndex == Integer.MAX_VALUE)
		{
			// -1 is more usable for not-found than MAX_VALUE
			minIndex = -1;
		}

		if (contains(filter.before(), FIRST_IN_PIPE))
		{
			filterList.add(0, filter);
		}
		else if (minIndex != -1)
		{
			filterList.add(minIndex, filter);
			// } else if (contains(filter.before(), LAST_IN_PIPE)) {
			// filterList.add(-1, filter);
		}
		else
		{
			filterList.add(filter);
		}
	}

	public int index(String filterName)
	{
		return FilterPipe.index(filterList, filterName);
	}

	public static int index(List list, final String filterName)
	{
		for (int i = 0; i < list.size(); i++)
		{
			if (filterName.equals(list.get(i).getClass().getName())) return i;
		}
		return -1;
	}

	public static boolean contains(Object[] array, Object value)
	{
		return (Arrays.binarySearch(array, value) != -1);
	}

	/**
	 * Filter some input and generate ouput. FilterPipe pipes the string input
	 * through every filter in the pipe and returns the resulting string.
	 *
	 * @param input
	 *        Input string which should be transformed
	 * @param context
	 *        FilterContext with information about the enviroment
	 * @return result Filtered output
	 */
	public String filter(String input, FilterContext context)
	{
		// Logger.debug("FilterPipe.filter: context = "+context);
		String output = input;
		Iterator filterIterator = filterList.iterator();
		RenderContext renderContext = context.getRenderContext();

		// Apply every filter in filterList to input string
		while (filterIterator.hasNext())
		{
			Filter f = (Filter) filterIterator.next();
			try
			{
				String tmp = f.filter(output, context);
				if (null == tmp)
				{
					log.warn("FilterPipe.filter: error while filtering: " + f);
				}
				else
				{
					output = tmp;
				}
			}
			catch (Exception e)
			{
				log.warn("Filtering exception: " + f, e);
			}
		}
		return output;
	}

	public Filter getFilter(int index)
	{
		return (Filter) filterList.get(index);
	}
}


text:
package org.kuali.kra.award.subcontracting.reporting;

import java.sql.Date;

public class SubcontractingExpenditureCategoryAmountsInDateRange extends SubcontractingExpenditureCategoryAmountsBase {

    private static final long serialVersionUID = 4702488408295836126L;

    private Date rangeStartDate;
    private Date rangeEndDate;

    public SubcontractingExpenditureCategoryAmountsInDateRange() {
        super();
    }

    public SubcontractingExpenditureCategoryAmountsInDateRange(String awardNumber, Date rangeStartDate, Date rangeEndDate) {
        this();
        // set the PK
        this.setAwardNumber(awardNumber);
        // set the range limits
        this.setRangeStartDate(rangeStartDate);
        this.setRangeEndDate(rangeEndDate);
    }

    public void setRangeStartDate(Date rangeStartDate) {
        this.rangeStartDate = rangeStartDate;
    }
    public Date getRangeStartDate() {
        return rangeStartDate;
    }
    public void setRangeEndDate(Date rangeEndDate) {
        this.rangeEndDate = rangeEndDate;
    }
    public Date getRangeEndDate() {
        return rangeEndDate;
    }

}


text:
//
//  AppDelegate.m
//  SPXDefines
//
//  Created by Shaps Mohsenin on 31/01/2015.
//  Copyright (c) 2015 Snippex. All rights reserved.
//

#import "AppDelegate.h"
#import "SPXDefines.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

/**
 *  Checkout the examples for usage. You can simply run the project to see the output in the console. All examples use static constructors to demonstrate more easily.
 */

@end


text:
from numpy import *
import theano
import theano.tensor as T
import theano.typed_list as tl
import theano.sparse as sparse
from scipy.misc import logsumexp
from scipy.optimize import fmin_ncg
import scipy.sparse as sp
import time

"""
Explore how to implement custom theano ops.
For now Python only
"""

class MySoftmax(theano.gof.Op):

    __props__ = ()

    def make_node(self, Eta):
        return theano.Apply(self, [Eta], [Eta.type(), Eta.type()])

    def perform(self, node, input_storage, output_storage):
        print "perform"
        Eta = input_storage[0]
        lNorm = logsumexp(Eta, axis=1).reshape(N,1)
        lP = Eta - lNorm
        output_storage[0][0] = exp(lP)
        output_storage[1][0] = exp(lP)

    def grad(self, inputs, g):
        print "gradnick"
        Eta = input_storage[0]

mysoftmax = MySoftmax()

random.seed(1)

K = 5 #nClasses
N = 6 #nSamples
D = 3 #nFeatures

#single precision for now
theano.config.floatX = 'float32'
theano.config.scan.allow_gc = False

#setup toy example
W = random.randn(D,K)
X = random.randn(N,D)
Eta = dot(X,W)
lNorm = logsumexp(Eta, axis=1).reshape(N,1)
lP = Eta - lNorm
#take one sample from a multinomial distribution specified by a row of lP
_,y = apply_along_axis(lambda row: random.multinomial(1, exp(row)), axis=1, arr=lP).nonzero()
W = W.astype(float32)
X = X.astype(float32)
y = y.astype(int32)

#setup theano
tW = T.matrix('W')
tX = T.matrix('X')
ty = T.ivector('y')
tlambda = T.scalar('lambda')

#symbolic representation
tEta = T.dot(tX, tW)
Eta = Eta.astype(float32)
b = theano.function([tEta], mysoftmax(tEta))
c = b(Eta)
tP = T.nnet.softmax(tEta)
tP2 = mysoftmax(tEta)
hey = theano.function( [tX, tW], tP2)
terror = T.nnet.categorical_crossentropy(tP, ty).mean() #+ tlambda * tW.norm(2)**2 # we could add some Tikhonov regularization
terr2 = T.nnet.categorical_crossentropy(tP2[0], ty).mean()
tgrad = T.grad(terror, tW)
#f = theano.function([tW, tX, ty, tlambda], terror)
#g = theano.function([tW, tX, ty, tlambda], tgrad)


text:
using Avanade.AzureDAM.Integrations.Clients;

namespace Avanade.AzureDAM.DemoSetup.Search
{
    public static class SearchCleanUp
    {
        private static SearchManagementClient _client;

        public static void Run()
        {
            _client = new SearchManagementClient();
            _client.DeleteIndex(SearchConfiguration.IndexName);
            _client.DeleteDataSource(SearchConfiguration.DatasourceName);
            _client.DeleteIndexer(SearchConfiguration.IndexerName);
        }

    }
}


text:
'use strict';

const models = require('./index');

/**
 * VpnGateway Resource.
 *
 * @extends models['Resource']
 */
class VpnGateway extends models['Resource'] {
  /**
   * Create a VpnGateway.
   * @property {object} [virtualHub] The VirtualHub to which the gateway
   * belongs
   * @property {string} [virtualHub.id] Resource ID.
   * @property {array} [connections] List of all vpn connections to the
   * gateway.
   * @property {object} [bgpSettings] Local network gateway's BGP speaker
   * settings.
   * @property {number} [bgpSettings.asn] The BGP speaker's ASN.
   * @property {string} [bgpSettings.bgpPeeringAddress] The BGP peering address
   * and BGP identifier of this BGP speaker.
   * @property {number} [bgpSettings.peerWeight] The weight added to routes
   * learned from this BGP speaker.
   * @property {string} [provisioningState] The provisioning state of the
   * resource. Possible values include: 'Succeeded', 'Updating', 'Deleting',
   * 'Failed'
   * @property {number} [vpnGatewayScaleUnit] The scale unit for this vpn
   * gateway.
   * @property {string} [etag] Gets a unique read-only string that changes
   * whenever the resource is updated.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of VpnGateway
   *
   * @returns {object} metadata of VpnGateway
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'VpnGateway',
      type: {
        name: 'Composite',
        className: 'VpnGateway',
        modelProperties: {
          id: {
            required: false,
            serializedName: 'id',
            type: {
              name: 'String'
            }
          },
          name: {
            required: false,
            readOnly: true,
            serializedName: 'name',
            type: {
              name: 'String'
            }
          },
          type: {
            required: false,
            readOnly: true,
            serializedName: 'type',
            type: {
              name: 'String'
            }
          },
          location: {
            required: false,
            serializedName: 'location',
            type: {
              name: 'String'
            }
          },
          tags: {
            required: false,
            serializedName: 'tags',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          virtualHub: {
            required: false,
            serializedName: 'properties.virtualHub',
            type: {
              name: 'Composite',
              className: 'SubResource'
            }
          },
          connections: {
            required: false,
            serializedName: 'properties.connections',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'VpnConnectionElementType',
                  type: {
                    name: 'Composite',
                    className: 'VpnConnection'
                  }
              }
            }
          },
          bgpSettings: {
            required: false,
            serializedName: 'properties.bgpSettings',
            type: {
              name: 'Composite',
              className: 'BgpSettings'
            }
          },
          provisioningState: {
            required: false,
            serializedName: 'properties.provisioningState',
            type: {
              name: 'String'
            }
          },
          vpnGatewayScaleUnit: {
            required: false,
            serializedName: 'properties.vpnGatewayScaleUnit',
            type: {
              name: 'Number'
            }
          },
          etag: {
            required: false,
            readOnly: true,
            serializedName: 'etag',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = VpnGateway;