text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// TransformBlock.cs
//
//
// A propagator block that runs a function on each input to produce a single output.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading.Tasks.Dataflow.Internal;
using System.Diagnostics.CodeAnalysis;

namespace System.Threading.Tasks.Dataflow
{
    /// Provides a dataflow block that invokes a provided <see cref="System.Func{TInput,TOutput}"/> delegate for every data element received.
    /// <typeparam name="TInput">Specifies the type of data received and operated on by this <see cref="TransformBlock{TInput,TOutput}"/>.</typeparam>
    /// <typeparam name="TOutput">Specifies the type of data output by this <see cref="TransformBlock{TInput,TOutput}"/>.</typeparam>
    [DebuggerDisplay("{DebuggerDisplayContent,nq}")]
    [DebuggerTypeProxy(typeof(TransformBlock<,>.DebugView))]
    public sealed class TransformBlock<TInput, TOutput> : IPropagatorBlock<TInput, TOutput>, IReceivableSourceBlock<TOutput>, IDebuggerDisplay
    {
        /// The target side.
        private readonly TargetCore<TInput> _target;
        /// Buffer used to reorder outputs that may have completed out-of-order between the target half and the source half.
        private readonly ReorderingBuffer<TOutput> _reorderingBuffer;
        /// The source side.
        private readonly SourceCore<TOutput> _source;

        /// Initializes the <see cref="TransformBlock{TInput,TOutput}"/> with the specified <see cref="System.Func{TInput,TOutput}"/>.
        /// <param name="transform">The function to invoke with each data element received.</param>
        /// <exception cref="System.ArgumentNullException">The <paramref name="transform"/> is null (Nothing in Visual Basic).</exception>
        public TransformBlock(Func<TInput, TOutput> transform) :
            this(transform, null, ExecutionDataflowBlockOptions.Default)
        { }

        ///
        /// Initializes the <see cref="TransformBlock{TInput,TOutput}"/> with the specified <see cref="System.Func{TInput,TOutput}"/> and
        /// <see cref="ExecutionDataflowBlockOptions"/>.
        ///
        /// <param name="transform">The function to invoke with each data element received.</param>
        /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="TransformBlock{TInput,TOutput}"/>.</param>
        /// <exception cref="System.ArgumentNullException">The <paramref name="transform"/> is null (Nothing in Visual Basic).</exception>
        /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception>
        public TransformBlock(Func<TInput, TOutput> transform, ExecutionDataflowBlockOptions dataflowBlockOptions) :
            this(transform, null, dataflowBlockOptions)
        { }

        /// Initializes the <see cref="TransformBlock{TInput,TOutput}"/> with the specified <see cref="System.Func{TInput,TOutput}"/>.
        /// <param name="transform">The function to invoke with each data element received.</param>
        /// <exception cref="System.ArgumentNullException">The <paramref name="transform"/> is null (Nothing in Visual Basic).</exception>
        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public TransformBlock(Func<TInput, Task<TOutput>> transform) :
            this(null, transform, ExecutionDataflowBlockOptions.Default)
        { }

        ///
        /// Initializes the <see cref="TransformBlock{TInput,TOutput}"/> with the specified <see cref="System.Func{TInput,TOutput}"/>
        /// and <see cref="ExecutionDataflowBlockOptions"/>.
        ///
        /// <param name="transform">The function to invoke with each data element received.</param>
        /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="TransformBlock{TInput,TOutput}"/>.</param>
        /// <exception cref="System.ArgumentNullException">The <paramref name="transform"/> is null (Nothing in Visual Basic).</exception>
        /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception>
        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public TransformBlock(Func<TInput, Task<TOutput>> transform, ExecutionDataflowBlockOptions dataflowBlockOptions) :
            this(null, transform, dataflowBlockOptions)
        { }

        ///
        /// Initializes the <see cref="TransformBlock{TInput,TOutput}"/> with the specified <see cref="System.Func{TInput,TOutput}"/>
        /// and <see cref="DataflowBlockOptions"/>.
        ///
        /// <param name="transformSync">The synchronous function to invoke with each data element received.</param>
        /// <param name="transformAsync">The asynchronous function to invoke with each data element received.</param>
        /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="TransformBlock{TInput,TOutput}"/>.</param>
        /// <exception cref="System.ArgumentNullException">The <paramref name="transformSync"/> and <paramref name="transformAsync"/> are both null (Nothing in Visual Basic).</exception>
        /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception>
        private TransformBlock(Func<TInput, TOutput> transformSync, Func<TInput, Task<TOutput>> transformAsync, ExecutionDataflowBlockOptions dataflowBlockOptions)
        {
            if (transformSync == null && transformAsync == null) throw new ArgumentNullException("transform");
            if (dataflowBlockOptions == null) throw new ArgumentNullException("dataflowBlockOptions");

            Contract.Requires(transformSync == null ^ transformAsync == null, "Exactly one of transformSync and transformAsync must be null.");
            Contract.EndContractBlock();

            // Ensure we have options that can't be changed by the caller
            dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone();

            // Initialize onItemsRemoved delegate if necessary
            Action<ISourceBlock<TOutput>, int> onItemsRemoved = null;
            if (dataflowBlockOptions.BoundedCapacity > 0)
                onItemsRemoved = (owningSource, count) => ((TransformBlock<TInput, TOutput>)owningSource)._target.ChangeBoundingCount(-count);

            // Initialize source component.
            _source = new SourceCore<TOutput>(this, dataflowBlockOptions,
                owningSource => ((TransformBlock<TInput, TOutput>)owningSource)._target.Complete(exception: null, dropPendingMessages: true),
                onItemsRemoved);

            // If parallelism is employed, we will need to support reordering messages that complete out-of-order
            if (dataflowBlockOptions.SupportsParallelExecution)
            {
                _reorderingBuffer = new ReorderingBuffer<TOutput>(this, (owningSource, message) => ((TransformBlock<TInput, TOutput>)owningSource)._source.AddMessage(message));
            }

            // Create the underlying target
            if (transformSync != null) // sync
            {
                _target = new TargetCore<TInput>(this,
                    messageWithId => ProcessMessage(transformSync, messageWithId),
                    _reorderingBuffer, dataflowBlockOptions, TargetCoreOptions.None);
            }
            else // async
            {
                Debug.Assert(transformAsync != null, "Incorrect delegate type.");
                _target = new TargetCore<TInput>(this,
                    messageWithId => ProcessMessageWithTask(transformAsync, messageWithId),
                    _reorderingBuffer, dataflowBlockOptions, TargetCoreOptions.UsesAsyncCompletion);
            }

            // Link up the target half with the source half.  In doing so,
            // ensure exceptions are propagated, and let the source know no more messages will arrive.
            // As the target has completed, and as the target synchronously pushes work
            // through the reordering buffer when async processing completes,
            // we know for certain that no more messages will need to be sent to the source.
            _target.Completion.ContinueWith((completed, state) =>
            {
                var sourceCore = (SourceCore<TOutput>)state;
                if (completed.IsFaulted) sourceCore.AddAndUnwrapAggregateException(completed.Exception);
                sourceCore.Complete();
            }, _source, CancellationToken.None, Common.GetContinuationOptions(), TaskScheduler.Default);

            // It is possible that the source half may fault on its own, e.g. due to a task scheduler exception.
            // In those cases we need to fault the target half to drop its buffered messages and to release its
            // reservations. This should not create an infinite loop, because all our implementations are designed
            // to handle multiple completion requests and to carry over only one.
            _source.Completion.ContinueWith((completed, state) =>
            {
                var thisBlock = ((TransformBlock<TInput, TOutput>)state) as IDataflowBlock;
                Debug.Assert(completed.IsFaulted, "The source must be faulted in order to trigger a target completion.");
                thisBlock.Fault(completed.Exception);
            }, this, CancellationToken.None, Common.GetContinuationOptions() | TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default);

            // Handle async cancellation requests by declining on the target
            Common.WireCancellationToComplete(
                dataflowBlockOptions.CancellationToken, Completion, state => ((TargetCore<TInput>)state).Complete(exception: null, dropPendingMessages: true), _target);
#if FEATURE_TRACING
            DataflowEtwProvider etwLog = DataflowEtwProvider.Log;
            if (etwLog.IsEnabled())
            {
                etwLog.DataflowBlockCreated(this, dataflowBlockOptions);
            }
#endif
        }

        /// Processes the message with a user-provided transform function that returns a TOutput.
        /// <param name="transform">The transform function to use to process the message.</param>
        /// <param name="messageWithId">The message to be processed.</param>
        private void ProcessMessage(Func<TInput, TOutput> transform, KeyValuePair<TInput, long> messageWithId)
        {
            // Process the input message to get the output message
            TOutput outputItem = default(TOutput);
            bool itemIsValid = false;
            try
            {
                outputItem = transform(messageWithId.Key);
                itemIsValid = true;
            }
            catch (Exception exc)
            {
                // If this exception represents cancellation, swallow it rather than shutting down the block.
                if (!Common.IsCooperativeCancellation(exc)) throw;
            }
            finally
            {
                // If we were not successful in producing an item, update the bounding
                // count to reflect that we're done with this input item.
                if (!itemIsValid) _target.ChangeBoundingCount(-1);

                // If there's no reordering buffer (because we're running sequentially),
                // simply pass the output message through. Otherwise, there's a reordering buffer,
                // so add to it instead (if a reordering buffer is used, we always need
                // to output the message to it, even if the operation failed and outputMessage
                // is null... this is because the reordering buffer cares about a strict sequence
                // of IDs, and it needs to know when a particular ID has completed. It will eliminate
                // null messages accordingly.)
                if (_reorderingBuffer == null)
                {
                    if (itemIsValid) _source.AddMessage(outputItem);
                }
                else _reorderingBuffer.AddItem(messageWithId.Value, outputItem, itemIsValid);
            }
        }

