text:
/**
 * The are the global vars that are used in the html program
 */

var Global = {
    CURR_MODE_GAME:  "game mode",
    CURR_MODE_QUOTE_SELECTOR:  "quote selector",
    CURR_MODE_COLLECTION_SELECTOR:  "collection selector",
    totalHidden:  0,  // may not be used
    gameWindow:  "",
    gamePanel:  "",
    currQuoteIndex:  0,
    currQuoteSet:  "",
    currQuoteSetLength:  0,
    currQuoteSetName:  "",
    currMenuNodeIndex:  0,
    savedQuotesCollection: "",
    memorizedArray:  [],
    currMode:  this.CURR_MODE_COLLECTION_SELECTOR,
    currQuoteSetLanguage:  "en",
    currQuoteLanguage:  "en",
    thisQuoteId: 0
};


text:
<?php

namespace Tests\PHPCensor\Model;

use PHPCensor\Common\Exception\InvalidArgumentException;
use PHPCensor\DatabaseManager;
use PHPCensor\Model\Build;
use PHPCensor\Model\Build\GitBuild;
use PHPCensor\Model\Build\GithubBuild;
use PHPCensor\Model\Build\GitlabBuild;
use PHPCensor\Model\Build\GogsBuild;
use PHPCensor\Model\Project;
use PHPCensor\Service\ProjectService;
use PHPCensor\StoreRegistry;
use PHPUnit\Framework\TestCase;

/**
 * Unit tests for the Build model class.
 *
 * @author Dan Cryer <dan@block8.co.uk>
 */
class BuildTest extends TestCase
{
    protected StoreRegistry $storeRegistry;
    protected DatabaseManager $databaseManager;
    protected ProjectService $projectService;

    protected function setUp(): void
    {
        $configuration   = $this->getMockBuilder('PHPCensor\ConfigurationInterface')->getMock();
        $this->databaseManager = $this
            ->getMockBuilder('PHPCensor\DatabaseManager')
            ->setConstructorArgs([$configuration])
            ->getMock();
        $this->storeRegistry = $this
            ->getMockBuilder('PHPCensor\StoreRegistry')
            ->setConstructorArgs([$this->databaseManager])
            ->getMock();

        $projectStore = $this
            ->getMockBuilder('PHPCensor\Store\ProjectStore')
            ->setConstructorArgs([$this->databaseManager, $this->storeRegistry])
            ->getMock();

        $this->projectService = new ProjectService($this->storeRegistry, $projectStore);
    }

    public function testConstruct()
    {
        $build = new Build($this->storeRegistry);

        self::assertInstanceOf('PHPCensor\Model', $build);
        self::assertInstanceOf('PHPCensor\Model\Build', $build);

        $build = new Build($this->storeRegistry, [
            'project_id' => 100,
            'branch'     => 'master',
        ]);

        self::assertEquals([
            'id'                    => null,
            'parent_id'             => null,
            'project_id'            => 100,
            'commit_id'             => null,
            'status'                => null,
            'log'                   => null,
            'branch'                => 'master',
            'tag'                   => null,
            'create_date'           => null,
            'start_date'            => null,
            'finish_date'           => null,
            'committer_email'       => null,
            'commit_message'        => null,
            'extra'                 => [],
            'environment_id'        => null,
            'source'                => Build::SOURCE_UNKNOWN,
            'user_id'               => null,
            'errors_total'          => null,
            'errors_total_previous' => null,
            'errors_new'            => null,
        ], $build->getDataArray());

        try {
            new Build($this->storeRegistry, [
                'project_id' => 101,
                'branch'     => 'dev',
                'unknown'    => 'unknown',
            ]);
        } catch (InvalidArgumentException $e) {
            self::assertEquals(
                'Model "PHPCensor\Model\Build" doesn\'t have field "unknown"',
                $e->getMessage()
            );
        }

        $build = new Build($this->storeRegistry);
        $build->setLog('log');
        self::assertEquals('log', $build->getLog());

        $build->setLog(null);
        self::assertEquals(null, $build->getLog());

        try {
            $build->setLog([]);
        } catch (\Throwable $e) {
            self::assertInstanceOf(
                \TypeError::class,
                $e
            );
        }

        $build->setSource(Build::SOURCE_WEBHOOK_PULL_REQUEST_CREATED);
        self::assertEquals(Build::SOURCE_WEBHOOK_PULL_REQUEST_CREATED, $build->getSource());

        try {
            $build->setSource('5');
        } catch (InvalidArgumentException $e) {
            self::assertEquals(
                'Column "source" must be an int.',
                $e->getMessage()
            );
        }

        try {
            $build->setId(null);
        } catch (\Throwable $e) {
            self::assertInstanceOf(
                \TypeError::class,
                $e
            );
        }
    }

    public function testExecute_TestBaseBuildDefaults()
    {
        $build = new Build($this->storeRegistry);
        self::assertEquals('#', $build->getCommitLink());
        self::assertEquals('#', $build->getBranchLink());
        self::assertEquals(null, $build->getFileLinkTemplate());
    }

    public function testExecute_TestIsSuccessful()
    {
        $build = new Build($this->storeRegistry);
        $build->setStatusPending();
        self::assertFalse($build->isSuccessful());

        $build->setStatusRunning();
        self::assertFalse($build->isSuccessful());

        $build->setStatusFailed();
        self::assertFalse($build->isSuccessful());

        $build->setStatusSuccess();
        self::assertTrue($build->isSuccessful());
    }

    public function testExecute_TestBuildExtra()
    {
        $info = [
            'item1' => 'Item One',
            'item2' => 2,
        ];

        $build = new Build($this->storeRegistry);
        $build->setExtra($info);

        self::assertEquals('Item One', $build->getExtra('item1'));
        self::assertEquals(2, $build->getExtra('item2'));
        self::assertNull($build->getExtra('item3'));
        self::assertEquals($info, $build->getExtra());

        $build->addExtraValue('item3', 'Item Three');

        self::assertEquals('Item One', $build->getExtra('item1'));
        self::assertEquals('Item Three', $build->getExtra('item3'));
    }

    public function testGitBuildLinks()
    {
        $project = new Project($this->storeRegistry);
        $project->setType(Project::TYPE_GIT);
        $project->setReference('https://git.repository/the-vendor/the-project.git');

        $configuration = $this->getMockBuilder('PHPCensor\ConfigurationInterface')->getMock();

        $stub = $this->getMockBuilder(GitBuild::class)
            ->setConstructorArgs([$configuration, $this->storeRegistry])
            ->setMethods(['getProject', 'getCommitId', 'getBranch'])
            ->getMock();

        $stub->method('getProject')
            ->will($this->returnValue($project));

        $stub->method('getCommitId')
            ->will($this->returnValue('abcdef'));

        $stub->method('getBranch')
            ->will($this->returnValue('master'));

        $this->assertEquals('#', $stub->getCommitLink());

        $this->assertEquals('#', $stub->getBranchLink());

        $this->assertEquals(null, $stub->getFileLinkTemplate());
    }

    public function testGitHubBuildLinks()
    {
        $project = new Project($this->storeRegistry);
        $project->setType(Project::TYPE_GITHUB);
        $project->setReference('git@github.com:php-censor/php-censor.git');
        $project = $this->projectService->processAccessInformation($project);

        $configuration = $this->getMockBuilder('PHPCensor\ConfigurationInterface')->getMock();

        $stub = $this->getMockBuilder(GithubBuild::class)
            ->setConstructorArgs([$configuration, $this->storeRegistry])
            ->setMethods(['getProject', 'getCommitId', 'getBranch', 'getTag'])
            ->getMock();

        $stub->method('getProject')
            ->will($this->returnValue($project));

        $stub->method('getCommitId')
            ->will($this->returnValue('abcdef'));

        $stub->method('getBranch')
            ->will($this->returnValue('master'));

        $stub->method('getTag')
            ->will($this->returnValue('2.0.7'));

        $this->assertEquals(
            '//github.com/php-censor/php-censor/commit/abcdef',
            $stub->getCommitLink()
        );

        $this->assertEquals(
            '//github.com/php-censor/php-censor/tree/master',
            $stub->getBranchLink()
        );

        $this->assertEquals(
            '//github.com/php-censor/php-censor/blob/abcdef/{FILE}#L{LINE}-L{LINE_END}',
            $stub->getFileLinkTemplate()
        );

        $this->assertEquals(
            '//github.com/php-censor/php-censor/tree/2.0.7',
            $stub->getTagLink()
        );
    }

    public function testGitlabBuildLinks()
    {
        $project = new Project($this->storeRegistry);
        $project->setType(Project::TYPE_GITLAB);
        $project->setReference('git@gitlab.com:php-censor/php-censor.git');
        $project = $this->projectService->processAccessInformation($project);

        $configuration = $this->getMockBuilder('PHPCensor\ConfigurationInterface')->getMock();

        $stub = $this->getMockBuilder(GitlabBuild::class)
            ->setConstructorArgs([$configuration, $this->storeRegistry])
            ->setMethods(['getProject', 'getCommitId', 'getBranch'])
            ->getMock();

        $stub->method('getProject')
            ->will($this->returnValue($project));

        $stub->method('getCommitId')
            ->will($this->returnValue('abcdef'));

        $stub->method('getBranch')
            ->will($this->returnValue('master'));

        $this->assertEquals(
            '//gitlab.com/php-censor/php-censor/commit/abcdef',
            $stub->getCommitLink()
        );

        $this->assertEquals(
            '//gitlab.com/php-censor/php-censor/tree/master',
            $stub->getBranchLink()
        );

        $this->assertEquals(
            '//gitlab.com/php-censor/php-censor/blob/abcdef/{FILE}#L{LINE}',
            $stub->getFileLinkTemplate()
        );
    }

