text:
using System;
using System.Collections.Immutable;
using System.Linq;
using Akka.Actor;
using Akka.Event;
using Akka.Pattern;
using Reactive.Streams;

namespace Akka.Streams.Implementation
{
    public class OutputBunch<T>
    {
        #region internal classes

        private sealed class FanoutOutputs : SimpleOutputs
        {
            private readonly int _id;

            public FanoutOutputs(int id, IActorRef actor, IPump pump) : base(actor, pump)
            {
                _id = id;
            }

            public new ISubscription CreateSubscription() => new FanOut.SubstreamSubscription(Actor, _id);
        }

        #endregion

        private readonly int _outputCount;
        private bool _bunchCancelled;
        private readonly FanoutOutputs[] _outputs;
        private readonly bool[] _marked;
        private int _markedCount;
        private readonly bool[] _pending;
        private int _markedPending;
        private readonly bool[] _cancelled;
        private int _markedCanceled;
        private readonly bool[] _completed;
        private readonly bool[] _errored;
        private bool _unmarkCancelled = true;
        private int _preferredId;

        public OutputBunch(int outputCount, IActorRef impl, IPump pump)
        {
            _outputCount = outputCount;
            _outputs = new FanoutOutputs[outputCount];
            for (var i = 0; i < outputCount; i++)
                _outputs[i] = new FanoutOutputs(i, impl, pump);

            _marked = new bool[outputCount];
            _pending = new bool[outputCount];
            _cancelled = new bool[outputCount];
            _completed = new bool[outputCount];
            _errored = new bool[outputCount];

            AllOfMarkedOutputs = new LambdaTransferState(
                isCompleted: () => _markedCanceled > 0 || _markedCount == 0,
                isReady: () => _markedPending == _markedCount);

            AnyOfMarkedOutputs = new LambdaTransferState(
                isCompleted: () => _markedCanceled == _markedCount,
                isReady: () => _markedPending > 0);

            // FIXME: Eliminate re-wraps
            SubReceive = new SubReceive(message => message.Match()
                .With<FanOut.ExposedPublishers<T>>(exposed =>
                {
                    var publishers = exposed.Publishers.GetEnumerator();
                    var outputs = _outputs.AsEnumerable().GetEnumerator();

                    while (publishers.MoveNext() && outputs.MoveNext())
                        outputs.Current.SubReceive.CurrentReceive(new ExposedPublisher(publishers.Current));
                })
                .With<FanOut.SubstreamRequestMore>(more =>
                {
                    if (more.Demand < 1)
                        // According to Reactive Streams Spec 3.9, with non-positive demand must yield onError
                        Error(more.Id, ReactiveStreamsCompliance.NumberOfElementsInRequestMustBePositiveException);
                    else
                    {
                        if (_marked[more.Id] && !_pending[more.Id])
                            _markedPending += 1;
                        _pending[more.Id] = true;
                        _outputs[more.Id].SubReceive.CurrentReceive(new RequestMore(null, more.Demand));
                    }
                })
                .With<FanOut.SubstreamCancel>(cancel =>
                {
                    if (_unmarkCancelled)
                        UnmarkOutput(cancel.Id);

                    if (_marked[cancel.Id] && !_cancelled[cancel.Id])
                        _markedCanceled += 1;

                    _cancelled[cancel.Id] = true;
                    OnCancel(cancel.Id);
                    _outputs[cancel.Id].SubReceive.CurrentReceive(new Cancel(null));
                })
                .With<FanOut.SubstreamSubscribePending>(pending => _outputs[pending.Id].SubReceive.CurrentReceive(SubscribePending.Instance))
                .WasHandled);
        }

        /// <summary>
        /// Will only transfer an element when all marked outputs
        /// have demand, and will complete as soon as any of the marked
        /// outputs have canceled.
        /// </summary>
        public readonly TransferState AllOfMarkedOutputs;

        /// <summary>
        /// Will transfer an element when any of the  marked outputs
        /// have demand, and will complete when all of the marked
        /// outputs have canceled.
        /// </summary>
        public readonly TransferState AnyOfMarkedOutputs;

        public readonly SubReceive SubReceive;

        public bool IsPending(int output) => _pending[output];

        public bool IsCompleted(int output) => _completed[output];

        public bool IsCancelled(int output) => _cancelled[output];

        public bool IsErrored(int output) => _errored[output];

        public void Complete()
        {
            if (!_bunchCancelled)
            {
                _bunchCancelled = true;

                for (var i = 0; i < _outputs.Length; i++)
                    Complete(i);
            }
        }

        public void Complete(int output)
        {
            if (!_completed[output] && !_errored[output] && !_cancelled[output])
            {
                _outputs[output].Complete();
                _completed[output] = true;
                UnmarkOutput(output);
            }
        }

        public void Cancel(Exception e)
        {
            if (!_bunchCancelled)
            {
                _bunchCancelled = true;
                for (var i = 0; i < _outputs.Length; i++)
                    Error(i, e);
            }
        }

        public void Error(int output, Exception e)
        {
            if (!_errored[output] && !_cancelled[output] && !_completed[output])
            {
                _outputs[output].Error(e);
                _errored[output] = true;
                UnmarkOutput(output);
            }
        }

        public void MarkOutput(int output)
        {
            if (!_marked[output])
            {
                if (_cancelled[output])
                    _markedCanceled += 1;
                if (_pending[output])
                    _markedPending += 1;

                _marked[output] = true;
                _markedCount += 1;
            }
        }

        public void UnmarkOutput(int output)
        {
            if (_marked[output])
            {
                if (_cancelled[output])
                    _markedCanceled -= 1;
                if (_pending[output])
                    _markedPending -= 1;

                _marked[output] = false;
                _markedCount -= 1;
            }
        }

        public void MarkAllOutputs()
        {
            for (var i = 0; i < _outputCount; i++)
                MarkOutput(i);
        }

        public void UnmarkAllOutputs()
        {
            for (var i = 0; i < _outputCount; i++)
                UnmarkOutput(i);
        }

        public void UnmarkCancelledOutputs(bool enabled) => _unmarkCancelled = enabled;

        public int IdToEnqueue()
        {
            var id = _preferredId;

            while (!(_marked[id] && _pending[id]))
            {
                id += 1;
                if (id == _outputCount)
                    id = 0;

                if (id != _preferredId)
                    throw new ArgumentException("Tried to equeue without waiting for any demand");
            }

            return id;
        }

        public void Enqueue(int id, T element)
        {
            var output = _outputs[id];
            output.EnqueueOutputElement(element);

            if (!output.IsDemandAvailable)
            {
                if (_marked[id])
                    _markedPending -= 1;

                _pending[id] = false;
            }
        }

        public void EnqueueMarked(T element)
        {
            for (var id = 0; id < _outputCount; id++)
                if (_marked[id])
                    Enqueue(id, element);
        }

        public int IdToEnqueueAndYield()
        {
            var id = IdToEnqueue();
            _preferredId = id + 1;

            if (_preferredId == _outputCount)
                _preferredId = 0;

            return id;
        }

        public void EnqueueAndYield(T element) => Enqueue(IdToEnqueueAndYield(), element);

        public void EnqueueAndPrefer(T element, int preferred)
        {
            var id = IdToEnqueue();
            _preferredId = preferred;
            Enqueue(id, element);
        }

        public void OnCancel(int output)
        {
        }

        public TransferState DemandAvailableFor(int id) =>
            new LambdaTransferState(isReady: () => _pending[id],
                isCompleted: () => _cancelled[id] || _completed[id] || _errored[id]);

        public TransferState DemandOrCancelAvailableFor(int id)
            => new LambdaTransferState(isReady: () => _pending[id] || _cancelled[id], isCompleted: () => false);
    }

    /// <summary>
    /// INTERNAL API
    /// </summary>
    public static class FanOut
    {
        [Serializable]
        public struct SubstreamRequestMore : INoSerializationVerificationNeeded, IDeadLetterSuppression
        {
            public readonly int Id;
            public readonly long Demand;

            public SubstreamRequestMore(int id, long demand)
            {
                Id = id;
                Demand = demand;
            }
        }

        [Serializable]
        public struct SubstreamCancel : INoSerializationVerificationNeeded, IDeadLetterSuppression
        {
            public readonly int Id;

            public SubstreamCancel(int id)
            {
                Id = id;
            }
        }

        [Serializable]
        public struct SubstreamSubscribePending : INoSerializationVerificationNeeded, IDeadLetterSuppression
        {
            public readonly int Id;

            public SubstreamSubscribePending(int id)
            {
                Id = id;
            }
        }

        public class SubstreamSubscription : ISubscription
        {
            private readonly IActorRef _parent;
            private readonly int _id;

            public SubstreamSubscription(IActorRef parent, int id)
            {
                _parent = parent;
                _id = id;
            }

            public void Request(long elements) => _parent.Tell(new SubstreamRequestMore(_id, elements));

            public void Cancel() => _parent.Tell(new SubstreamCancel(_id));

            public override string ToString() => "SubstreamSubscription" + GetHashCode();
        }

        [Serializable]
        public struct ExposedPublishers<T> : INoSerializationVerificationNeeded, IDeadLetterSuppression
        {
            public readonly ImmutableList<ActorPublisher<T>> Publishers;

            public ExposedPublishers(ImmutableList<ActorPublisher<T>> publishers)
            {
                Publishers = publishers;
            }
        }
    }

    /// <summary>
    /// INTERNAL API
    /// </summary>
    public abstract class FanOut<T> : ActorBase, IPump
    {

        #region internal classes

        private sealed class AnonymousBatchingInputBuffer : BatchingInputBuffer
        {
            private readonly FanOut<T> _pump;

            public AnonymousBatchingInputBuffer(int count, FanOut<T> pump) : base(count, pump)
            {
                _pump = pump;
            }

            protected override void OnError(Exception e) => _pump.Fail(e);
        }

        #endregion

        private readonly ActorMaterializerSettings _settings;
        protected readonly OutputBunch<T> OutputBunch;
        protected readonly BatchingInputBuffer PrimaryInputs;

        protected FanOut(ActorMaterializerSettings settings, int outputCount)
        {
            _log = Context.GetLogger();
            _settings = settings;
            OutputBunch = new OutputBunch<T>(outputCount, Self, this);
            PrimaryInputs = new AnonymousBatchingInputBuffer(settings.MaxInputBufferSize, this);
            this.Init();
        }

        #region Actor implementation

        private ILoggingAdapter _log;
        protected ILoggingAdapter Log => _log ?? (_log = Context.GetLogger());

        protected override void PostStop()
        {
            PrimaryInputs.Cancel();
            OutputBunch.Cancel(new AbruptTerminationException(Self));
        }