        /// Processes the message with a user-provided transform function that returns a task of TOutput.
        /// <param name="transform">The transform function to use to process the message.</param>
        /// <param name="messageWithId">The message to be processed.</param>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void ProcessMessageWithTask(Func<TInput, Task<TOutput>> transform, KeyValuePair<TInput, long> messageWithId)
        {
            Contract.Requires(transform != null, "Function to invoke is required.");

            // Run the transform function to get the task that represents the operation's completion
            Task<TOutput> task = null;
            Exception caughtException = null;
            try
            {
                task = transform(messageWithId.Key);
            }
            catch (Exception exc) { caughtException = exc; }

            // If no task is available, we're done.
            if (task == null)
            {
                // If we didn't get a task because an exception occurred,
                // store it (if the exception was cancellation, just ignore it).
                if (caughtException != null && !Common.IsCooperativeCancellation(caughtException))
                {
                    Common.StoreDataflowMessageValueIntoExceptionData(caughtException, messageWithId.Key);
                    _target.Complete(caughtException, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: false);
                }

                // If there's a reordering buffer, notify it that this message is done.
                if (_reorderingBuffer != null) _reorderingBuffer.IgnoreItem(messageWithId.Value);

                // Signal that we're done this async operation, and remove the bounding
                // count for the input item that didn't yield any output.
                _target.SignalOneAsyncMessageCompleted(boundingCountChange: -1);
                return;
            }

            // Otherwise, join with the asynchronous operation when it completes.
            task.ContinueWith((completed, state) =>
            {
                var tuple = (Tuple<TransformBlock<TInput, TOutput>, KeyValuePair<TInput, long>>)state;
                tuple.Item1.AsyncCompleteProcessMessageWithTask(completed, tuple.Item2);
            }, Tuple.Create(this, messageWithId), CancellationToken.None,
            Common.GetContinuationOptions(TaskContinuationOptions.ExecuteSynchronously), TaskScheduler.Default);
        }

        /// Completes the processing of an asynchronous message.
        /// <param name="completed">The completed task storing the output data generated for an input message.</param>
        /// <param name="messageWithId">The originating message</param>
        private void AsyncCompleteProcessMessageWithTask(Task<TOutput> completed, KeyValuePair<TInput, long> messageWithId)
        {
            Contract.Requires(completed != null, "Completed task is required.");
            Contract.Requires(completed.IsCompleted, "Task must be completed to be here.");

            bool isBounded = _target.IsBounded;
            bool gotOutputItem = false;
            TOutput outputItem = default(TOutput);

            switch (completed.Status)
            {
                case TaskStatus.RanToCompletion:
                    outputItem = completed.Result;
                    gotOutputItem = true;
                    break;

                case TaskStatus.Faulted:
                    // We must add the exception before declining and signaling completion, as the exception
                    // is part of the operation, and the completion conditions depend on this.
                    AggregateException aggregate = completed.Exception;
                    Common.StoreDataflowMessageValueIntoExceptionData(aggregate, messageWithId.Key, targetInnerExceptions: true);
                    _target.Complete(aggregate, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: true);
                    break;
                    // Nothing special to do for cancellation
            }

            // Adjust the bounding count if necessary (we only need to decrement it for faulting
            // and cancellation, since in the case of success we still have an item that's now in the output buffer).
            // Even though this is more costly (again, only in the non-success case, we do this before we store the
            // message, so that if there's a race to remove the element from the source buffer, the count is
            // appropriately incremented before it's decremented.
            if (!gotOutputItem && isBounded) _target.ChangeBoundingCount(-1);

            // If there's no reordering buffer (because we're running sequentially),
            // and we got a message, simply pass the output message through.
            if (_reorderingBuffer == null)
            {
                if (gotOutputItem) _source.AddMessage(outputItem);
            }
            // Otherwise, there's a reordering buffer, so add to it instead.
            // Even if something goes wrong, we need to update the
            // reordering buffer, so it knows that an item isn't missing.
            else _reorderingBuffer.AddItem(messageWithId.Value, outputItem, itemIsValid: gotOutputItem);

            // Let the target know that one of the asynchronous operations it launched has completed.
            _target.SignalOneAsyncMessageCompleted();
        }

        /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' />
        public void Complete() { _target.Complete(exception: null, dropPendingMessages: false); }

        /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' />
        void IDataflowBlock.Fault(Exception exception)
        {
            if (exception == null) throw new ArgumentNullException("exception");
            Contract.EndContractBlock();

            _target.Complete(exception, dropPendingMessages: true);
        }

        /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' />
        public IDisposable LinkTo(ITargetBlock<TOutput> target, DataflowLinkOptions linkOptions)
        {
            return _source.LinkTo(target, linkOptions);
        }

        /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' />
        public Boolean TryReceive(Predicate<TOutput> filter, out TOutput item)
        {
            return _source.TryReceive(filter, out item);
        }

        /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' />
        public bool TryReceiveAll(out IList<TOutput> items) { return _source.TryReceiveAll(out items); }

        /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
        public Task Completion { get { return _source.Completion; } }

        /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="InputCount"]/*' />
        public int InputCount { get { return _target.InputCount; } }

        /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="OutputCount"]/*' />
        public int OutputCount { get { return _source.OutputCount; } }

        /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' />
        DataflowMessageStatus ITargetBlock<TInput>.OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, Boolean consumeToAccept)
        {
            return _target.OfferMessage(messageHeader, messageValue, source, consumeToAccept);
        }

        /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' />
        TOutput ISourceBlock<TOutput>.ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target, out Boolean messageConsumed)
        {
            return _source.ConsumeMessage(messageHeader, target, out messageConsumed);
        }

        /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' />
        bool ISourceBlock<TOutput>.ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
        {
            return _source.ReserveMessage(messageHeader, target);
        }

        /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' />
        void ISourceBlock<TOutput>.ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
        {
            _source.ReleaseReservation(messageHeader, target);
        }

        /// Gets the number of messages waiting to be processed.  This must only be used from the debugger as it avoids taking necessary locks.
        private int InputCountForDebugger { get { return _target.GetDebuggingInformation().InputCount; } }
        /// Gets the number of messages waiting to be processed.  This must only be used from the debugger as it avoids taking necessary locks.
        private int OutputCountForDebugger { get { return _source.GetDebuggingInformation().OutputCount; } }

        /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' />
        public override string ToString() { return Common.GetNameForDebugger(this, _source.DataflowBlockOptions); }

        /// The data to display in the debugger display attribute.
        [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
        private object DebuggerDisplayContent
        {
            get
            {
                return string.Format("{0}, InputCount={1}, OutputCount={2}",
                    Common.GetNameForDebugger(this, _source.DataflowBlockOptions),
                    InputCountForDebugger,
                    OutputCountForDebugger);
            }
        }
        /// Gets the data to display in the debugger display attribute for this instance.
        object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } }

        /// Provides a debugger type proxy for the TransformBlock.
        private sealed class DebugView
        {
            /// The transform being viewed.
            private readonly TransformBlock<TInput, TOutput> _transformBlock;
            /// The target half of the block being viewed.
            private readonly TargetCore<TInput>.DebuggingInformation _targetDebuggingInformation;
            /// The source half of the block being viewed.
            private readonly SourceCore<TOutput>.DebuggingInformation _sourceDebuggingInformation;

            /// Initializes the debug view.
            /// <param name="transformBlock">The transform being viewed.</param>
            public DebugView(TransformBlock<TInput, TOutput> transformBlock)
            {
                Contract.Requires(transformBlock != null, "Need a block with which to construct the debug view.");
                _transformBlock = transformBlock;
                _targetDebuggingInformation = transformBlock._target.GetDebuggingInformation();
                _sourceDebuggingInformation = transformBlock._source.GetDebuggingInformation();
            }

            /// Gets the messages waiting to be processed.
            public IEnumerable<TInput> InputQueue { get { return _targetDebuggingInformation.InputQueue; } }
            /// Gets any postponed messages.
            public QueuedMap<ISourceBlock<TInput>, DataflowMessageHeader> PostponedMessages { get { return _targetDebuggingInformation.PostponedMessages; } }
            /// Gets the messages waiting to be received.
            public IEnumerable<TOutput> OutputQueue { get { return _sourceDebuggingInformation.OutputQueue; } }

            /// Gets the number of outstanding input operations.
            public Int32 CurrentDegreeOfParallelism { get { return _targetDebuggingInformation.CurrentDegreeOfParallelism; } }
            /// Gets the task being used for output processing.
            public Task TaskForOutputProcessing { get { return _sourceDebuggingInformation.TaskForOutputProcessing; } }

            /// Gets the DataflowBlockOptions used to configure this block.
            public ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _targetDebuggingInformation.DataflowBlockOptions; } }
            /// Gets whether the block is declining further messages.
            public bool IsDecliningPermanently { get { return _targetDebuggingInformation.IsDecliningPermanently; } }
            /// Gets whether the block is completed.
            public bool IsCompleted { get { return _sourceDebuggingInformation.IsCompleted; } }
            /// Gets the block's Id.
            public int Id { get { return Common.GetBlockId(_transformBlock); } }

            /// Gets the set of all targets linked from this block.
            public TargetRegistry<TOutput> LinkedTargets { get { return _sourceDebuggingInformation.LinkedTargets; } }
            /// Gets the target that holds a reservation on the next message, if any.
            public ITargetBlock<TOutput> NextMessageReservedFor { get { return _sourceDebuggingInformation.NextMessageReservedFor; } }
        }
    }
}


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

/*
Package iconvg implements a compact, binary format for simple vector graphics:
icons, logos, glyphs and emoji.

WARNING: THIS FORMAT IS EXPERIMENTAL AND SUBJECT TO INCOMPATIBLE CHANGES.

A longer overview is at
https://github.com/google/iconvg

The file format is specified at
https://github.com/google/iconvg/blob/main/spec/iconvg-spec.md

This package's encoder emits byte-identical output for the same input,
independent of the platform (and specifically its floating-point hardware).
*/
package iconvg

// TODO: shapes (circles, rects) and strokes? Or can we assume that authoring
// tools will convert shapes and strokes to paths?

// TODO: mark somehow that a graphic (such as a back arrow) should be flipped
// horizontally or its paths otherwise varied when presented in a Right-To-Left
// context, such as among Arabic and Hebrew text? Or should that be the
// responsibility of higher layers, selecting different IconVG graphics based
// on context, the way they would select different PNG graphics.

// TODO: hinting?

redpajama_set_name: RedPajamaGithub


text: SELECT * FROM Followers WHERE user_id = ?


text:
.class Lcom/android/server/BatteryService$2;
.super Landroid/os/UEventObserver;
.source "BatteryService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/BatteryService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/BatteryService;

# direct methods
.method constructor <init>(Lcom/android/server/BatteryService;)V
    .locals 0
    .parameter