    public function testGogsBuildLinks()
    {
        $project = new Project($this->storeRegistry);
        $project->setType(Project::TYPE_GOGS);
        $project->setReference('https://gogs.repository/the-vendor/the-project.git');

        $configuration = $this->getMockBuilder('PHPCensor\ConfigurationInterface')->getMock();

        $stub = $this->getMockBuilder(GogsBuild::class)
            ->setConstructorArgs([$configuration, $this->storeRegistry])
            ->setMethods(['getProject', 'getCommitId', 'getBranch'])
            ->getMock();

        $stub->method('getProject')
            ->will($this->returnValue($project));

        $stub->method('getCommitId')
            ->will($this->returnValue('abcdef'));

        $stub->method('getBranch')
            ->will($this->returnValue('master'));

        $this->assertEquals(
            'https://gogs.repository/the-vendor/the-project/commit/abcdef',
            $stub->getCommitLink()
        );

        $this->assertEquals(
            'https://gogs.repository/the-vendor/the-project/src/master',
            $stub->getBranchLink()
        );

        $this->assertEquals(
            'https://gogs.repository/the-vendor/the-project/src/abcdef/{FILE}#L{LINE}',
            $stub->getFileLinkTemplate()
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace tesseract {

// Runs two or more networks in series (layers) on the same input.
class Series : public Plumbing {
 public:
  // ni_ and no_ will be set by AddToStack.
  explicit Series(const STRING& name);
  virtual ~Series();

  // Returns the shape output from the network given an input shape (which may
  // be partially unknown ie zero).
  virtual StaticShape OutputShape(const StaticShape& input_shape) const;

  virtual STRING spec() const {
    STRING spec("[");
    for (int i = 0; i < stack_.size(); ++i)
      spec += stack_[i]->spec();
    spec += "]";
    return spec;
  }

  // Sets up the network for training. Initializes weights using weights of
  // scale `range` picked according to the random number generator `randomizer`.
  // Returns the number of weights initialized.
  virtual int InitWeights(float range, TRand* randomizer);

  // Sets needs_to_backprop_ to needs_backprop and returns true if
  // needs_backprop || any weights in this network so the next layer forward
  // can be told to produce backprop for this layer if needed.
  virtual bool SetupNeedsBackprop(bool needs_backprop);

  // Returns an integer reduction factor that the network applies to the
  // time sequence. Assumes that any 2-d is already eliminated. Used for
  // scaling bounding boxes of truth data.
  // WARNING: if GlobalMinimax is used to vary the scale, this will return
  // the last used scale factor. Call it before any forward, and it will return
  // the minimum scale factor of the paths through the GlobalMinimax.
  virtual int XScaleFactor() const;

  // Provides the (minimum) x scale factor to the network (of interest only to
  // input units) so they can determine how to scale bounding boxes.
  virtual void CacheXScaleFactor(int factor);

  // Runs forward propagation of activations on the input line.
  // See Network for a detailed discussion of the arguments.
  virtual void Forward(bool debug, const NetworkIO& input,
                       const TransposedArray* input_transpose,
                       NetworkScratch* scratch, NetworkIO* output);

  // Runs backward propagation of errors on the deltas line.
  // See Network for a detailed discussion of the arguments.
  virtual bool Backward(bool debug, const NetworkIO& fwd_deltas,
                        NetworkScratch* scratch,
                        NetworkIO* back_deltas);

  // Splits the series after the given index, returning the two parts and
  // deletes itself. The first part, up to network with index last_start, goes
  // into start, and the rest goes into end.
  void SplitAt(int last_start, Series** start, Series** end);

  // Appends the elements of the src series to this, removing from src and
  // deleting it.
  void AppendSeries(Network* src);
};

}  // namespace tesseract.

#endif  // TESSERACT_LSTM_SERIES_H_


text:
'use strict'

const test = require('tap').test
const CGR = require('../')
const fixture = require('./fixtures/fixture')
const results = require('./fixtures/results')

test('fetchPR without number', function(t) {
  t.plan(2)
  var cgr = new CGR({
    token: '1234'
  })

  cgr.fetchPR(null, function(err) {
    t.type(err, Error)
    t.equal(err.message, 'PR number is required')
  })
})

test('fetchPR error', function(t) {
  t.plan(2)
  var cgr = new CGR({
    token: '1234'
  })

  var orig = cgr.github.issues.getComments
  cgr.github.issues.getComments = function(opts, cb) {
    process.nextTick(function() {
      cb(new Error('Error'))
    })
  }

  cgr.fetchPR(123, function(err) {
    cgr.github.issues.getComments = orig
    t.type(err, Error)
    t.equal(err.message, 'Error')
  })
})

test('fetchPR success', function(t) {
  t.plan(2)
  var cgr = new CGR({
    token: '1234'
  })

  var orig = cgr.github.issues.getComments
  cgr.github.issues.getComments = function(opts, cb) {
    process.nextTick(function() {
      cb(null, fixture)
    })
  }

  cgr.fetchPR(123, function(err, out) {
    cgr.github.issues.getComments = orig
    t.ifError(err, 'err should not exist')
    t.deepEqual(out, results)
  })
})

test('generate', function(t) {
  t.plan(1)
  var cgr = CGR({
    token: '1234'
  })
  var out = cgr.generate(123, results)
  t.deepEqual(out, `
PR-URL: https://github.com/nodejs/node/pull/123
Reviewed-By: Steven R Loomis <srloomis@us.ibm.com>
Reviewed-By: Roman Reiss <me@silverwind.io>
Reviewed-By: Rod Vagg <rod@vagg.org>`)
})

test('generate with invalid username', function(t) {
  t.plan(1)
  var cgr = CGR({
    token: '1234'
  })
  t.throws(function() {
    cgr.generate(123, [
      {
        username: 'evan'
      }
    ])
  }, /Cannot find email for reviewer evan/)
})

test('getReviewer', function(t) {
  t.plan(2)
  var cgr = CGR({
    token: '1234'
  })

  t.notOk(cgr.getReviewer('biscuits'))
  t.equal(cgr.getReviewer('evanlucas'), 'Evan Lucas <evanlucas@me.com>')
})


text:
import Omni = require('../../lib/omni-sharp-server/omni');
import {Observable, CompositeDisposable} from "rx";
import {setupFeature, restoreBuffers, openEditor} from "../test-helpers";

describe('Run Tests', () => {
    setupFeature(['features/run-tests']);

    it('adds commands', () => {
        var disposable = new CompositeDisposable();

        runs(() => {
            var commands: any = atom.commands;

            expect(commands.registeredCommands['omnisharp-atom:run-all-tests']).toBeTruthy();
            expect(commands.registeredCommands['omnisharp-atom:run-fixture-tests']).toBeTruthy();
            expect(commands.registeredCommands['omnisharp-atom:run-single-test']).toBeTruthy();
            expect(commands.registeredCommands['omnisharp-atom:run-last-test']).toBeTruthy();
            disposable.dispose();
        });
    });

    // TODO: Test functionality
});


text:
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM;
using TTC2017.SmartGrids.CIM.IEC61968.Common;
using TTC2017.SmartGrids.CIM.IEC61970.Contingency;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Generation.Production;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.EnergyScheduling;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.Financial;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfERPSupport;
using TTC2017.SmartGrids.CIM.IEC61970.LoadModel;
using TTC2017.SmartGrids.CIM.IEC61970.Meas;
using TTC2017.SmartGrids.CIM.IEC61970.Wires;

namespace TTC2017.SmartGrids.CIM.IEC61970.Informative.MarketOperations
{

    /// <summary>
    /// The default implementation of the SecurityConstraints class
    /// </summary>
    [XmlNamespaceAttribute("http://iec.ch/TC57/2009/CIM-schema-cim14#MarketOperations")]
    [XmlNamespacePrefixAttribute("cimMarketOperations")]
    [ModelRepresentationClassAttribute("http://iec.ch/TC57/2009/CIM-schema-cim14#//IEC61970/Informative/MarketOperations/" +
        "SecurityConstraints")]
    [DebuggerDisplayAttribute("SecurityConstraints {UUID}")]
    public partial class SecurityConstraints : IdentifiedObject, ISecurityConstraints, IModelElement
    {

        /// <summary>
        /// The backing field for the MinMW property
        /// </summary>
        private float _minMW;

        private static Lazy<ITypedElement> _minMWAttribute = new Lazy<ITypedElement>(RetrieveMinMWAttribute);

        /// <summary>
        /// The backing field for the MaxMW property
        /// </summary>
        private float _maxMW;

        private static Lazy<ITypedElement> _maxMWAttribute = new Lazy<ITypedElement>(RetrieveMaxMWAttribute);

        /// <summary>
        /// The backing field for the ActualMW property
        /// </summary>
        private float _actualMW;

        private static Lazy<ITypedElement> _actualMWAttribute = new Lazy<ITypedElement>(RetrieveActualMWAttribute);

        private static Lazy<ITypedElement> _rTOReference = new Lazy<ITypedElement>(RetrieveRTOReference);

        /// <summary>
        /// The backing field for the RTO property
        /// </summary>
        private IRTO _rTO;

        private static IClass _classInstance;

        /// <summary>
        /// The minMW property
        /// </summary>
        [XmlElementNameAttribute("minMW")]
        [XmlAttributeAttribute(true)]
        public virtual float MinMW
        {
            get
            {
                return this._minMW;
            }
            set
            {
                if ((this._minMW != value))
                {
                    float old = this._minMW;
                    ValueChangedEventArgs e = new ValueChangedEventArgs(old, value);
                    this.OnMinMWChanging(e);
                    this.OnPropertyChanging("MinMW", e, _minMWAttribute);
                    this._minMW = value;
                    this.OnMinMWChanged(e);
                    this.OnPropertyChanged("MinMW", e, _minMWAttribute);
                }
            }
        }

        /// <summary>
        /// The maxMW property
        /// </summary>
        [XmlElementNameAttribute("maxMW")]
        [XmlAttributeAttribute(true)]
        public virtual float MaxMW
        {
            get
            {
                return this._maxMW;
            }
            set
            {
                if ((this._maxMW != value))
                {
                    float old = this._maxMW;
                    ValueChangedEventArgs e = new ValueChangedEventArgs(old, value);
                    this.OnMaxMWChanging(e);
                    this.OnPropertyChanging("MaxMW", e, _maxMWAttribute);
                    this._maxMW = value;
                    this.OnMaxMWChanged(e);
                    this.OnPropertyChanged("MaxMW", e, _maxMWAttribute);
                }
            }
        }

        /// <summary>
        /// The actualMW property
        /// </summary>
        [XmlElementNameAttribute("actualMW")]
        [XmlAttributeAttribute(true)]
        public virtual float ActualMW
        {
            get
            {
                return this._actualMW;
            }
            set
            {
                if ((this._actualMW != value))
                {
                    float old = this._actualMW;
                    ValueChangedEventArgs e = new ValueChangedEventArgs(old, value);
                    this.OnActualMWChanging(e);
                    this.OnPropertyChanging("ActualMW", e, _actualMWAttribute);
                    this._actualMW = value;
                    this.OnActualMWChanged(e);
                    this.OnPropertyChanged("ActualMW", e, _actualMWAttribute);
                }
            }
        }

        /// <summary>
        /// The RTO property
        /// </summary>
        [XmlAttributeAttribute(true)]
        [XmlOppositeAttribute("SecurityConstraints")]
        public virtual IRTO RTO
        {
            get
            {
                return this._rTO;
            }
            set
            {
                if ((this._rTO != value))
                {
                    IRTO old = this._rTO;
                    ValueChangedEventArgs e = new ValueChangedEventArgs(old, value);
                    this.OnRTOChanging(e);
                    this.OnPropertyChanging("RTO", e, _rTOReference);
                    this._rTO = value;
                    if ((old != null))
                    {
                        old.SecurityConstraints.Remove(this);
                        old.Deleted -= this.OnResetRTO;
                    }
                    if ((value != null))
                    {
                        value.SecurityConstraints.Add(this);
                        value.Deleted += this.OnResetRTO;
                    }
                    this.OnRTOChanged(e);
                    this.OnPropertyChanged("RTO", e, _rTOReference);
                }
            }
        }

        /// <summary>
        /// Gets the referenced model elements of this model element
        /// </summary>
        public override IEnumerableExpression<IModelElement> ReferencedElements
        {
            get
            {
                return base.ReferencedElements.Concat(new SecurityConstraintsReferencedElementsCollection(this));
            }
        }

        /// <summary>
        /// Gets the Class model for this type
        /// </summary>
        public new static IClass ClassInstance
        {
            get
            {
                if ((_classInstance == null))
                {
                    _classInstance = ((IClass)(MetaRepository.Instance.Resolve("http://iec.ch/TC57/2009/CIM-schema-cim14#//IEC61970/Informative/MarketOperations/" +
                            "SecurityConstraints")));
                }
                return _classInstance;
            }
        }

        /// <summary>
        /// Gets fired before the MinMW property changes its value
        /// </summary>
        public event System.EventHandler<ValueChangedEventArgs> MinMWChanging;

        /// <summary>
        /// Gets fired when the MinMW property changed its value
        /// </summary>
        public event System.EventHandler<ValueChangedEventArgs> MinMWChanged;

        /// <summary>
        /// Gets fired before the MaxMW property changes its value
        /// </summary>
        public event System.EventHandler<ValueChangedEventArgs> MaxMWChanging;

        /// <summary>
        /// Gets fired when the MaxMW property changed its value
        /// </summary>
        public event System.EventHandler<ValueChangedEventArgs> MaxMWChanged;

        /// <summary>
        /// Gets fired before the ActualMW property changes its value
        /// </summary>
        public event System.EventHandler<ValueChangedEventArgs> ActualMWChanging;

        /// <summary>
        /// Gets fired when the ActualMW property changed its value
        /// </summary>
        public event System.EventHandler<ValueChangedEventArgs> ActualMWChanged;

        /// <summary>
        /// Gets fired before the RTO property changes its value
        /// </summary>
        public event System.EventHandler<ValueChangedEventArgs> RTOChanging;

        /// <summary>
        /// Gets fired when the RTO property changed its value
        /// </summary>
        public event System.EventHandler<ValueChangedEventArgs> RTOChanged;

        private static ITypedElement RetrieveMinMWAttribute()
        {
            return ((ITypedElement)(((ModelElement)(SecurityConstraints.ClassInstance)).Resolve("minMW")));
        }

        /// <summary>
        /// Raises the MinMWChanging event
        /// </summary>
        /// <param name="eventArgs">The event data</param>
        protected virtual void OnMinMWChanging(ValueChangedEventArgs eventArgs)
        {
            System.EventHandler<ValueChangedEventArgs> handler = this.MinMWChanging;
            if ((handler != null))
            {
                handler.Invoke(this, eventArgs);
            }
        }

        /// <summary>
        /// Raises the MinMWChanged event
        /// </summary>
        /// <param name="eventArgs">The event data</param>
        protected virtual void OnMinMWChanged(ValueChangedEventArgs eventArgs)
        {
            System.EventHandler<ValueChangedEventArgs> handler = this.MinMWChanged;
            if ((handler != null))
            {
                handler.Invoke(this, eventArgs);
            }
        }

        private static ITypedElement RetrieveMaxMWAttribute()
        {
            return ((ITypedElement)(((ModelElement)(SecurityConstraints.ClassInstance)).Resolve("maxMW")));
        }

        /// <summary>
        /// Raises the MaxMWChanging event
        /// </summary>
        /// <param name="eventArgs">The event data</param>
        protected virtual void OnMaxMWChanging(ValueChangedEventArgs eventArgs)
        {
            System.EventHandler<ValueChangedEventArgs> handler = this.MaxMWChanging;
            if ((handler != null))
            {
                handler.Invoke(this, eventArgs);
            }
        }

        /// <summary>
        /// Raises the MaxMWChanged event
        /// </summary>
        /// <param name="eventArgs">The event data</param>
        protected virtual void OnMaxMWChanged(ValueChangedEventArgs eventArgs)
        {
            System.EventHandler<ValueChangedEventArgs> handler = this.MaxMWChanged;
            if ((handler != null))
            {
                handler.Invoke(this, eventArgs);
            }
        }

        private static ITypedElement RetrieveActualMWAttribute()
        {
            return ((ITypedElement)(((ModelElement)(SecurityConstraints.ClassInstance)).Resolve("actualMW")));
        }

        /// <summary>
        /// Raises the ActualMWChanging event
        /// </summary>
        /// <param name="eventArgs">The event data</param>
        protected virtual void OnActualMWChanging(ValueChangedEventArgs eventArgs)
        {
            System.EventHandler<ValueChangedEventArgs> handler = this.ActualMWChanging;
            if ((handler != null))
            {
                handler.Invoke(this, eventArgs);
            }
        }

        /// <summary>
        /// Raises the ActualMWChanged event
        /// </summary>
        /// <param name="eventArgs">The event data</param>
        protected virtual void OnActualMWChanged(ValueChangedEventArgs eventArgs)
        {
            System.EventHandler<ValueChangedEventArgs> handler = this.ActualMWChanged;
            if ((handler != null))
            {
                handler.Invoke(this, eventArgs);
            }
        }

        private static ITypedElement RetrieveRTOReference()
        {
            return ((ITypedElement)(((ModelElement)(SecurityConstraints.ClassInstance)).Resolve("RTO")));
        }

        /// <summary>
        /// Raises the RTOChanging event
        /// </summary>
        /// <param name="eventArgs">The event data</param>
        protected virtual void OnRTOChanging(ValueChangedEventArgs eventArgs)
        {
            System.EventHandler<ValueChangedEventArgs> handler = this.RTOChanging;
            if ((handler != null))
            {
                handler.Invoke(this, eventArgs);
            }
        }

        /// <summary>
        /// Raises the RTOChanged event
        /// </summary>
        /// <param name="eventArgs">The event data</param>
        protected virtual void OnRTOChanged(ValueChangedEventArgs eventArgs)
        {
            System.EventHandler<ValueChangedEventArgs> handler = this.RTOChanged;
            if ((handler != null))
            {
                handler.Invoke(this, eventArgs);
            }
        }

        /// <summary>
        /// Handles the event that the RTO property must reset
        /// </summary>
        /// <param name="sender">The object that sent this reset request</param>
        /// <param name="eventArgs">The event data for the reset event</param>
        private void OnResetRTO(object sender, System.EventArgs eventArgs)
        {
            this.RTO = null;
        }

        /// <summary>
        /// Resolves the given attribute name
        /// </summary>
        /// <returns>The attribute value or null if it could not be found</returns>
        /// <param name="attribute">The requested attribute name</param>
        /// <param name="index">The index of this attribute</param>
        protected override object GetAttributeValue(string attribute, int index)
        {
            if ((attribute == "MINMW"))
            {
                return this.MinMW;
            }
            if ((attribute == "MAXMW"))
            {
                return this.MaxMW;
            }
            if ((attribute == "ACTUALMW"))
            {
                return this.ActualMW;
            }
            return base.GetAttributeValue(attribute, index);
        }

        /// <summary>
        /// Sets a value to the given feature
        /// </summary>
        /// <param name="feature">The requested feature</param>
        /// <param name="value">The value that should be set to that feature</param>
        protected override void SetFeature(string feature, object value)
        {
            if ((feature == "RTO"))
            {
                this.RTO = ((IRTO)(value));
                return;
            }
            if ((feature == "MINMW"))
            {
                this.MinMW = ((float)(value));
                return;
            }
            if ((feature == "MAXMW"))
            {
                this.MaxMW = ((float)(value));
                return;
            }
            if ((feature == "ACTUALMW"))
            {
                this.ActualMW = ((float)(value));
                return;
            }
            base.SetFeature(feature, value);
        }

        /// <summary>
        /// Gets the property expression for the given attribute
        /// </summary>
        /// <returns>An incremental property expression</returns>
        /// <param name="attribute">The requested attribute in upper case</param>
        protected override NMF.Expressions.INotifyExpression<object> GetExpressionForAttribute(string attribute)
        {
            if ((attribute == "RTO"))
            {
                return new RTOProxy(this);
            }
            return base.GetExpressionForAttribute(attribute);
        }

        /// <summary>
        /// Gets the property expression for the given reference
        /// </summary>
        /// <returns>An incremental property expression</returns>
        /// <param name="reference">The requested reference in upper case</param>
        protected override NMF.Expressions.INotifyExpression<NMF.Models.IModelElement> GetExpressionForReference(string reference)
        {
            if ((reference == "RTO"))
            {
                return new RTOProxy(this);
            }
            return base.GetExpressionForReference(reference);
        }

        /// <summary>
        /// Gets the Class for this model element
        /// </summary>
        public override IClass GetClass()
        {
            if ((_classInstance == null))
            {
                _classInstance = ((IClass)(MetaRepository.Instance.Resolve("http://iec.ch/TC57/2009/CIM-schema-cim14#//IEC61970/Informative/MarketOperations/" +
                        "SecurityConstraints")));
            }
            return _classInstance;
        }

        /// <summary>
        /// The collection class to to represent the children of the SecurityConstraints class
        /// </summary>
        public class SecurityConstraintsReferencedElementsCollection : ReferenceCollection, ICollectionExpression<IModelElement>, ICollection<IModelElement>
        {

            private SecurityConstraints _parent;

            /// <summary>
            /// Creates a new instance
            /// </summary>
            public SecurityConstraintsReferencedElementsCollection(SecurityConstraints parent)
            {
                this._parent = parent;
            }

            /// <summary>
            /// Gets the amount of elements contained in this collection
            /// </summary>
            public override int Count
            {
                get
                {
                    int count = 0;
                    if ((this._parent.RTO != null))
                    {
                        count = (count + 1);
                    }
                    return count;
                }
            }

            protected override void AttachCore()
            {
                this._parent.RTOChanged += this.PropagateValueChanges;
            }

            protected override void DetachCore()
            {
                this._parent.RTOChanged -= this.PropagateValueChanges;
            }

            /// <summary>
            /// Adds the given element to the collection
            /// </summary>
            /// <param name="item">The item to add</param>
            public override void Add(IModelElement item)
            {
                if ((this._parent.RTO == null))
                {
                    IRTO rTOCasted = item.As<IRTO>();
                    if ((rTOCasted != null))
                    {
                        this._parent.RTO = rTOCasted;
                        return;
                    }
                }
            }

            /// <summary>
            /// Clears the collection and resets all references that implement it.
            /// </summary>
            public override void Clear()
            {
                this._parent.RTO = null;
            }

            /// <summary>
            /// Gets a value indicating whether the given element is contained in the collection
            /// </summary>
            /// <returns>True, if it is contained, otherwise False</returns>
            /// <param name="item">The item that should be looked out for</param>
            public override bool Contains(IModelElement item)
            {
                if ((item == this._parent.RTO))
                {
                    return true;
                }
                return false;
            }

            /// <summary>
            /// Copies the contents of the collection to the given array starting from the given array index
            /// </summary>
            /// <param name="array">The array in which the elements should be copied</param>
            /// <param name="arrayIndex">The starting index</param>
            public override void CopyTo(IModelElement[] array, int arrayIndex)
            {
                if ((this._parent.RTO != null))
                {
                    array[arrayIndex] = this._parent.RTO;
                    arrayIndex = (arrayIndex + 1);
                }
            }

            /// <summary>
            /// Removes the given item from the collection
            /// </summary>
            /// <returns>True, if the item was removed, otherwise False</returns>
            /// <param name="item">The item that should be removed</param>
            public override bool Remove(IModelElement item)
            {
                if ((this._parent.RTO == item))
                {
                    this._parent.RTO = null;
                    return true;
                }
                return false;
            }

            /// <summary>
            /// Gets an enumerator that enumerates the collection
            /// </summary>
            /// <returns>A generic enumerator</returns>
            public override IEnumerator<IModelElement> GetEnumerator()
            {
                return Enumerable.Empty<IModelElement>().Concat(this._parent.RTO).GetEnumerator();
            }
        }

        /// <summary>
        /// Represents a proxy to represent an incremental access to the minMW property
        /// </summary>
        private sealed class MinMWProxy : ModelPropertyChange<ISecurityConstraints, float>
        {

            /// <summary>
            /// Creates a new observable property access proxy
            /// </summary>
            /// <param name="modelElement">The model instance element for which to create the property access proxy</param>
            public MinMWProxy(ISecurityConstraints modelElement) :
                    base(modelElement, "minMW")
            {
            }

            /// <summary>
            /// Gets or sets the value of this expression
            /// </summary>
            public override float Value
            {
                get
                {
                    return this.ModelElement.MinMW;
                }
                set
                {
                    this.ModelElement.MinMW = value;
                }
            }
        }

        /// <summary>
        /// Represents a proxy to represent an incremental access to the maxMW property
        /// </summary>
        private sealed class MaxMWProxy : ModelPropertyChange<ISecurityConstraints, float>
        {

            /// <summary>
            /// Creates a new observable property access proxy
            /// </summary>
            /// <param name="modelElement">The model instance element for which to create the property access proxy</param>
            public MaxMWProxy(ISecurityConstraints modelElement) :
                    base(modelElement, "maxMW")
            {
            }

            /// <summary>
            /// Gets or sets the value of this expression
            /// </summary>
            public override float Value
            {
                get
                {
                    return this.ModelElement.MaxMW;
                }
                set
                {
                    this.ModelElement.MaxMW = value;
                }
            }
        }

        /// <summary>
        /// Represents a proxy to represent an incremental access to the actualMW property
        /// </summary>
        private sealed class ActualMWProxy : ModelPropertyChange<ISecurityConstraints, float>
        {

            /// <summary>
            /// Creates a new observable property access proxy
            /// </summary>
            /// <param name="modelElement">The model instance element for which to create the property access proxy</param>
            public ActualMWProxy(ISecurityConstraints modelElement) :
                    base(modelElement, "actualMW")
            {
            }

            /// <summary>
            /// Gets or sets the value of this expression
            /// </summary>
            public override float Value
            {
                get
                {
                    return this.ModelElement.ActualMW;
                }
                set
                {
                    this.ModelElement.ActualMW = value;
                }
            }
        }

        /// <summary>
        /// Represents a proxy to represent an incremental access to the RTO property
        /// </summary>
        private sealed class RTOProxy : ModelPropertyChange<ISecurityConstraints, IRTO>
        {

            /// <summary>
            /// Creates a new observable property access proxy
            /// </summary>
            /// <param name="modelElement">The model instance element for which to create the property access proxy</param>
            public RTOProxy(ISecurityConstraints modelElement) :
                    base(modelElement, "RTO")
            {
            }

            /// <summary>
            /// Gets or sets the value of this expression
            /// </summary>
            public override IRTO Value
            {
                get
                {
                    return this.ModelElement.RTO;
                }
                set
                {
                    this.ModelElement.RTO = value;
                }
            }
        }
    }
}


text:
using System.Linq;
using System.Reflection;
using GraphQL.Server.Sample.Operations;
using GraphQL.Server.Sample.Repository;
using GraphQL.Server.Security;
using GraphQL.Server.SimpleInjector;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using NUnit.Framework;

namespace GraphQL.Server.Test
{
    public class TestBase
    {
        private JsonSerializerSettings SerializerSettings { get; set; }
        private DocumentExecuter Executer { get; set; }
        private GraphQLContainer Container { get; set; }
        private AuthorizationMap AuthorizationMap { get; set; }
        private ApiSchema Schema { get; set; }
        public Data Data { get; set; }

        [SetUp]
        public void SetUp()
        {
            SerializerSettings = new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.None,
                Formatting = Formatting.Indented,
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
            SerializerSettings.Converters.Add(new StringEnumConverter());
            Container = new GraphQLContainer();
            Data = new Data();
            AuthorizationMap = new AuthorizationMap()
            {
                AllowMissingAuthorizations = true
            };

            Container.Register<IContainer>(() => Container);
            Container.Register(() => Data);
            Container.Register(() => AuthorizationMap);
            Container.Register<AllOperations>();
            Schema = new ApiSchema(Container);
            Schema.MapAssemblies(Assembly.GetAssembly(typeof(AllOperations)));
            Container.Verify();

            Executer = new DocumentExecuter();

            Schema.Lock();
        }

        protected void AssertQuery(string query, Inputs inputs, string expectedJson)
        {
            var actualJson = RunOperation(query, inputs);
            var expectedObject = JsonConvert.DeserializeObject(expectedJson);
            expectedJson = JsonConvert.SerializeObject(expectedObject, SerializerSettings);
            StringAssert.Contains(expectedJson, actualJson);
        }

        private string RunOperation(string query, Inputs inputs)
        {
            var executionOptions = new ExecutionOptions()
            {
                Schema = Schema,
                Query = query,
                Inputs = inputs
            };
            var executionResult = Executer.ExecuteAsync(executionOptions).Result;
            var output = new GraphQLOutput(executionResult.Data, executionResult.Errors?.ToArray());
            return JsonConvert.SerializeObject(output, SerializerSettings);
        }
    }
}


text:
#include <AudioToolbox/AudioFormat.h>
#include <Accelerate/Accelerate.h>

#include <speex/speex.h>
#include <speex/speex_header.h>
#include <speex/speex_callbacks.h>

#include "OggSpeexDecoder.h"
#include "CFWrapper.h"
#include "CFErrorUtilities.h"
#include "Logger.h"

#define MAX_FRAME_SIZE 2000
#define READ_SIZE_BYTES 4096

namespace {

	void RegisterOggSpeexDecoder() __attribute__ ((constructor));
	void RegisterOggSpeexDecoder()
	{
		SFB::Audio::Decoder::RegisterSubclass<SFB::Audio::OggSpeexDecoder>();
	}

}

#pragma mark Static Methods

CFArrayRef SFB::Audio::OggSpeexDecoder::CreateSupportedFileExtensions()
{
	CFStringRef supportedExtensions [] = { CFSTR("spx") };
	return CFArrayCreate(kCFAllocatorDefault, (const void **)supportedExtensions, 1, &kCFTypeArrayCallBacks);
}

CFArrayRef SFB::Audio::OggSpeexDecoder::CreateSupportedMIMETypes()
{
	CFStringRef supportedMIMETypes [] = { CFSTR("audio/speex"), CFSTR("audio/ogg") };
	return CFArrayCreate(kCFAllocatorDefault, (const void **)supportedMIMETypes, 2, &kCFTypeArrayCallBacks);
}

bool SFB::Audio::OggSpeexDecoder::HandlesFilesWithExtension(CFStringRef extension)
{
	if(nullptr == extension)
		return false;

	if(kCFCompareEqualTo == CFStringCompare(extension, CFSTR("spx"), kCFCompareCaseInsensitive))
		return true;

	return false;
}

bool SFB::Audio::OggSpeexDecoder::HandlesMIMEType(CFStringRef mimeType)
{
	if(nullptr == mimeType)
		return false;

	if(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR("audio/speex"), kCFCompareCaseInsensitive))
		return true;

	if(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR("audio/ogg"), kCFCompareCaseInsensitive))
		return true;

	return false;
}

SFB::Audio::Decoder::unique_ptr SFB::Audio::OggSpeexDecoder::CreateDecoder(InputSource::unique_ptr inputSource)
{
	return unique_ptr(new OggSpeexDecoder(std::move(inputSource)));
}

#pragma mark Creation and Destruction

SFB::Audio::OggSpeexDecoder::OggSpeexDecoder(InputSource::unique_ptr inputSource)
	: Decoder(std::move(inputSource)), mSpeexDecoder(nullptr), mCurrentFrame(0), mTotalFrames(-1), mOggPacketCount(0), mSpeexFramesPerOggPacket(0), mExtraSpeexHeaderCount(0), mSpeexSerialNumber(-1), mSpeexEOSReached(false)
{}

SFB::Audio::OggSpeexDecoder::~OggSpeexDecoder()
{
	if(IsOpen())
		Close();
}

#pragma mark Functionality

bool SFB::Audio::OggSpeexDecoder::_Open(CFErrorRef *error)
{
	// Initialize Ogg data struct
	ogg_sync_init(&mOggSyncState);

	// Get the ogg buffer for writing
	char *data = ogg_sync_buffer(&mOggSyncState, READ_SIZE_BYTES);

	// Read bitstream from input file
	ssize_t bytesRead = (ssize_t)GetInputSource().Read(data, READ_SIZE_BYTES);
	if(-1 == bytesRead) {
		if(error) {
			SFB::CFString description = CFCopyLocalizedString(CFSTR("The file "%@" could not be read."), "");
			SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Read error"), "");
			SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("Unable to read from the input file."), "");

			*error = CreateErrorForURL(Decoder::ErrorDomain, Decoder::InputOutputError, description, mInputSource->GetURL(), failureReason, recoverySuggestion);
		}

		ogg_sync_destroy(&mOggSyncState);
		return false;
	}