        protected override void PostRestart(Exception reason)
        {
            base.PostRestart(reason);
            throw new IllegalStateException("This actor cannot be restarted");
        }

        protected void Fail(Exception e)
        {
            if (_settings.IsDebugLogging)
                Log.Debug($"fail due to: {e.Message}");

            PrimaryInputs.Cancel();
            OutputBunch.Cancel(e);
            Pump();
        }

        protected override bool Receive(object message)
        {
            return PrimaryInputs.SubReceive.CurrentReceive(message) ||
                   OutputBunch.SubReceive.CurrentReceive(message);
        }

        #endregion

        #region Pump implementation

        public TransferState TransferState { get; set; }

        public Action CurrentAction { get; set; }

        public bool IsPumpFinished => this.IsPumpFinished();

        public void InitialPhase(int waitForUpstream, TransferPhase andThen)
            => Pumps.InitialPhase(this, waitForUpstream, andThen);

        public void WaitForUpstream(int waitForUpstream) => Pumps.WaitForUpstream(this, waitForUpstream);

        public void GotUpstreamSubscription() => Pumps.GotUpstreamSubscription(this);

        public void NextPhase(TransferPhase phase) => Pumps.NextPhase(this, phase);

        public void Pump() => Pumps.Pump(this);

        public void PumpFailed(Exception e) => Fail(e);

        public void PumpFinished()
        {
            PrimaryInputs.Cancel();
            OutputBunch.Complete();
            Context.Stop(Self);
        }

        #endregion
    }

    /// <summary>
    /// INTERNAL API
    /// </summary>
    internal static class Unzip
    {
        public static Props Props<T>(ActorMaterializerSettings settings)
            => Actor.Props.Create(() => new Unzip<T>(settings, 2)).WithDeploy(Deploy.Local);
    }

    /// <summary>
    /// INTERNAL API
    /// TODO Find out where this class will be used and check if the type parameter fit
    /// since we need to cast messages into a tuple and therefore maybe need aditional type parameters
    /// </summary>
    internal sealed class Unzip<T> : FanOut<T>
    {
        public Unzip(ActorMaterializerSettings settings, int outputCount = 2) : base(settings, outputCount)
        {
            OutputBunch.MarkAllOutputs();

            InitialPhase(1, new TransferPhase(PrimaryInputs.NeedsInput.And(OutputBunch.AllOfMarkedOutputs), () =>
            {
                var message = PrimaryInputs.DequeueInputElement();
                var tuple = message as Tuple<T, T>;

                if (tuple == null)
                    throw new ArgumentException($"Unable to unzip elements of type {message.GetType().Name}");

                OutputBunch.Enqueue(0, tuple.Item1);
                OutputBunch.Enqueue(1, tuple.Item2);
            }));
        }
    }
}


text:
class WXDLLIMPEXP_GL wxGLContext : public wxGLContextBase
{
public:
    wxGLContext(wxGLCanvas *win, const wxGLContext* other = NULL);
///    virtual ~wxGLContext();

    virtual bool SetCurrent(const wxGLCanvas& win) const wxOVERRIDE;

private:
    QGLContext *m_glContext;

    wxDECLARE_CLASS(wxGLContext);
};

// ----------------------------------------------------------------------------
// wxGLCanvas: OpenGL output window
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_GL wxGLCanvas : public wxGLCanvasBase
{
public:
    wxEXPLICIT // avoid implicitly converting a wxWindow* to wxGLCanvas
    wxGLCanvas(wxWindow *parent,
               wxWindowID id = wxID_ANY,
               const int *attribList = NULL,
               const wxPoint& pos = wxDefaultPosition,
               const wxSize& size = wxDefaultSize,
               long style = 0,
               const wxString& name = wxGLCanvasName,
               const wxPalette& palette = wxNullPalette);

    bool Create(wxWindow *parent,
                wxWindowID id = wxID_ANY,
                const wxPoint& pos = wxDefaultPosition,
                const wxSize& size = wxDefaultSize,
                long style = 0,
                const wxString& name = wxGLCanvasName,
                const int *attribList = NULL,
                const wxPalette& palette = wxNullPalette);

    virtual bool SwapBuffers();

    static bool ConvertWXAttrsToQtGL(const int *wxattrs, QGLFormat &format);

    virtual QGLWidget *GetHandle() const { return static_cast<QGLWidget *>(m_qtWindow); }

private:

//    wxDECLARE_EVENT_TABLE();
    wxDECLARE_CLASS(wxGLCanvas);
};

#endif // _WX_GLCANVAS_H_

redpajama_set_name: RedPajamaGithub


text:
var addon = require('./build/Release/addon');

module.exports = function(workerId, datacenterId){
    "use strict";
    return new addon.IdWorker(workerId, datacenterId);
};

var datacenterIds = {
        'beta': [31, 30, 29, 28, 27, 26],
        'production': [19, 18, 17, 16, 15, 14, 13, 12, 11, 10]
    },
    datacenterId = datacenterIds[process.env.NODE_ENV] || 0;

if(Array.isArray(datacenterId)){
    datacenterId = datacenterId[Math.floor(Math.random() * datacenterId.length)];
}

var workerId = Math.floor(Math.random()*31);

var worker;

var i = -1,
    start = Date.now(),
    bench = 1000000,
    stop = -1,
    totalTime = -1,
    worker = new addon.IdWorker(workerId, datacenterId);

for(i = 1; i <= bench; i++){
    worker.getNextId();
}

// var os = require('os'),
//     ifaces=os.networkInterfaces(),
//     name;

// for (name in ifaces) {
//     ifaces[name].forEach(function(details){
//         if (details.family == 'IPv4' && details.name === 'eth') {
//             console.log(details.address);
//         }
//     });
// }
stop = Date.now();
totalTime = stop - start;
console.log('generated ' + bench + ' ids in ' + totalTime + ' ms, ' +
    'or ' + (bench/ totalTime) + ' ids/second');

var alpha = 'abcdefghijklmnopqrstuvwxyz'.toUpperCase().split(''),
    vowels = 'aeiouy'.toUpperCase().split('');


text:
<?php

use SMW\NamespaceManager;
use SMW\NumberFormatter;
use SMW\SPARQLStore\SparqlDBConnectionProvider;

/**
 * Global functions specified and used by Semantic MediaWiki. In general, it is
 * tried to fit functions in suitable classes as static methods if they clearly
 * belong to some particular sub-function of SMW. Most functions here are used
 * in diverse contexts so that they do not have fonud a place in any such class
 * yet.
 * @ingroup SMW
 */

/**
 * @see NamespaceExaminer
 *
 * @return boolean
 * @deprecated since 1.9 and will be removed in 1.11
 */
function smwfIsSemanticsProcessed( $namespace ) {
	return \SMW\NamespaceExaminer::getInstance()->isSemanticEnabled( $namespace );
}

/**
 * Takes a title text and turns it safely into its DBKey. This function
 * reimplements most of the title normalization as done in Title.php in order
 * to achieve conversion with less overhead. The official code could be called
 * here if more advanced normalization is needed.
 *
 * @param string $text
 */
function smwfNormalTitleDBKey( $text ) {
	global $wgCapitalLinks;

	$text = trim( $text );

	if ( $wgCapitalLinks ) {
		$text = ucfirst( $text );
	}

	return str_replace( ' ', '_', $text );
}

/**
 * Takes a text and turns it into a normalised version. This function
 * reimplements the title normalization as done in Title.php in order to
 * achieve conversion with less overhead. The official code could be called
 * here if more advanced normalization is needed.
 *
 * @param string $text
 */
function smwfNormalTitleText( $text ) {
	global $wgCapitalLinks, $wgContLang;

	$text = trim( $text );

	if ( $wgCapitalLinks ) {
		$text = $wgContLang->ucfirst( $text );
	}

	return str_replace( '_', ' ', $text );
}

/**
 * Escapes text in a way that allows it to be used as XML content (e.g. as a
 * string value for some property).
 *
 * @param string $text
 */
function smwfXMLContentEncode( $text ) {
	return str_replace( array( '&', '<', '>' ), array( '&', '<', '>' ), Sanitizer::decodeCharReferences( $text ) );
}

/**
 * Decodes character references and inserts Unicode characters instead, using
 * the MediaWiki Sanitizer.
 *
 * @param string $text
 */
function smwfHTMLtoUTF8( $text ) {
	return Sanitizer::decodeCharReferences( $text );
}

/**
 * @deprecated since 2.1, use NumberFormatter instead
 */
function smwfNumberFormat( $value, $decplaces = 3 ) {
	return NumberFormatter::getInstance()->formatNumberToLocalizedText( $value, $decplaces );
}

/**
 * Formats an array of message strings so that it appears as a tooltip.
 * $icon should be one of: 'warning' (default), 'info'.
 *
 * @param array $messages
 * @param string $icon Acts like an enum. Callers must ensure safety, since this value is used directly in the output.
 * @param string $seperator
 * @param boolean $escape Should the messages be escaped or not (ie when they already are)
 *
 * @return string
 */
function smwfEncodeMessages( array $messages, $type = 'warning', $seperator = ' ', $escape = true ) {
	if (  $messages !== array() ) {

		if ( $escape ) {
			$messages = array_map( 'htmlspecialchars', $messages );
		}

		if ( count( $messages ) == 1 )  {
			$errorList = $messages[0];
		}
		else {
			foreach ( $messages as &$message ) {
				$message = '
' . $message . '
';
			}

			$errorList = '
' . implode( $seperator, $messages ) . '
';
		}

		// Type will be converted internally
		$highlighter = SMW\Highlighter::factory( $type );
		$highlighter->setContent( array (
			'caption'   => null,
			'content'   => $errorList
		) );

		return $highlighter->getHtml();
	} else {
		return '';
	}
}

/**
 * Returns an instance for the storage back-end
 *
 * @return SMWStore
 */
function &smwfGetStore() {
	$store = \SMW\StoreFactory::getStore();
	return $store;
}

/**
 * @codeCoverageIgnore
 *
 * Get the SMWSparqlDatabase object to use for connecting to a SPARQL store,
 * or null if no SPARQL backend has been set up.
 *
 * Currently, it just returns one globally defined object, but the
 * infrastructure allows to set up load balancing and task-dependent use of
 * stores (e.g. using other stores for fast querying than for storing new
 * facts), somewhat similar to MediaWiki's DB implementation.
 *
 * @since 1.6
 *
 * @return SMWSparqlDatabase or null
 */
function &smwfGetSparqlDatabase() {

	if ( !isset( $GLOBALS['smwgSparqlDatabaseMaster'] ) ) {
		$connectionProvider = new SparqlDBConnectionProvider();
		$GLOBALS['smwgSparqlDatabaseMaster'] = $connectionProvider->getConnection();
	}

	return $GLOBALS['smwgSparqlDatabaseMaster'];
}