    .prologue
    .line 208
    iput-object p1, p0, Lcom/android/server/BatteryService$2;->this$0:Lcom/android/server/BatteryService;

    invoke-direct {p0}, Landroid/os/UEventObserver;-><init>()V

    return-void
.end method

# virtual methods
.method public onUEvent(Landroid/os/UEventObserver$UEvent;)V
    .locals 3
    .parameter "event"

    .prologue
    .line 211
    const-string v1, "1"

    const-string v2, "SWITCH_STATE"

    invoke-virtual {p1, v2}, Landroid/os/UEventObserver$UEvent;->get(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_1

    const/4 v0, 0x1

    .line 212
    .local v0, invalidCharger:I
    :goto_0
    iget-object v1, p0, Lcom/android/server/BatteryService$2;->this$0:Lcom/android/server/BatteryService;

    #getter for: Lcom/android/server/BatteryService;->mInvalidCharger:I
    invoke-static {v1}, Lcom/android/server/BatteryService;->access$100(Lcom/android/server/BatteryService;)I

    move-result v1

    if-eq v1, v0, :cond_0

    .line 213
    iget-object v1, p0, Lcom/android/server/BatteryService$2;->this$0:Lcom/android/server/BatteryService;

    #setter for: Lcom/android/server/BatteryService;->mInvalidCharger:I
    invoke-static {v1, v0}, Lcom/android/server/BatteryService;->access$102(Lcom/android/server/BatteryService;I)I

    .line 214
    iget-object v1, p0, Lcom/android/server/BatteryService$2;->this$0:Lcom/android/server/BatteryService;

    #calls: Lcom/android/server/BatteryService;->update()V
    invoke-static {v1}, Lcom/android/server/BatteryService;->access$000(Lcom/android/server/BatteryService;)V

    .line 216
    :cond_0
    return-void

    .line 211
    .end local v0           #invalidCharger:I
    :cond_1
    const/4 v0, 0x0

    goto :goto_0
.end method


text:
/*global sinon, todo, chai, describe, it, calledOnce*/

// basic sanity check.
// base object is tested in apiPerfReportView_integrationTests.js

describe('NodeReportView.js spec', function() {
    beforeEach(function() {
        $('body').html('

' +
            '
 ' +
            '
' +
            '
' +
            '<form class="global-refresh-selector" role="form">' +
            '
' +
            '
' +
            '
' +
            '<select class="form-control" id="global-refresh-range">' +
            '<option value="15">refresh 15s</option>' +
            '<option value="30" selected>refresh 30s</option>' +
            '<option value="60">refresh 1m</option>' +
            '<option value="300">refresh 5m</option>' +
            '<option value="-1">refresh off</option>' +
            '</select>' +
            '
' +
            '
' +
            '
' +
            '</form>' +
            '
' +
            '
' +
            '<form class="global-lookback-selector" role="form">' +
            '
' +
            '
' +
            '
' +
            '<select class="form-control" id="global-lookback-range">' +
            '<option value="15">lookback 15m</option>' +
            '<option value="60" selected>lookback 1h</option>' +
            '<option value="360">lookback 6h</option>' +
            '<option value="1440">lookback 1d</option>' +
            '</select>' +
            '
' +
            '
' +
            '
' +
            '</form>' +
            '
');

        // to answer GET requests
        this.server = sinon.fakeServer.create();
        this.server.autoRespond = true;
        this.server.respondWith("GET", "*", [200, {
            "Content-Type": "application/json"
        }, 'OK']);

        // confirm that dom is clear of view elements before each test:
        expect($('svg').length).to.equal(0);
        expect($('#spinner').length).to.equal(0);

        // blueSpinnerGif = "../../../goldstone/static/images/ajax-loader-solinea-blue.gif";app = {};
        goldstone.globalLookbackRefreshSelectors = new GlobalLookbackRefreshButtonsView({});

        this.testView = new NodeReportPageView({
            el: '.test-container',
            node_uuid: 'power-of-greyskull'
        });
    });
    afterEach(function() {
        $('body').html('');
        this.server.restore();
    });
    describe('view is constructed', function() {
        it('should exist', function() {
            assert.isDefined(this.testView, 'this.testView has been defined');
            expect(this.testView).to.be.an('object');
            expect(this.testView.el).to.equal('.test-container');
        });
        it('should exist', function() {
            this.testView.render();
        });
        it('view responds to global selector changes', function() {
            this.getGlobalLookbackRefresh_spy = sinon.spy(this.testView, "getGlobalLookbackRefresh");
            expect(this.getGlobalLookbackRefresh_spy.callCount).to.equal(0);

            goldstone.globalLookbackRefreshSelectors.trigger('globalRefreshChange');
            expect(this.getGlobalLookbackRefresh_spy.callCount).to.equal(1);

            goldstone.globalLookbackRefreshSelectors.trigger('globalLookbackChange');
            expect(this.getGlobalLookbackRefresh_spy.callCount).to.equal(2);

            $('#global-refresh-range').val('-1');
            this.testView.getGlobalLookbackRefresh();
            this.testView.scheduleInterval();
            expect(this.getGlobalLookbackRefresh_spy.callCount).to.equal(3);

            this.getGlobalLookbackRefresh_spy.restore();
        });
        it('should correctly parse the node from the url', function() {
            var test1 = this.testView.constructHostName('http://localhost:8000/report/node/controller-01.lab.solinea.com');
            var test2 = this.testView.constructHostName('http://localhost:8000/report/node/controller-01');
            var test3 = this.testView.constructHostName('http://localhost:8000/report/node/controller-01.a.b.c.d.e.f.g.h');
            var test4 = this.testView.constructHostName('http://localhost:8000/report/node/');
            expect(test1).to.equal('controller-01');
            expect(test2).to.equal('controller-01');
            expect(test3).to.equal('controller-01');
            expect(test4).to.equal('');
        });
        it('should show/hide report sections accordingly', function() {
            this.testView.initializeChartButtons();
            $('#headerBar').click();
            expect($('#servicesReport').css('display')).to.equal('block');
            expect($('#reportsReport').css('display')).to.equal('none');
            expect($('#eventsReport').css('display')).to.equal('none');
            $('.reportsButton').click();
            expect($('#servicesReport').css('display')).to.equal('block');
            expect($('#reportsReport').css('display')).to.equal('block');
            expect($('#eventsReport').css('display')).to.equal('none');
            $('.eventsButton').click();
            expect($('#servicesReport').css('display')).to.equal('block');
            expect($('#reportsReport').css('display')).to.equal('block');
            expect($('#eventsReport').css('display')).to.equal('block');
        });
    });
});


text:
package gov.nih.nci.nbia.util;

import org.apache.log4j.Logger;

public class UidDisplayUtil {
	private static transient Logger logger = Logger.getLogger(UidDisplayUtil.class);
    private static final String UID_DELIMETER = "...";

    public static String getDisplayUid(String original) {
       String lengthString =System.getProperty("gov.nih.nci.ncia.ui.uid.display.length");
       int length = 100;
       if(lengthString != null && lengthString.length() > 0){
    	   try{
    		   length = Integer.valueOf(lengthString);
    	   }catch(NumberFormatException nfe){
    		   nfe.printStackTrace();
    		   logger.error("Display Length Property Not Set: gov.nih.nci.ncia.ui.uid.display.length");
    		   logger.error("Using default length of :"+length);
    	   }
       }
       //sit on this deployment error?  might want to fail fast instead to let folks know things are screwed up in properties-service.xml?
       if (original != null && original.length() > length) {

            StringBuilder uid = new StringBuilder();
            uid.append(original.subSequence(0, length / 2));
            uid.append(UID_DELIMETER);
            uid
                    .append(original.substring(original.length()
                            - (length / 2)));
            return uid.toString();
        } else {
            return original;
        }
    }
}


text:
inline std::string NowTime();

enum TLogLevel
{
    logERROR,
    logWARNING,
    logINFO,
    logDEBUG,
    logDEBUG1,
    logDEBUG2,
    logDEBUG3,
    logDEBUG4
};

template <typename T>
class Log
{

public:
    Log();
    virtual ~Log();
    std::ostringstream& Get(TLogLevel level = logINFO);

public:
    static TLogLevel& ReportingLevel();
    static std::string ToString(TLogLevel level);
    static TLogLevel FromString(const std::string& level);

protected:
    std::ostringstream os;

private:
    Log(const Log&);
    Log& operator =(const Log&);

};

template <typename T>
Log<T>::Log()
{
}

template <typename T>
std::ostringstream& Log<T>::Get(TLogLevel level)
{
    os << "- " << NowTime();
    os << " " << ToString(level) << ": ";
    os << std::string(level > logDEBUG ? level - logDEBUG : 0, '\t');
    return os;
}

template <typename T>
Log<T>::~Log()
{
    os << std::endl;
    T::Output(os.str());
}

template <typename T>
TLogLevel& Log<T>::ReportingLevel()
{
    static TLogLevel reportingLevel = logDEBUG4;
    return reportingLevel;
}

template <typename T>
std::string Log<T>::ToString(TLogLevel level)
{
    static const char* const buffer[] = {
        "ERROR",
        "WARNING",
        "INFO",
        "DEBUG",
        "DEBUG1",
        "DEBUG2",
        "DEBUG3",
        "DEBUG4"
    };
    return buffer[level];
}

template <typename T>
TLogLevel Log<T>::FromString(const std::string& level)
{
    if (level == "DEBUG4")
        return logDEBUG4;
    if (level == "DEBUG3")
        return logDEBUG3;
    if (level == "DEBUG2")
        return logDEBUG2;
    if (level == "DEBUG1")
        return logDEBUG1;
    if (level == "DEBUG")
        return logDEBUG;
    if (level == "INFO")
        return logINFO;
    if (level == "WARNING")
        return logWARNING;
    if (level == "ERROR")
        return logERROR;

    Log<T>().Get(logWARNING) << "Unknown logging level '" << level << "'. Using INFO level as default.";
    return logINFO;
}

class Output2FILE
{

public:
    static FILE*& Stream();
    static void Output(const std::string& msg);

};

inline FILE*& Output2FILE::Stream()
{
    static FILE* pStream = stderr;
    return pStream;
}

inline void Output2FILE::Output(const std::string& msg)
{
    FILE* pStream = Stream();
    if (!pStream)
        return;
    fprintf(pStream, "%s", msg.c_str());
    fflush(pStream);
}

class Output2STD
{

public:
    static void Output(const std::string& msg);

};

inline void Output2STD::Output(const std::string &msg)
{
    std::cout << msg << std::endl;
}

#define FILELOG_DECLSPEC
class FILELOG_DECLSPEC FILELog : public Log<Output2FILE> {};
class STDLog : public Log<Output2STD> {};

#ifndef FILELOG_MAX_LEVEL
#define FILELOG_MAX_LEVEL logDEBUG4
#endif

#define FILE_LOG(level) \
    if (level > FILELOG_MAX_LEVEL) ;\
    else if (level > FILELog::ReportingLevel() || !Output2FILE::Stream()) ; \
    else FILELog().Get(level)

#include <sys/time.h>

inline std::string NowTime()
{
    char buffer[11];
    time_t t;
    time(&t);
    tm r = {0};
    strftime(buffer, sizeof(buffer), "%X", localtime_r(&t, &r));
    struct timeval tv;
    gettimeofday(&tv, 0);
    char result[100] = {0};
    sprintf(result, "%s.%03ld", buffer, (long)tv.tv_usec / 1000);
    return result;
}

#endif //__LOG_H__


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
* Exceptions Class
*
* Extends CI Exceptions
*
* @author     http://stackoverflow.com/questions/260597/in-codeigniter-how-can-i-have-php-error-messages-emailed-to-me
*/
class MY_Exceptions extends CI_Exceptions
{
    function __construct()
    {
        return parent::__construct();
    }

    function show_error($heading, $message, $template = 'error_general', $status_code = 500)
    {
        if (!is_null($CI =& get_instance()) AND $status_code >= 500)
        {
            $error_data['heading'] = $heading;
            $error_data['message'] = is_array($message) ? '<pre>'.print_r($message, TRUE).'</pre>' : $message;

            $CI->load->helper('email');
            report_error($template, $error_data);
        }

        return parent::show_error($heading, $message, $template, $status_code);
    }

    function show_php_error($severity, $message, $filepath, $line)
    {
        if (!is_null($CI =& get_instance()))
        {
            $error_data['severity'] = $severity;
            $error_data['message'] = $message;
            $error_data['filepath'] = $filepath;
            $error_data['line'] = $line;

            $CI->load->helper('email');
            report_error('error_php', $error_data);
        }

        return parent::show_php_error($severity, $message, $filepath, $line);
    }

    function show_exception($exception)
    {
        if (!is_null($CI =& get_instance()))
        {
            $message = $exception->getMessage();
            if (empty($message))
            {
                $message = '(null)';
            }

            $error_data['exception'] = $exception;
            $error_data['message'] = $message;

            $CI->load->helper('email');
            report_error('error_exception', $error_data);
        }

        return parent::show_exception($exception);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>AlignmentTextProp (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.poi.hslf.model.textproperties

Class AlignmentTextProp

java.lang.Object

org.apache.poi.hslf.model.textproperties.TextProp

org.apache.poi.hslf.model.textproperties.AlignmentTextProp

All Implemented Interfaces:

java.lang.Cloneable

public class AlignmentTextProp
extends TextProp

Definition for the alignment text property.

Field Summary

Fields

Modifier and Type
Field and Description

static int
CENTER

static int
JUSTIFY

static int
JUSTIFYLOW

static int
LEFT

static int
RIGHT

static int
THAIDISTRIBUTED

Fields inherited from class org.apache.poi.hslf.model.textproperties.TextProp

dataValue, maskInHeader, propName, sizeOfDataBlock

Constructor Summary

Constructors

Constructor and Description

AlignmentTextProp()

Method Summary

Methods inherited from class org.apache.poi.hslf.model.textproperties.TextProp

clone, getMask, getName, getSize, getValue, getWriteMask, setValue

Methods inherited from class java.lang.Object

equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

LEFT

public static final int LEFT

See Also:

Constant Field Values

CENTER

public static final int CENTER

See Also:

Constant Field Values

RIGHT

public static final int RIGHT

See Also:

Constant Field Values

JUSTIFY

public static final int JUSTIFY

See Also:

Constant Field Values

THAIDISTRIBUTED

public static final int THAIDISTRIBUTED

See Also:

Constant Field Values

JUSTIFYLOW

public static final int JUSTIFYLOW

See Also:

Constant Field Values

Constructor Detail

AlignmentTextProp

public AlignmentTextProp()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

                Copyright 2014 The Apache Software Foundation or
        its licensors, as applicable.


text:
import csv

from django.contrib.auth.models import User
from Aluno.models import Aluno

def run():
    reader = csv.reader(open('scripts/alunos.csv', 'rb'), delimiter=';')#, quotechar='|'
    print "inserindo alunos"
    for al in reader:
        matricula = al[0]
        nome = al[1]
        email = al[2]

        user = User(email=email,first_name=nome)
        user.save()
        user.username=user.id
        user.set_password(matricula)
        user.save()
        al = user.aluno_set.create(matricula=matricula)
        print "  %s %s %s" %(matricula,nome,email)


text:
import {Models} from "../base"
import {version as js_version} from "../version"
import {logger} from "../core/logging"
import {BokehEvent, LODStart, LODEnd} from "core/bokeh_events"
import {HasProps} from "core/has_props"
import {Attrs} from "core/types"
import {Signal0} from "core/signaling"
import {Struct, is_ref} from "core/util/refs"
import {decode_column_data, Buffers} from "core/util/serialization"
import {MultiDict, Set as OurSet} from "core/util/data_structures"
import {difference, intersection, copy, includes} from "core/util/array"
import {values} from "core/util/object"
import {isEqual} from "core/util/eq"
import {isArray, isPlainObject} from "core/util/types"
import {LayoutDOM} from "models/layouts/layout_dom"
import {ColumnDataSource} from "models/sources/column_data_source"
import {ClientSession} from "client/session"
import {Model} from "model"
import {
  DocumentChanged, DocumentChangedEvent,
  ModelChanged, ModelChangedEvent,
  RootAddedEvent, RootRemovedEvent,
  TitleChangedEvent,
  MessageSentEvent,
} from "./events"

export class EventManager {
  // Dispatches events to the subscribed models

  session: ClientSession | null = null
  subscribed_models: Set<string> = new Set()

  constructor(readonly document: Document) {}

  send_event(bokeh_event: BokehEvent): void {
    const event = new MessageSentEvent(this.document, "bokeh_event", bokeh_event.to_json())
    this.document._trigger_on_change(event)
  }

  trigger(event: BokehEvent): void {
    for (const id of this.subscribed_models) {
      if (event.origin != null && event.origin.id !== id)
        continue
      const model = this.document._all_models[id]
      if (model != null && model instanceof Model)
        model._process_event(event)
    }
  }
}

export interface DocJson {
  version?: string
  title?: string
  roots: {
    root_ids: string[]
    references: Struct[]
  }
}

export interface Patch {
  references: Struct[]
  events: DocumentChanged[]
}

export type References = {[key: string]: HasProps}

export const documents: Document[] = []

export const DEFAULT_TITLE = "Bokeh Application"

// This class should match the API of the Python Document class
// as much as possible.
export class Document {

  readonly event_manager: EventManager
  readonly idle: Signal0<this>

  protected readonly _init_timestamp: number
  protected _title: string
  protected _roots: Model[]
  /*protected*/ _all_models: {[key: string]: HasProps}
  protected _all_models_by_name: MultiDict<HasProps>
  protected _all_models_freeze_count: number
  protected _callbacks: ((event: DocumentChangedEvent) => void)[]
  protected _message_callbacks: Map<string, Set<(data: unknown) => void>>
  private _idle_roots: WeakMap<Model, boolean>
  protected _interactive_timestamp: number | null
  protected _interactive_plot: Model | null

  constructor() {
    documents.push(this)
    this._init_timestamp = Date.now()
    this._title = DEFAULT_TITLE
    this._roots = []
    this._all_models = {}
    this._all_models_by_name = new MultiDict()
    this._all_models_freeze_count = 0
    this._callbacks = []
    this._message_callbacks = new Map()
    this.event_manager = new EventManager(this)
    this.idle = new Signal0(this, "idle")
    this._idle_roots = new WeakMap() // TODO: WeakSet would be better
    this._interactive_timestamp = null
    this._interactive_plot = null
  }

  get layoutables(): LayoutDOM[] {
    return this._roots.filter((root): root is LayoutDOM => root instanceof LayoutDOM)
  }

  get is_idle(): boolean {
    for (const root of this.layoutables) {
      if (!this._idle_roots.has(root))
        return false
    }
    return true
  }

  notify_idle(model: Model): void {
    this._idle_roots.set(model, true)
    if (this.is_idle) {
      logger.info(`document idle at ${Date.now() - this._init_timestamp} ms`)
      this.idle.emit()
    }
  }

  clear(): void {
    this._push_all_models_freeze()
    try {
      while (this._roots.length > 0) {
        this.remove_root(this._roots[0])
      }
    } finally {
      this._pop_all_models_freeze()
    }
  }

  interactive_start(plot: Model): void {
    if (this._interactive_plot == null) {
      this._interactive_plot = plot
      this._interactive_plot.trigger_event(new LODStart())
    }
    this._interactive_timestamp = Date.now()
  }

  interactive_stop(plot: Model): void {
    if (this._interactive_plot != null && this._interactive_plot.id === plot.id) {
      this._interactive_plot.trigger_event(new LODEnd())
    }
    this._interactive_plot = null
    this._interactive_timestamp = null
  }

  interactive_duration(): number {
    if (this._interactive_timestamp == null)
      return -1
    else
      return Date.now() - this._interactive_timestamp
  }

  destructively_move(dest_doc: Document): void {
    if (dest_doc === this) {
      throw new Error("Attempted to overwrite a document with itself")
    }
    dest_doc.clear()
    // we have to remove ALL roots before adding any
    // to the new doc or else models referenced from multiple
    // roots could be in both docs at once, which isn't allowed.
    const roots = copy(this._roots)
    this.clear()

    for (const root of roots) {
      if (root.document != null)
        throw new Error(`Somehow we didn't detach ${root}`)
    }

    if (Object.keys(this._all_models).length !== 0) {
      throw new Error(`this._all_models still had stuff in it: ${this._all_models}`)
    }

    for (const root of roots) {
      dest_doc.add_root(root)
    }

    dest_doc.set_title(this._title)
  }

  // TODO other fields of doc
  protected _push_all_models_freeze(): void {
    this._all_models_freeze_count += 1
  }

  protected _pop_all_models_freeze(): void {
    this._all_models_freeze_count -= 1
    if (this._all_models_freeze_count === 0) {
      this._recompute_all_models()
    }
  }

  /*protected*/ _invalidate_all_models(): void {
    logger.debug("invalidating document models")
    // if freeze count is > 0, we'll recompute on unfreeze
    if (this._all_models_freeze_count === 0) {
      this._recompute_all_models()
    }
  }

  protected _recompute_all_models(): void {
    let new_all_models_set = new OurSet<HasProps>()
    for (const r of this._roots) {
      new_all_models_set = new_all_models_set.union(r.references())
    }
    const old_all_models_set = new OurSet(values(this._all_models))
    const to_detach = old_all_models_set.diff(new_all_models_set)
    const to_attach = new_all_models_set.diff(old_all_models_set)
    const recomputed: {[key: string]: HasProps} = {}
    for (const m of new_all_models_set.values) {
      recomputed[m.id] = m
    }
    for (const d of to_detach.values) {
      d.detach_document()
      if (d instanceof Model && d.name != null)
        this._all_models_by_name.remove_value(d.name, d)
    }
    for (const a of to_attach.values) {
      a.attach_document(this)
      if (a instanceof Model && a.name != null)
        this._all_models_by_name.add_value(a.name, a)
    }
    this._all_models = recomputed
  }

  roots(): Model[] {
    return this._roots
  }

  add_root(model: Model, setter_id?: string): void {
    logger.debug(`Adding root: ${model}`)
    if (includes(this._roots, model))
      return

    this._push_all_models_freeze()
    try {
      this._roots.push(model)
    } finally {
      this._pop_all_models_freeze()
    }
    this._trigger_on_change(new RootAddedEvent(this, model, setter_id))
  }

  remove_root(model: Model, setter_id?: string): void {
    const i = this._roots.indexOf(model)
    if (i < 0)
      return

    this._push_all_models_freeze()
    try {
      this._roots.splice(i, 1)
    } finally {
      this._pop_all_models_freeze()
    }
    this._trigger_on_change(new RootRemovedEvent(this, model, setter_id))
  }

  title(): string {
    return this._title
  }

  set_title(title: string, setter_id?: string): void {
    if (title !== this._title) {
      this._title = title
      this._trigger_on_change(new TitleChangedEvent(this, title, setter_id))
    }
  }

  get_model_by_id(model_id: string): HasProps | null {
    if (model_id in this._all_models) {
      return this._all_models[model_id]
    } else {
      return null
    }
  }

  get_model_by_name(name: string): HasProps | null {
    return this._all_models_by_name.get_one(name, `Multiple models are named '${name}'`)
  }

  on_message(msg_type: string, callback: (msg_data: unknown) => void): void {
    const message_callbacks = this._message_callbacks.get(msg_type)
    if (message_callbacks == null)
      this._message_callbacks.set(msg_type, new Set([callback]))
    else
      message_callbacks.add(callback)
  }

  remove_on_message(msg_type: string, callback: (msg_data: unknown) => void): void {
    this._message_callbacks.get(msg_type)?.delete(callback)
  }

  protected _trigger_on_message(msg_type: string, msg_data: unknown): void {
    const message_callbacks = this._message_callbacks.get(msg_type)
    if (message_callbacks != null) {
      for (const cb of message_callbacks) {
        cb(msg_data)
      }
    }
  }

  on_change(callback: (event: DocumentChangedEvent) => void): void {
    if (!includes(this._callbacks, callback))
      this._callbacks.push(callback)
  }

  remove_on_change(callback: (event: DocumentChangedEvent) => void): void {
    const i = this._callbacks.indexOf(callback)
    if (i >= 0)
      this._callbacks.splice(i, 1)
  }

  _trigger_on_change(event: DocumentChangedEvent): void {
    for (const cb of this._callbacks) {
      cb(event)
    }
  }

  // called by the model
  _notify_change(model: HasProps, attr: string, old: any, new_: any, options?: {setter_id?: string, hint?: any}): void {
    if (attr === 'name') {
      this._all_models_by_name.remove_value(old, model)
      if (new_ != null)
        this._all_models_by_name.add_value(new_, model)
    }
    const setter_id = options != null ? options.setter_id : void 0
    const hint = options != null ? options.hint : void 0
    this._trigger_on_change(new ModelChangedEvent(this, model, attr, old, new_, setter_id, hint))
  }

  static _references_json(references: HasProps[], include_defaults: boolean = true): Struct[] {
    const references_json: Struct[] = []
    for (const r of references) {
      const struct = r.struct()
      struct.attributes = r.attributes_as_json(include_defaults)
      // server doesn't want id in here since it's already in ref above
      delete struct.attributes.id
      references_json.push(struct)
    }
    return references_json
  }

  static _instantiate_object(obj_id: string, obj_type: string, obj_attrs: Attrs): HasProps {
    const full_attrs = {...obj_attrs, id: obj_id, __deferred__: true}
    const model = Models(obj_type)
    return new (model as any)(full_attrs)
  }

  // given a JSON representation of all models in a graph, return a
  // dict of new model objects
  static _instantiate_references_json(references_json: Struct[], existing_models: {[key: string]: HasProps}): References {
    // Create all instances, but without setting their props
    const references: References = {}
    for (const obj of references_json) {
      const obj_id = obj.id
      const obj_type = obj.type
      const obj_attrs = obj.attributes || {}

      let instance: HasProps
      if (obj_id in existing_models)
        instance = existing_models[obj_id]
      else {
        instance = Document._instantiate_object(obj_id, obj_type, obj_attrs)
        if (obj.subtype != null)
          instance.set_subtype(obj.subtype)
      }
      references[instance.id] = instance
    }
    return references
  }

  // if v looks like a ref, or a collection, resolve it, otherwise return it unchanged
  // recurse into collections but not into HasProps
  static _resolve_refs(value: any, old_references: References, new_references: References): any {
    function resolve_ref(v: any): any {
      if (is_ref(v)) {
        if (v.id in old_references)
          return old_references[v.id]
        else if (v.id in new_references)
          return new_references[v.id]
        else
          throw new Error(`reference ${JSON.stringify(v)} isn't known (not in Document?)`)
      } else if (isArray(v))
        return resolve_array(v)
      else if (isPlainObject(v))
        return resolve_dict(v)
      else
        return v
    }

    function resolve_array(array: unknown[]) {
      const results: unknown[] = []
      for (const v of array) {
        results.push(resolve_ref(v))
      }
      return results
    }

    function resolve_dict(dict: {[key: string]: unknown}) {
      const resolved: {[key: string]: unknown} = {}
      for (const k in dict) {
        const v = dict[k]
        resolved[k] = resolve_ref(v)
      }
      return resolved
    }

    return resolve_ref(value)
  }

  // given a JSON representation of all models in a graph and new
  // model instances, set the properties on the models from the
  // JSON
  static _initialize_references_json(references_json: Struct[], old_references: References, new_references: References): void {
    type ID = string
    const to_update = new Map<ID, {instance: HasProps, is_new: boolean}>()
    for (const {id, attributes} of references_json) {
      const is_new = !(id in old_references)
      const instance = is_new ? new_references[id] : old_references[id]

      // replace references with actual instances in obj_attrs
      const resolved_attrs = Document._resolve_refs(attributes, old_references, new_references)
      instance.setv(resolved_attrs, {silent: true})
      to_update.set(id, {instance, is_new})
    }

    const ordered_instances: HasProps[] = []
    const handled = new Set<ID>()
    const finalize_all_by_dfs = (v: unknown) => {
      if (v instanceof HasProps) {
        // note that we ignore instances that aren't updated (not in to_update)
        if (to_update.has(v.id) && !handled.has(v.id)) {
          handled.add(v.id)
          const {instance, is_new} = to_update.get(v.id)!
          const {attributes} = instance
          for (const a in attributes)
            finalize_all_by_dfs(attributes[a])
          if (is_new) {
            // Finalizing here just to avoid iterating
            // over `ordered_instances` twice.
            instance.finalize()
            // Preserving an ordered collection of instances
            // to avoid having to go through DFS again.
            ordered_instances.push(instance)
          }
        }
      } else if (isArray(v)) {
        for (const e of v)
          finalize_all_by_dfs(e)
      } else if (isPlainObject(v)) {
        for (const k in v)
          finalize_all_by_dfs(v[k])
      }
    }

    for (const item of to_update.values())
      finalize_all_by_dfs(item.instance)

    // `connect_signals` has to be executed last because it
    // may rely on properties of dependencies that are initialized
    // only in `finalize`. It's a problem that appears when
    // there are circular references, e.g. as in
    // CDS -> CustomJS (on data change) -> GlyphRenderer (in args) -> CDS.
    ordered_instances.forEach(i => { i.connect_signals() })
  }

  static _event_for_attribute_change(changed_obj: Struct, key: string, new_value: any, doc: Document, value_refs: {[key: string]: HasProps}): ModelChanged | null {
    const changed_model = doc.get_model_by_id(changed_obj.id)! // XXX!
    if (!changed_model.attribute_is_serializable(key))
      return null
    else {
      const event: ModelChanged = {
        kind: "ModelChanged",
        model: {id: changed_obj.id},
        attr: key,
        new: new_value,
      }
      HasProps._json_record_references(doc, new_value, value_refs, true) // true = recurse
      return event
    }
  }

  static _events_to_sync_objects(from_obj: Struct, to_obj: Struct, to_doc: Document, value_refs: {[key: string]: HasProps}): ModelChanged[] {
    const from_keys = Object.keys(from_obj.attributes!) //XXX!
    const to_keys = Object.keys(to_obj.attributes!) //XXX!
    const removed = difference(from_keys, to_keys)
    const added = difference(to_keys, from_keys)
    const shared = intersection(from_keys, to_keys)
    const events: (ModelChanged | null)[] = []

    for (const key of removed) {
      // we don't really have a "remove" event - not sure this ever
      // happens even. One way this could happen is if the server
      // does include_defaults=True and we do
      // include_defaults=false ... in that case it'd be best to
      // just ignore this probably. Warn about it, could mean
      // there's a bug if we don't have a key that the server sent.
      logger.warn(`Server sent key ${key} but we don't seem to have it in our JSON`)
    }

    for (const key of added) {
      const new_value = to_obj.attributes![key] // XXX!
      events.push(Document._event_for_attribute_change(from_obj, key, new_value, to_doc, value_refs))
    }

    for (const key of shared) {
      const old_value = from_obj.attributes![key] // XXX!
      const new_value = to_obj.attributes![key] // XXX!
      if (old_value == null && new_value == null) {
      } else if (old_value == null || new_value == null) {
        events.push(Document._event_for_attribute_change(from_obj, key, new_value, to_doc, value_refs))
      } else {
        if (!isEqual(old_value, new_value))
          events.push(Document._event_for_attribute_change(from_obj, key, new_value, to_doc, value_refs))
      }
    }

    return events.filter((e): e is ModelChanged => e != null)
  }

  // we use this to detect changes during document deserialization
  // (in model constructors and initializers)
  static _compute_patch_since_json(from_json: DocJson, to_doc: Document): Patch {
    const to_json = to_doc.to_json(false) // include_defaults=false

    function refs(json: DocJson): {[key: string]: Struct} {
      const result: {[key: string]: Struct} = {}
      for (const obj of json.roots.references)
        result[obj.id] = obj
      return result
    }

    const from_references = refs(from_json)
    const from_roots: {[key: string]: Struct} = {}
    const from_root_ids: string[] = []
    for (const r of from_json.roots.root_ids) {
      from_roots[r] = from_references[r]
      from_root_ids.push(r)
    }

    const to_references = refs(to_json)
    const to_roots: {[key: string]: Struct} = {}
    const to_root_ids: string[] = []
    for (const r of to_json.roots.root_ids) {
      to_roots[r] = to_references[r]
      to_root_ids.push(r)
    }

    from_root_ids.sort()
    to_root_ids.sort()

    if (difference(from_root_ids, to_root_ids).length > 0 ||
        difference(to_root_ids, from_root_ids).length > 0) {
      // this would arise if someone does add_root/remove_root during
      // document deserialization, hopefully they won't ever do so.
      throw new Error("Not implemented: computing add/remove of document roots")
    }

    const value_refs: {[key: string]: HasProps} = {}
    let events: DocumentChanged[] = []

    for (const id in to_doc._all_models) {
      if (id in from_references) {
        const update_model_events = Document._events_to_sync_objects(from_references[id], to_references[id], to_doc, value_refs)
        events = events.concat(update_model_events)
      }
    }
    return {
      references: Document._references_json(values(value_refs), false), // include_defaults=false
      events,
    }
  }

  to_json_string(include_defaults: boolean = true): string {
    return JSON.stringify(this.to_json(include_defaults))
  }

  to_json(include_defaults: boolean = true): DocJson {
    const root_ids = this._roots.map((r) => r.id)
    const root_references = values(this._all_models)
    return {
      version: js_version,
      title: this._title,
      roots: {
        root_ids,
        references: Document._references_json(root_references, include_defaults),
      },
    }
  }

  static from_json_string(s: string): Document {
    const json: any = JSON.parse(s)
    return Document.from_json(json)
  }

  static from_json(json: DocJson): Document {
    logger.debug("Creating Document from JSON")

    function pyify(version: string) {
      return version.replace(/-(dev|rc)\./, "$1")
    }

    const py_version = json.version! // XXX!
    const is_dev = py_version.indexOf('+') !== -1 || py_version.indexOf('-') !== -1
    const versions_string = `Library versions: JS (${js_version}) / Python (${py_version})`
    if (!is_dev && pyify(js_version) != py_version) {
      logger.warn("JS/Python version mismatch")
      logger.warn(versions_string)
    } else
      logger.debug(versions_string)

    const roots_json = json.roots
    const root_ids = roots_json.root_ids
    const references_json = roots_json.references

    const references = Document._instantiate_references_json(references_json, {})
    Document._initialize_references_json(references_json, {}, references)

    const doc = new Document()
    for (const r of root_ids)
      doc.add_root(references[r] as Model) // XXX: HasProps
    doc.set_title(json.title!) // XXX!
    return doc
  }

  replace_with_json(json: DocJson): void {
    const replacement = Document.from_json(json)
    replacement.destructively_move(this)
  }

  create_json_patch_string(events: DocumentChangedEvent[]): string {
    return JSON.stringify(this.create_json_patch(events))
  }

  create_json_patch(events: DocumentChangedEvent[]): Patch {
    const references: References = {}
    const json_events: DocumentChanged[] = []
    for (const event of events) {
      if (event.document !== this) {
        logger.warn("Cannot create a patch using events from a different document, event had ", event.document, " we are ", this)
        throw new Error("Cannot create a patch using events from a different document")
      }
      json_events.push(event.json(references))
    }
    return {
      events: json_events,
      references: Document._references_json(values(references)),
    }
  }

  apply_json_patch(patch: Patch, buffers: Buffers | ReturnType<Buffers["entries"]> = new Map(), setter_id?: string): void {
    const references_json = patch.references
    const events_json = patch.events
    const references = Document._instantiate_references_json(references_json, this._all_models)

    if (!(buffers instanceof Map)) {
      buffers = new Map(buffers)
    }

    // The model being changed isn't always in references so add it in
    for (const event_json of events_json) {
      switch (event_json.kind) {
        case "RootAdded":
        case "RootRemoved":
        case "ModelChanged": {
          const model_id = event_json.model.id
          if (model_id in this._all_models) {
            references[model_id] = this._all_models[model_id]
          } else {
            if (!(model_id in references)) {
              logger.warn("Got an event for unknown model ", event_json.model)
              throw new Error("event model wasn't known")
            }
          }
          break
        }
      }
    }

    // split references into old and new so we know whether to initialize or update
    const old_references: {[key: string]: HasProps} = {}
    const new_references: {[key: string]: HasProps} = {}
    for (const id in references) {
      const value = references[id]
      if (id in this._all_models)
        old_references[id] = value
      else
        new_references[id] = value
    }

    Document._initialize_references_json(references_json, old_references, new_references)

    for (const event_json of events_json) {
      switch (event_json.kind) {
        case 'MessageSent': {
          const {msg_type, msg_data} = event_json
          let data: unknown
          if (msg_data === undefined) {
            if (buffers.size == 1) {
              const [[, buffer]] = buffers
              data = buffer
            } else {
              throw new Error("expected exactly one buffer")
            }
          } else {
            data = Document._resolve_refs(msg_data, old_references, new_references)
          }

          this._trigger_on_message(msg_type, data)
          break
        }
        case 'ModelChanged': {
          const patched_id = event_json.model.id
          if (!(patched_id in this._all_models)) {
            throw new Error(`Cannot apply patch to ${patched_id} which is not in the document`)
          }
          const patched_obj = this._all_models[patched_id]
          const attr = event_json.attr
          // XXXX currently still need this first branch, some updates (initial?) go through here
          if (attr === 'data' && patched_obj.type === 'ColumnDataSource') {
            const [data, shapes] = decode_column_data(event_json.new, buffers)
            patched_obj.setv({_shapes: shapes, data}, {setter_id})
          } else {
            const value = Document._resolve_refs(event_json.new, old_references, new_references)
            patched_obj.setv({[attr]: value}, {setter_id})
          }
          break
        }
        case 'ColumnDataChanged': {
          const column_source_id = event_json.column_source.id
          if (!(column_source_id in this._all_models)) {
            throw new Error(`Cannot stream to ${column_source_id} which is not in the document`)
          }
          const column_source = this._all_models[column_source_id] as ColumnDataSource
          const [data, shapes] = decode_column_data(event_json.new, buffers)
          if (event_json.cols != null) {
            for (const k in column_source.data) {
              if (!(k in data)) {
                data[k] = column_source.data[k]
              }
            }
            for (const k in column_source._shapes) {
              if (!(k in shapes)) {
                shapes[k] = column_source._shapes[k]
              }
            }
          }
          column_source.setv({
            _shapes: shapes,
            data,
          }, {
            setter_id,
            check_eq: false,
          })
          break
        }
        case 'ColumnsStreamed': {
          const column_source_id = event_json.column_source.id
          if (!(column_source_id in this._all_models)) {
            throw new Error(`Cannot stream to ${column_source_id} which is not in the document`)
          }
          const column_source = this._all_models[column_source_id]
          if (!(column_source instanceof ColumnDataSource)) {
            throw new Error("Cannot stream to non-ColumnDataSource")
          }
          const data = event_json.data
          const rollover = event_json.rollover
          column_source.stream(data, rollover, setter_id)
          break
        }
        case 'ColumnsPatched': {
          const column_source_id = event_json.column_source.id
          if (!(column_source_id in this._all_models)) {
            throw new Error(`Cannot patch ${column_source_id} which is not in the document`)
          }
          const column_source = this._all_models[column_source_id]
          if (!(column_source instanceof ColumnDataSource)) {
            throw new Error("Cannot patch non-ColumnDataSource")
          }
          const patches = event_json.patches
          column_source.patch(patches, setter_id)
          break
        }
        case 'RootAdded': {
          const root_id = event_json.model.id
          const root_obj = references[root_id]
          this.add_root(root_obj as Model, setter_id) // XXX: HasProps
          break
        }
        case 'RootRemoved': {
          const root_id = event_json.model.id
          const root_obj = references[root_id]
          this.remove_root(root_obj as Model, setter_id) // XXX: HasProps
          break
        }
        case 'TitleChanged': {
          this.set_title(event_json.title, setter_id)
          break
        }
        default:
          throw new Error("Unknown patch event " + JSON.stringify(event_json))
      }
    }
  }
}


text:
<!--- 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. -->

# 'Parallel Advantage-Actor Critic' Implementation

This repo contains a MXNet implementation of a variant of the A3C algorithm from [Asynchronous Methods for Deep Reinforcement Learning](https://arxiv.org/pdf/1602.01783v2.pdf).

Trajectories are obtained from multiple environments in a single process, batched together, and used to update the model with a single forward and backward pass.

[Generalized Advantage Estimation](https://arxiv.org/pdf/1506.02438v5.pdf) is used to estimate the advantage function.

Please see the accompanying [tutorial](https://minpy.readthedocs.io/en/latest/tutorial/rl_policy_gradient_tutorial/rl_policy_gradient.html#improved-rl-with-parallel-advantage-actor-critic) for additional background.

Author: Sean Welleck ([@wellecks](https://github.com/wellecks)), Reed Lee ([@loofahcus](https://github.com/loofahcus))

## Prerequisites
  - Install Scikit-learn: `python -m pip install --user sklearn`
  - Install SciPy: `python -m pip install --user scipy`
  - Install the required OpenAI environments. For example, install Atari: `pip install gym[atari]`

For more details refer: https://github.com/openai/gym

## Training

#### Atari Pong

The model can be trained on various OpenAI gym environments, but was primarily tested on `PongDeterministic-v3`. To train on
this environment with default parameters (16 environments), use:

```bash
python train.py
```

Training a model to achieve a score of 20 takes roughly an hour on a Macbook Pro.

#### Other environments

Note that other environments may require additional tuning or architecture adjustments. Use `python train.py -h` to see the command-line arguments.
For instance, to train on `CartPole-v0`, performing updates every 50 steps,
use:

```bash
python train.py --env-type CartPole-v0 --t-max 50
```


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace scott.forge.editor
{
    /// <summary>
    /// Info on a sprite animation
    /// </summary>
    public class SpriteAnimationEntry
    {
        public String Name { get; set; }
        public float SecondsPerFrame { get; set; }
        public List<SourceImageEntry> Images { get; set; }

        /// <summary>
        /// Constructor
        /// </summary>
        public SpriteAnimationEntry( string name )
        {
            Name = name;
            SecondsPerFrame = 1.0f;
            Images = new List<SourceImageEntry>();
        }
    }

    /// <summary>
    /// Represents a SpriteEntry from the resource database
    /// </summary>
    public class SpriteEntry
    {
        public string Name { get; set; }
        public List<SpriteAnimationEntry> Animations { get; private set; }

        public SpriteEntry( string name )
        {
            Name       = name;
            Animations = new List<SpriteAnimationEntry>();
        }

        /// <summary>
        /// Unserialize this sprite
        /// </summary>
        /// <param name="bundleNode"></param>
        /// <returns></returns>
        public static SpriteEntry Read( XmlNode spriteNode, bool isStaticSprite )
        {
            List<SpriteAnimationEntry> animations = new List<SpriteAnimationEntry>();

            // Pull properties
            string name = spriteNode.Attributes["name"].Value;

            // Read all of the animations
            if ( isStaticSprite )
            {
                // This is a static_sprite, meaning it only has a single image
                // inside of it
                XmlNode imageNode      = spriteNode.SelectSingleNode( "static_sprite" );
                SourceImageEntry image = SourceImageEntry.Read( imageNode );

                // Create a single animation called "DEFAULT" with only one frame
                SpriteAnimationEntry animation = new SpriteAnimationEntry( Constants.DEFAULT_ANIMATION_NAME );
                animation.Images.Add( image );

                // Now register the animation
                animations.Add( animation );
            }
            else
            {
                // Read all of the animations in
                XmlNodeList animationNodes = spriteNode.SelectNodes( "animation" );

                foreach ( XmlNode animationNode in animationNodes )
                {
                    string animationName           = animationNode.Attributes["name"].Value;
                    List<SourceImageEntry> images  = ReadAnimationList( animationNode );
                    SpriteAnimationEntry animation = new SpriteAnimationEntry( animationName );

                    animation.Images = images;
                    animations.Add( animation );
                }
            }

            // Create the sprite entry before returning it
            SpriteEntry sprite = new SpriteEntry( name );
            sprite.Animations  = animations;

            return sprite;
        }

        /// <summary>
        /// Reads an animation list
        /// </summary>
        /// <param name="animationNode"></param>
        /// <returns></returns>
        public static List<SourceImageEntry> ReadAnimationList( XmlNode animationNode )
        {
            List<SourceImageEntry> animations = new List<SourceImageEntry>();
            XmlNodeList imageNodes = animationNode.SelectNodes( "image" );

            foreach ( XmlNode imageNode in imageNodes )
            {
                SourceImageEntry image = SourceImageEntry.Read( imageNode );
                animations.Add( image );
            }

            return animations;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="ivy-report.xsl"?>
<ivy-report version="1.0">
	<info
		organisation="default"
		module="swallow-sim-build"
		revision="0.1-SNAPSHOT"
		extra-scalaVersion="2.10"
		extra-sbtVersion="0.13"
		conf="compile"
		confs="compile, runtime, test, provided, optional, compile-internal, runtime-internal, test-internal, plugin, sources, docs, pom, scala-tool"
		date="20170910195205"/>
	<dependencies>
		<module organisation="org.scala-sbt" name="global-plugins">
			<revision name="0.0" status="integration" pubdate="20170910195156" resolver="inter-project" artresolver="inter-project" extra-scalaVersion="2.10" extra-sbtVersion="0.13" downloaded="false" searched="false" default="false" conf="compile, default(compile)" position="0">
				<metadata-artifact status="failed" details="" size="0" time="0" searched="false"/>
				<caller organisation="default" name="swallow-sim-build" conf="compile" rev="0.0" rev-constraint-default="0.0" rev-constraint-dynamic="0.0" callerrev="0.1-SNAPSHOT" extra-scalaVersion="2.10" extra-sbtVersion="0.13"/>
				<artifacts>
				</artifacts>
			</revision>
		</module>
	</dependencies>
</ivy-report>


text:
import xml.etree.ElementTree as ET
import api

name, cards, actions, state = api.request()
state = ET.parse(state)

fear = False
for act in state.getroot().findall('./betting/round/action'):
    if act.get('type') in ('raise',):
        fear = True
        break

if fear:
    api.response('fold')
else:
    api.response(
        api.first_possible(
            ('check', 'call', 'allin'),
            actions
        )
    )


text:
// +build ignore

// check-license checks that AGPL license header in all files matches header in this file.
package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"runtime"
)

func getHeader() string {
	_, file, _, ok := runtime.Caller(0)
	if !ok {
		panic("runtime.Caller(0) failed")
	}
	f, err := os.Open(file)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	var header string
	s := bufio.NewScanner(f)
	for s.Scan() {
		if s.Text() == "" {
			break
		}
		header += s.Text() + "\n"
	}
	header += "\n"
	if err := s.Err(); err != nil {
		log.Fatal(err)
	}
	return header
}

var generatedHeader = regexp.MustCompile(`^// Code generated .* DO NOT EDIT\.`)

func checkHeader(path string, header string) bool {
	f, err := os.Open(path)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	actual := make([]byte, len(header))
	_, err = io.ReadFull(f, actual)
	if err == io.ErrUnexpectedEOF {
		err = nil // some files are shorter than license header
	}
	if err != nil {
		log.Printf("%s - %s", path, err)
		return false
	}

	if generatedHeader.Match(actual) {
		return true
	}

	if header != string(actual) {
		log.Print(path)
		return false
	}
	return true
}

func main() {
	log.SetFlags(0)
	flag.Usage = func() {
		fmt.Fprintln(flag.CommandLine.Output(), "Usage: go run .github/check-license.go")
		flag.CommandLine.PrintDefaults()
	}
	flag.Parse()

	header := getHeader()

	ok := true
	filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.IsDir() {
			switch info.Name() {
			case ".git", "vendor":
				return filepath.SkipDir
			default:
				return nil
			}
		}

		if filepath.Ext(info.Name()) == ".go" {
			if !checkHeader(path, header) {
				ok = false
			}
		}
		return nil
	})

	if ok {
		os.Exit(0)
	}
	log.Print("Please update license header in those files.")
	os.Exit(1)
}


text:
<?php
require 'vendor/autoload.php';

use org\bovigo\vfs\content\LargeFileContent;
use Respect\Validation\Validator as v;
use org\bovigo\vfs\vfsStream;

$root = vfsStream::setup();

$file = vfsStream::newFile('2kb.txt')->withContent(LargeFileContent::withKilobytes(2))->at($root);
v::exists()->check($file->url());

$splFile = new SplFileInfo($file->url());
v::exists()->assert($splFile);
?>
--EXPECTF--


text:
package org.apache.maven.plugin.rresource.it;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}


text: export { MnemonicInput } from './MnemonicInput';


text:
export const ready = function (fn) {
  const completed = () => {
    document.removeEventListener('DOMContentLoaded', completed)
    window.removeEventListener('load', completed)
    fn()
  }

  if (document.readyState !== 'loading') {
    setTimeout(fn) // Execute asynchronously to have a consistent behavior
  } else {
    document.addEventListener('DOMContentLoaded', completed)

    // A fallback to window.onload, that will always work
    window.addEventListener('load', completed)
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">

	<context:annotation-config/>
	<bean id="resourceLoader" class="com.jk.util.resources.JKDefaultResourceLoader" />
	<bean id="exceptionHandler" class="com.jk.util.exceptions.handler.JKDefaultExceptionHandler" />
	<bean class="com.jk.util.factory.TestImpl" />
</beans>


text:
package au.gov.dva.sopapi.sopref.data.sops;

import au.gov.dva.sopapi.interfaces.model.DefinedTerm;

public class StoredDefinedTerm implements DefinedTerm {
    private final String term;

    @Override
    public String getTerm() {
        return term;
    }

    @Override
    public String getDefinition() {
        return definition;
    }

    private final String definition;

    public StoredDefinedTerm(String term, String definition)
    {

        this.term = term;
        this.definition = definition;
    }
}


text:
package org.apache.qpid.jms.test.testpeer.matchers.types;

import org.apache.qpid.proton.amqp.Binary;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.UnsignedLong;
import org.apache.qpid.proton.amqp.messaging.AmqpValue;
import org.hamcrest.Description;

public class EncodedDataMatcher extends EncodedAmqpTypeMatcher
{
    private static final Symbol DESCRIPTOR_SYMBOL = Symbol.valueOf("amqp:data:binary");
    private static final UnsignedLong DESCRIPTOR_CODE = UnsignedLong.valueOf(0x0000000000000075L);

    /**
     * @param expectedValue the value that is expected to be IN the
     * received {@link org.apache.qpid.proton.amqp.messaging.Data}
     */
    public EncodedDataMatcher(Binary expectedValue)
    {
        this(expectedValue, false);
    }

    /**
     * @param expectedValue the value that is expected to be IN the
     * received {@link org.apache.qpid.proton.amqp.messaging.Data}
     * @param permitTrailingBytes if it is permitted for bytes to be left in the Binary after consuming the {@link AmqpValue}
     */
    public EncodedDataMatcher(Binary expectedValue, boolean permitTrailingBytes)
    {
        super(DESCRIPTOR_SYMBOL, DESCRIPTOR_CODE, expectedValue, permitTrailingBytes);
    }

    @Override
    public void describeTo(Description description)
    {
        description
            .appendText("a Binary encoding of a Data that wraps a Binary containing: ")
            .appendValue(getExpectedValue());
    }

}


text:
package test

import bug.Global

object Test {
  def main(args: Array[String]): Unit = {
    val m = new Main()
    m.init()
    m.start()
  }
}

class Main extends Outer {
  m_glob = new Global()
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Hjortstam, Roberts & Spooner, Kew Bull. 53(4): 806 (1998)

#### Original name
Mucronella belalongensis P. Roberts, 1998

### Remarks
null


text:
Tabel of contents
=================

Content
-------

.. toctree::
   :maxdepth: 2

   README
   CHANGELOG
   LICENSE


text:
[![Slack Room][slack-badge]][slack-link]

# Cyber-Trance

A fork of the original [Cyber] Theme:

* Lightweight and simple ➞ **pragmatic**
* Optimized for speed ➞ **no bloat**
* Kinda _semantic coloring_ options (powered by [`cprintf`](https://github.com/Markcial/cprintf)) ➞ **suited for most species**
* Easy to change ➞ **flexible**.

![Cyber-Trance]

## Requirements

The terminal needs to have some capabilities:

* **UTF8** (few characters used)
* **256 colors** or more (all the cool kids have it :children_crossing:)

> Tested on *iTerm2 nightlies*:
>
> `brew cask install iterm2-nightly`

## Integration

While truly optional the following tools are supported:

* [`vcprompt`](https://bitbucket.org/gward/vcprompt) - **git**, **hg**, and **svn** info at low latencies
* [`pyenv`](https://github.com/yyuu/pyenv) - the currently activated **virtualenv** is shown __or__ the version of **Python** currently enabled by *pyenv*
* [`ry`](https://github.com/jneen/ry) - the version of **Ruby** currently enabled by *ry*.

On *OS X* *homebrew* can be used to get these:

```
brew install vcprompt --HEAD
brew install pyenv --HEAD
brew install ry
```

> Note: The *bitbucket* repo of `vcprompt` *homebrew* uses is one of the few actually being maintained.

## Install

With [fisherman]

```fish
fisher fishgretel/cyber-trance
```

## Terminal Settings

Works well with the original color sets

* [Cyber.terminal]
* [Cyber.itermcolors]

A recommandable and well-matching font:

* [Literation Mono](https://github.com/powerline/fonts/tree/master/LiberationMono)

## Got BASH?

If you tend to use `bash` please check out the [`pragmaprompt`](https://github.com/gretel/pragmaprompt) for a similar approach.

[slack-link]: https://fisherman-wharf.herokuapp.com/
[slack-badge]: https://fisherman-wharf.herokuapp.com/badge.svg
[Cyber-Trance]: https://cloud.githubusercontent.com/assets/80815/15529646/1776807a-224f-11e6-8bf0-77c210919af1.png
[Fisherman]: https://github.com/fisherman/fisherman
[Cyber]: https://github.com/fisherman/cyber
[Cyber.terminal]: https://github.com/fishery/cyber/raw/master/Cyber.terminal
[Cyber.itermcolors]: https://github.com/fishery/cyber/raw/master/Cyber.itermcolors


text:
describe("asap", function () {
    it("itWillCallParam", function () {
        var done = false;
        b.asap(function () { return done = true; });
        waitsFor(function () { return done; });
    });
    it("itWillCallParam100times", function () {
        var done = 0;
        for (var i = 0; i < 100; i++) {
            b.asap(function () { return done++; });
        }
        waitsFor(function () { return done === 100; });
    });
    it("itWillCallParam100timesInSequence", function () {
        var done = 0;
        var repeat = function () {
            done++;
            if (done < 100)
                b.asap(repeat);
        };
        b.asap(repeat);
        waitsFor(function () { return done === 100; });
    });
});
describe("Promise", function () {
    it("itwillcallThenResolve", function () {
        var promise = new b.Promise(function (resolve, revoke) {
            resolve("OK");
        });
        var done = "";
        promise.then(function (v) {
            done = v;
        });
        waitsFor(function () { return done === "OK"; });
    });
    it("itwillcallThenResolveAsync", function () {
        var promise = new b.Promise(function (resolve, revoke) {
            setTimeout(function () { return resolve("OK"); }, 0);
        });
        var done = "";
        promise.then(function (v) {
            done = v;
        });
        waitsFor(function () { return done === "OK"; });
    });
    it("itwillcallThenRevoke", function () {
        var promise = new b.Promise(function (resolve, revoke) {
            revoke("OK");
        });
        var done = "";
        promise.then(null, function (r) {
            done = r;
        });
        waitsFor(function () { return done === "OK"; });
    });
    it("itwillcallThenRevokeAsync", function () {
        var promise = new b.Promise(function (resolve, revoke) {
            setTimeout(function () { return revoke("OK"); }, 0);
        });
        var done = "";
        promise.then(null, function (r) {
            done = r;
        });
        waitsFor(function () { return done === "OK"; });
    });
    it("thenChainingSuccess", function () {
        var promise = new b.Promise(function (resolve, revoke) {
            setTimeout(function () { return resolve("O"); }, 0);
        });
        var done = "";
        promise.then(function (v) {
            return v + "K";
        }).then(function (v) { return done = v; });
        waitsFor(function () { return done === "OK"; });
    });
    it("thenChainingFailure", function () {
        var promise = new b.Promise(function (resolve, revoke) {
            setTimeout(function () { return revoke("OK"); }, 0);
        });
        var done = "";
        promise.then(function (v) {
            return v + "K";
        }).then(null, function (v) { return done = v; });
        waitsFor(function () { return done === "OK"; });
    });
});
function delay(time, value) {
    return new b.Promise(function (resolve) {
        setTimeout(function () { return resolve(value); }, time);
    });
}
describe("Promise.all", function () {
    it("zeroParams", function () {
        var done = false;
        b.Promise.all().then(function (p) {
            expect(p).toEqual([]);
            done = true;
        });
        waitsFor(function () { return done; });
    });
    it("someNonPromiseParams", function () {
        var done = false;
        b.Promise.all(1, "A", true).then(function (p) {
            expect(p).toEqual([1, "A", true]);
            done = true;
        });
        waitsFor(function () { return done; });
    });
    it("someNonPromiseArrayParam", function () {
        var done = false;
        b.Promise.all([1, "A", true]).then(function (p) {
            expect(p).toEqual([1, "A", true]);
            done = true;
        });
        waitsFor(function () { return done; });
    });
    it("PromiseParam", function () {
        var done = false;
        b.Promise.all([1, b.Promise.resolve("A"), true]).then(function (p) {
            expect(p).toEqual([1, "A", true]);
            done = true;
        });
        waitsFor(function () { return done; });
    });
    it("TimerPromiseParams", function () {
        var done = false;
        var start = b.now();
        b.Promise.all(delay(100, 1), delay(300, "A"), delay(200, true)).then(function (p) {
            expect(p).toEqual([1, "A", true]);
            expect(b.now() - start).toBeLessThan(400);
            done = true;
        });
        waitsFor(function () { return done; });
    });
    it("TimerPromiseParamsOneFail", function () {
        var done = false;
        var start = b.now();
        b.Promise.all(delay(100, 1), b.Promise.reject("OK"), delay(200, true)).then(null, function (err) {
            expect(err).toEqual("OK");
            expect(b.now() - start).toBeLessThan(100);
            done = true;
        });
        waitsFor(function () { return done; });
    });
});
describe("Promise.race", function () {
    it("TimerPromiseParamsFastestWin", function () {
        var done = false;
        var start = b.now();
        b.Promise.race([delay(100, 1), delay(300, "A"), delay(200, true)]).then(function (value) {
            expect(value).toEqual(1);
            expect(b.now() - start).toBeLessThan(200);
            done = true;
        });
        waitsFor(function () { return done; });
    });
    it("TimerPromiseParamsFastestWinEvenFailure", function () {
        var done = false;
        var start = b.now();
        b.Promise.race([delay(100, 1), b.Promise.reject("OK"), delay(200, true)]).then(null, function (err) {
            expect(err).toEqual("OK");
            expect(b.now() - start).toBeLessThan(100);
            done = true;
        });
        waitsFor(function () { return done; });
    });
});
//# sourceMappingURL=promise.js.map


text:
package cards;

import server.Card;
import server.Game;
import server.Player;

import java.util.Set;

public class ThroneRoom extends Card {

	@Override
	public String name() {
		return "Throne Room";
	}

	@Override
	public Set<Type> types() {
		return types(Type.ACTION);
	}

	@Override
	public int cost() {
		return 4;
	}

    @Override
    public String[] description() {
        return new String[] {"You may play an_Action card from your_hand twice."};
    }

	@Override
	public boolean onPlay(Player player, Game game, boolean hasMoved) {
		return onThroneRoomVariant(player, game, 2, false, hasMoved);
	}

}