	// Tell the sync layer how many bytes were written to its internal buffer
	int result = ogg_sync_wrote(&mOggSyncState, bytesRead);
	if(-1 == result) {
		if(error) {
			SFB::CFString description = CFCopyLocalizedString(CFSTR("The file "%@" is not a valid Ogg file."), "");
			SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Not an Ogg file"), "");
			SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "");

			*error = CreateErrorForURL(Decoder::ErrorDomain, Decoder::InputOutputError, description, mInputSource->GetURL(), failureReason, recoverySuggestion);
		}

		ogg_sync_destroy(&mOggSyncState);
		return false;
	}

	// Turn the data we wrote into an ogg page
	result = ogg_sync_pageout(&mOggSyncState, &mOggPage);
	if(1 != result) {
		if(error) {
			SFB::CFString description = CFCopyLocalizedString(CFSTR("The file "%@" is not a valid Ogg file."), "");
			SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Not an Ogg file"), "");
			SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "");

			*error = CreateErrorForURL(Decoder::ErrorDomain, Decoder::InputOutputError, description, mInputSource->GetURL(), failureReason, recoverySuggestion);
		}

		ogg_sync_destroy(&mOggSyncState);
		return false;
	}

	// Initialize the stream and grab the serial number
	ogg_stream_init(&mOggStreamState, ogg_page_serialno(&mOggPage));

	// Get the first Ogg page
	result = ogg_stream_pagein(&mOggStreamState, &mOggPage);
	if(0 != result) {
		if(error) {
			SFB::CFString description = CFCopyLocalizedString(CFSTR("The file "%@" is not a valid Ogg file."), "");
			SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Not an Ogg file"), "");
			SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "");

			*error = CreateErrorForURL(Decoder::ErrorDomain, Decoder::InputOutputError, description, mInputSource->GetURL(), failureReason, recoverySuggestion);
		}

		ogg_sync_destroy(&mOggSyncState);
		return false;
	}

	// Get the first packet (should be the header) from the page
	ogg_packet op;
	result = ogg_stream_packetout(&mOggStreamState, &op);
	if(1 != result) {
		if(error) {
			SFB::CFString description = CFCopyLocalizedString(CFSTR("The file "%@" is not a valid Ogg file."), "");
			SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Not an Ogg file"), "");
			SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "");

			*error = CreateErrorForURL(Decoder::ErrorDomain, Decoder::InputOutputError, description, mInputSource->GetURL(), failureReason, recoverySuggestion);
		}

		ogg_sync_destroy(&mOggSyncState);
		return false;
	}

	if(op.bytes >= 5 && !memcmp(op.packet, "Speex", 5))
		mSpeexSerialNumber = mOggStreamState.serialno;

	++mOggPacketCount;

	// Convert the packet to the Speex header
	SpeexHeader *header = speex_packet_to_header((char *)op.packet, (int)op.bytes);
	if(nullptr == header) {
		if(error) {
			SFB::CFString description = CFCopyLocalizedString(CFSTR("The file "%@" is not a valid Ogg Speex file."), "");
			SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Not an Ogg Speex file"), "");
			SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "");

			*error = CreateErrorForURL(Decoder::ErrorDomain, Decoder::FileFormatNotRecognizedError, description, mInputSource->GetURL(), failureReason, recoverySuggestion);
		}

		ogg_sync_destroy(&mOggSyncState);
		return false;
	}
	else if(SPEEX_NB_MODES <= header->mode) {
		if(error) {
			SFB::CFString description = CFCopyLocalizedString(CFSTR("The Speex mode in the file "%@" is not supported."), "");
			SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Unsupported Ogg Speex file mode"), "");
			SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("This file may have been encoded with a newer version of Speex."), "");

			*error = CreateErrorForURL(Decoder::ErrorDomain, Decoder::FileFormatNotSupportedError, description, mInputSource->GetURL(), failureReason, recoverySuggestion);
		}

		speex_header_free(header), header = nullptr;
		ogg_sync_destroy(&mOggSyncState);
		return false;
	}

	const SpeexMode *mode = speex_lib_get_mode(header->mode);
	if(mode->bitstream_version != header->mode_bitstream_version) {
		if(error) {
			SFB::CFString description = CFCopyLocalizedString(CFSTR("The Speex version in the file "%@" is not supported."), "");
			SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Unsupported Ogg Speex file version"), "");
			SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("This file was encoded with a different version of Speex."), "");

			*error = CreateErrorForURL(Decoder::ErrorDomain, Decoder::FileFormatNotSupportedError, description, mInputSource->GetURL(), failureReason, recoverySuggestion);
		}

		speex_header_free(header), header = nullptr;
		ogg_sync_destroy(&mOggSyncState);
		return false;
	}

	// Initialize the decoder
	mSpeexDecoder = speex_decoder_init(mode);
	if(nullptr== mSpeexDecoder) {
		if(error) {
			SFB::CFString description = CFCopyLocalizedString(CFSTR("Unable to initialize the Speex decoder."), "");
			SFB::CFString failureReason = CFCopyLocalizedString(CFSTR("Error initializing Speex decoder"), "");
			SFB::CFString recoverySuggestion = CFCopyLocalizedString(CFSTR("An unknown error occurred."), "");

			*error = CreateErrorForURL(Decoder::ErrorDomain, Decoder::InputOutputError, description, mInputSource->GetURL(), failureReason, recoverySuggestion);
		}

		speex_header_free(header), header = nullptr;
		ogg_sync_destroy(&mOggSyncState);
		return false;
	}

	speex_decoder_ctl(mSpeexDecoder, SPEEX_SET_SAMPLING_RATE, &header->rate);

	mSpeexFramesPerOggPacket = (0 == header->frames_per_packet ? 1 : header->frames_per_packet);
	mExtraSpeexHeaderCount = (UInt32)header->extra_headers;

	// Initialize the speex bit-packing data structure
	speex_bits_init(&mSpeexBits);

	// Initialize the stereo mode
	mSpeexStereoState = speex_stereo_state_init();

	if(2 == header->nb_channels) {
		SpeexCallback callback;
		callback.callback_id = SPEEX_INBAND_STEREO;
		callback.func = speex_std_stereo_request_handler;
		callback.data = mSpeexStereoState;
		speex_decoder_ctl(mSpeexDecoder, SPEEX_SET_HANDLER, &callback);
	}

	// Canonical Core Audio format
	mFormat.mFormatID			= kAudioFormatLinearPCM;
	mFormat.mFormatFlags		= kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;

	mFormat.mBitsPerChannel		= 8 * sizeof(float);
	mFormat.mSampleRate			= header->rate;
	mFormat.mChannelsPerFrame	= (UInt32)header->nb_channels;

	mFormat.mBytesPerPacket		= (mFormat.mBitsPerChannel / 8);
	mFormat.mFramesPerPacket	= 1;
	mFormat.mBytesPerFrame		= mFormat.mBytesPerPacket * mFormat.mFramesPerPacket;

	mFormat.mReserved			= 0;

	// Set up the source format
	mSourceFormat.mFormatID				= 'SPEE';

	mSourceFormat.mSampleRate			= header->rate;
	mSourceFormat.mChannelsPerFrame		= (UInt32)header->nb_channels;

	switch(header->nb_channels) {
		case 1:		mChannelLayout = ChannelLayout::ChannelLayoutWithTag(kAudioChannelLayoutTag_Mono);		break;
		case 2:		mChannelLayout = ChannelLayout::ChannelLayoutWithTag(kAudioChannelLayoutTag_Stereo);	break;
	}

	speex_header_free(header), header = nullptr;

	// Allocate the buffer list
	spx_int32_t speexFrameSize = 0;
	speex_decoder_ctl(mSpeexDecoder, SPEEX_GET_FRAME_SIZE, &speexFrameSize);

	if(!mBufferList.Allocate(mFormat, (UInt32)speexFrameSize)) {
		if(error)
			*error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, ENOMEM, nullptr);

		speex_header_free(header), header = nullptr;
		speex_stereo_state_destroy(mSpeexStereoState), mSpeexStereoState = nullptr;
		speex_decoder_destroy(mSpeexDecoder), mSpeexDecoder = nullptr;
		speex_bits_destroy(&mSpeexBits);

		ogg_sync_destroy(&mOggSyncState);
		return false;
	}

	for(UInt32 i = 0; i < mBufferList->mNumberBuffers; ++i)
		mBufferList->mBuffers[i].mDataByteSize = 0;

	return true;
}