/**
 * Compatibility helper for using Linker methods.
 * MW 1.16 has a Linker with non-static methods,
 * where in MW 1.19 they are static, and a DummyLinker
 * class is introduced, which can be instantaited for
 * compat reasons.
 *
 * @since 1.6
 *
 * @return Linker or DummyLinker
 */
function smwfGetLinker() {
	static $linker = false;

	if ( $linker === false ) {
		$linker = class_exists( 'DummyLinker' ) ? new DummyLinker() : new Linker();
	}

	return $linker;
}

/**
 * Function to switch on Semantic MediaWiki. This function must be called in
 * LocalSettings.php after including SMW_Settings.php. It is used to ensure
 * that required parameters for SMW are really provided explicitly. For
 * readability, this is the only global function that does not adhere to the
 * naming conventions.
 *
 * This function also sets up all autoloading, such that all SMW classes are
 * available as early on. Moreover, jobs and special pages are registered.
 *
 * @param mixed $namespace
 * @param boolean $complete
 *
 * @return true
 *
 * @codeCoverageIgnore
 */
function enableSemantics( $namespace = null, $complete = false ) {
	global $smwgNamespace;

	// $GLOBALS ought to be injected from the top-level but that would require
	// to change the interface which would bring no benefits for the end user
	// as enableSemantics() is only targeted to be included in LocalSettings
	NamespaceManager::initCustomNamespace( $GLOBALS );

	if ( !$complete && ( $smwgNamespace !== '' ) ) {
		// The dot tells that the domain is not complete. It will be completed
		// in the Export since we do not want to create a title object here when
		// it is not needed in many cases.
		$smwgNamespace = '.' . $namespace;
	} else {
		$smwgNamespace = $namespace;
	}

	return true;
}