bool SFB::Audio::OggSpeexDecoder::_Close(CFErrorRef */*error*/)
{
	mBufferList.Deallocate();

	// Speex cleanup
	speex_stereo_state_destroy(mSpeexStereoState), mSpeexStereoState = nullptr;
	speex_decoder_destroy(mSpeexDecoder), mSpeexDecoder = nullptr;
	speex_bits_destroy(&mSpeexBits);

	// Ogg cleanup
	ogg_stream_clear(&mOggStreamState);
	ogg_sync_clear(&mOggSyncState);

	return true;
}

SFB::CFString SFB::Audio::OggSpeexDecoder::_GetSourceFormatDescription() const
{
	return CFStringCreateWithFormat(kCFAllocatorDefault,
									nullptr,
									CFSTR("Ogg Speex, %u channels, %u Hz"),
									(unsigned int)mSourceFormat.mChannelsPerFrame,
									(unsigned int)mSourceFormat.mSampleRate);
}

UInt32 SFB::Audio::OggSpeexDecoder::_ReadAudio(AudioBufferList *bufferList, UInt32 frameCount)
{
	if(bufferList->mNumberBuffers != mFormat.mChannelsPerFrame) {
		LOGGER_WARNING("org.sbooth.AudioEngine.Decoder.OggSpeex", "_ReadAudio() called with invalid parameters");
		return 0;
	}

	UInt32 framesRead = 0;

	// Reset output buffer data size
	for(UInt32 i = 0; i < bufferList->mNumberBuffers; ++i)
		bufferList->mBuffers[i].mDataByteSize = 0;

	for(;;) {

		UInt32	framesRemaining	= frameCount - framesRead;
		UInt32	framesToSkip	= (UInt32)(bufferList->mBuffers[0].mDataByteSize / sizeof(float));
		UInt32	framesInBuffer	= (UInt32)(mBufferList->mBuffers[0].mDataByteSize / sizeof(float));
		UInt32	framesToCopy	= std::min(framesInBuffer, framesRemaining);

		// Copy data from the buffer to output
		for(UInt32 i = 0; i < mBufferList->mNumberBuffers; ++i) {
			float *floatBuffer = (float *)bufferList->mBuffers[i].mData;
			memcpy(floatBuffer + framesToSkip, mBufferList->mBuffers[i].mData, framesToCopy * sizeof(float));
			bufferList->mBuffers[i].mDataByteSize += framesToCopy * sizeof(float);

			// Move remaining data in buffer to beginning
			if(framesToCopy != framesInBuffer) {
				floatBuffer = (float *)mBufferList->mBuffers[i].mData;
				memmove(floatBuffer, floatBuffer + framesToCopy, (framesInBuffer - framesToCopy) * sizeof(float));
			}

			mBufferList->mBuffers[i].mDataByteSize -= framesToCopy * sizeof(float);
		}

		framesRead += framesToCopy;

		// All requested frames were read
		if(framesRead == frameCount)
			break;

		// EOS reached
		if(mSpeexEOSReached)
			break;

		// Attempt to process the desired number of packets
		unsigned packetsDesired = 1;
		while(0 < packetsDesired && !mSpeexEOSReached) {

			// Process any packets in the current page
			while(0 < packetsDesired && !mSpeexEOSReached) {

				// Grab a packet from the streaming layer
				ogg_packet oggPacket;
				int result = ogg_stream_packetout(&mOggStreamState, &oggPacket);
				if(-1 == result) {
					LOGGER_ERR("org.sbooth.AudioEngine.Decoder.OggSpeex", "Ogg Speex decoding error: Ogg loss of streaming");
					break;
				}

				// If result is 0, there is insufficient data to assemble a packet
				if(0 == result)
					break;

				// Otherwise, we got a valid packet for processing
				if(1 == result) {
					if(5 <= oggPacket.bytes && !memcmp(oggPacket.packet, "Speex", 5))
						mSpeexSerialNumber = mOggStreamState.serialno;

					if(-1 == mSpeexSerialNumber || mOggStreamState.serialno != mSpeexSerialNumber)
						break;

					// Ignore the following:
					//  - Speex comments in packet #2
					//  - Extra headers (optionally) in packets 3+
					if(1 != mOggPacketCount && 1 + mExtraSpeexHeaderCount <= mOggPacketCount) {
						// Detect Speex EOS
						if(oggPacket.e_o_s && mOggStreamState.serialno == mSpeexSerialNumber)
							mSpeexEOSReached = true;

						// SPEEX_GET_FRAME_SIZE is in samples
						spx_int32_t speexFrameSize;
						speex_decoder_ctl(mSpeexDecoder, SPEEX_GET_FRAME_SIZE, &speexFrameSize);
						float buffer [(2 == mFormat.mChannelsPerFrame) ? 2 * speexFrameSize : speexFrameSize];

						// Copy the Ogg packet to the Speex bitstream
						speex_bits_read_from(&mSpeexBits, (char *)oggPacket.packet, (int)oggPacket.bytes);

						// Decode each frame in the Speex packet
						for(spx_int32_t i = 0; i < mSpeexFramesPerOggPacket; ++i) {

							result = speex_decode(mSpeexDecoder, &mSpeexBits, buffer);

							// -1 indicates EOS
							if(-1 == result)
								break;
							else if(-2 == result) {
								LOGGER_ERR("org.sbooth.AudioEngine.Decoder.OggSpeex", "Ogg Speex decoding error: possible corrupted stream");
								break;
							}

							if(0 > speex_bits_remaining(&mSpeexBits)) {
								LOGGER_ERR("org.sbooth.AudioEngine.Decoder.OggSpeex", "Ogg Speex decoding overflow: possible corrupted stream");
								break;
							}

							// Normalize the values
							float maxSampleValue = 1u << 15;
							vDSP_vsdiv(buffer, 1, &maxSampleValue, buffer, 1, (vDSP_Length)speexFrameSize);

							// Copy the frames from the decoding buffer to the output buffer, skipping over any frames already decoded
							framesInBuffer = mBufferList->mBuffers[0].mDataByteSize / sizeof(float);
							memcpy((float *)mBufferList->mBuffers[0].mData + framesInBuffer, buffer, (size_t)speexFrameSize * sizeof(float));
							mBufferList->mBuffers[0].mDataByteSize += (size_t)speexFrameSize * sizeof(float);

							// Process stereo channel, if present
							if(2 == mFormat.mChannelsPerFrame) {
								speex_decode_stereo(buffer, speexFrameSize, mSpeexStereoState);
								vDSP_vsdiv(buffer + speexFrameSize, 1, &maxSampleValue, buffer + speexFrameSize, 1, (vDSP_Length)speexFrameSize);

								memcpy((float *)mBufferList->mBuffers[1].mData + framesInBuffer, buffer + speexFrameSize, (size_t)speexFrameSize * sizeof(float));
								mBufferList->mBuffers[1].mDataByteSize += (size_t)speexFrameSize * sizeof(float);
							}

							// Packet processing finished
							--packetsDesired;
						}
					}

					++mOggPacketCount;
				}
			}

			// Grab a new Ogg page for processing, if necessary
			if(!mSpeexEOSReached && 0 < packetsDesired) {
				while(1 != ogg_sync_pageout(&mOggSyncState, &mOggPage)) {
					// Get the ogg buffer for writing
					char *data = ogg_sync_buffer(&mOggSyncState, READ_SIZE_BYTES);

					// Read bitstream from input file
					ssize_t bytesRead = (ssize_t)GetInputSource().Read(data, READ_SIZE_BYTES);
					if(-1 == bytesRead) {
						LOGGER_ERR("org.sbooth.AudioEngine.Decoder.OggSpeex", "Unable to read from the input file");
						break;
					}

					ogg_sync_wrote(&mOggSyncState, bytesRead);

					// No more data available from input file
					if(0 == bytesRead)
						break;
				}

				// Ensure all Ogg streams are read
				if(ogg_page_serialno(&mOggPage) != mOggStreamState.serialno)
					ogg_stream_reset_serialno(&mOggStreamState, ogg_page_serialno(&mOggPage));

				// Get the resultant Ogg page
				int result = ogg_stream_pagein(&mOggStreamState, &mOggPage);
				if(0 != result) {
					LOGGER_ERR("org.sbooth.AudioEngine.Decoder.OggSpeex", "Error reading Ogg page");
					break;
				}
			}
		}
	}

	mCurrentFrame += framesRead;

	if(0 == framesRead && mSpeexEOSReached)
		mTotalFrames = mCurrentFrame;

	return framesRead;
}


text:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_example_balamex_BalamexLib */

#ifndef _Included_com_example_balamex_BalamexLib
#define _Included_com_example_balamex_BalamexLib
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_example_balamex_BalamexLib
 * Method:    balamatorIOn
 * Signature: (J)J
 */
JNIEXPORT jlong JNICALL Java_com_example_balamex_BalamexLib_balamatorIOn
  (JNIEnv *, jclass, jlong);

/*
 * Class:     com_example_balamex_BalamexLib
 * Method:    balamatorIOff
 * Signature: (J)J
 */
JNIEXPORT jlong JNICALL Java_com_example_balamex_BalamexLib_balamatorIOff
  (JNIEnv *, jclass, jlong);

#ifdef __cplusplus
}
#endif
#endif


text:
namespace gfx {

namespace {

SkColor GetColorAtTopLeft(const Canvas& canvas) {
  return canvas.GetBitmap().getColor(0, 0);
}

class MockCanvas : public SkCanvas {
 public:
  MockCanvas(int width, int height) : SkCanvas(width, height) {}

  MockCanvas(const MockCanvas&) = delete;
  MockCanvas& operator=(const MockCanvas&) = delete;

  // SkCanvas overrides:
  void onDrawPath(const SkPath& path, const SkPaint& paint) override {
    paths_.push_back(path);
  }