text:
The [Open Location Code for Swift and Objective-C](https://github.com/google/open-location-code-swift)
library supports Objective-C for iOS, macOS, tvOS, and watchOS. It is
implemented in Swift 5.0 with a complete
[Objective-C interface](https://github.com/google/open-location-code-swift#objective-c-code-example).

It can be built as a Framework, supports
[Carthage](https://github.com/Carthage/Carthage), and is available via
[CocoaPods](https://cocoapods.org/pods/OpenLocationCodeFramework).


text:
<?xml version="1.0"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
 -->

<!-- See http://james.apache.org/server/3/config.html for usage -->

<mailetcontainer enableJmx="true">

  <context>
    <postmaster>Postmaster@localhost</postmaster>
  </context>

  <spooler>
    <threads> 20 </threads>
  </spooler>

  <processors>
    <processor state="root" enableJmx="true">
      <mailet match="All" class="PostmasterAlias"/>
      <mailet match="RelayLimit=30" class="Null"/>
      <mailet match="SMTPAuthSuccessful" class="ToProcessor">
        <processor>transport</processor>
      </mailet>
      <mailet match="InSpammerBlacklist=dnsbl.njabl.org." class="ToProcessor">
        <processor>spam</processor>
        <notice>550 Requested action not taken: rejected - see http://njabl.org/ </notice>
       </mailet>
       <mailet match="All" class="ToProcessor">
        <processor>transport</processor>
       </mailet>
     </processor>

    <processor state="transport" enableJmx="true">
      <mailet match="SMTPAuthSuccessful" class="SetMimeHeader">
        <name>X-UserIsAuth</name>
        <value>true</value>
      </mailet>
      <mailet match="All" class="RecipientRewriteTable">
        <recipientrewritetable>DefaultRecipientRewriteTable</recipientrewritetable>
      </mailet>
      <!-- Disable this if you want to have case-sensitive local-parts of the recipients -->
      <mailet match="RecipientIsLocal" class="RecipientToLowerCase"/>

      <mailet match="RecipientIsLocal" class="LocalDelivery"/>
      <mailet match="HostIsLocal" class="ToProcessor">
        <processor>local-address-error</processor>
        <notice>550 - Requested action not taken: no such user here</notice>
      </mailet>
      <mailet match="All" class="RemoteDelivery">
        <outgoingQueue>outgoing</outgoingQueue>
        <delayTime>5 minutes</delayTime>
        <delayTime>10 minutes</delayTime>
        <delayTime>45 minutes</delayTime>
        <delayTime>2 hours</delayTime>
        <delayTime>3 hours</delayTime>
        <delayTime>6 hours</delayTime>
        <maxRetries>25</maxRetries>
        <maxDnsProblemRetries>0</maxDnsProblemRetries>
        <deliveryThreads>10</deliveryThreads>
        <sendpartial>true</sendpartial>
        <bounceProcessor>bounces</bounceProcessor>
      </mailet>
    </processor>

    <processor state="error" enableJmx="true">
      <mailet match="All" class="ToRepository">
        <repositoryPath>file://var/mail/error/</repositoryPath>
      </mailet>
    </processor>

    <processor state="spam" enableJmx="true">
      <mailet match="All" class="ToRepository">
        <repositoryPath>file://var/mail/spam/</repositoryPath>
      </mailet>
    </processor>

    <processor state="local-address-error" enableJmx="true">
      <mailet match="All" class="ToRepository">
        <repositoryPath>file://var/mail/address-error/</repositoryPath>
      </mailet>
    </processor>

    <processor state="relay-denied" enableJmx="true">
      <mailet match="All" class="ToRepository">
        <repositoryPath>file://var/mail/relay-denied/</repositoryPath>
      </mailet>
    </processor>

    <processor state="bounces" enableJmx="true">
      <mailet match="All" class="DSNBounce">
        <passThrough>false</passThrough>
      </mailet>
    </processor>
  </processors>
</mailetcontainer>


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Almond Biscotti</title>
      <categories>
        <cat>Cooking</cat>
        <cat>Live</cat></categories>
      <yield>1</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>3</qty>
          <unit>large</unit></amt>
        <item>Eggs</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit/></amt>
        <item>Pinches salt</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Sugar</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>teaspoon</unit></amt>
        <item>Vanilla extract</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit/></amt>
        <item>Stick butter; melted or 1/2 cup vegetable oil</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Coarsely chopped almonds or other nuts</item></ing>
      <ing>
        <amt>
          <qty>2 1/2</qty>
          <unit>cups</unit></amt>
        <item>Unbleached; all purpose flour</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>tablespoon</unit></amt>
        <item>Baking powder</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>teaspoon</unit></amt>
        <item>Cinnamon; (optional)</item></ing></ingredients>
    <directions>
      <step>  Preheat oven to 350 degrees and set a rack in the middle level. Line a
  jelly-roll pan or cookie sheet with parchment or foil.

  In a mixing bowl, whisk eggs and salt until liquid. Whisk in sugar and
  vanilla smoothly. Whisk in butter or oil, then stir in nuts. Combine flour
  with baking powder and cinnamon and stir with a dry whisk to mix. Fold
  flour mixture into egg mixture until all the flour is absorbed - the dough
  will be very soft. Use a spoon to form two logs of dough on the prepared
  pan, adjusting the sides with the tip of the spoon to make the logs even.
  Bake the logs of dough about 30 minutes, or until well risen and firm when
  pressed with a fingertip. Cool on pan to room temperature.

  Slice baked logs diagonally about 1/4 to 1/2-inch thick, using a sharp
  serrated knife. Return biscotti to pan, cut side down, and bake up to 20
  minutes longer, or until biscotti are a deep golden color. Cool on pan and
  store in a tin.

  Yield: 5 dozen or more, depending on how thinly they are sliced.

  Notes: Recipe courtesy of Nick Malgieri

  Recipe by: Cooking live Show #9021

  Posted to MC-Recipe Digest V1 #967 by "Angele and Jon Freeman"
  <jfreeman@comteck.com> on Dec 19, 1997

</step></directions></recipe></recipeml>


text:
package com.defano.wyldcard.part.builder;

import com.defano.hypertalk.ast.model.Value;
import com.defano.wyldcard.part.card.CardLayerPartModel;
import com.defano.wyldcard.part.model.PartModel;
import com.defano.wyldcard.runtime.ExecutionContext;

import java.awt.*;

public abstract class PartModelBuilder<ModelType extends PartModel, BuilderType extends PartModelBuilder> {

    protected final ExecutionContext context = new ExecutionContext();

    public abstract ModelType build();
    public abstract BuilderType getBuilder();

    public BuilderType withId(Object id) {
        build().define(PartModel.PROP_ID).asConstant(id);
        return getBuilder();
    }

    public BuilderType withScript(Object script) {
        build().set(context, PartModel.PROP_SCRIPT, new Value(script));
        return getBuilder();
    }

    public BuilderType withName(Object name) {
        build().set(context, PartModel.PROP_NAME, new Value(name));
        return getBuilder();
    }

    public BuilderType withPartStyle(Object v) {
        build().set(context, CardLayerPartModel.PROP_STYLE, new Value(v));
        return getBuilder();
    }

    public BuilderType withContents(Object contents) {
        build().set(context, PartModel.PROP_CONTENTS, new Value(contents));
        return getBuilder();
    }

    public BuilderType withIsVisible(Object isVisible) {
        build().set(context, PartModel.PROP_VISIBLE, new Value(isVisible));
        return getBuilder();
    }

    public BuilderType withTop(Object top) {
        build().set(context, PartModel.PROP_TOP, new Value(top));
        return getBuilder();
    }

    public BuilderType withLeft(Object left) {
        build().set(context, PartModel.PROP_LEFT, new Value(left));
        return getBuilder();
    }

    public BuilderType withHeight(Object height) {
        build().set(context, PartModel.PROP_HEIGHT, new Value(height));
        return getBuilder();
    }

    public BuilderType withWidth(Object width) {
        build().set(context, PartModel.PROP_WIDTH, new Value(width));
        return getBuilder();
    }

    public BuilderType withBounds(Rectangle rectangle) {
        withTop(rectangle.y);
        withLeft(rectangle.x);
        withWidth(rectangle.width);
        withHeight(rectangle.height);
        return getBuilder();
    }

    public BuilderType withTextFont(Object v) {
        build().set(context, CardLayerPartModel.PROP_TEXTFONT, new Value(v));
        return getBuilder();
    }

    public BuilderType withTextSize(Object v) {
        build().set(context, CardLayerPartModel.PROP_TEXTSIZE, new Value(v));
        return getBuilder();
    }

    public BuilderType withTextStyle(Object v) {
        build().set(context, CardLayerPartModel.PROP_TEXTSTYLE, new Value(v));
        return getBuilder();
    }

    public BuilderType withTextAlign(Object v) {
        build().set(context, CardLayerPartModel.PROP_TEXTALIGN, new Value(v));
        return getBuilder();
    }

    public BuilderType withPartNumber(Object v) {
        build().set(context, CardLayerPartModel.PROP_ZORDER, new Value(v));
        return getBuilder();
    }

}


text:
#include "qcommonnamespaces_p.h"

#include "qcommonsequencetypes_p.h"
#include "qfunctionfactory_p.h"
#include "qgeneralcomparison_p.h"
#include "qliteral_p.h"
#include "qschemanumeric_p.h"
#include "qvaluecomparison_p.h"

#include "qoptimizerblocks_p.h"

QT_BEGIN_NAMESPACE

using namespace QPatternist;

ByIDIdentifier::ByIDIdentifier(const Expression::ID id) : m_id(id)
{
}

bool ByIDIdentifier::matches(const Expression::Ptr &expr) const
{
    return expr->is(m_id);
}

ComparisonIdentifier::ComparisonIdentifier(const QVector<Expression::ID> hosts,
                                           const AtomicComparator::Operator op) : m_hosts(hosts),
                                                                                m_op(op)
{
}

bool ComparisonIdentifier::matches(const Expression::Ptr &e) const
{
    const Expression::ID eID = e->id();

    if(eID == Expression::IDGeneralComparison)
    {
        if(m_hosts.contains(Expression::IDGeneralComparison))
            return e->as<GeneralComparison>()->operatorID() == m_op;
        else
            return false;
    }
    else if(eID == Expression::IDValueComparison)
    {
        if(m_hosts.contains(Expression::IDValueComparison))
            return e->as<ValueComparison>()->operatorID() == m_op;
        else
            return false;
    }
    else
        return false;
}

BySequenceTypeIdentifier::BySequenceTypeIdentifier(const SequenceType::Ptr &seqType) : m_seqType(seqType)
{
    Q_ASSERT(seqType);
}

bool BySequenceTypeIdentifier::matches(const Expression::Ptr &expr) const
{
    const SequenceType::Ptr t(expr->staticType());

    return m_seqType->itemType()->xdtTypeMatches(t->itemType())
           &&
           m_seqType->cardinality().isMatch(t->cardinality());
}

IntegerIdentifier::IntegerIdentifier(const xsInteger num) : m_num(num)
{
}

bool IntegerIdentifier::matches(const Expression::Ptr &expr) const
{
    return expr->is(Expression::IDIntegerValue) &&
           expr->as<Literal>()->item().as<Numeric>()->toInteger() == m_num;
}

BooleanIdentifier::BooleanIdentifier(const bool value) : m_value(value)
{
}

bool BooleanIdentifier::matches(const Expression::Ptr &expr) const
{
    return expr->is(Expression::IDBooleanValue) &&
           expr->evaluateEBV(DynamicContext::Ptr()) == m_value;
}

ByIDCreator::ByIDCreator(const Expression::ID id) : m_id(id)
{
    Q_ASSERT(id != Expression::IDIgnorableExpression);
}

Expression::Ptr ByIDCreator::create(const Expression::List &operands,
                                    const StaticContext::Ptr &context,
                                    const SourceLocationReflection *const r) const
{
    return create(m_id, operands, context, r);
}

Expression::Ptr ByIDCreator::create(const Expression::ID id,
                                    const Expression::List &operands,
                                    const StaticContext::Ptr &context,
                                    const SourceLocationReflection *const r)
{
    Q_ASSERT(context);

    QXmlName::LocalNameCode fnName;

    switch(id)
    {
        case Expression::IDExistsFN:
        {
            fnName = StandardLocalNames::exists;
            break;
        }
        case Expression::IDEmptyFN:
        {
            fnName = StandardLocalNames::empty;
            break;
        }
        default:
        {
            Q_ASSERT_X(false, Q_FUNC_INFO,
                       "Cannot create an expression of requested type; m_id is wrong.");
            return Expression::Ptr();
        }
    }

    /* The reason we don't simply do 'new ExistsFN()' ourselves, is that all FunctionCall
     * instances needs their FunctionSignature in order to function, and the FunctionFactories
     * sets that. */
    const QXmlName qName(StandardNamespaces::fn, fnName);

    const Expression::Ptr result(context->functionSignatures()->createFunctionCall(qName, operands, context, r));
    context->wrapExpressionWith(r, result);
    return result;
}

QT_END_NAMESPACE


text:
namespace Lekarite.Mvc.Infrastructure.Mapping
{
    using AutoMapper;

    public interface IHaveCustomMappings
    {
        void CreateMappings(IConfiguration configuration);
    }
}


text:
package io.undertow.websockets.extensions;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.Deflater;

import io.undertow.websockets.WebSocketExtension;
import io.undertow.websockets.core.WebSocketLogger;

/**
 * Implementation of {@code permessage-deflate} WebSocket Extension handshake.
 *

 * This implementation supports parameters: {@code server_no_context_takeover, client_no_context_takeover} .
 *

 * This implementation does not support parameters: {@code server_max_window_bits, client_max_window_bits} .
 *
 * @see Compression Extensions for WebSocket
 *
 * @author Lucas Ponce
 */
public class PerMessageDeflateHandshake implements ExtensionHandshake {

    private static final String PERMESSAGE_DEFLATE = "permessage-deflate";
    private static final String SERVER_NO_CONTEXT_TAKEOVER = "server_no_context_takeover";
    private static final String CLIENT_NO_CONTEXT_TAKEOVER = "client_no_context_takeover";
    private static final String SERVER_MAX_WINDOW_BITS = "server_max_window_bits";
    private static final String CLIENT_MAX_WINDOW_BITS = "client_max_window_bits";

    private final Set<String> incompatibleExtensions = new HashSet<>();

    private boolean compressContextTakeover;
    private boolean decompressContextTakeover;

    private final boolean client;
    private final int deflaterLevel;

    /**
     * Default configuration for DEFLATE algorithm implementation
     */
    public static final int DEFAULT_DEFLATER = Deflater.DEFAULT_COMPRESSION;

    public PerMessageDeflateHandshake() {
        this(false);
    }

    /**
     * Create a new {@code PerMessageDeflateHandshake} instance.
     *
     * @param client indicate if extension is configured in client ({@code true }) context or server ({@code false }) context.
     */
    public PerMessageDeflateHandshake(final boolean client) {
        this(client, DEFAULT_DEFLATER);
    }

    /**
     * Create a new {@code PerMessageDeflateHandshake} instance.
     *
     * @param client        indicate if extension is configured in client ({@code true }) context or server ({@code false }) context
     * @param deflaterLevel the level of configuration of DEFLATE algorithm implementation
     */
    public PerMessageDeflateHandshake(final boolean client, final int deflaterLevel) {
        this(client, deflaterLevel, true, true);
    }

    /**
     * Create a new {@code PerMessageDeflateHandshake} instance.
     *
     * @param client                    flag for client ({@code true }) context or server ({@code false }) context
     * @param compressContextTakeover   flag for compressor context takeover or without compressor context
     * @param decompressContextTakeover flag for decompressor context takeover or without decompressor context
     */
    public PerMessageDeflateHandshake(final boolean client, boolean compressContextTakeover, boolean decompressContextTakeover) {
        this(client, DEFAULT_DEFLATER, compressContextTakeover, decompressContextTakeover);
    }

    /**
     * Create a new {@code PerMessageDeflateHandshake} instance.
     *
     * @param client                    flag for client ({@code true }) context or server ({@code false }) context
     * @param deflaterLevel             the level of configuration of DEFLATE algorithm implementation
     * @param compressContextTakeover   flag for compressor context takeover or without compressor context
     * @param decompressContextTakeover flag for decompressor context takeover or without decompressor context
     */
    public PerMessageDeflateHandshake(final boolean client, final int deflaterLevel, boolean compressContextTakeover, boolean decompressContextTakeover) {
        this.client = client;
        this.deflaterLevel = deflaterLevel;
        /*
            This extension is incompatible with multiple instances of same extension in the same Endpoint.
         */
        incompatibleExtensions.add(PERMESSAGE_DEFLATE);
        this.compressContextTakeover = compressContextTakeover;
        this.decompressContextTakeover = decompressContextTakeover;
    }

    @Override
    public String getName() {
        return PERMESSAGE_DEFLATE;
    }

    @Override
    public WebSocketExtension accept(final WebSocketExtension extension) {
        if (extension == null || !extension.getName().equals(getName())) return null;

        WebSocketExtension negotiated = new WebSocketExtension(extension.getName());

        if (extension.getParameters() == null || extension.getParameters().size() == 0) return negotiated;
        for (WebSocketExtension.Parameter parameter : extension.getParameters()) {
            if (parameter.getName().equals(SERVER_MAX_WINDOW_BITS)) {
                /*
                    Not supported
                 */
            } else if (parameter.getName().equals(CLIENT_MAX_WINDOW_BITS)) {
                /*
                    Not supported
                 */
            } else if (parameter.getName().equals(SERVER_NO_CONTEXT_TAKEOVER)) {
                negotiated.getParameters().add(parameter);
                if (client) {
                    decompressContextTakeover = false;
                } else {
                    compressContextTakeover = false;
                }
            } else if (parameter.getName().equals(CLIENT_NO_CONTEXT_TAKEOVER)) {
                negotiated.getParameters().add(parameter);
                if (client) {
                    compressContextTakeover = false;
                } else {
                    decompressContextTakeover = false;
                }
            } else {
                WebSocketLogger.EXTENSION_LOGGER.incorrectExtensionParameter(parameter);
                return null;
            }
        }
        return negotiated;
    }

    @Override
    public boolean isIncompatible(List<ExtensionHandshake> extensions) {
        for (ExtensionHandshake extension : extensions) {
            if (incompatibleExtensions.contains(extension.getName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public ExtensionFunction create() {
        return new PerMessageDeflateFunction(deflaterLevel, compressContextTakeover, decompressContextTakeover);
    }
}


text:
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("FluentSiteMap.Core Unit Tests")]
[assembly: AssemblyDescription("Unit tests for the types in FluentSiteMap.Core")]

[assembly: ComVisible(false)]
[assembly: Guid("120b59cc-df91-45d2-bb34-a2e574fa54c2")]


text:
package com.googlecode.blaisemath.primitive;

/**
 * Defines location(s) of arrowheads on a path.
 * @author Elisha Peterson
 */
public enum ArrowLocation {
    NONE,
    START,
    END,
    BOTH
}


text:
"""When it comes to combining multiple controller or view functions
(however you want to call them) you need a dispatcher. A simple way
would be applying regular expression tests on the ``PATH_INFO`` and
calling registered callback functions that return the value then.

This module implements a much more powerful system than simple regular
expression matching because it can also convert values in the URLs and
build URLs.

Here a simple example that creates a URL map for an application with
two subdomains (www and kb) and some URL rules:

.. code-block:: python

    m = Map([
        # Static URLs
        Rule('/', endpoint='static/index'),
        Rule('/about', endpoint='static/about'),
        Rule('/help', endpoint='static/help'),
        # Knowledge Base
        Subdomain('kb', [
            Rule('/', endpoint='kb/index'),
            Rule('/browse/', endpoint='kb/browse'),
            Rule('/browse/<int:id>/', endpoint='kb/browse'),
            Rule('/browse/<int:id>/<int:page>', endpoint='kb/browse')
        ])
    ], default_subdomain='www')

If the application doesn't use subdomains it's perfectly fine to not set
the default subdomain and not use the `Subdomain` rule factory. The
endpoint in the rules can be anything, for example import paths or
unique identifiers. The WSGI application can use those endpoints to get the
handler for that URL.  It doesn't have to be a string at all but it's
recommended.

Now it's possible to create a URL adapter for one of the subdomains and
build URLs:

.. code-block:: python

    c = m.bind('example.com')

    c.build("kb/browse", dict(id=42))
    'http://kb.example.com/browse/42/'

    c.build("kb/browse", dict())
    'http://kb.example.com/browse/'

    c.build("kb/browse", dict(id=42, page=3))
    'http://kb.example.com/browse/42/3'

    c.build("static/about")
    '/about'

    c.build("static/index", force_external=True)
    'http://www.example.com/'

    c = m.bind('example.com', subdomain='kb')

    c.build("static/about")
    'http://www.example.com/about'

The first argument to bind is the server name *without* the subdomain.
Per default it will assume that the script is mounted on the root, but
often that's not the case so you can provide the real mount point as
second argument:

.. code-block:: python

    c = m.bind('example.com', '/applications/example')

The third argument can be the subdomain, if not given the default
subdomain is used.  For more details about binding have a look at the
documentation of the `MapAdapter`.

And here is how you can match URLs:

.. code-block:: python

    c = m.bind('example.com')

    c.match("/")
    ('static/index', {})

    c.match("/about")
    ('static/about', {})

    c = m.bind('example.com', '/', 'kb')

    c.match("/")
    ('kb/index', {})

    c.match("/browse/42/23")
    ('kb/browse', {'id': 42, 'page': 23})

If matching fails you get a ``NotFound`` exception, if the rule thinks
it's a good idea to redirect (for example because the URL was defined
to have a slash at the end but the request was missing that slash) it
will raise a ``RequestRedirect`` exception. Both are subclasses of
``HTTPException`` so you can use those errors as responses in the
application.

If matching succeeded but the URL rule was incompatible to the given
method (for example there were only rules for ``GET`` and ``HEAD`` but
routing tried to match a ``POST`` request) a ``MethodNotAllowed``
exception is raised.
"""
from .converters import AnyConverter as AnyConverter
from .converters import BaseConverter as BaseConverter
from .converters import FloatConverter as FloatConverter
from .converters import IntegerConverter as IntegerConverter
from .converters import PathConverter as PathConverter
from .converters import UnicodeConverter as UnicodeConverter
from .converters import UUIDConverter as UUIDConverter
from .converters import ValidationError as ValidationError
from .exceptions import BuildError as BuildError
from .exceptions import NoMatch as NoMatch
from .exceptions import RequestAliasRedirect as RequestAliasRedirect
from .exceptions import RequestPath as RequestPath
from .exceptions import RequestRedirect as RequestRedirect
from .exceptions import RoutingException as RoutingException
from .exceptions import WebsocketMismatch as WebsocketMismatch
from .map import Map as Map
from .map import MapAdapter as MapAdapter
from .matcher import StateMachineMatcher as StateMachineMatcher
from .rules import EndpointPrefix as EndpointPrefix
from .rules import parse_converter_args as parse_converter_args
from .rules import Rule as Rule
from .rules import RuleFactory as RuleFactory
from .rules import RuleTemplate as RuleTemplate
from .rules import RuleTemplateFactory as RuleTemplateFactory
from .rules import Subdomain as Subdomain
from .rules import Submount as Submount


text:
import pygame

KEYBOARD_EVENTS = [pygame.KEYDOWN]
GAMEPAD_EVENTS = [pygame.JOYBUTTONDOWN, pygame.JOYAXISMOTION]

_queue = []
_controllers = []

def add_controller(controller_kind, controller_index=None):
  global _controllers
  _controllers.append((controller_kind, controller_index))

def fits(event, controller_kind, controller_index):
  if controller_kind == 'keyboard':
    return event.type in KEYBOARD_EVENTS
  if controller_kind == 'gamepad':
    return event.type in GAMEPAD_EVENTS and event.joy == controller_index
  assert False, 'Unknown controller kind!'

def get(controller_kind, controller_index=None):
  global _queue
  global _controllers
  _queue.extend(pygame.event.get())
  result = []
  new_state = []
  for event in _queue:
    if fits(event, controller_kind, controller_index):
      result.append(event)
    else:
      for controller in _controllers:
        if fits(event, *controller):
          new_state.append(event)
          break
  _queue = new_state
  return result


text:
<meta>
	<info author="MulTi"/>

		<script src="dxclass/client.class.lua" type="client"/>
		<script src="dxclass/client.userful.lua" type="client"/>

		<script src="aktien_server.lua" />
		<script src="aktien_client.lua" type="client"/>

		<script src="aktien_gui.lua" type="client"/>

		<file src="images/goog.png"/>
		<file src="images/fb.png"/>
		<file src="images/yhoo.png"/>

</meta>


text:
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>

#import <React/RCTModuleMethod.h>

@interface RCTMethodArgumentTests : XCTestCase

@end

@implementation RCTMethodArgumentTests

extern NSString *RCTParseMethodSignature(const char *methodSignature, NSArray **argTypes);

- (void)testOneArgument
{
  NSArray *arguments;
  const char *methodSignature = "foo:(NSInteger)foo";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo:");
  XCTAssertEqual(arguments.count, (NSUInteger)1);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"NSInteger");
}

- (void)testTwoArguments
{
  NSArray *arguments;
  const char *methodSignature = "foo:(NSInteger)foo bar:(BOOL)bar";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo:bar:");
  XCTAssertEqual(arguments.count, (NSUInteger)2);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"NSInteger");
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[1]).type, @"BOOL");
}

- (void)testSpaces
{
  NSArray *arguments;
  const char *methodSignature = "foo : (NSInteger)foo bar : (BOOL) bar";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo:bar:");
  XCTAssertEqual(arguments.count, (NSUInteger)2);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"NSInteger");
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[1]).type, @"BOOL");
}

- (void)testNewlines
{
  NSArray *arguments;
  const char *methodSignature = "foo : (NSInteger)foo\nbar : (BOOL) bar";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo:bar:");
  XCTAssertEqual(arguments.count, (NSUInteger)2);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"NSInteger");
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[1]).type, @"BOOL");
}

- (void)testUnnamedArgs
{
  NSArray *arguments;
  const char *methodSignature = "foo:(NSInteger)foo:(BOOL)bar";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo::");
  XCTAssertEqual(arguments.count, (NSUInteger)2);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"NSInteger");
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[1]).type, @"BOOL");
}

- (void)testUntypedUnnamedArgs
{
  NSArray *arguments;
  const char *methodSignature = "foo:foo:bar:bar";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo:::");
  XCTAssertEqual(arguments.count, (NSUInteger)3);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"id");
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[1]).type, @"id");
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[2]).type, @"id");
}

- (void)testNamespacedCxxStruct
{
  NSArray *arguments;
  const char *methodSignature = "foo:(foo::type &)foo bar:(bar::type &)bar";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo:bar:");
  XCTAssertEqual(arguments.count, (NSUInteger)2);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"foo::type");
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[1]).type, @"bar::type");
}

- (void)testAttributes
{
  NSArray *arguments;
  const char *methodSignature = "foo:(__attribute__((unused)) NSString *)foo bar:(__unused BOOL)bar";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo:bar:");
  XCTAssertEqual(arguments.count, (NSUInteger)2);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"NSString");
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[1]).type, @"BOOL");
}

- (void)testNullability
{
  NSArray *arguments;
  const char *methodSignature = "foo:(nullable NSString *)foo bar:(nonnull NSNumber *)bar baz:(id)baz";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo:bar:baz:");
  XCTAssertEqual(arguments.count, (NSUInteger)3);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"NSString");
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[1]).type, @"NSNumber");
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[2]).type, @"id");
  XCTAssertEqual(((RCTMethodArgument *)arguments[0]).nullability, RCTNullable);
  XCTAssertEqual(((RCTMethodArgument *)arguments[1]).nullability, RCTNonnullable);
  XCTAssertEqual(((RCTMethodArgument *)arguments[2]).nullability, RCTNullabilityUnspecified);
}

- (void)testSemicolonStripping
{
  NSArray *arguments;
  const char *methodSignature = "foo:(NSString *)foo bar:(BOOL)bar;";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo:bar:");
  XCTAssertEqual(arguments.count, (NSUInteger)2);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"NSString");
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[1]).type, @"BOOL");
}

- (void)testUnused
{
  NSArray *arguments;
  const char *methodSignature = "foo:(__unused NSString *)foo bar:(NSNumber *)bar";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo:bar:");
  XCTAssertEqual(arguments.count, (NSUInteger)2);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"NSString");
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[1]).type, @"NSNumber");
  XCTAssertTrue(((RCTMethodArgument *)arguments[0]).unused);
  XCTAssertFalse(((RCTMethodArgument *)arguments[1]).unused);
}

- (void)testGenericArray
{
  NSArray *arguments;
  const char *methodSignature = "foo:(NSArray<NSString *> *)foo;";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo:");
  XCTAssertEqual(arguments.count, (NSUInteger)1);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"NSStringArray");
}

- (void)testNestedGenericArray
{
  NSArray *arguments;
  const char *methodSignature = "foo:(NSArray<NSArray<NSString *> *> *)foo;";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo:");
  XCTAssertEqual(arguments.count, (NSUInteger)1);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"NSStringArrayArray");
}

- (void)testGenericSet
{
  NSArray *arguments;
  const char *methodSignature = "foo:(NSSet<NSNumber *> *)foo;";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo:");
  XCTAssertEqual(arguments.count, (NSUInteger)1);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"NSNumberSet");
}

- (void)testGenericDictionary
{
  NSArray *arguments;
  const char *methodSignature = "foo:(NSDictionary<NSString *, NSNumber *> *)foo;";
  NSString *selector = RCTParseMethodSignature(methodSignature, &arguments);
  XCTAssertEqualObjects(selector, @"foo:");
  XCTAssertEqual(arguments.count, (NSUInteger)1);
  XCTAssertEqualObjects(((RCTMethodArgument *)arguments[0]).type, @"NSNumberDictionary");
}

@end