  const std::vector<SkPath>& paths() const { return paths_; }

 private:
  std::vector<SkPath> paths_;
};

// Tests that a relative move to command (R_MOVE_TO) after a close command
// (CLOSE) uses the correct starting point. See crbug.com/697497
TEST(VectorIconTest, RelativeMoveToAfterClose) {
  cc::PaintRecorder recorder;
  Canvas canvas(recorder.beginRecording(100, 100), 1.0f);

  const PathElement elements[] = {
      MOVE_TO, 4, 5, LINE_TO, 10, 11, CLOSE,
      // This move should use (4, 5) as the start point rather than (10, 11).
      R_MOVE_TO, 20, 21, R_LINE_TO, 50, 51};
  const VectorIconRep rep_list[] = {{elements, std::size(elements)}};
  const VectorIcon icon(rep_list, 1u, nullptr);

  PaintVectorIcon(&canvas, icon, 100, SK_ColorMAGENTA);
  sk_sp<cc::PaintRecord> record = recorder.finishRecordingAsPicture();

  MockCanvas mock(100, 100);
  record->Playback(&mock);

  ASSERT_EQ(1U, mock.paths().size());
  SkPoint last_point;
  EXPECT_TRUE(mock.paths()[0].getLastPt(&last_point));
  EXPECT_EQ(SkIntToScalar(74), last_point.x());
  EXPECT_EQ(SkIntToScalar(77), last_point.y());
}

TEST(VectorIconTest, FlipsInRtl) {
  // Set the locale to a rtl language otherwise FLIPS_IN_RTL will do nothing.
  base::i18n::SetICUDefaultLocale("he");
  ASSERT_TRUE(base::i18n::IsRTL());

  const int canvas_size = 20;
  const SkColor color = SK_ColorWHITE;

  Canvas canvas(gfx::Size(canvas_size, canvas_size), 1.0f, true);

  // Create a 20x20 square icon which has FLIPS_IN_RTL, and CANVAS_DIMENSIONS
  // are twice as large as |canvas|.
  const PathElement elements[] = {CANVAS_DIMENSIONS,
                                  2 * canvas_size,
                                  FLIPS_IN_RTL,
                                  MOVE_TO,
                                  10,
                                  10,
                                  R_H_LINE_TO,
                                  20,
                                  R_V_LINE_TO,
                                  20,
                                  R_H_LINE_TO,
                                  -20,
                                  CLOSE};
  const VectorIconRep rep_list[] = {{elements, std::size(elements)}};
  const VectorIcon icon(rep_list, 1u, nullptr);
  PaintVectorIcon(&canvas, icon, canvas_size, color);

  // Count the number of pixels in the canvas.
  auto bitmap = canvas.GetBitmap();
  int colored_pixel_count = 0;
  for (int i = 0; i < bitmap.width(); ++i) {
    for (int j = 0; j < bitmap.height(); ++j) {
      if (bitmap.getColor(i, j) == color)
        colored_pixel_count++;
    }
  }

  // Verify that the amount of colored pixels on the canvas bitmap should be a
  // quarter of the original icon, since each side should be scaled down by a
  // factor of two.
  EXPECT_EQ(100, colored_pixel_count);
}

TEST(VectorIconTest, CorrectSizePainted) {
  // Create a set of 5 icons reps, sized {48, 32, 24, 20, 16} for the test icon.
  // Color each of them differently so they can be differentiated (the parts of
  // an icon painted with PATH_COLOR_ARGB will not be overwritten by the color
  // provided to it at creation time).
  const SkColor kPath48Color = SK_ColorRED;
  const PathElement elements48[] = {CANVAS_DIMENSIONS,
                                    48,
                                    PATH_COLOR_ARGB,
                                    0xFF,
                                    SkColorGetR(kPath48Color),
                                    SkColorGetG(kPath48Color),
                                    SkColorGetB(kPath48Color),
                                    MOVE_TO,
                                    0,
                                    0,
                                    H_LINE_TO,
                                    48,
                                    V_LINE_TO,
                                    48,
                                    H_LINE_TO,
                                    0,
                                    V_LINE_TO,
                                    0,
                                    CLOSE};
  const SkColor kPath32Color = SK_ColorGREEN;
  const PathElement elements32[] = {CANVAS_DIMENSIONS,
                                    32,
                                    PATH_COLOR_ARGB,
                                    0xFF,
                                    SkColorGetR(kPath32Color),
                                    SkColorGetG(kPath32Color),
                                    SkColorGetB(kPath32Color),
                                    MOVE_TO,
                                    0,
                                    0,
                                    H_LINE_TO,
                                    32,
                                    V_LINE_TO,
                                    32,
                                    H_LINE_TO,
                                    0,
                                    V_LINE_TO,
                                    0,
                                    CLOSE};
  const SkColor kPath24Color = SK_ColorBLUE;
  const PathElement elements24[] = {CANVAS_DIMENSIONS,
                                    24,
                                    PATH_COLOR_ARGB,
                                    0xFF,
                                    SkColorGetR(kPath24Color),
                                    SkColorGetG(kPath24Color),
                                    SkColorGetB(kPath24Color),
                                    MOVE_TO,
                                    0,
                                    0,
                                    H_LINE_TO,
                                    24,
                                    V_LINE_TO,
                                    24,
                                    H_LINE_TO,
                                    0,
                                    V_LINE_TO,
                                    0,
                                    CLOSE};
  const SkColor kPath20Color = SK_ColorYELLOW;
  const PathElement elements20[] = {CANVAS_DIMENSIONS,
                                    20,
                                    PATH_COLOR_ARGB,
                                    0xFF,
                                    SkColorGetR(kPath20Color),
                                    SkColorGetG(kPath20Color),
                                    SkColorGetB(kPath20Color),
                                    MOVE_TO,
                                    0,
                                    0,
                                    H_LINE_TO,
                                    20,
                                    V_LINE_TO,
                                    20,
                                    H_LINE_TO,
                                    0,
                                    V_LINE_TO,
                                    0,
                                    CLOSE};
  const SkColor kPath16Color = SK_ColorCYAN;
  const PathElement elements16[] = {CANVAS_DIMENSIONS,
                                    16,
                                    PATH_COLOR_ARGB,
                                    0xFF,
                                    SkColorGetR(kPath16Color),
                                    SkColorGetG(kPath16Color),
                                    SkColorGetB(kPath16Color),
                                    MOVE_TO,
                                    0,
                                    0,
                                    H_LINE_TO,
                                    16,
                                    V_LINE_TO,
                                    16,
                                    H_LINE_TO,
                                    0,
                                    V_LINE_TO,
                                    0,
                                    CLOSE};
  // VectorIconReps are always sorted in descending order of size.
  const VectorIconRep rep_list[] = {{elements48, std::size(elements48)},
                                    {elements32, std::size(elements32)},
                                    {elements24, std::size(elements24)},
                                    {elements20, std::size(elements20)},
                                    {elements16, std::size(elements16)}};
  const VectorIcon icon(rep_list, 5u, nullptr);

  // Test exact sizes paint the correctly sized icon, including the largest and
  // smallest icon.
  Canvas canvas_100(gfx::Size(100, 100), 1.0, true);
  PaintVectorIcon(&canvas_100, icon, 48, SK_ColorBLACK);
  EXPECT_EQ(kPath48Color, GetColorAtTopLeft(canvas_100));
  PaintVectorIcon(&canvas_100, icon, 32, SK_ColorBLACK);
  EXPECT_EQ(kPath32Color, GetColorAtTopLeft(canvas_100));
  PaintVectorIcon(&canvas_100, icon, 16, SK_ColorBLACK);
  EXPECT_EQ(kPath16Color, GetColorAtTopLeft(canvas_100));

  // The largest icon may be upscaled to a size larger than what it was
  // designed for.
  PaintVectorIcon(&canvas_100, icon, 50, SK_ColorBLACK);
  EXPECT_EQ(kPath48Color, GetColorAtTopLeft(canvas_100));

  // Other requests will be satisfied by downscaling.
  PaintVectorIcon(&canvas_100, icon, 27, SK_ColorBLACK);
  EXPECT_EQ(kPath32Color, GetColorAtTopLeft(canvas_100));
  PaintVectorIcon(&canvas_100, icon, 8, SK_ColorBLACK);
  EXPECT_EQ(kPath16Color, GetColorAtTopLeft(canvas_100));

  // Except in cases where an exact divisor is found.
  PaintVectorIcon(&canvas_100, icon, 40, SK_ColorBLACK);
  EXPECT_EQ(kPath20Color, GetColorAtTopLeft(canvas_100));
  PaintVectorIcon(&canvas_100, icon, 64, SK_ColorBLACK);
  EXPECT_EQ(kPath32Color, GetColorAtTopLeft(canvas_100));

  // Test icons at a scale factor < 100%, still with an exact size, paint the
  // correctly sized icon.
  Canvas canvas_75(gfx::Size(100, 100), 0.75, true);
  PaintVectorIcon(&canvas_75, icon, 32, SK_ColorBLACK);  // 32 * 0.75 = 24.
  EXPECT_EQ(kPath24Color, GetColorAtTopLeft(canvas_75));

  // Test icons at a scale factor > 100%, still with an exact size, paint the
  // correctly sized icon.
  Canvas canvas_125(gfx::Size(100, 100), 1.25, true);
  PaintVectorIcon(&canvas_125, icon, 16, SK_ColorBLACK);  // 16 * 1.25 = 20.
  EXPECT_EQ(kPath20Color, GetColorAtTopLeft(canvas_125));

  // Inexact sizes at scale factors < 100%.
  PaintVectorIcon(&canvas_75, icon, 12, SK_ColorBLACK);  // 12 * 0.75 = 9.
  EXPECT_EQ(kPath16Color, GetColorAtTopLeft(canvas_75));
  PaintVectorIcon(&canvas_75, icon, 28, SK_ColorBLACK);  // 28 * 0.75 = 21.
  EXPECT_EQ(kPath24Color, GetColorAtTopLeft(canvas_75));

  // Inexact sizes at scale factors > 100%.
  PaintVectorIcon(&canvas_125, icon, 12, SK_ColorBLACK);  // 12 * 1.25 = 15.
  EXPECT_EQ(kPath16Color, GetColorAtTopLeft(canvas_125));
  PaintVectorIcon(&canvas_125, icon, 28, SK_ColorBLACK);  // 28 * 1.25 = 35.
  EXPECT_EQ(kPath48Color, GetColorAtTopLeft(canvas_125));

  // Painting without a requested size will default to the smallest icon rep.
  PaintVectorIcon(&canvas_100, icon, SK_ColorBLACK);
  EXPECT_EQ(kPath16Color, GetColorAtTopLeft(canvas_100));
  // But doing this in another scale factor should assume the smallest icon rep
  // size, then scale it up by the DSF.
  PaintVectorIcon(&canvas_125, icon, SK_ColorBLACK);  // 16 * 1.25 = 20.
  EXPECT_EQ(kPath20Color, GetColorAtTopLeft(canvas_125));
}

}  // namespace

}  // namespace gfx


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        android:icon="@drawable/ic_search_white_24px"
        android:title="action_search"
        app:showAsAction="ifRoom|collapseActionView" />
    <item
        android:id="@+id/action_delete"
        android:icon="@drawable/ic_delete_white_24dp"
        android:title="delete"
        app:showAsAction="ifRoom|collapseActionView" />

    <item
        android:id="@+id/sort"
        android:icon="@drawable/ic_sort_white_24px"
        android:title="排序"
        app:showAsAction="ifRoom">
        <menu>
            <group>
                <item
                    android:id="@+id/sort_by_alpha"
                    android:title="Sort alphabetically" />
                <item
                    android:id="@+id/sort_by_time"
                    android:checked="true"
                    android:title="Sort by time" />
            </group>
        </menu>
    </item>