text:
<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

	use UserTrait, RemindableTrait;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = array('password', 'remember_token');

	protected $fillable = array('username', 'email', 'password');

	public static $rules = array(
		'firstname' => 'required|alpha|min:2',
		'lastname' => 'required|alpha|min:2',
		'email' => 'required|email|unique:users',
		'password' => 'required|alpha_num|between:6,12|confirmed',
		'password_confirmation' => 'required|alpha_num|between:6,12'
		//'organization' => 'required|alpha|min:2'
	);

	public static $loginRules = [
		'email' => 'required|email',
		'password' => 'required|alpha_num|between:6,12'

	];

	public static $changePassword = [
		'email' => 'required|email',
		'new' => 'required|alpha_num|between:6,12',
		'new1' => 'required|alpha_num|between:6,12',
		'old' => 'required|alpha_num|between:6,12'

	];

	public function projects() {
		return $this->belongsToMany('Project', 'project_user', 'user_id', 'project_id');
	}

	public function programs() {
		return $this->belongsToMany('Program', 'program_user', 'user_id', 'program_id');
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.duang.easyecard.Activity.MessagesBoardActivity"
    tools:showIn="@layout/activity_messages_board">

    <com.rey.material.widget.ProgressView
        android:id="@+id/messages_board_progress_view"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="100dp"
        app:pv_autostart="true"
        app:pv_progressMode="indeterminate"/>

    <com.yalantis.phoenix.PullToRefreshView
        android:id="@+id/messages_board_pull_to_refresh_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ListView
            android:id="@+id/messages_board_list_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </com.yalantis.phoenix.PullToRefreshView>

</FrameLayout>


text:
from oslo_concurrency import lockutils
from oslo_log import log as logging

from neutron.api.rpc.callbacks.consumer import registry
from neutron.api.rpc.callbacks import events
from neutron.api.rpc.callbacks import resources
from neutron.api.rpc.handlers import resources_rpc
from neutron.common import rpc as n_rpc
from neutron.conf.services import logging as log_cfg
from neutron import manager

LOG = logging.getLogger(__name__)

log_cfg.register_log_driver_opts()

class L3LoggingExtensionBase(object):
    """Base class for l3 logging extension like

    SNATLogExtension, FWaaSV2LogExtension
    """

    SUPPORTED_RESOURCE_TYPES = [resources.LOGGING_RESOURCE]

    def consume_api(self, agent_api):
        self.agent_api = agent_api

    def _load_driver_cls(self, namesapce, driver_name):
        return manager.NeutronManager.load_class_for_provider(
            namesapce, driver_name)

    def _register_rpc_consumers(self):
        registry.register(
            self._handle_notification, resources.LOGGING_RESOURCE)
        self._connection = n_rpc.Connection()
        endpoints = [resources_rpc.ResourcesPushRpcCallback()]
        topic = resources_rpc.resource_type_versioned_topic(
            resources.LOGGING_RESOURCE)
        self._connection.create_consumer(topic, endpoints, fanout=True)
        self._connection.consume_in_threads()

    def _get_router_info(self, router_id):
        router_info = self.agent_api.get_router_info(router_id)
        if router_info:
            return router_info
        LOG.debug("Router %s is not managed by this agent. "
                  "It was possibly deleted concurrently.",
                  router_id)

    @lockutils.synchronized('log')
    def _handle_notification(self, context, resource_type,
                             log_resources, event_type):
        with self.log_driver.defer_apply():
            if event_type == events.UPDATED:
                self._update_logging(context, log_resources)
            elif event_type == events.CREATED:
                self.log_driver.start_logging(
                    context, log_resources=log_resources)
            elif event_type == events.DELETED:
                self.log_driver.stop_logging(
                    context, log_resources=log_resources)

    def _update_logging(self, context, log_resources):
        enables = []
        disables = []
        for log_resource in log_resources:
            if log_resource.enabled:
                enables.append(log_resource)
            else:
                disables.append(log_resource)
        if enables:
            self.log_driver.start_logging(context, log_resources=enables)
        if disables:
            self.log_driver.stop_logging(context, log_resources=disables)

    def _process_update_router(self, context, router):
        router_info = self._get_router_info(router['id'])
        if router_info:
            self.log_driver.start_logging(context, router_info=router_info)

    @lockutils.synchronized('log-port')
    def add_router(self, context, data):
        self._process_update_router(context, data)

    @lockutils.synchronized('log-port')
    def update_router(self, context, data):
        self._process_update_router(context, data)

    def delete_router(self, context, data):
        self.log_driver.stop_logging(context, router_info=data)

    def ha_state_change(self, context, data):
        pass


text:
/*
 * Reference:
 * http://getbootstrap.com/examples/dashboard/dashboard.css
 */

/* Product list */
#product-list .sale-info { font-size: 1.1em; }
#product-list .sale-info .item-name { color: gray; display: inline-block; width: 6.5em; }
#product-list .sale-info > p > span:last-child { font-size: 1.2em; }
#product-list .product.out-of-stock .price,
#product-list .product.off-shelf .price { color: gray; }
#product-list .product.off-shelf h3 { text-decoration: line-through; color: gray; }

/*
 * Base structure
 */

/* Move down content because we have a fixed navbar that is 50px tall */
body {
  padding-top: 50px;
}

/*
 * Global add-ons
 */

.sub-header {
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

/*
 * Top navigation
 * Hide default border to remove 1px line.
 */
.navbar-fixed-top {
  border: 0;
}

/*
 * Sidebar
 */

/* Hide for mobile, show later */
.sidebar {
  display: none;
}
@media (min-width: 768px) {
  .sidebar {
    position: fixed;
    top: 51px;
    bottom: 0;
    left: 0;
    z-index: 1000;
    display: block;
    padding: 20px;
    overflow-x: hidden;
    overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
    background-color: #f5f5f5;
    border-right: 1px solid #eee;
  }
}

/* Sidebar navigation */
.nav-sidebar {
  margin-right: -21px; /* 20px padding + 1px border */
  margin-bottom: 20px;
  margin-left: -20px;
}
.nav-sidebar > li > a {
  padding-right: 20px;
  padding-left: 20px;
}
.nav-sidebar > .active > a,
.nav-sidebar > .active > a:hover,
.nav-sidebar > .active > a:focus {
  color: #fff;
  background-color: #428bca;
}

/*
 * Main content
 */
.main {
  padding: 20px;
}
@media (min-width: 768px) {
  .main {
    padding-right: 40px;
    padding-left: 40px;
  }
}
.main .page-header {
  margin-top: 0;
}


text:
// ***********************************************************************
// Assembly         : MusicPickerService
// Author           : Pierre
// Created          : 06-15-2015
//
// Last Modified By : Pierre
// Last Modified On : 06-21-2015
// ***********************************************************************
// <copyright file="MusicHub.cs" company="Hutopi">
//     Copyright ©  2015 Hugo Caille, Pierre Defache & Thomas Fossati.
//     Music Picker is released upon the terms of the Apache 2.0 License.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using MusicPickerService.Models;
using StackExchange.Redis;
using Microsoft.AspNet.SignalR;

/// <summary>
/// The Hubs namespace.
/// </summary>
namespace MusicPickerService.Hubs
{
    /// <summary>
    /// Class MusicHub.
    /// </summary>
    public class MusicHub : Hub
    {
        /// <summary>
        /// The redis connection
        /// </summary>
        private static ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
        /// <summary>
        /// The database context
        /// </summary>
        private ApplicationDbContext dbContext = new ApplicationDbContext();

        /// <summary>
        /// Gets the store (database).
        /// </summary>
        /// <value>The store.</value>
        private IDatabase store
        {
            get
            {
                return redis.GetDatabase();
            }
        }

        /// <summary>
        /// Gets the user manager.
        /// </summary>
        /// <value>The user manager.</value>
        private ApplicationUserManager userManager
        {
            get
            {
                return HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
        }

        /// <summary>
        /// Registers the device.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        [Authorize]
        public void RegisterDevice(int deviceId)
        {
            Device device = dbContext.Devices.Find(deviceId);
            if (device.OwnerId != Context.User.Identity.GetUserId())
            {
                return;
            }

            store.StringSet(String.Format("musichub.devices.{0}", Context.ConnectionId), deviceId);
            store.StringSet(String.Format("musichub.device.{0}.connection", deviceId), Context.ConnectionId);
        }

        /// <summary>
        /// Registers the client.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        [Authorize]
        public void RegisterClient(int deviceId)
        {
            Device device = dbContext.Devices.Find(deviceId);
            if (device.OwnerId != Context.User.Identity.GetUserId())
            {
                return;
            }

            store.SetAdd(String.Format("musichub.client.{0}.devices", Context.ConnectionId), deviceId);
            Groups.Add(Context.ConnectionId, String.Format("device.{0}", deviceId));
            store.SetAdd(String.Format("musichub.device.{0}.clients", deviceId), Context.ConnectionId);
        }

        /// <summary>
        /// Return if the device is connected or not
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public bool DeviceConnected(int deviceId)
        {
            return store.KeyExists(String.Format("musichub.device.{0}.connection", deviceId));
        }

        /// <summary>
        /// Called when a connection disconnects from this hub gracefully or due to a timeout.
        /// </summary>
        /// <param name="stopCalled">true, if stop was called on the client closing the connection gracefully;
        /// false, if the connection has been lost for longer than the
        /// <see cref="P:Microsoft.AspNet.SignalR.Configuration.IConfigurationManager.DisconnectTimeout" />.
        /// Timeouts can be caused by clients reconnecting to another SignalR server in scaleout.</param>
        /// <returns>A <see cref="T:System.Threading.Tasks.Task" /></returns>
        public override Task OnDisconnected(bool stopCalled)
        {
            string deviceId;
            deviceId = store.StringGet(String.Format("musichub.devices.{0}", Context.ConnectionId));

            if (deviceId != null)
            {
                store.KeyDelete(String.Format("musichub.device.{0}.current", deviceId));
                store.KeyDelete(String.Format("musichub.device.{0}.duration", deviceId));
                store.KeyDelete(String.Format("musichub.device.{0}.playing", deviceId));
                store.KeyDelete(String.Format("musichub.device.{0}.paused", deviceId));
                store.KeyDelete(String.Format("musichub.device.{0}.lastpause", deviceId));
                store.KeyDelete(String.Format("musichub.device.{0}.queue", deviceId));
                store.KeyDelete(String.Format("musichub.device.{0}.queue.device", deviceId));
                store.KeyDelete(String.Format("musichub.device.{0}.clients", deviceId));
                store.KeyDelete(String.Format("musichub.device.{0}.connection", deviceId));
            }
            else
            {
                RedisValue[] members = store.SetMembers(String.Format("musichub.client.{0}.devices", Context.ConnectionId));
                foreach (string member in members)
                {
                    store.SetRemove(String.Format("musichub.client.{0}.devices", Context.ConnectionId), member);
                    Groups.Remove(Context.ConnectionId, String.Format("device.{0}", member));
                    store.SetRemove(String.Format("musichub.device.{0}.clients", member), Context.ConnectionId);
                }
            }

            return base.OnDisconnected(stopCalled);
        }

        /// <summary>
        /// Creates the state of the device.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        /// <returns>DeviceState.</returns>
        private DeviceState CreateDeviceState(int deviceId)
        {
            return new DeviceState()
            {
                Current = (int)store.StringGet(String.Format("musichub.device.{0}.current", deviceId)),
                Duration = (int)store.StringGet(String.Format("musichub.device.{0}.duration", deviceId)),
                Playing = (bool)store.StringGet(String.Format("musichub.device.{0}.playing", deviceId)),
                Paused = (bool)store.StringGet(String.Format("musichub.device.{0}.paused", deviceId)),
                LastPause = DateTime.FromFileTimeUtc((long)store.StringGet(String.Format("musichub.device.{0}.lastpause", deviceId))),
                Queue = (int[])Array.ConvertAll(store.ListRange(String.Format("musichub.device.{0}.queue", deviceId)), item => (int)item)
            };
        }
        /// <summary>
        /// Sends the state of the client.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        private void SendClientState(int deviceId)
        {
            Clients.Group(String.Format("device.{0}", deviceId)).SetState(CreateDeviceState(deviceId));
        }

        /// <summary>
        /// Determines whether the specified device identifier is registered.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        /// <returns><c>true</c> if the specified device identifier is registered; otherwise, <c>false</c>.</returns>
        private bool IsRegistered(int deviceId)
        {
            if (store.StringGet(String.Format("musichub.device.{0}.connection", deviceId)) == Context.ConnectionId)
            {
                return true;
            }

            return store.SetContains(String.Format("musichub.device.{0}.clients", deviceId), Context.ConnectionId);
        }

        /// <summary>
        /// Queues the specified tracks on the device which has deviceId as id.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        /// <param name="trackIds">The track ids.</param>
        public void Queue(int deviceId, int[] trackIds)
        {
            if (!IsRegistered(deviceId)
                ||
                !store.KeyExists(String.Format("musichub.device.{0}.connection", deviceId)))
            {
                return;
            }

            string queue = String.Format("musichub.device.{0}.queue", deviceId);
            string deviceQueue = String.Format("musichub.device.{0}.queue.device", deviceId);
            store.KeyDelete(queue);
            store.KeyDelete(deviceQueue);

            foreach (int trackId in trackIds)
            {
                try
                {
                    string trackDeviceId = (from dt in this.dbContext.DeviceTracks
                                            where dt.DeviceId == deviceId && dt.TrackId == trackId
                                            select dt.DeviceTrackId).First();
                    store.ListRightPush(queue, trackId);
                    store.ListRightPush(deviceQueue, trackDeviceId);
                }
                catch
                {
                    continue;
                }
            }

            SendClientState(deviceId);
            if ((bool) store.StringGet(String.Format("musichub.device.{0}.playing", deviceId)))
            {
                RequestNext(deviceId);
            }
            else
            {
                store.StringSet(String.Format("musichub.device.{0}.playing", deviceId), false);
                Play(deviceId);
            }
        }

        /// <summary>
        /// Gets the state of the device.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        public void GetState(int deviceId)
        {
            if (!IsRegistered(deviceId)
                ||
                !store.KeyExists(String.Format("musichub.device.{0}.connection", deviceId)))
            {
                return;
            }

            Clients.Caller.SetState(CreateDeviceState(deviceId));
        }

        /// <summary>
        /// Plays the tracks on the specified device.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        public void Play(int deviceId)
        {
            if (!IsRegistered(deviceId)
                ||
                !store.KeyExists(String.Format("musichub.device.{0}.connection", deviceId)))
            {
                return;
            }

            bool sendTrack = (int)store.ListLength(String.Format("musichub.device.{0}.queue", deviceId)) == 0;
            QueueVote(deviceId);

            string deviceClientId = store.StringGet(String.Format("musichub.device.{0}.connection", deviceId));

            if (store.ListLength(String.Format("musichub.device.{0}.queue", deviceId)) > 0)
            {
                store.StringSet(String.Format("musichub.device.{0}.playing", deviceId), true);
                store.StringSet(String.Format("musichub.device.{0}.lastpause", deviceId), DateTime.Now.ToFileTimeUtc());

                if (!(bool) store.StringGet(String.Format("musichub.device.{0}.paused", deviceId)))
                {
                    Clients.Client(deviceClientId).Stop();
                    string currentDeviceTrack = UpdateState(deviceId);
                    Clients.Client(deviceClientId).SetTrackId(currentDeviceTrack);
                }
                else
                {
                    store.StringSet(String.Format("musichub.device.{0}.paused", deviceId), false);
                }

                Clients.Client(deviceClientId).Play();
                SendClientState(deviceId);
            }
        }

        /// <summary>
        /// Pauses the musics on the specified device.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        public void Pause(int deviceId)
        {
            if (!IsRegistered(deviceId)
                ||
                !store.KeyExists(String.Format("musichub.device.{0}.connection", deviceId)))
            {
                return;
            }

            store.StringSet(String.Format("musichub.device.{0}.playing", deviceId), false);
            store.StringSet(String.Format("musichub.device.{0}.paused", deviceId), true);
            store.StringSet(String.Format("musichub.device.{0}.lastpause", deviceId), DateTime.Now.ToFileTimeUtc());

            SendClientState(deviceId);

            string deviceClientId = store.StringGet(String.Format("musichub.device.{0}.connection", deviceId));
            Clients.Client(deviceClientId).Pause();
        }

        /// <summary>
        /// Requests the next song.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        public void RequestNext(int deviceId)
        {
            if (!IsRegistered(deviceId)
                ||
                !store.KeyExists(String.Format("musichub.device.{0}.connection", deviceId)))
            {
                return;
            }

            store.StringSet(String.Format("musichub.device.{0}.playing", deviceId), false);
            store.KeyDelete(String.Format("musichub.device.{0}.lastpause", deviceId));

            SendClientState(deviceId);

            string deviceClientId = store.StringGet(String.Format("musichub.device.{0}.connection", deviceId));
            Clients.Client(deviceClientId).Stop();
        }

        /// <summary>
        /// Updates the state.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        /// <returns>System.String.</returns>
        private string UpdateState(int deviceId)
        {
            int current = (int)store.ListLeftPop(String.Format("musichub.device.{0}.queue", deviceId), 0);
            string currentDeviceTrack = store.ListLeftPop(String.Format("musichub.device.{0}.queue.device", deviceId), 0);
            store.StringSet(String.Format("musichub.device.{0}.current", deviceId), current);

            int duration = (from dt in this.dbContext.DeviceTracks
                            where dt.DeviceId == deviceId && dt.TrackId == current
                            select dt.TrackDuration).First();
            store.StringSet(String.Format("musichub.device.{0}.duration", deviceId), duration);
            return currentDeviceTrack;
        }

        /// <summary>
        /// Play the next song on the specified device.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        public void Next(int deviceId)
        {
            if (!IsRegistered(deviceId)
                ||
                !store.KeyExists(String.Format("musichub.device.{0}.connection", deviceId)))
            {
                return;
            }

            QueueVote(deviceId);

            if (store.ListLength(String.Format("musichub.device.{0}.queue", deviceId)) == 0)
            {
                return;
            }

            Play(deviceId);
        }

        /// <summary>
        /// Sends the vote options.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        private void SendVoteOptions(int deviceId)
        {
            List<VoteOption> votes = new List<VoteOption>();

            IEnumerable<RedisKey> keys = redis.GetServer(redis.GetEndPoints()[0]).Keys(0, String.Format("musichub.device.{0}.vote.*", deviceId));
            foreach (RedisKey key in keys)
            {
                votes.Add(new VoteOption()
                {
                    TrackId = (int)store.HashGet(key, "track"),
                    Votes = (int)store.HashGet(key, "votes")
                });
            }
            Clients.Group(String.Format("device.{0}", deviceId)).SetVoteOptions(votes);
        }

        /// <summary>
        /// Queues the vote.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        private void QueueVote(int deviceId)
        {
            IEnumerable<RedisKey> keys = redis.GetServer(redis.GetEndPoints()[0]).Keys(0, String.Format("musichub.device.{0}.vote.*", deviceId));
            int track = -1;
            int maxVotes = -1;

            foreach (RedisKey key in keys)
            {
                int votes = (int)store.HashGet(key, "votes");
                if (votes > maxVotes)
                {
                    maxVotes = votes;
                    track = (int)store.HashGet(key, "track");
                }
            }

            if (track != -1)
            {
                store.ListRightPush(String.Format("musichub.device.{0}.queue", deviceId), track);
                string trackDeviceId = (from dt in this.dbContext.DeviceTracks
                                        where dt.DeviceId == deviceId && dt.TrackId == track
                                        select dt.DeviceTrackId).First();
                store.ListRightPush(String.Format("musichub.device.{0}.queue.device", deviceId), trackDeviceId);
            }

            ResetVote(deviceId);
        }

        /// <summary>
        /// Resets the vote.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        private void ResetVote(int deviceId)
        {
            IEnumerable<RedisKey> keys = redis.GetServer(redis.GetEndPoints()[0]).Keys(0, String.Format("musichub.device.{0}.vote.*", deviceId));
            foreach (RedisKey key in keys)
            {
                store.KeyDelete(key);
            }
        }

        /// <summary>
        /// Submits the vote options.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        /// <param name="trackIds">The track ids.</param>
        public void SubmitVoteOptions(int deviceId, int[] trackIds)
        {
            if (!IsRegistered(deviceId)
               ||
               !store.KeyExists(String.Format("musichub.device.{0}.connection", deviceId)))
            {
                return;
            }

            ResetVote(deviceId);

            foreach (int trackId in trackIds)
            {
                store.HashSet(String.Format("musichub.device.{0}.vote.{1}", deviceId, trackId), "track", trackId);
                store.HashSet(String.Format("musichub.device.{0}.vote.{1}", deviceId, trackId), "votes", 0);
            }

            SendVoteOptions(deviceId);
        }

        /// <summary>
        /// Votes for track.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        /// <param name="trackId">The track identifier.</param>
        public void VoteForTrack(int deviceId, int trackId)
        {
            if (!IsRegistered(deviceId)
               ||
               !store.KeyExists(String.Format("musichub.device.{0}.connection", deviceId)))
            {
                return;
            }

            store.HashIncrement(String.Format("musichub.device.{0}.vote.{1}", deviceId, trackId), "votes");
            SendVoteOptions(deviceId);
        }
    }
}


text:
require 'spec_helper_integration'

describe Doorkeeper::TokenInfoController do

  describe "when requesting tokeninfo with valid token" do

    let(:doorkeeper_token) { FactoryGirl.create(:access_token) }

    before(:each) do
      allow(controller).to receive(:doorkeeper_token) { doorkeeper_token }
    end

    def do_get
      get :show
    end

    describe "successful request" do

      it "responds with tokeninfo" do
        do_get
        expect(response.body).to eq(doorkeeper_token.to_json)
      end

      it "responds with a 200 status" do
        do_get
        expect(response.status).to eq 200
      end
    end

    describe "invalid token response" do
      before(:each) do
        allow(controller).to receive(:doorkeeper_token).and_return(nil)
      end
      it "responds with 401 when doorkeeper_token is not valid" do
        do_get
        expect(response.status).to eq 401
        expect(response.headers["WWW-Authenticate"]).to match(/^Bearer/)
      end

      it "responds with 401 when doorkeeper_token is invalid, expired or revoked" do
        allow(controller).to receive(:doorkeeper_token).and_return(doorkeeper_token)
        allow(doorkeeper_token).to receive(:accessible?).and_return(false)
        do_get
        expect(response.status).to eq 401
        expect(response.headers["WWW-Authenticate"]).to match(/^Bearer/)
      end

      it "responds body message for error" do
        do_get
        expect(response.body).to eq(Doorkeeper::OAuth::ErrorResponse.new(:name => :invalid_request, :status => :unauthorized).body.to_json)
      end
    end

  end

end


text:
export default {
  setupFilesAfterEnv: ['jest-extended'],
  testTimeout: 20000,
  testMatch: [
    '**/web_src/**/*.test.js',
  ],
  transform: {},
  verbose: false,
};


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

namespace NitroDebugger.RSP
{
	/// <summary>
	/// Represents the Presentation layer.
	/// </summary>
	public class Presentation
	{
		private const int MaxWriteAttemps = 10;
		private const byte PacketSeparator = 0x24;	// '$'

		private Session session;
		private CancellationTokenSource cts;
		private CommandPacket lastCommandSent;

		public Presentation(string hostname, int port)
		{
			this.session = new Session(hostname, port);
			this.ResetCancellationToken();
		}

		public void Close()
		{
			this.session.Close();
		}

		public void SendCommand(CommandPacket command)
		{
			this.lastCommandSent = command;
			this.SendData(PacketBinConverter.ToBinary(command));
		}

		private void SendData(byte[] data)
		{
			int count = 0;
			int response;

			do {
				if (count == MaxWriteAttemps)
					throw new ProtocolViolationException("[PRES] Can not send correctly");
				count++;

				this.session.Write(data);
				response = this.session.ReadByte();
			} while (response != RawPacket.Ack);
		}

		public ReplyPacket SendInterrupt()
		{
			this.SendData(new byte[] { RawPacket.Interrupt });
			return this.ReceiveReply();
		}

		public void SendNack()
		{
			this.session.Write(RawPacket.Nack);
		}

		public ReplyPacket ReceiveReply()
		{
			ReplyPacket response = null;
			int count = 0;

			do {
				if (count == MaxWriteAttemps)
					throw new ProtocolViolationException("[PRES] Can not receive correctly");
				count++;

				response = this.NextReply();
			} while (response == null);

			return response;
		}

		private ReplyPacket NextReply()
		{
			ReplyPacket response = null;
			try {
				// Get data
				byte[] packet = this.session.ReadPacket(PacketSeparator);
				response = PacketBinConverter.FromBinary(packet, lastCommandSent);

				// Send ACK
				this.session.Write(RawPacket.Ack);
			} catch (FormatException) {
				// Error... send NACK
				this.session.Write(RawPacket.Nack);
			}

			return response;
		}

		public void CancelRead(Task taskToCancell)
		{
			try {
				this.cts.Cancel();
				taskToCancell.Wait(this.cts.Token);
			} catch (OperationCanceledException) {
			} catch (AggregateException) {
			}

			this.ResetCancellationToken();
		}

		private void ResetCancellationToken()
		{
			this.cts = new CancellationTokenSource();
			this.session.Cancellation = this.cts.Token;
		}
	}
}


text:
from twisted.trial import unittest
from twisted.protocols import dict

paramString = b"\"This is a dqstring \\w\\i\\t\\h boring stuff like: \\\"\" and t\\hes\\\"e are a\\to\\ms"
goodparams = [b"This is a dqstring with boring stuff like: \"", b"and", b"thes\"e", b"are", b"atoms"]

class ParamTests(unittest.TestCase):
    def testParseParam(self):
        """Testing command response handling"""
        params = []
        rest = paramString
        while 1:
            (param, rest) = dict.parseParam(rest)
            if param == None:
                break
            params.append(param)
        self.assertEqual(params, goodparams)#, "DictClient.parseParam returns unexpected results")


text:
<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model backend\modules\ecommerce\models\ProductTransaction */

$this->title = 'Create Product Transaction';
$this->params['breadcrumbs'][] = ['label' => 'Product Transactions', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?= $this->render('_form', [
        'model' => $model,
    ]) ?>


text:
<included>
  <appender name="OUTPUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%date{ISO8601,UTC} %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>
</included>


text:
*******
How Tos
*******

.. contents:: Contents
   :depth: 4
   :local:

.. include:: user_information/how_tos/agenda.rst
.. include:: user_information/how_tos/device_setup.rst
.. include:: user_information/how_tos/revent.rst


text:
<?php

  require("../constant.php");

  $num=$_GET['id'];

  $link = mysql_connect("localhost", $id, $passwd);
  mysql_select_db("laundry") or die("無法選擇資料庫");

  mysql_query("SET NAMES 'utf8'");
  mysql_query("SET CHARACTER_SET_CLIENT=utf8");
  mysql_query("SET CHARACTER_SET_RESULTS=utf8");

  $deltable = "Delete FROM $table WHERE id = $num";
  $deldata = "Delete FROM data WHERE id = $num";

  mysql_query($deltable) or die("刪除失敗" . mysql_error( ));
  mysql_query($deldata) or die("刪除失敗" . mysql_error( ));

?>


text:
import { CUSTOM_ELEMENTS_SCHEMA, NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
import { SharedModule } from '../../shared/shared.module';
import { WorkflowAddComponent } from './add/workflow.add.component';
import { WorkflowBreadCrumbComponent } from './breadcrumb/workflow.breadcrumb.component';
import { WorkflowGraphComponent } from './graph/workflow.graph.component';
import { WorkflowRunArtifactListComponent } from './run/node/artifact/artifact.list.component';
import { WorkflowNodeRunHistoryComponent } from './run/node/history/history.component';
import { WorkflowRunNodePipelineComponent } from './run/node/pipeline/node.pipeline.component';
import { WorkflowNodeRunSummaryComponent } from './run/node/summary/run.summary.component';
import { WorkflowRunTestTableComponent } from './run/node/test/table/test.table.component';
import { WorkflowRunTestsResultComponent } from './run/node/test/tests.component';
import { WorkflowNodeRunComponent } from './run/node/workflow.run.node.component';
import { WorkflowRunSummaryComponent } from './run/summary/workflow.run.summary.component';
import { WorkflowRunComponent } from './run/workflow.run.component';
import { WorkflowAdminComponent } from './show/admin/workflow.admin.component';
import { WorkflowNotificationFormComponent } from './show/notification/form/workflow.notification.form.component';
import { WorkflowNotificationListComponent } from './show/notification/list/workflow.notification.list.component';
import { WorkflowShowComponent } from './show/workflow.component';
import { WorkflowSidebarCodeComponent } from './sidebar/code/sidebar.code.component';
import { WorkflowComponent } from './workflow.component';
import { workflowRouting } from './workflow.routing';
import { WorkflowDeleteModalComponent } from './show/admin/delete-modal/delete-modal.component';

@NgModule({
    declarations: [
        WorkflowAddComponent,
        WorkflowAdminComponent,
        WorkflowBreadCrumbComponent,
        WorkflowComponent,
        WorkflowGraphComponent,
        WorkflowNodeRunComponent,
        WorkflowNodeRunHistoryComponent,
        WorkflowNodeRunSummaryComponent,
        WorkflowNotificationFormComponent,
        WorkflowNotificationListComponent,
        WorkflowRunArtifactListComponent,
        WorkflowRunComponent,
        WorkflowRunNodePipelineComponent,
        WorkflowRunSummaryComponent,
        WorkflowRunTestsResultComponent,
        WorkflowRunTestTableComponent,
        WorkflowShowComponent,
        WorkflowSidebarCodeComponent,
        WorkflowDeleteModalComponent
    ],
    imports: [
        SharedModule,
        workflowRouting
    ],
    schemas: [
        CUSTOM_ELEMENTS_SCHEMA,
        NO_ERRORS_SCHEMA
    ]
})
export class WorkflowModule {
}


text:
require 'rdoc/markup'
require 'rdoc/markup/formatter'

##
# This Markup outputter is used for testing purposes.

class RDoc::Markup::ToTest < RDoc::Markup::Formatter

  ##
  # :section: Visitor

  def start_accepting
    @res = []
  end

  def end_accepting
    @res
  end

  def accept_paragraph(am, fragment)
    @res << fragment.to_s
  end

  def accept_verbatim(am, fragment)
    @res << fragment.to_s
  end

  def accept_list_start(am, fragment)
    @res << fragment.to_s
  end

  def accept_list_end(am, fragment)
    @res << fragment.to_s
  end

  def accept_list_item(am, fragment)
    @res << fragment.to_s
  end

  def accept_blank_line(am, fragment)
    @res << fragment.to_s
  end

  def accept_heading(am, fragment)
    @res << fragment.to_s
  end

  def accept_rule(am, fragment)
    @res << fragment.to_s
  end

end


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.autofill_assistant;

import android.content.Context;

import androidx.annotation.Nullable;

import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;

/**
 * Represents a button.
 */
@JNINamespace("autofill_assistant")
public class AssistantDialogButton {
    private final AssistantInfoPageUtil mInfoPageUtil;
    private final String mLabel;
    @Nullable
    private final String mUrl;

    @CalledByNative
    public AssistantDialogButton(
            AssistantInfoPageUtil infoPageUtil, String label, @Nullable String url) {
        mInfoPageUtil = infoPageUtil;
        mLabel = label;
        mUrl = url;
    }

    public void onClick(Context context) {
        if (mUrl != null) {
            mInfoPageUtil.showInfoPage(context, mUrl);
        }
    }

    public String getLabel() {
        return mLabel;
    }
}


text:
const target = {
  type: 'Class',
  value: 'android.support.test.espresso.Espresso'
};

module.exports = {
  target
};