</menu>


text:
using System.Linq;
using EFSqlTranslator.EFModels;
using EFSqlTranslator.Translation;
using EFSqlTranslator.Translation.DbObjects.SqliteObjects;
using EFSqlTranslator.Translation.Extensions;
using Xunit;

namespace EFSqlTranslator.Tests.TranslatorTests
{
    public class DistinctCountTranslationTests
    {
        [Fact]
        public void Test_DistinctCount_In_GroupBy()
        {
            using (var db = new TestingContext())
            {
                var query = db.Posts.
                    Where(p => p.Content != null).
                    GroupBy(p => p.BlogId).
                    Select(g => new { cnt = g.DistinctCount(p => p.UserId) });

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory());
                var sql = script.ToString();

                const string expected = @"
select count(distinct p0.UserId) as 'cnt'
from Posts p0
where p0.Content is not null
group by p0.BlogId";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }

        [Fact]
        public void Test_DistinctCount_On_Child_Relation()
        {
            using (var db = new TestingContext())
            {
                var query = db.Blogs.
                    Where(b => b.Url != null).
                    Select(b => new
                    {
                        b.Name,
                        cnt = b.Posts.DistinctCount(p => p.PostId)
                    });

                var script = QueryTranslator.Translate(query.Expression, new EFModelInfoProvider(db), new SqliteObjectFactory());
                var sql = script.ToString();

                const string expected = @"
select b0.Name, coalesce(sq0.count0, 0) as 'cnt'
from Blogs b0
left outer join (
    select p0.BlogId as 'BlogId_jk0', count(distinct p0.PostId) as 'count0'
    from Posts p0
    group by p0.BlogId
) sq0 on b0.BlogId = sq0.BlogId_jk0
where b0.Url is not null";

                TestUtils.AssertStringEqual(expected, sql);
            }
        }
    }
}


text:
from .cli import run_pipeline, parse_args, parse_cell_magic

__all__ = ['run_pipeline', 'parse_args', 'parse_cell_magic']


text:
package org.hawkular.metrics.api.jaxrs.param;

import java.util.Arrays;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 * @author Thomas Segismont
 */
@RunWith(Parameterized.class)
public class InvalidDurationConverterTest {

    @Parameters(name = "{0}")
    public static Iterable<Object[]> params() {
        return Arrays.asList(
                new Object[][]{
                        {"jdklsqj 0484d8sq"},
                        {"1u"},
                        {"7du"},
                        {"45640894809"},
                        {"ms"},
                }
        );
    }

    @Rule
    public final ExpectedException expectedException = ExpectedException.none();

    private String value;

    public InvalidDurationConverterTest(String value) {
        this.value = value;
    }

    @Test
    public void testFromString() throws Exception {
        expectedException.expect(IllegalArgumentException.class);
        //noinspection ResultOfMethodCallIgnored
        new DurationConverter().fromString(value);
    }
}


text:
<!DOCTYPE html>
    <?php
    session_start();
    include('library/form/connection.php');
    include ('library/function/functions.php');
    $db = new db();
    $session_USER_FIRSTNAME = htmlspecialchars($_SESSION['USER_FIRSTNAME']);
    $session_USER_MIDDLENAME = htmlspecialchars($_SESSION['USER_MIDDLENAME']);
    $session_USER_LASTNAME = htmlspecialchars($_SESSION['USER_LASTNAME']);
    date_default_timezone_set('Asia/Hong_Kong');
    $time = time();

    $sql = 'SELECT * FROM disaster_type WHERE ID = ' . $_GET["disaster"];
    $result = $db->connection->query($sql);
    $count = mysqli_num_rows($result);
    $DisasterInfo = $result->fetch_assoc();

    ?>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Disaster Risk Management</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap-theme.min.css" rel="stylesheet">
    <link href="css/app.css" rel="stylesheet">
    <link href="css/jquery.datetimepicker.css" rel="stylesheet">

<?php include('library/html/navbar.php'); ?>

Forecasting  / Forecast Possible Casualties

                    Forecast

                    <span style="color: <?php echo $DisasterInfo['COLOR']; ?>;" class="glyphicon glyphicon-stop">
                    <?php echo $DisasterInfo['NAME']; ?>
                    in

                <form method="get" action="CdrrmoPredictionResult.php">
                    <input style="display: none;" name="disaster" type="text" value="<?php echo $DisasterInfo['ID']; ?>" />

                        District
                        <select id="District" name="District" class="form-control">
                        </select>

                        Barangay
                        <select id="Barangay" name="Barangay" class="form-control">
                        </select>

                        Year
                        <select id="Year" name="Year" class="form-control">
                        </select>

                    <button type="submit" class="btn btn-primary pull-right">Forecast </button>

                </form>

<?php include('library/html/footer.php'); ?>


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2014 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.chromium.native_test"
      android:versionCode="1"
      android:versionName="1.0">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS"/>
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.USE_CREDENTIALS"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <!-- Explicitly set the attribute requestLegacyExternalStorage to "true"
         since it is "false" by default on apps targeting Android 10, and that
         breaks test listing. See
         https://developer.android.com/training/data-storage#scoped-storage and
         https://developer.android.com/training/data-storage/compatibility. -->
    <application android:label="NativeTests"
            android:requestLegacyExternalStorage="true"
            android:name="org.chromium.native_test.NativeTestApplication">
        <activity android:name=".NativeUnitTestActivity"
                android:label="NativeTest"
                android:configChanges="orientation|keyboardHidden"
                android:exported="true"
                android:process=":test_process">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="org.chromium.net.test.DummySpnegoAuthenticatorService"
                android:exported="false"
                android:process=":test_process">
            <intent-filter>
                <action android:name="android.accounts.AccountAuthenticator" />
            </intent-filter>
            <meta-data android:name="android.accounts.AccountAuthenticator"
                     android:resource="@xml/dummy_spnego_authenticator" />
        </service>
    </application>

    <instrumentation android:name="org.chromium.build.gtest_apk.NativeTestInstrumentationTestRunner"
            android:targetPackage="org.chromium.native_test"
            android:label="Instrumentation entry point for org.chromium.native_test"
            chromium-junit3="true"/>

</manifest>


text:
export DYLD_FRAMEWORK_PATH=$BUILT_PRODUCTS_DIR

# Create an array of test executables
test_executables=("$BUILT_PRODUCTS_DIR/sample1_unittest"
                  "$BUILT_PRODUCTS_DIR/sample2_unittest"
                  "$BUILT_PRODUCTS_DIR/sample3_unittest"
                  "$BUILT_PRODUCTS_DIR/sample4_unittest"
                  "$BUILT_PRODUCTS_DIR/sample5_unittest"
                  "$BUILT_PRODUCTS_DIR/sample6_unittest"

                  "$BUILT_PRODUCTS_DIR/gtest_unittest"
                  "$BUILT_PRODUCTS_DIR/gtest-death-test_test"
                  "$BUILT_PRODUCTS_DIR/gtest-filepath_test"
                  "$BUILT_PRODUCTS_DIR/gtest-message_test"
                  "$BUILT_PRODUCTS_DIR/gtest-options_test"
                  "$BUILT_PRODUCTS_DIR/gtest_pred_impl_unittest"
                  "$BUILT_PRODUCTS_DIR/gtest_environment_test"
                  "$BUILT_PRODUCTS_DIR/gtest_no_test_unittest"
                  "$BUILT_PRODUCTS_DIR/gtest_main_unittest"
                  "$BUILT_PRODUCTS_DIR/gtest_prod_test"
                  "$BUILT_PRODUCTS_DIR/gtest_repeat_test"
                  "$BUILT_PRODUCTS_DIR/gtest_sole_header_test"
                  "$BUILT_PRODUCTS_DIR/gtest_stress_test"
                  "$BUILT_PRODUCTS_DIR/gtest_test_part_test"
                  "$BUILT_PRODUCTS_DIR/gtest-typed-test_test"

                  "$BUILT_PRODUCTS_DIR/gtest_output_test.py"
                  "$BUILT_PRODUCTS_DIR/gtest_color_test.py"
                  "$BUILT_PRODUCTS_DIR/gtest_env_var_test.py"
                  "$BUILT_PRODUCTS_DIR/gtest_filter_unittest.py"
                  "$BUILT_PRODUCTS_DIR/gtest_break_on_failure_unittest.py"
                  "$BUILT_PRODUCTS_DIR/gtest_list_tests_unittest.py"
                  "$BUILT_PRODUCTS_DIR/gtest_xml_output_unittest.py"
                  "$BUILT_PRODUCTS_DIR/gtest_xml_outfiles_test.py"
                  "$BUILT_PRODUCTS_DIR/gtest_uninitialized_test.py"
)

# Now execute each one in turn keeping track of how many succeeded and failed.
succeeded=0
failed=0
failed_list=()
for test in ${test_executables[*]}; do
  "$test"
  result=$?
  if [ $result -eq 0 ]; then
    succeeded=$(( $succeeded + 1 ))
  else
    failed=$(( failed + 1 ))
    failed_list="$failed_list $test"
  fi
done

# Report the successes and failures to the console
echo "Tests complete with $succeeded successes and $failed failures."
if [ $failed -ne 0 ]; then
  echo "The following tests failed:"
  echo $failed_list
fi
exit $failed


text:
package com.github.grantwest.sparkj.Tools;

import java.io.*;

public class SparkCredentials {
    public String deviceId;
    public String username;
    public String password;

    public SparkCredentials(String path) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(new File(path)));
        deviceId = br.readLine();
        username = br.readLine();
        password = br.readLine();
        br.close();
    }
}


text:
package org.xmly.thrall.page;

public enum SortDirection {
    ASC("asc"),
    DESC("desc");

    private String direction;

    private SortDirection(String direction) {
        this.direction = direction;
    }

    public static SortDirection fromCode(String value) {
        for (SortDirection sortDirection : values()) {
            if (sortDirection.getDirection().equals(value)) {
                return sortDirection;
            }
        }
        return null;
    }

    public String getDirection() {
        return this.direction;
    }
}


text:
package org.opendaylight.atrium.bgprouter.impl;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.atrium.util.AtriumInterface;
import org.opendaylight.atrium.util.AtriumInterfaceIpAddress;
import org.opendaylight.atrium.util.AtriumIp4Prefix;
import org.opendaylight.atrium.util.AtriumIpAddress;
import org.opendaylight.atrium.util.AtriumIpPrefix;
import org.opendaylight.atrium.util.AtriumVlanId;
import org.opendaylight.atrium.bgprouter.impl.Bgprouter;
import org.opendaylight.atrium.bgprouter.impl.TunnellingConnectivityManager;
import org.opendaylight.atrium.routingservice.api.RoutingService;
import org.opendaylight.atrium.routingservice.config.api.RoutingConfigService;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ConsumerContext;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgpconfig.api.rev150725.BgpSpeakers;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgpconfig.api.rev150725.bgpspeakers.BgpSpeaker;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgpconfig.api.rev150725.bgpspeakers.bgpspeaker.InterfaceAddresses;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.didm.drivers.atrium.rev150211.FilterInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.didm.drivers.atrium.rev150211.ForwardInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.didm.drivers.atrium.rev150211.AtriumFlowObjectiveService;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;

/**
 * This class tests adding a control and data switch.
 */
@RunWith(MockitoJUnitRunner.class)
public class BgprouterTest {

	@Mock
	private TunnellingConnectivityManager connectivityManager;
	@Mock
	private DataBroker dataBroker;
	@Mock
	private RoutingConfigService routingConfigService;
	@Mock
	private RoutingService routingService;
	@Mock
	private PacketProcessingService packetService;
	@Mock
	private AtriumFlowObjectiveService flowObjectives;

	private Bgprouter bgpRouter;

	/**
	 * Instantiates bgp router
	 */
	private void setupBgpRouter() throws InterruptedException, ExecutionException {
		ReadOnlyTransaction readOnlyTransaction = mock(ReadOnlyTransaction.class);
		Optional<Nodes> nodes = Optional.of(mock(Nodes.class));
		CheckedFuture<Optional<Nodes>, ReadFailedException> checkedNodes = mock(CheckedFuture.class);

		when(dataBroker.newReadOnlyTransaction()).thenReturn(readOnlyTransaction);
		when(readOnlyTransaction.read(any(LogicalDatastoreType.class),
				(InstanceIdentifier<Nodes>) any(InstanceIdentifier.class))).thenReturn(checkedNodes);
		when(checkedNodes.get()).thenReturn(nodes);

		bgpRouter = new Bgprouter(connectivityManager, dataBroker, routingConfigService, routingService, packetService,
				flowObjectives);
	}

	/**
	 * Sets up the details of bgp speakers
	 */
	private void setupBgpSpeakers() {
		BgpSpeakers bgps = mock(BgpSpeakers.class);
		BgpSpeaker bgp = mock(BgpSpeaker.class);
		InterfaceAddresses intfAddress = mock(InterfaceAddresses.class);

		NodeConnectorId ncId = new NodeConnectorId("openflow:20:17");
		List<InterfaceAddresses> interfaceAddresses = new ArrayList<InterfaceAddresses>();
		interfaceAddresses.add(intfAddress);

		when(bgp.getInterfaceAddresses()).thenReturn(interfaceAddresses);
		when(intfAddress.getOfPortId()).thenReturn(ncId);
		when(bgp.getAttachmentDpId()).thenReturn(NodeId.getDefaultInstance("00:00:00:00:00:00:00:bb"));

		List<BgpSpeaker> bgpSpeakers = new ArrayList<BgpSpeaker>();
		bgpSpeakers.add(bgp);

		NodeConnector connectPoint = mock(NodeConnector.class);

		when(connectPoint.getId()).thenReturn(ncId);

		Set<AtriumInterfaceIpAddress> ipAddresses = new HashSet<AtriumInterfaceIpAddress>();

		AtriumIpAddress ipAddress = AtriumIpAddress.valueOf("192.168.10.1");
		AtriumIpPrefix prefix = AtriumIp4Prefix.valueOf("1.1.1.0/24");
		AtriumInterfaceIpAddress intfIp = new AtriumInterfaceIpAddress(ipAddress, prefix);
		ipAddresses.add(intfIp);

		MacAddress mac = new MacAddress("aa:bb:cc:dd:ee:0f");
		AtriumVlanId vlanId = mock(AtriumVlanId.class);

		AtriumInterface intf = new AtriumInterface(connectPoint, ipAddresses, mac, vlanId);

		Set<AtriumInterface> interfaces = new HashSet<AtriumInterface>();
		interfaces.add(intf);

		when(routingConfigService.getBgpSpeakers()).thenReturn(bgps);
		when(bgps.getBgpSpeaker()).thenReturn(bgpSpeakers);
		when(routingConfigService.getInterfaces()).thenReturn(interfaces);
	}

	/**
	 * Starts the bgp router
	 */
	@Before
	public void init() throws InterruptedException, ExecutionException {
		setupBgpRouter();
		bgpRouter.onSessionInitialized(mock(ConsumerContext.class));
		setupBgpSpeakers();
		bgpRouter.start();
	}

	/**
	 * Tests adding a control plane switch
	 */
	@Test
	public void testProcessControlSwitchAdd() {
		NodeId dpnId = NodeId.getDefaultInstance("20");
		bgpRouter.processNodeAdd(dpnId);

		verify(flowObjectives, atLeast(1)).forward(any(ForwardInput.class));
	}

	/**
	 * Tests adding a data plane switch
	 */
	@Test
	public void testProcessDeviceAdd() {
		NodeId dpnId = NodeId.getDefaultInstance("openflow:20");
		bgpRouter.processNodeAdd(dpnId);

		verify(flowObjectives, times(1)).filter(any(FilterInput.class));
		verify(flowObjectives, times(1)).forward(any(ForwardInput.class));
	}

	/**
	 * Stops the bgp router
	 */
	@After
	public void destroy() throws Exception {
		bgpRouter.close();
	}

}


text:
<?php

namespace OC\Files\Storage;

class Loader {
	/**
	 * @var callable[] $storageWrappers
	 */
	private $storageWrappers = array();

	/**
	 * allow modifier storage behaviour by adding wrappers around storages
	 *
	 * $callback should be a function of type (string $mountPoint, Storage $storage) => Storage
	 *
	 * @param callable $callback
	 */
	public function addStorageWrapper($wrapperName, $callback) {
		$this->storageWrappers[$wrapperName] = $callback;
	}

	/**
	 * @param string|boolean $mountPoint
	 * @param string $class
	 */
	public function load($mountPoint, $class, $arguments) {
		return $this->wrap($mountPoint, new $class($arguments));
	}

	/**
	 * @param string|boolean $mountPoint
	 */
	public function wrap($mountPoint, $storage) {
		foreach ($this->storageWrappers as $wrapper) {
			$storage = $wrapper($mountPoint, $storage);
		}
		return $storage;
	}
}