text:
// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Roslyn.Utilities;
using Cci = Microsoft.Cci;

namespace Microsoft.CodeAnalysis.CodeGen
{
    partial class ILBuilder
    {
        private sealed class LocalScopeManager
        {
            private readonly LocalScopeInfo rootScope;
            private readonly Stack<ScopeInfo> scopes;
            private ExceptionHandlerScope enclosingExceptionHandler;

            internal LocalScopeManager()
            {
                rootScope = new LocalScopeInfo();
                scopes = new Stack<ScopeInfo>(1);
                scopes.Push(rootScope);
            }

            private ScopeInfo CurrentScope
            {
                get
                {
                    return scopes.Peek();
                }
            }

            internal ScopeInfo OpenScope(ScopeType scopeType, Microsoft.Cci.ITypeReference exceptionType)
            {
                var scope = CurrentScope.OpenScope(scopeType, exceptionType, this.enclosingExceptionHandler);
                scopes.Push(scope);

                if (scope.IsExceptionHandler)
                {
                    this.enclosingExceptionHandler = (ExceptionHandlerScope)scope;
                }

                Debug.Assert(this.enclosingExceptionHandler == GetEnclosingExceptionHandler());
                return scope;
            }

            internal void FinishFilterCondition(ILBuilder builder)
            {
                CurrentScope.FinishFilterCondition(builder);
            }

            internal void ClosingScope(ILBuilder builder)
            {
                CurrentScope.ClosingScope(builder);
            }

            internal void CloseScope(ILBuilder builder)
            {
                var scope = scopes.Pop();
                scope.CloseScope(builder);

                if (scope.IsExceptionHandler)
                {
                    this.enclosingExceptionHandler = GetEnclosingExceptionHandler();
                }

                Debug.Assert(this.enclosingExceptionHandler == GetEnclosingExceptionHandler());
            }

            internal ExceptionHandlerScope EnclosingExceptionHandler
            {
                get { return this.enclosingExceptionHandler; }
            }

            private ExceptionHandlerScope GetEnclosingExceptionHandler()
            {
                foreach (var scope in scopes)
                {
                    switch (scope.Type)
                    {
                        case ScopeType.Try:
                        case ScopeType.Catch:
                        case ScopeType.Filter:
                        case ScopeType.Finally:
                        case ScopeType.Fault:
                            return (ExceptionHandlerScope)scope;
                    }
                }
                return null;
            }

            internal BasicBlock CreateBlock(ILBuilder builder)
            {
                var scope = (LocalScopeInfo)CurrentScope;
                return scope.CreateBlock(builder);
            }

            internal SwitchBlock CreateSwitchBlock(ILBuilder builder)
            {
                var scope = (LocalScopeInfo)CurrentScope;
                return scope.CreateSwitchBlock(builder);
            }

            internal void AddLocal(LocalDefinition variable)
            {
                var scope = (LocalScopeInfo)CurrentScope;
                scope.AddLocal(variable);
            }

            internal void AddLocalConstant(LocalConstantDefinition constant)
            {
                var scope = (LocalScopeInfo)CurrentScope;
                scope.AddLocalConstant(constant);
            }

            /// <summary>
            /// Gets all scopes that contain variables.
            /// </summary>
            /// <param name="edgeInclusive">Specifies whether scope spans should be reported as edge inclusive
            /// (position at "start + length" is IN the scope). VB EE expects that.</param>
            /// <returns></returns>
            /// <remarks>
            /// NOTE that edgeInclusive affects only how results are _reported_.
            /// All internal representation is EDGE EXCLUSIVE.
            /// </remarks>
            internal ImmutableArray<LocalScope> GetAllScopesWithLocals(bool edgeInclusive = false)
            {
                var result = ArrayBuilder<LocalScope>.GetInstance();
                ScopeBounds rootBounds = rootScope.GetScopesWithLocals(result, edgeInclusive);

                uint expectedRootScopeLength = rootBounds.End - rootBounds.Begin;
                if (edgeInclusive)
                {
                    expectedRootScopeLength--;
                }

                // Add root scope if it was not already added.
                // we add it even if it does not contain any locals
                if (result.Count > 0 && result[result.Count - 1].Length != expectedRootScopeLength)
                {
                    result.Add(new LocalScope(
                        0,
                        expectedRootScopeLength,
                        null,
                        SpecializedCollections.EmptyEnumerable<LocalDefinition>(),
                        SpecializedCollections.EmptyEnumerable<LocalDefinition>()));
                }

                //scopes should be sorted by position and size
                result.Sort(ScopeComparer.Instance);

                return result.ToImmutableAndFree();
            }

            /// <summary>
            /// Returns an ExceptionHandlerRegion for each exception handler clause
            /// beneath the root scope. Each ExceptionHandlerRegion indicates the type
            /// of clause (catch or finally) and the bounds of the try block and clause block.
            /// </summary>
            internal ImmutableArray<Cci.ExceptionHandlerRegion> GetExceptionHandlerRegions()
            {
                var result = ArrayBuilder<Cci.ExceptionHandlerRegion>.GetInstance();
                rootScope.GetExceptionHandlerRegions(result);
                return result.ToImmutableAndFree();
            }

            internal ImmutableArray<LocalScope> GetIteratorScopes(bool edgeInclusive)
            {
                var result = ArrayBuilder<LocalScope>.GetInstance();
                rootScope.GetIteratorScopes(result, edgeInclusive);
                return result.ToImmutableAndFree();
            }

            internal void AddIteratorVariable(int index)
            {
                var scope = (LocalScopeInfo)CurrentScope;
                scope.AddIteratorVariable(index);
            }

            internal void FreeBasicBlocks()
            {
                rootScope.FreeBasicBlocks();
            }

            internal bool PossiblyDefinedOutsideOfTry(LocalDefinition local)
            {
                foreach (var s in this.scopes)
                {
                    if (s.ContainsLocal(local))
                    {
                        return false;
                    }

                    if (s.Type == ScopeType.Try)
                    {
                        return true;
                    }
                }

                // not recoreded in scopes, could be a temp
                // we cannot tell anything.
                return true;
            }
        }

        /// <summary>
        /// Base class for IL scopes where a scope contains IL blocks and other nested
        /// scopes. A scope may represent a scope for variable declarations, an exception
        /// handler clause, or an entire exception handler (multiple clauses).
        /// </summary>
        internal abstract class ScopeInfo
        {
            public abstract ScopeType Type { get; }

            public virtual ScopeInfo OpenScope(ScopeType scopeType,
                Microsoft.Cci.ITypeReference exceptionType,
                ExceptionHandlerScope currentHandler)
            {
                if (scopeType == ScopeType.TryCatchFinally)
                {
                    return new ExceptionHandlerContainerScope(currentHandler);
                }
                else
                {
                    Debug.Assert(scopeType == ScopeType.Variable || scopeType == ScopeType.IteratorVariable);
                    return new LocalScopeInfo();
                }
            }

            public virtual void ClosingScope(ILBuilder builder)
            {
            }

            public virtual void CloseScope(ILBuilder builder)
            {
            }

            public virtual void FinishFilterCondition(ILBuilder builder)
            {
                throw ExceptionUtilities.Unreachable;
            }

            public bool IsExceptionHandler
            {
                get
                {
                    switch (this.Type)
                    {
                        case ScopeType.Try:
                        case ScopeType.Catch:
                        case ScopeType.Filter:
                        case ScopeType.Finally:
                        case ScopeType.Fault:
                            return true;
                        default:
                            return false;
                    }
                }
            }

            internal abstract void GetExceptionHandlerRegions(ArrayBuilder<Cci.ExceptionHandlerRegion> regions);

            /// <summary>
            /// Recursively calculates the start and end of the given scope.
            /// Only scopes with locals are actually dumped to the list.
            /// </summary>
            internal abstract ScopeBounds GetScopesWithLocals(ArrayBuilder<LocalScope> scopesWithVariables, bool edgeInclusive);

            protected static ScopeBounds GetScopesWithLocals<TScopeInfo>(ArrayBuilder<LocalScope> scopesWithVariables, ImmutableArray<TScopeInfo>.Builder scopes, bool edgeInclusive)
                where TScopeInfo : ScopeInfo
            {
                Debug.Assert(scopes.Count > 0);

                uint begin = uint.MaxValue;
                uint end = 0;

                foreach (var scope in scopes)
                {
                    ScopeBounds bounds = scope.GetScopesWithLocals(scopesWithVariables, edgeInclusive);
                    begin = Math.Min(begin, bounds.Begin);
                    end = Math.Max(end, bounds.End);
                }

                return new ScopeBounds(begin, end);
            }

            /// <summary>
            /// Recursively calculates the start and end of the given scope.
            /// Only scopes with locals are actually dumped to the list.
            /// </summary>
            internal abstract ScopeBounds GetIteratorScopes(ArrayBuilder<LocalScope> scopesWithIteratorLocals, bool edgeInclusive);

            protected static ScopeBounds GetIteratorScopes<TScopeInfo>(ArrayBuilder<LocalScope> scopesWithIteratorLocals, ImmutableArray<TScopeInfo>.Builder scopes, bool edgeInclusive)
                where TScopeInfo : ScopeInfo
            {
                Debug.Assert(scopes.Count > 0);

                uint begin = uint.MaxValue;
                uint end = 0;

                foreach (var scope in scopes)
                {
                    ScopeBounds bounds = scope.GetIteratorScopes(scopesWithIteratorLocals, edgeInclusive);
                    begin = Math.Min(begin, bounds.Begin);
                    end = Math.Max(end, bounds.End);
                }

                return new ScopeBounds(begin, end);
            }

            /// <summary>
            /// Free any basic blocks owned by this scope or sub-scopes.
            /// </summary>
            public abstract void FreeBasicBlocks();

            internal virtual bool ContainsLocal(LocalDefinition local)
            {
                return false;
            }
        }

        /// <summary>
        /// Class that collects content of the scope (blocks, nested scopes, variables etc).
        /// There is one for every opened scope.
        /// </summary>
        internal class LocalScopeInfo : ScopeInfo
        {
            private ImmutableArray<LocalDefinition>.Builder LocalVariables;
            private ImmutableArray<LocalConstantDefinition>.Builder LocalConstants;
            private ImmutableArray<int>.Builder IteratorVariables;

            // Nested scopes and blocks are not relevant for PDB.
            // We need these only to figure scope bounds.
            private ImmutableArray<ScopeInfo>.Builder NestedScopes;
            protected ImmutableArray<BasicBlock>.Builder Blocks;

            public override ScopeType Type
            {
                get { return ScopeType.Variable; }
            }

            public override ScopeInfo OpenScope(
                ScopeType scopeType,
                Microsoft.Cci.ITypeReference exceptionType,
                ExceptionHandlerScope currentExceptionHandler)
            {
                var scope = base.OpenScope(scopeType, exceptionType, currentExceptionHandler);
                if (NestedScopes == null)
                {
                    NestedScopes = ImmutableArray.CreateBuilder<ScopeInfo>(1);
                }
                NestedScopes.Add(scope);
                return scope;
            }

            internal void AddLocal(LocalDefinition variable)
            {
                if (LocalVariables == null)
                {
                    LocalVariables = ImmutableArray.CreateBuilder<LocalDefinition>(1);
                }

                LocalVariables.Add(variable);
            }

            internal void AddLocalConstant(LocalConstantDefinition constant)
            {
                if (LocalConstants == null)
                {
                    LocalConstants = ImmutableArray.CreateBuilder<LocalConstantDefinition>(1);
                }

                LocalConstants.Add(constant);
            }

            internal void AddIteratorVariable(int index)
            {
                if (IteratorVariables == null)
                {
                    IteratorVariables = ImmutableArray.CreateBuilder<int>(1);
                }

                IteratorVariables.Add(index);
            }

            internal override bool ContainsLocal(LocalDefinition local)
            {
                var locals = this.LocalVariables;
                return locals != null && locals.Contains(local);
            }

            public virtual BasicBlock CreateBlock(ILBuilder builder)
            {
                var enclosingHandler = builder.EnclosingExceptionHandler;
                var block = enclosingHandler == null ?
                    AllocatePooledBlock(builder) :
                    new BasicBlockWithHandlerScope(builder, enclosingHandler);

                AddBlock(block);
                return block;
            }

            private static BasicBlock AllocatePooledBlock(ILBuilder builder)
            {
                var block = BasicBlock.Pool.Allocate();
                block.Initialize(builder);
                return block;
            }

            public SwitchBlock CreateSwitchBlock(ILBuilder builder)
            {
                var block = new SwitchBlock(builder, builder.EnclosingExceptionHandler);
                AddBlock(block);
                return block;
            }

            protected void AddBlock(BasicBlock block)
            {
                if (Blocks == null)
                {
                    Blocks = ImmutableArray.CreateBuilder<BasicBlock>(4);
                }

                Blocks.Add(block);
            }

            internal override void GetExceptionHandlerRegions(ArrayBuilder<Cci.ExceptionHandlerRegion> regions)
            {
                if (NestedScopes != null)
                {
                    for (int i = 0, cnt = NestedScopes.Count; i < cnt; i++)
                    {
                        NestedScopes[i].GetExceptionHandlerRegions(regions);
                    }
                }
            }

            internal override ScopeBounds GetScopesWithLocals(ArrayBuilder<LocalScope> scopesWithVariables, bool edgeInclusive)
            {
                uint begin = uint.MaxValue;
                uint end = 0;

                // It may seem overkill to scan all blocks,
                // but blocks may be reordered so we cannot be sure which ones are first/last.
                if (Blocks != null)
                {
                    for (int i = 0; i < Blocks.Count; i++)
                    {
                        var block = Blocks[i];

                        if (block.Reachability != Reachability.NotReachable)
                        {
                            begin = Math.Min(begin, (uint)block.Start);
                            end = Math.Max(end, (uint)(block.Start + block.TotalSize));
                        }
                    }
                }

                // if there are nested scopes, dump them too
                // also may need to adjust current scope bounds.
                if (NestedScopes != null)
                {
                    ScopeBounds nestedBounds = GetScopesWithLocals(scopesWithVariables, NestedScopes, edgeInclusive);
                    begin = Math.Min(begin, nestedBounds.Begin);
                    end = Math.Max(end, nestedBounds.End);
                }

                // we are not interested in scopes with no variables or no code in them.
                if ((this.LocalVariables != null || this.LocalConstants != null) && end > begin)
                {
                    uint endAdjusted = edgeInclusive ? end - 1 : end;
                    IEnumerable<Microsoft.Cci.ILocalDefinition> localConstantDefinitions = this.LocalConstants == null
                        ? SpecializedCollections.EmptyEnumerable<Microsoft.Cci.ILocalDefinition>()
                        : this.LocalConstants.ToArray();
                    IEnumerable<Microsoft.Cci.ILocalDefinition> localDefinitions = this.LocalVariables == null
                        ? SpecializedCollections.EmptyEnumerable<Microsoft.Cci.ILocalDefinition>()
                        : this.LocalVariables.ToArray();
                    LocalScope newScope = new LocalScope(begin, endAdjusted, null, localConstantDefinitions, localDefinitions);
                    scopesWithVariables.Add(newScope);
                }

                return new ScopeBounds(begin, end);
            }

            internal override ScopeBounds GetIteratorScopes(ArrayBuilder<LocalScope> scopesWithIteratorLocals, bool edgeInclusive)
            {
                uint begin = uint.MaxValue;
                uint end = 0;

                // It may seem overkill to scan all blocks,
                // but blocks may be reordered so we cannot be sure which ones are first/last.
                if (Blocks != null)
                {
                    for (int i = 0; i < Blocks.Count; i++)
                    {
                        var block = Blocks[i];

                        if (block.Reachability != Reachability.NotReachable)
                        {
                            begin = Math.Min(begin, (uint)block.Start);
                            end = Math.Max(end, (uint)(block.Start + block.TotalSize));
                        }
                    }
                }

                // if there are nested scopes, dump them too
                // also may need to adjust current scope bounds.
                if (NestedScopes != null)
                {
                    ScopeBounds nestedBounds = GetIteratorScopes(scopesWithIteratorLocals, NestedScopes, edgeInclusive);
                    begin = Math.Min(begin, nestedBounds.Begin);
                    end = Math.Max(end, nestedBounds.End);
                }

                // we are not interested in scopes with no variables or no code in them.
                if (this.IteratorVariables != null && end > begin)
                {
                    uint endAdjusted = edgeInclusive ? end - 1 : end;
                    var newScope = new LocalScope(begin, endAdjusted, null, null, null);
                    foreach (var iv in this.IteratorVariables)
                    {
                        while (scopesWithIteratorLocals.Count <= iv) scopesWithIteratorLocals.Add(null);
                        scopesWithIteratorLocals[iv] = newScope;
                    }
                }

                return new ScopeBounds(begin, end);
            }

            public override void FreeBasicBlocks()
            {
                if (Blocks != null)
                {
                    for (int i = 0, cnt = Blocks.Count; i < cnt; i++)
                    {
                        Blocks[i].Free();
                    }
                }

                if (NestedScopes != null)
                {
                    for (int i = 0, cnt = NestedScopes.Count; i < cnt; i++)
                    {
                        NestedScopes[i].FreeBasicBlocks();
                    }
                }
            }
        }

        /// <summary>
        /// A scope for a single try, catch, or finally clause. If the clause
        /// is a catch clause, ExceptionType will be set.
        /// </summary>
        internal sealed class ExceptionHandlerScope : LocalScopeInfo
        {
            private readonly ExceptionHandlerContainerScope containingScope;
            private readonly ScopeType type;
            private readonly Microsoft.Cci.ITypeReference exceptionType;

            private BasicBlock lastFilterConditionBlock;

            // branches mey become "blocked by finally" if finally does not terminate (throws or contains infinite loop)
            // we cannot guarantee that the original lable will be emitted (it might be unreachable).
            // on the other hand, it does not matter what blocked branches target as long as it is still blocked by same finally
            // so we provide this "special" block that is located right after finally that any blocked branch can safely target
            // We do guarantee that special block will be emitted as long as something uses it as a target of a branch.
            private object blockedByFinallyDestination;

            public ExceptionHandlerScope(ExceptionHandlerContainerScope containingScope, ScopeType type, Microsoft.Cci.ITypeReference exceptionType)
            {
                Debug.Assert((type == ScopeType.Try) || (type == ScopeType.Catch) || (type == ScopeType.Filter) || (type == ScopeType.Finally) || (type == ScopeType.Fault));
                Debug.Assert((type == ScopeType.Catch) == (exceptionType != null));

                this.containingScope = containingScope;
                this.type = type;
                this.exceptionType = exceptionType;
            }

            public ExceptionHandlerContainerScope ContainingExceptionScope
            {
                get
                {
                    return containingScope;
                }
            }

            public override ScopeType Type
            {
                get { return this.type; }
            }

            public Microsoft.Cci.ITypeReference ExceptionType
            {
                get { return this.exceptionType; }
            }

            // pessimistically sets destination for blocked branches.
            // called when finally block is inserted in the outer TryFinally scope.
            // reachability analysis will clear the label as son as it proves
            // that finally is not blocking.
            public void SetBlockedByFinallyDestination(object label)
            {
                this.blockedByFinallyDestination = label;
            }

            // if current finally does not terminate, this is where
            // branches going through it should be retargeted.
            // Otherwise returns null.
            public object BlockedByFinallyDestination
            {
                get { return this.blockedByFinallyDestination; }
            }

            // Called when finally is determined to be non-blocking
            public void UnblockFinally()
            {
                this.blockedByFinallyDestination = null;
            }

            public uint FilterHandlerStart
            {
                get
                {
                    return (uint)(lastFilterConditionBlock.Start + lastFilterConditionBlock.TotalSize);
                }
            }

            public override void FinishFilterCondition(ILBuilder builder)
            {
                Debug.Assert(this.type == ScopeType.Filter);
                Debug.Assert(this.lastFilterConditionBlock == null);

                this.lastFilterConditionBlock = builder.FinishFilterCondition();
            }

            public override void ClosingScope(ILBuilder builder)
            {
                switch (this.type)
                {
                    case ScopeType.Finally:
                    case ScopeType.Fault:
                        // Emit endfinally|endfault - they are the same opcode.
                        builder.EmitEndFinally();
                        break;

                    default:
                        // Emit branch to label after exception handler.
                        // ("br" will be rewritten as "leave" later by ILBuilder.)
                        var endLabel = this.containingScope.EndLabel;
                        Debug.Assert(endLabel != null);

                        builder.EmitBranch(ILOpCode.Br, endLabel);
                        break;
                }
            }

            public override void CloseScope(ILBuilder builder)
            {
                Debug.Assert(LeaderBlock != null);
            }

            public override BasicBlock CreateBlock(ILBuilder builder)
            {
                Debug.Assert(builder.EnclosingExceptionHandler == this);
                var block = (Blocks == null) ?
                    new ExceptionHandlerLeaderBlock(builder, this, this.GetLeaderBlockType()) :
                    new BasicBlockWithHandlerScope(builder, this);

                AddBlock(block);
                return block;
            }

            public ExceptionHandlerLeaderBlock LeaderBlock
            {
                get { return (Blocks == null) ? null : (ExceptionHandlerLeaderBlock)Blocks[0]; }
            }

            private BlockType GetLeaderBlockType()
            {
                switch (this.type)
                {
                    case ScopeType.Try:
                        return BlockType.Try;
                    case ScopeType.Catch:
                        return BlockType.Catch;
                    case ScopeType.Filter:
                        return BlockType.Filter;
                    case ScopeType.Finally:
                        return BlockType.Finally;
                    default:
                        return BlockType.Fault;
                }
            }

            public override void FreeBasicBlocks()
            {
                base.FreeBasicBlocks();
            }
        }

        /// <summary>
        /// A scope for an entire exception handler (a try block with either several
        /// catches or a finally block). Unlike other scopes, this scope contains
        /// nested scopes only, no IL blocks (although nested ExceptionHandlerScopes
        /// for the clauses will contain IL blocks).
        /// </summary>
        internal sealed class ExceptionHandlerContainerScope : ScopeInfo
        {
            private readonly ImmutableArray<ExceptionHandlerScope>.Builder handlers;
            private readonly object endLabel;
            private readonly ExceptionHandlerScope containingHandler;

            public ExceptionHandlerContainerScope(ExceptionHandlerScope containingHandler)
            {
                this.handlers = ImmutableArray.CreateBuilder<ExceptionHandlerScope>(2);
                this.containingHandler = containingHandler;
                this.endLabel = new object();
            }

            public ExceptionHandlerScope ContainingHandler
            {
                get
                {
                    return containingHandler;
                }
            }

            public object EndLabel
            {
                get { return this.endLabel; }
            }

            public override ScopeType Type
            {
                get { return ScopeType.TryCatchFinally; }
            }

            public override ScopeInfo OpenScope(ScopeType scopeType,
                Microsoft.Cci.ITypeReference exceptionType,
                ExceptionHandlerScope currentExceptionHandler)
            {
                Debug.Assert(((this.handlers.Count == 0) && (scopeType == ScopeType.Try)) ||
                    ((this.handlers.Count > 0) && ((scopeType == ScopeType.Catch) || (scopeType == ScopeType.Filter) || (scopeType == ScopeType.Finally) || (scopeType == ScopeType.Fault))));

                Debug.Assert(currentExceptionHandler == this.containingHandler);

                var handler = new ExceptionHandlerScope(this, scopeType, exceptionType);
                this.handlers.Add(handler);
                return handler;
            }

            public override void CloseScope(ILBuilder builder)
            {
                Debug.Assert(this.handlers.Count > 1);

                // Fix up the NextExceptionHandler reference of each leader block.
                var tryScope = this.handlers[0];
                var previousBlock = tryScope.LeaderBlock;

                for (int i = 1; i < this.handlers.Count; i++)
                {
                    var handlerScope = this.handlers[i];
                    var nextBlock = handlerScope.LeaderBlock;

                    previousBlock.NextExceptionHandler = nextBlock;
                    previousBlock = nextBlock;
                }

                // Generate label for try/catch "leave" target.
                builder.MarkLabel(this.endLabel);

                // hide the following code, since it could be reached through the label above.
                builder.DefineHiddenSeqPoint();

                Debug.Assert(builder.currentBlock == builder.labelInfos[this.endLabel].bb);

                if (this.handlers[1].Type == ScopeType.Finally)
                {
                    // Generate "nop" branch to itself. If this block is unreachable
                    // (because the finally block does not complete), the "nop" will be
                    // replaced by Br_s. On the other hand, if this block is reachable,
                    // the "nop" will be skipped so any "leave" instructions jumping
                    // to this block will jump to the next instead.
                    builder.EmitBranch(ILOpCode.Nop, this.endLabel);

                    this.handlers[1].SetBlockedByFinallyDestination(this.endLabel);
                }
            }

            internal override void GetExceptionHandlerRegions(ArrayBuilder<Cci.ExceptionHandlerRegion> regions)
            {
                Debug.Assert(this.handlers.Count > 1);

                ExceptionHandlerScope tryScope = null;
                ScopeBounds tryBounds = new ScopeBounds();

                foreach (var handlerScope in this.handlers)
                {
                    // Partition I, section 12.4.2.5:
                    // The ordering of the exception clauses in the Exception Handler Table is important. If handlers are nested,
                    // the most deeply nested try blocks shall come before the try blocks that enclose them.
                    //
                    // so we collect the inner regions first.
                    handlerScope.GetExceptionHandlerRegions(regions);

                    var handlerBounds = GetBounds(handlerScope);

                    if (tryScope == null)
                    {
                        // the first scope that we see should be Try.
                        Debug.Assert(handlerScope.Type == ScopeType.Try);

                        tryScope = handlerScope;
                        tryBounds = handlerBounds;

                        var reachability = tryScope.LeaderBlock.Reachability;
                        Debug.Assert((reachability == Reachability.Reachable) || (reachability == Reachability.NotReachable));

                        // All handler blocks should have same reachability.
                        Debug.Assert(this.handlers.All(h => (h.LeaderBlock.Reachability == reachability)));

                        if (reachability != Reachability.Reachable)
                        {
                            return;
                        }
                    }
                    else
                    {
                        Cci.ExceptionHandlerRegion region;
                        switch (handlerScope.Type)
                        {
                            case ScopeType.Finally:
                                region = new Cci.ExceptionHandlerRegionFinally(tryBounds.Begin, tryBounds.End, handlerBounds.Begin, handlerBounds.End);
                                break;

                            case ScopeType.Fault:
                                region = new Cci.ExceptionHandlerRegionFault(tryBounds.Begin, tryBounds.End, handlerBounds.Begin, handlerBounds.End);
                                break;

                            case ScopeType.Catch:
                                region = new Cci.ExceptionHandlerRegionCatch(tryBounds.Begin, tryBounds.End, handlerBounds.Begin, handlerBounds.End, handlerScope.ExceptionType);
                                break;

                            case ScopeType.Filter:
                                region = new Cci.ExceptionHandlerRegionFilter(tryBounds.Begin, tryBounds.End, handlerScope.FilterHandlerStart, handlerBounds.End, handlerBounds.Begin);
                                break;

                            default:
                                throw ExceptionUtilities.UnexpectedValue(handlerScope.Type);
                        }

                        regions.Add(region);
                    }
                }
            }

            internal override ScopeBounds GetScopesWithLocals(ArrayBuilder<LocalScope> scopesWithVariables, bool edgeInclusive)
            {
                return GetScopesWithLocals(scopesWithVariables, this.handlers, edgeInclusive);
            }

            internal override ScopeBounds GetIteratorScopes(ArrayBuilder<LocalScope> scopesWithIteratorVariables, bool edgeInclusive)
            {
                return GetIteratorScopes(scopesWithIteratorVariables, this.handlers, edgeInclusive);
            }

            private static ScopeBounds GetBounds(ExceptionHandlerScope scope)
            {
                var scopes = ArrayBuilder<LocalScope>.GetInstance();
                var result = scope.GetScopesWithLocals(scopes, edgeInclusive: false);
                scopes.Free();
                return result;
            }

            public override void FreeBasicBlocks()
            {
                // No basic blocks owned directly here.

                foreach (var scope in this.handlers)
                {
                    scope.FreeBasicBlocks();
                }
            }
        }

        internal struct ScopeBounds
        {
            internal readonly uint Begin;
            internal readonly uint End;

            internal ScopeBounds(uint begin, uint end)
            {
                this.Begin = begin;
                this.End = end;
            }
        }

        /// <summary>
        /// Compares scopes by their start (ascending) and then size (descending).
        /// </summary>
        private sealed class ScopeComparer : IComparer<LocalScope>
        {
            public static readonly ScopeComparer Instance = new ScopeComparer();

            private ScopeComparer() { }

            public int Compare(LocalScope x, LocalScope y)
            {
                var res = x.Offset.CompareTo(y.Offset);
                if (res == 0)
                {
                    res = y.Length.CompareTo(x.Length);
                }

                return res;
            }
        }
    }
}


text:
1. Fork the project
2. Create a new feature branch with your contribution
3. Implement your great new feature or bug fix
4. Create a pull request

## System Requirements

* nodejs
* yarn

## Building and Testing

```
yarn install
yarn build
yarn test
```

## Code Formatting

Please follow the code format of existing code. Do never reformat a file!

redpajama_set_name: RedPajamaGithub


text:
__justifiedGallery_galleryID = 0;

(function($){

   $.fn.justifiedGallery = function(options){

		var settings = $.extend( {
			'sizeSuffixes' : {'lt100':'_t', 'lt240':'_m', 'lt320':'_n', 'lt500':'', 'lt640':'_z', 'lt1024':'_b'},
			'usedSuffix' : 'lt240',
			'justifyLastRow' : true,
			'rowHeight' : 120,
			'fixedHeight' : false,
			'lightbox' : false,
			'captions' : true,
			'margins' : 1,
			'extension' : '.jpg',
			'refreshTime' : 500
		}, options);

		function getErrorHtml(message, classOfError){
			return "
" + message + "
";
		}

		return this.each(function(index, cont){
			$(cont).addClass("justifiedGallery");

			var loaded = 0;
			var images = new Array($(cont).find("img").length);

			__justifiedGallery_galleryID++;

			if(images.length == 0) return;

			$(cont).append("

");

			$(cont).find("a").each(function(index, entry){
				var img = $(entry).find("img");

				images[index] = new Array(5);
				images[index]["src"] = $(img).attr("src");
				images[index]["alt"] = $(img).attr("alt");
				images[index]["href"] = $(entry).attr("href");
				images[index]["title"] = $(entry).attr("title");
				images[index]["rel"] = "lightbox[gallery-" + __justifiedGallery_galleryID + "]";

				$(entry).remove(); //remove de image, we have its data

				var img = new Image();

				$(img).load(function() {
					if(images[index]["height"] != settings.rowHeight)
						images[index]["width"] = Math.ceil(this.width / (this.height / settings.rowHeight));
					else
						images[index]["width"] = this.width;
					images[index]["height"] = settings.rowHeight;
					images[index]["src"] = images[index]["src"].slice(0, images[index]["src"].length
										 - (settings.sizeSuffixes[settings.usedSuffix] + settings.extension).length);
		    		if(++loaded == images.length) startProcess(cont, images, settings);
				});

				$(img).error(function() {
					$(cont).prepend(getErrorHtml("The image can't be loaded: \"" + images[index]["src"] +"\"", "jg-usedPrefixImageNotFound"));
					images[index] = null;
					if(++loaded == images.length) startProcess(cont, images, settings);
				});

				$(img).attr('src', images[index]["src"]);

			});
		});

		function startProcess(cont, images, settings){
			//FadeOut the loading image and FadeIn the images after their loading
			$(cont).find(".jg-loading").fadeOut(500, function(){
				$(this).remove(); //remove the loading image
				processesImages($, cont, images, 0, settings);
			});
		}

		function buildImage(image, suffix, nw, nh, l, minRowHeight, settings){
			var ris;
			ris =  "
";
			ris += " ";
			ris += "  ";

			if(settings.captions)
				ris += "
" + image["alt"] + "
";

			ris += "
";
			return ris;
		}

		function buildContRow(row, images, extraW, settings){
			var j, l = 0;
			var minRowHeight;
			for(var j = 0; j < row.length; j++){
				row[j]["nh"] = Math.ceil(images[row[j]["indx"]]["height"] *
					            ((images[row[j]["indx"]]["width"] + extraW) /
							 	images[row[j]["indx"]]["width"]));

				row[j]["nw"] = images[row[j]["indx"]]["width"] + extraW;

				row[j]["suffix"] = getSuffix(row[j]["nw"], row[j]["nh"], settings);

				row[j]["l"] = l;

				if(!settings.fixedHeight){
					if(j == 0)
						minRowHeight = row[j]["nh"];
					else
						if(minRowHeight > row[j]["nh"]) minRowHeight = row[j]["nh"];
				}

				l += row[j]["nw"] + settings.margins;
			}

			if(settings.fixedHeight) minRowHeight = settings.rowHeight;

			var rowCont = "";
			for(var j = 0; j < row.length; j++){
				rowCont += buildImage(images[row[j]["indx"]], row[j]["suffix"],
					                  row[j]["nw"], row[j]["nh"], row[j]["l"], minRowHeight, settings);
			}

			return "
" + rowCont + "
";
		}

		function getSuffix(nw, nh, settings){
			var n;
			if(nw > nh) n = nw; else n = nh;
			if(n <= 100){
				return settings.sizeSuffixes.lt100; //thumbnail (longest side:100)
			}else if(n <= 240){
				return settings.sizeSuffixes.lt240; //small (longest side:240)
			}else if(n <= 320){
				return settings.sizeSuffixes.lt320; //small (longest side:320)
			}else if(n <= 500){
				return settings.sizeSuffixes.lt500; //small (longest side:320)
			}else if(n <= 640){
				return settings.sizeSuffixes.lt640; //medium (longest side:640)
			}else{
				return settings.sizeSuffixes.lt1024; //large (longest side:1024)
			}
		}

		function processesImages($, cont, images, lastRowWidth, settings){
			var row = new Array();
			var row_i, i;
			var partialRowWidth = 0;
			var extraW;
			var rowWidth = $(cont).width();

			for(i = 0, row_i = 0; i < images.length; i++){
				if(images[i] == null) continue;
				if(partialRowWidth + images[i]["width"] + settings.margins <= rowWidth){
					//we can add the image
					partialRowWidth += images[i]["width"] + settings.margins;
					row[row_i] = new Array(5);
					row[row_i]["indx"] = i;
					row_i++;
				}else{
					//the row is full
					extraW = Math.ceil((rowWidth - partialRowWidth + 1) / row.length);
					$(cont).append(buildContRow(row, images, extraW, settings));

					row = new Array();
					row[0] = new Array(5);
					row[0]["indx"] = i;
					row_i = 1;
					partialRowWidth = images[i]["width"] + settings.margins;
				}
			}

			//last row----------------------
			//now we have all the images index loaded in the row arra
			if(settings.justifyLastRow){
				extraW = Math.ceil((rowWidth - partialRowWidth + 1) / row.length);
			}else{
				extraW = 0;
			}
			$(cont).append(buildContRow(row, images, extraW, settings));
			//---------------------------

			//lightbox-------------------
			if(settings.lightbox){
				try{
					$(cont).find(".jg-image a").colorbox({maxWidth:"80%",maxHeight:"80%",opacity:0.8,transition:"elastic", current:""});
				}catch(e){
					$(cont).html(getErrorHtml("No Colorbox founded!", "jg-noColorbox"));
				}
			}

			//Captions---------------------
			if(settings.captions){
				$(cont).find(".jg-image").mouseenter(function(sender){
					$(sender.currentTarget).find(".jg-image-label").stop();
					$(sender.currentTarget).find(".jg-image-label").fadeTo(500, 0.7);
				});
				$(cont).find(".jg-image").mouseleave(function(sender){
					$(sender.currentTarget).find(".jg-image-label").stop();
					$(sender.currentTarget).find(".jg-image-label").fadeTo(500, 0);
				});
			}

			$(cont).find(".jg-resizedImageNotFound").remove();

			//fade in the images that we have changed and need to be reloaded
			$(cont).find(".jg-image img").load(function(){
					$(this).fadeTo(500, 1);
			}).error(function(){
				$(cont).prepend(getErrorHtml("The image can't be loaded: \"" +  $(this).attr("src") +"\"", "jg-resizedImageNotFound"));
			}).each(function(){
					if(this.complete) $(this).load();
			});

			checkWidth($, cont, images, rowWidth, settings);

		}

		function checkWidth($, cont, images, lastRowWidth, settings){
			var id = setInterval(function(){

				if(lastRowWidth != $(cont).width()){
					$(cont).find(".jg-row").remove();
					clearInterval(id);
					processesImages($, cont, images, lastRowWidth, settings);
					return;
				}
			}, settings.refreshTime);
		}

   }

})(jQuery);


text:
package jokrey.utilities.encoder.tag_based.tests;

import jokrey.utilities.encoder.tag_based.additional.functionality.wrapper.delegation.compression.deflate.DeflateAlgorithmHelper;
import jokrey.utilities.encoder.tag_based.additional.functionality.wrapper.delegation.compression.deflate.DeflateContentCompressingBytesEncoder;
import jokrey.utilities.encoder.tag_based.implementation.length_indicator.bytes.LITagBytesEncoder;
import org.junit.Test;

import java.security.SecureRandom;
import java.util.Arrays;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * Test for the EncryptingBytesEncoder
 *
 * @author jokrey
 */
public class DeflateCompressingBytesEncoderTest {
    @Test
    public void simple_comparing_tag_system_test() {
        LITagBytesEncoder raw_encoder = new LITagBytesEncoder();
        DeflateContentCompressingBytesEncoder content_compressing_encoder = new DeflateContentCompressingBytesEncoder(new LITagBytesEncoder());

        TagSystemTestHelper.enter_values(raw_encoder);
        TagSystemTestHelper.enter_values(content_compressing_encoder);

        //what follows is the worst possible way to check whether or not it has been properly encrypted:
        assertFalse(Arrays.equals(raw_encoder.getEncodedBytes(), content_compressing_encoder.getEncodedBytes()));
//        assertTrue(raw_encoder.getEncodedBytes().length > content_compressing_encoder.getEncodedBytes().length);  //CANNOT BE GENERALLY ASSERTED--- Compression will only work with some data.

        TagSystemTestHelper.do_tag_system_assertions_without_delete(raw_encoder);
        TagSystemTestHelper.do_tag_system_assertions_without_delete(content_compressing_encoder);

        TagSystemTestHelper.basic_typed_system_test(raw_encoder);
        TagSystemTestHelper.basic_typed_system_test(content_compressing_encoder);

        TagSystemTestHelper.do_tag_system_assertions_delete(raw_encoder);
        TagSystemTestHelper.do_tag_system_assertions_delete(content_compressing_encoder);

        TagSystemTestHelper.do_stream_test(raw_encoder);
        TagSystemTestHelper.do_stream_test(content_compressing_encoder);
    }

    //NOTE:: especially with random data compression is not generally possible.
    @Test
    public void simple_compression_test() {
        run_compression_test(new SecureRandom().generateSeed(100000), 9);
        byte[] test = new byte[10000];
        for(int i=0;i<test.length;i++)
            test[i] = (byte) (i%40);
        run_compression_test(test, 3);
        run_compression_test(test, 9);
    }
    private void run_compression_test(byte[] orig, int level) {
        byte[] compressed = DeflateAlgorithmHelper.compress(orig, level);
        byte[] decompressed = DeflateAlgorithmHelper.decompress(compressed);

        assertArrayEquals(orig, decompressed);

        System.out.println("compressed length ratio: "+((double) compressed.length) / orig.length);
    }
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace Microsoft.Azure.WebJobs.Host
{
    /// Defines an activator that creates an instance of a job type.
    public interface IJobActivator
    {
        /// Creates a new instance of a job type.
        /// <typeparam name="T">The job type.</typeparam>
        /// <returns>A new instance of the job type.</returns>
        T CreateInstance<T>();
    }
}


text:
from __future__ import absolute_import

from .production import *

########## STATIC FILES CONFIGURATION
# See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html
AWS_STORAGE_BUCKET_NAME = 'inonemonth'

# See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html
STATIC_URL = 'https://s3-eu-west-1.amazonaws.com/{0}/'.format(
    AWS_STORAGE_BUCKET_NAME)

# See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

# See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html
AWS_ACCESS_KEY_ID = get_env_setting('AWS_ACCESS_KEY_ID')

# See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html
AWS_SECRET_ACCESS_KEY = get_env_setting('AWS_SECRET_ACCESS_KEY')

# See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html
STATICFILES_STORAGE = DEFAULT_FILE_STORAGE
########## END STATIC FILES CONFIGURATION

########## ALLAUTH CONFIGURATION
# See: http://django-allauth.readthedocs.org/en/latest/#github
ALLAUTH_SOCIAL_APP_GITHUB_ID = "189e9b562c8b67cb17bb"
########## END ALLAUTH CONFIGURATION


text:
package rlbot.vec;

import com.google.flatbuffers.FlatBufferBuilder;

public class Vector3 extends rlbot.vector.Vector3 {

    public Vector3(float x, float y, float z) {
        super(x, y, z);
    }

    public Vector3(double x, double y, double z) {
        super((float) x, (float) y, (float) z);
    }

    public int toFlatbuffer(FlatBufferBuilder builder) {
        return rlbot.flat.Vector3.createVector3(builder, -x, y, z);
    }

    public static Vector3 fromFlatbuffer(rlbot.flat.Vector3 vec) {
        // Invert the X value so that the axes make more sense.
        return new Vector3(-vec.x(), vec.y(), vec.z());
    }

    public Vector3() {
        this(0, 0, 0);
    }

    public Vector3 plus(Vector3 other) {
        return new Vector3(x + other.x, y + other.y, z + other.z);
    }

    public Vector3 minus(Vector3 other) {
        return new Vector3(x - other.x, y - other.y, z - other.z);
    }

    public Vector3 scaled(float scale) {
        return new Vector3(x * scale, y * scale, z * scale);
    }

    /**
     * If magnitude is negative, we will return a vector facing the opposite direction.
     */
    public Vector3 scaledToMagnitude(float magnitude) {
        if (isZero()) {
            throw new IllegalStateException("Cannot scale up a vector with length zero!");
        }
        float scaleRequired = magnitude / magnitude();
        return scaled(scaleRequired);
    }

    public double distance(Vector3 other) {
        double xDiff = x - other.x;
        double yDiff = y - other.y;
        double zDiff = z - other.z;
        return Math.sqrt(xDiff * xDiff + yDiff * yDiff + zDiff * zDiff);
    }

    public float magnitude() {
        return (float) Math.sqrt(magnitudeSquared());
    }

    public float magnitudeSquared() {
        return x * x + y * y + z * z;
    }

    public Vector3 normalized() {

        if (isZero()) {
            throw new IllegalStateException("Cannot normalize a vector with length zero!");
        }
        return this.scaled(1 / magnitude());
    }

    public double dotProduct(Vector3 other) {
        return x * other.x + y * other.y + z * other.z;
    }

    public boolean isZero() {
        return x == 0 && y == 0 && z == 0;
    }

    public Vector2 flatten() {
        return new Vector2(x, y);
    }

    public float angle(Vector3 v) {
        double mag2 = magnitudeSquared();
        double vmag2 = v.magnitudeSquared();
        double dot = dotProduct(v);
        return (float) Math.acos(dot / Math.sqrt(mag2 * vmag2));
    }

    public Vector3 crossProduct(Vector3 v) {
        float tx = y * v.z - z * v.y;
        float ty = z * v.x - x * v.z;
        float tz = x * v.y - y * v.x;
        return new Vector3(tx, ty, tz);
    }
}


text: module.exports=["a","abbr","acronym","b","br","code","em","font","i","img","ins","kbd","map","samp","small","span","strong","sub","sup"];


text:
<?php
/**
 * Plugin Name: Custom admin notices
 * Version: 0.4.2-beta
 * Description: This plugin allows you to create your own notices that show up in the WordPress admin.
 * Author: Christian Nikkanen
 * Author URI: https://github.com/k1sul1/
 * Text Domain: custom-admin-notices
 * @package Custom admin notices
 */

namespace k1sul1\custom_admin_notices;

// Value for get_option (database name)
const SETTING_NAME = "can_settings";

// Settings page slug
const PAGE_NAME = "can-settings";

// Settings page title
const PAGE_TITLE = "Custom admin notices settings";

// Settings page description
const PAGE_DESCRIPTION = "Settings for custom admin notices";

// Menu title (in plugins menu)
const MENU_TITLE = "Custom admin notices";

// Helper for absolute path references
const HOME_DIR = __DIR__;

// Helpers for use get_plugin_data
const BASE_NAME = __FILE__;

// Capability required for managing settings
const REQUIRE_CAPS = "manage_options";

// Include settings and actions
require HOME_DIR . DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . "class.custom-admin-notices.php";
require HOME_DIR . DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . "settings.php";
require HOME_DIR . DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . "admin-actions.php";
require HOME_DIR . DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . "actions.php";


text:
<@override name="admin-content">

		新增用户

		<form action="save" method="POST" id="user_info_form">
			<input type="hidden" value="${user_token}" name="userToken"
				id="user_token">

				用户邮箱 <input type="email"
					class="form-control" id="email" name="email" placeholder="邮箱">

				用户名 <input type="text"
					class="form-control" id="userName" name="userName"
					placeholder="用户名">

				密码 <input type="password"
					class="form-control" id="password" name="password" placeholder="密码">

				 头像 <input type="file"
					id="fileupload" name="files"> <input type="hidden"
					name="icon" id="icon">

上传头像.

					${error_msg}

			<button type="button" id="submit_but" class="btn btn-default">新增</button>
		</form>

</@override> <@override name="script_ext_page_end">

</@override> <@extends name="/admin/master-admin.html"/>


text:
Robot proximity sensor
======================

This sensor can be used to determine which other objects are within a
certain radius of the sensor. It performs its test based only on distance.
The type of tracked objects can be specified using the 'Track' property.

Files
-----

- Blender: ``$MORSE_ROOT/data/sensors/proximity.blend``
- Python: ``$MORSE_ROOT/src/morse/sensors/proximity.py``

Local data
----------

- **near_objects**: (Dictionary) A list of the tracked objects located within the given radius.
  The keys of the dictionary are the object names, and the values are the distances
  (in meters) from the sensor.
- **near_robots**: deprecated. Points to near_objects for compatibility sake.

Configurable parameters
-----------------------

The Empty object corresponding to this sensor has the following parameters:

- **Track**: (String) The type of tracked objects. This type is looked for as a
  game property of scene objects. You must then add a new game property to the objects
  you want to be detected by the proximity sensor. Default is "Robot_Tag".
- **Range**: (Float) The distance, in meters beyond which this sensor is
  unable to locate other robots.

Services
--------

- **set_range**: (synchronous) the method expects a float **range**, and
  modify the range used to detect objects around the proximity sensor
- **set_tracked_tag**: (synchronous) the method allows to modify the kind of
  objects detected by the proximity sensor.

Applicable modifiers
--------------------

No proximity modifiers available at the moment


text:
@implementation OSCTopicEntity

///////////////////////////////////////////////////////////////////////////////////////////////////
- (id)initWithDictionary:(NSDictionary*)dic
{
    if (!dic || ![dic isKindOfClass:[NSDictionary class]]) {
        return nil;
    }

    self = [super initWithDictionary:dic];
    if (self) {
        self.repliesCount = [dic[@"answerCount"] longLongValue];
        // TODO: last replier info
    }

    return self;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
+ (id)entityWithDictionary:(NSDictionary*)dic
{
    if (!dic || ![dic isKindOfClass:[NSDictionary class]]) {
        return nil;
    }

    OSCTopicEntity* entity = [[OSCTopicEntity alloc] initWithDictionary:dic];
    return entity;
}

@end


text:
title: Special Formatting Methods
localeTitle: Métodos especiales de formateo
---
## Métodos especiales de formateo

Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md) .

[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Más información:


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="top.ftas.dunit.sample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="false"
        android:theme="@style/AppTheme">
        <activity android:name=".activity.HelloActivity" />
        <activity android:name=".activity.HelloSupportActivity" />

    </application>

</manifest>


text:
require "./test/test_helper_with_wrong"
require "./test/canonical_transform_cases"

require "predicated/from/xml"
include Predicated

regarding "convert an xml string to a predicate" do
  include CanonicalTransformCases

  @expectations = {
    "simple operations" => {
      "eq" => Predicate.from_xml("<equal><left>a</left><right>3</right></equal>"),
      "gt" => Predicate.from_xml("<greaterThan><left>a</left><right>3</right></greaterThan>"),
      "lt" => Predicate.from_xml("<lessThan><left>a</left><right>3</right></lessThan>"),
      "gte" =>
        Predicate.from_xml("<greaterThanOrEqualTo><left>a</left><right>3</right></greaterThanOrEqualTo>"),
      "lte" =>
        Predicate.from_xml("<lessThanOrEqualTo><left>a</left><right>3</right></lessThanOrEqualTo>")
    },
    "primitive types" => {
      "false" => Predicate.from_xml("<equal><left>a</left><right>false</right></equal>"),
      "true" => Predicate.from_xml("<equal><left>a</left><right>true</right></equal>"),
      "string" => Predicate.from_xml("<equal><left>a</left><right>yyy</right></equal>"),
    },
    "not" => {
      "simple" => Predicate.from_xml("<not><equal><left>a</left><right>true</right></equal></not>")
    },
    "simple and / or" => {
      #parens are necessary around AND's in solr in order to force precedence
      "and" => Predicate.from_xml(%{
        <and>
          <equal><left>a</left><right>1</right></equal>
          <equal><left>b</left><right>2</right></equal>
        </and>
      }),
      "or" => Predicate.from_xml(%{
        <or>
          <equal><left>a</left><right>1</right></equal>
          <equal><left>b</left><right>2</right></equal>
        </or>
      })
    },
    "complex and / or" => {
      "or and" => Predicate.from_xml(%{
        <or>
          <and>
            <equal><left>a</left><right>1</right></equal>
            <equal><left>b</left><right>2</right></equal>
          </and>
          <equal><left>c</left><right>3</right></equal>
        </or>
      })
    }
  }

  create_canonical_tests(@expectations, proper_typing=false)
end


text:
<?php

namespace Tobion\Retry;

use Doctrine\DBAL\Exception\RetryableException;

/**
 * Simple retry entry point providing shortcuts.
 *
 * @author Tobias Schultze <http://tobion.de>
 */
final class Retry
{
    /**
     * Returns a builder to configure custom retry logic.
     */
    public static function configure(): RetryConfigurator
    {
        return new RetryConfigurator();
    }

    /**
     * Executes the passed callable and its arguments with the a preconfigured retry behavior suitable for Doctrine database transactions.
     *
     * @return mixed The return value of the passed callable
     */
    public static function onDoctrineExceptionWith2Retries300MsDelay(callable $callable, ...$arguments)
    {
        return self::configure()
            ->maxRetries(2)
            ->delayInMs(300)
            ->retryOnSpecificExceptions(RetryableException::class)
            ->call($callable, ...$arguments);
    }

    /**
     * This class cannot be instantiated.
     */
    private function __construct()
    {
    }
}


text:
from __future__ import absolute_import

import numpy as nm

from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr,\
    assert_
from sfepy.base.timing import Timer
import six
from sfepy.mechanics.tensors import get_cauchy_strain

def parse_approx_order(approx_order):
    """
    Parse the uniform approximation order value (str or int).
    """
    ao_msg = 'unsupported approximation order! (%s)'
    force_bubble = False
    discontinuous = False

    if approx_order is None:
        return 'iga', force_bubble, discontinuous

    elif isinstance(approx_order, basestr):
        if approx_order.startswith('iga'):
            return approx_order, force_bubble, discontinuous

    try:
        ao = int(approx_order)
    except ValueError:
        mode = approx_order[-1].lower()

        if mode == 'b':
            ao = int(approx_order[:-1])
            force_bubble = True

        elif mode == 'd':
            ao = int(approx_order[:-1])
            discontinuous = True

        else:
            raise ValueError(ao_msg % approx_order)

    if ao < 0:
        raise ValueError(ao_msg % approx_order)

    elif ao == 0:
        discontinuous = True

    return ao, force_bubble, discontinuous

def parse_shape(shape, dim):
    if isinstance(shape, basestr):
        try:
            shape = {'scalar' : (1,),
                     'vector' : (dim,)}[shape]
        except KeyError:
            raise ValueError('unsupported field shape! (%s)', shape)

    elif isinstance(shape, six.integer_types):
        shape = (int(shape),)

    return shape

def setup_extra_data(conn_info):
    """
    Setup extra data required for non-volume integration.
    """
    for key, ii, info in iter_dict_of_lists(conn_info, return_keys=True):
        for var in info.all_vars:
            field = var.get_field()
            if var == info.primary:
                field.setup_extra_data(info.ps_tg, info, info.is_trace)

def fields_from_conf(conf, regions):
    fields = {}
    for key, val in six.iteritems(conf):
        field = Field.from_conf(val, regions)
        fields[field.name] = field

    return fields

class Field(Struct):
    """
    Base class for fields.
    """
    _all = None

    @staticmethod
    def from_args(name, dtype, shape, region, approx_order=1,
                  space='H1', poly_space_base='lagrange'):
        """
        Create a Field subclass instance corresponding to a given space.

        Parameters
        ----------
        name : str
            The field name.
        dtype : numpy.dtype
            The field data type: float64 or complex128.
        shape : int/tuple/str
            The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,)
            or 3 or (3,)) or 'vector', or a tuple. The field shape determines
            the shape of the FE base functions and is related to the number of
            components of variables and to the DOF per node count, depending
            on the field kind.
        region : Region
            The region where the field is defined.
        approx_order : int/str
            The FE approximation order, e.g. 0, 1, 2, '1B' (1 with bubble).
        space : str
            The function space name.
        poly_space_base : str
            The name of polynomial space base.

        Notes
        -----
        Assumes one cell type for the whole region!
        """
        conf = Struct(name=name, dtype=dtype, shape=shape, region=region.name,
                      approx_order=approx_order, space=space,
                      poly_space_base=poly_space_base)
        return Field.from_conf(conf, {region.name : region})

    @staticmethod
    def from_conf(conf, regions):
        """
        Create a Field subclass instance based on the configuration.
        """
        if Field._all is None:
            from sfepy import get_paths
            from sfepy.base.base import load_classes

            field_files = [ii for ii
                           in get_paths('sfepy/discrete/fem/fields*.py')
                           if 'fields_base.py' not in ii]
            field_files += get_paths('sfepy/discrete/iga/fields*.py')
            field_files += get_paths('sfepy/discrete/structural/fields*.py')
            field_files += get_paths('sfepy/discrete/dg/fields.py')
            Field._all = load_classes(field_files, [Field], ignore_errors=True,
                                      name_attr='family_name')
        table = Field._all

        space = conf.get('space', 'H1')
        poly_space_base = conf.get('poly_space_base', 'lagrange')

        key = space + '_' + poly_space_base

        approx_order = parse_approx_order(conf.approx_order)
        ao, force_bubble, discontinuous = approx_order
        region = regions[conf.region]

        if region.kind == 'cell':
            # Volume fields.
            kind = 'volume'

            if discontinuous:
                cls = table[kind + '_' + key + '_discontinuous']

            else:
                cls = table[kind + '_' + key]

            obj = cls(conf.name, conf.dtype, conf.shape, region,
                      approx_order=approx_order[:2])

        else:
            # Surface fields.
            kind = 'surface'

            cls = table[kind + '_' + key]
            obj = cls(conf.name, conf.dtype, conf.shape, region,
                      approx_order=approx_order[:2])

        return obj

    def _setup_kind(self):
        name = self.get('family_name', None,
                        'An abstract Field method called!')
        aux = name.split('_')
        self.space = aux[1]
        self.poly_space_base = aux[2]

    def clear_mappings(self, clear_all=False):
        """
        Clear current reference mappings.
        """
        self.mappings = {}
        if clear_all:
            if hasattr(self, 'mappings0'):
                self.mappings0.clear()
            else:
                self.mappings0 = {}

    def save_mappings(self):
        """
        Save current reference mappings to `mappings0` attribute.
        """
        import sfepy.base.multiproc as multi

        if multi.is_remote_dict(self.mappings0):
            for k, v in six.iteritems(self.mappings):
                m, _ = self.mappings[k]
                nv = (m.bf, m.bfg, m.det, m.volume, m.normal)
                self.mappings0[k] = nv
        else:
            self.mappings0 = self.mappings.copy()

    def get_mapping(self, region, integral, integration,
                    get_saved=False, return_key=False):
        """
        For given region, integral and integration type, get a reference
        mapping, i.e. jacobians, element volumes and base function
        derivatives for Volume-type geometries, and jacobians, normals
        and base function derivatives for Surface-type geometries
        corresponding to the field approximation.

        The mappings are cached in the field instance in `mappings`
        attribute. The mappings can be saved to `mappings0` using
        `Field.save_mappings`. The saved mapping can be retrieved by
        passing `get_saved=True`. If the required (saved) mapping
        is not in cache, a new one is created.

        Returns
        -------
        geo : CMapping instance
            The reference mapping.
        mapping : VolumeMapping or SurfaceMapping instance
            The mapping.
        key : tuple
            The key of the mapping in `mappings` or `mappings0`.
        """
        import sfepy.base.multiproc as multi

        key = (region.name, integral.order, integration)

        if get_saved:
            out = self.mappings0.get(key, None)
            if multi.is_remote_dict(self.mappings0) and out is not None:
                m, i = self.create_mapping(region, integral, integration)
                m.bf[:], m.bfg[:], m.det[:], m.volume[:] = out[0:4]
                if m.normal is not None:
                    m.normal[:] = m[4]
                out = m, i
        else:
            out = self.mappings.get(key, None)

        if out is None:
            out = self.create_mapping(region, integral, integration)
            self.mappings[key] = out

        if return_key:
            out = out + (key,)

        return out

    def set_dofs(self, fun=0.0, region=None, dpn=None, warn=None):
        """
        Set the values of DOFs in a given `region` using a function of space
        coordinates or value `fun`.

        If `fun` is a function, the l2 projection that is global for all region
        facets is used to set the DOFs.

        If `dpn > 1`, and `fun` is a function, it has to return the values
        point-by-point, i.e. all components in the first point, in the second
        point etc., concatenated to an array that is reshapable to the shape
        `(n_point, dpn)`.

        Parameters
        ----------
        fun : float or array of length dpn or callable
            The DOF values.
        region : Region
            The region containing the DOFs.
        dpn : int, optional
            The DOF-per-node count. If not given, the number of field
            components is used.
        warn : str, optional
            The warning message printed when the region selects no DOFs.

        Returns
        -------
        nods : array, shape (n_dof,)
            The field DOFs (or node indices) given by the region.
        vals : array, shape (n_dof, dpn)
            The values of the DOFs, node-by-node when raveled in C (row-major)
            order.

        Notes
        -----
        The nodal basis fields (lagrange) reimplement this function to set DOFs
        directly.

        The hierarchical basis field (lobatto) do not support surface mappings,
        so also reimplement this function.
        """
        if region is None:
            region = self.region

        if dpn is None:
            dpn = self.n_components

        aux = self.get_dofs_in_region(region)
        nods = nm.unique(aux)

        if nm.isscalar(fun):
            vals = nm.repeat([fun], nods.shape[0] * dpn)

        elif isinstance(fun, nm.ndarray):
            try:
                assert_(len(fun) == dpn)

            except (TypeError, ValueError):
                msg = ('wrong array value shape for setting'
                       ' DOFs of "%s" field!'
                       ' (shape %s should be %s)'
                       % (self.name, fun.shape, (dpn,)))
                raise ValueError(msg)

            vals = nm.repeat(fun, nods.shape[0])

        elif callable(fun):
            from sfepy.discrete.projections import project_to_facets

            vals = project_to_facets(region, fun, dpn, self)

        else:
            raise ValueError('unknown function/value type! (%s)' % type(fun))

        vals.shape = (len(nods), -1)

        return nods, vals

    def create_eval_mesh(self):
        """
        Create a mesh for evaluating the field. The default implementation
        returns None, because this mesh is for most fields the same as the one
        created by `Field.create_mesh()`.
        """

    def evaluate_at(self, coors, source_vals, mode='val', strategy='general',
                    close_limit=0.1, get_cells_fun=None, cache=None,
                    ret_cells=False, ret_status=False, ret_ref_coors=False,
                    verbose=False):
        """
        Evaluate source DOF values corresponding to the field in the given
        coordinates using the field interpolation.

        Parameters
        ----------
        coors : array, shape ``(n_coor, dim)``
            The coordinates the source values should be interpolated into.
        source_vals : array, shape ``(n_nod, n_components)``
            The source DOF values corresponding to the field.
        mode : {'val', 'grad', 'div', 'cauchy_strain'}, optional
            The evaluation mode: the field value (default), the field value
            gradient, divergence, or cauchy strain.
        strategy : {'general', 'convex'}, optional
            The strategy for finding the elements that contain the
            coordinates. For convex meshes, the 'convex' strategy might be
            faster than the 'general' one.
        close_limit : float, optional
            The maximum limit distance of a point from the closest
            element allowed for extrapolation.
        get_cells_fun : callable, optional
            If given, a function with signature ``get_cells_fun(coors, cmesh,
            **kwargs)`` returning cells and offsets that potentially contain
            points with the coordinates `coors`. Applicable only when
            `strategy` is 'general'. When not given,
            :func:`get_potential_cells()
            <sfepy.discrete.common.global_interp.get_potential_cells>` is used.
        cache : Struct, optional
            To speed up a sequence of evaluations, the field mesh and other
            data can be cached. Optionally, the cache can also contain the
            reference element coordinates as `cache.ref_coors`, `cache.cells`
            and `cache.status`, if the evaluation occurs in the same
            coordinates repeatedly. In that case the mesh related data are
            ignored. See :func:`Field.get_evaluate_cache()
            <sfepy.discrete.fem.fields_base.FEField.get_evaluate_cache()>`.
        ret_ref_coors : bool, optional
            If True, return also the found reference element coordinates.
        ret_status : bool, optional
            If True, return also the enclosing cell status for each point.
        ret_cells : bool, optional
            If True, return also the cell indices the coordinates are in.
        verbose : bool
            If False, reduce verbosity.

        Returns
        -------
        vals : array
            The interpolated values with shape ``(n_coor, n_components)`` or
            gradients with shape ``(n_coor, n_components, dim)`` according to
            the `mode`. If `ret_status` is False, the values where the status
            is greater than one are set to ``numpy.nan``.
        ref_coors : array
            The found reference element coordinates, if `ret_ref_coors` is True.
        cells : array
            The cell indices, if `ret_ref_coors` or `ret_cells` or `ret_status`
            are True.
        status : array
            The status, if `ret_ref_coors` or `ret_status` are True, with the
            following meaning: 0 is success, 1 is extrapolation within
            `close_limit`, 2 is extrapolation outside `close_limit`, 3 is
            failure, 4 is failure due to non-convergence of the Newton
            iteration in tensor product cells. If close_limit is 0, then for
            the 'general' strategy the status 5 indicates points outside of the
            field domain that had no potential cells.
        """
        from sfepy.discrete.common.global_interp import get_ref_coors
        from sfepy.discrete.common.extmods.crefcoors import evaluate_in_rc
        from sfepy.base.base import complex_types

        output('evaluating in %d points...' % coors.shape[0], verbose=verbose)

        ref_coors, cells, status = get_ref_coors(self, coors,
                                                 strategy=strategy,
                                                 close_limit=close_limit,
                                                 get_cells_fun=get_cells_fun,
                                                 cache=cache,
                                                 verbose=verbose)

        timer = Timer(start=True)

        n_comp, nc, dim = source_vals.shape[1], coors.shape[0], coors.shape[1]
        # Interpolate to the reference coordinates.
        source_dtype = nm.float64 if source_vals.dtype in complex_types\
            else source_vals.dtype
        if mode == 'val':
            vals = nm.empty((nc, n_comp, 1), dtype=source_dtype)
            cmode = 0

        elif mode in ['grad', 'div', 'cauchy_strain']:
            vals = nm.empty((nc, n_comp, dim), dtype=source_dtype)
            cmode = 1

        ctx = self.create_basis_context()

        if source_vals.dtype in complex_types:
            valsi = vals.copy()
            evaluate_in_rc(vals, ref_coors, cells, status,
                           nm.ascontiguousarray(source_vals.real),
                           self.get_econn('volume', self.region), cmode, ctx)
            evaluate_in_rc(valsi, ref_coors, cells, status,
                           nm.ascontiguousarray(source_vals.imag),
                           self.get_econn('volume', self.region), cmode, ctx)
            vals = vals + valsi * 1j
        else:
            evaluate_in_rc(vals, ref_coors, cells, status, source_vals,
                           self.get_econn('volume', self.region), cmode, ctx)

        output('interpolation: %f s' % timer.stop(),verbose=verbose)

        output('...done',verbose=verbose)

        if mode == 'val':
            vals.shape = (nc, n_comp)

        elif mode == 'div':
            assert_(n_comp == dim)
            vals = nm.trace(vals, axis1=1, axis2=2).reshape(nc, 1, 1)

        elif mode == 'cauchy_strain':
            assert_(n_comp == dim)
            vals = get_cauchy_strain(vals)

        if not ret_status:
            ii = nm.where(status > 1)[0]
            vals[ii] = nm.nan

        if ret_ref_coors:
            return vals, ref_coors, cells, status

        elif ret_status:
            return vals, cells, status

        elif ret_cells:
            return vals, cells

        else:
            return vals


text:
"""Test utilities for tf.data benchmarking functionality."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import time

import numpy as np

from tensorflow.python.client import session
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.util import nest
from tensorflow.python.eager import context
from tensorflow.python.platform import test

class DatasetBenchmarkBase(test.Benchmark):
  """Base class for dataset benchmarks."""

  def _run_eager_benchmark(self, iterable, iters, warmup):
    """Benchmark the iterable in eager mode.

    Runs the iterable `iters` times. In each iteration, the benchmark measures
    the time it takes to go execute the iterable.

    Args:
      iterable: The tf op or tf.data Dataset to benchmark.
      iters: Number of times to repeat the timing.
      warmup: If true, warms up the session caches by running an untimed run.

    Returns:
      A float, representing the median time (with respect to `iters`)
      it takes for the iterable to be executed `iters` num of times.

    Raises:
      RuntimeError: When executed in graph mode.
    """

    deltas = []
    if not context.executing_eagerly():
      raise RuntimeError(
          "Eager mode benchmarking is not supported in graph mode.")

    for _ in range(iters):
      if warmup:
        iterator = iter(iterable)
        next(iterator)

      iterator = iter(iterable)
      start = time.time()
      next(iterator)
      end = time.time()
      deltas.append(end - start)
    return np.median(deltas)

  def _run_graph_benchmark(self,
                           iterable,
                           iters,
                           warmup,
                           session_config,
                           initializer=None):
    """Benchmarks the iterable in graph mode.

    Runs the iterable `iters` times. In each iteration, the benchmark measures
    the time it takes to go execute the iterable.

    Args:
      iterable: The tf op or tf.data Dataset to benchmark.
      iters: Number of times to repeat the timing.
      warmup: If true, warms up the session caches by running an untimed run.
      session_config: A ConfigProto protocol buffer with configuration options
        for the session. Applicable only for benchmarking in graph mode.
      initializer: The initializer op required to initialize the iterable.

    Returns:
      A float, representing the median time (with respect to `iters`)
      it takes for the iterable to be executed `iters` num of times.

    Raises:
      RuntimeError: When executed in eager mode.
    """

    deltas = []
    if context.executing_eagerly():
      raise RuntimeError(
          "Graph mode benchmarking is not supported in eager mode.")

    for _ in range(iters):
      with session.Session(config=session_config) as sess:
        if warmup:
          # Run once to warm up the session caches.
          if initializer:
            sess.run(initializer)
          sess.run(iterable)

        if initializer:
          sess.run(initializer)
        start = time.time()
        sess.run(iterable)
        end = time.time()
      deltas.append(end - start)
    return np.median(deltas)

  def run_op_benchmark(self, op, iters=1, warmup=True, session_config=None):
    """Benchmarks the op.

    Runs the op `iters` times. In each iteration, the benchmark measures
    the time it takes to go execute the op.

    Args:
      op: The tf op to benchmark.
      iters: Number of times to repeat the timing.
      warmup: If true, warms up the session caches by running an untimed run.
      session_config: A ConfigProto protocol buffer with configuration options
        for the session. Applicable only for benchmarking in graph mode.

    Returns:
      A float, representing the per-execution wall time of the op in seconds.
      This is the median time (with respect to `iters`) it takes for the op
      to be executed `iters` num of times.
    """

    if context.executing_eagerly():
      return self._run_eager_benchmark(iterable=op, iters=iters, warmup=warmup)

    return self._run_graph_benchmark(
        iterable=op, iters=iters, warmup=warmup, session_config=session_config)

  def run_benchmark(self,
                    dataset,
                    num_elements,
                    iters=1,
                    warmup=True,
                    apply_default_optimizations=False,
                    session_config=None):
    """Benchmarks the dataset.

    Runs the dataset `iters` times. In each iteration, the benchmark measures
    the time it takes to go through `num_elements` elements of the dataset.

    Args:
      dataset: Dataset to benchmark.
      num_elements: Number of dataset elements to iterate through each benchmark
        iteration.
      iters: Number of times to repeat the timing.
      warmup: If true, warms up the session caches by running an untimed run.
      apply_default_optimizations: Determines whether default optimizations
        should be applied.
      session_config: A ConfigProto protocol buffer with configuration options
        for the session. Applicable only for benchmarking in graph mode.

    Returns:
      A float, representing the per-element wall time of the dataset in seconds.
      This is the median time (with respect to `iters`) it takes for the dataset
      to go through `num_elements` elements, divided by `num_elements.`
    """

    # The options that have been applied to the dataset are preserved so that
    # they are not overwritten while benchmarking.
    options = dataset_ops.Options()
    options.experimental_optimization.apply_default_optimizations = (
        apply_default_optimizations)
    dataset = dataset.with_options(options)

    # NOTE: We use `dataset.skip()` to perform the iterations in C++, avoiding
    # the overhead of having to execute a TensorFlow op for each step of the
    # input pipeline. Note that this relies on the underlying implementation of
    # `skip` to execute upstream computation. If it is optimized in the future,
    # we will have to change this code.
    dataset = dataset.skip(num_elements - 1)

    if context.executing_eagerly():
      median_duration = self._run_eager_benchmark(
          iterable=dataset, iters=iters, warmup=warmup)
      return median_duration / float(num_elements)

    iterator = dataset_ops.make_initializable_iterator(dataset)
    next_element = iterator.get_next()
    op = nest.flatten(next_element)[0].op
    median_duration = self._run_graph_benchmark(
        iterable=op,
        iters=iters,
        warmup=warmup,
        session_config=session_config,
        initializer=iterator.initializer)
    return median_duration / float(num_elements)

  def run_and_report_benchmark(self,
                               dataset,
                               num_elements,
                               name,
                               iters=5,
                               extras=None,
                               warmup=True,
                               apply_default_optimizations=False,
                               session_config=None):
    """Benchmarks the dataset and reports the stats.

    Runs the dataset `iters` times. In each iteration, the benchmark measures
    the time it takes to go through `num_elements` elements of the dataset.
    This is followed by logging/printing the benchmark stats.

    Args:
      dataset: Dataset to benchmark.
      num_elements: Number of dataset elements to iterate through each benchmark
        iteration.
      name: Name of the benchmark.
      iters: Number of times to repeat the timing.
      extras: A dict which maps string keys to additional benchmark info.
      warmup: If true, warms up the session caches by running an untimed run.
      apply_default_optimizations: Determines whether default optimizations
        should be applied.
      session_config: A ConfigProto protocol buffer with configuration options
        for the session. Applicable only for benchmarking in graph mode.

    Returns:
      A float, representing the per-element wall time of the dataset in seconds.
      This is the median time (with respect to `iters`) it takes for the dataset
      to go through `num_elements` elements, divided by `num_elements.`
    """
    wall_time = self.run_benchmark(
        dataset=dataset,
        num_elements=num_elements,
        iters=iters,
        warmup=warmup,
        apply_default_optimizations=apply_default_optimizations,
        session_config=session_config)
    if extras is None:
      extras = {}
    if context.executing_eagerly():
      name = "{}.eager".format(name)
      extras["implementation"] = "eager"
    else:
      name = "{}.graph".format(name)
      extras["implementation"] = "graph"
    extras["num_elements"] = num_elements
    self.report_benchmark(
        wall_time=wall_time, iters=iters, name=name, extras=extras)
    return wall_time


text:
/* array.h - automatic dynamic array for pointers */

/*
 * Copyright (c) 2008, Natacha Porté
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#ifndef LITHIUM_ARRAY_H
#define LITHIUM_ARRAY_H

#include <stdlib.h>

/********************
 * TYPE DEFINITIONS *
 ********************/

/* struct array • generic linear array */
struct array {
	void*	base;
	int	size;
	int	asize;
	size_t	unit; };

/* struct parray • array of pointers */
struct parray {
	void **	item;
	int	size;
	int	asize; };

/* array_cmp_fn • comparison functions for sorted arrays */
typedef int (*array_cmp_fn)(void *key, void *array_entry);

/***************************
 * GENERIC ARRAY FUNCTIONS *
 ***************************/

/* arr_adjust • shrink the allocated memory to fit exactly the needs */
int
arr_adjust(struct array *);

/* arr_free • frees the structure contents (buf NOT the struct itself) */
void
arr_free(struct array *);

/* arr_grow • increases the array size to fit the given number of elements */
int
arr_grow(struct array *, int);

/* arr_init • initialization of the contents of the struct */
void
arr_init(struct array *, size_t);

/* arr_insert • inserting elements nb before the nth one */
int
arr_insert(struct array *, int nb, int n);

/* arr_item • returns a pointer to the n-th element */
void *
arr_item(struct array *, int);

/* arr_newitem • returns the index of a new element appended to the array */
int
arr_newitem(struct array *);

/* arr_remove • removes the n-th elements of the array */
void
arr_remove(struct array *, int);

/* arr_sorted_find • O(log n) search in a sorted array, returning entry */
/* equivalent to bsearch(key, arr->base, arr->size, arr->unit, cmp) */
void *
arr_sorted_find(struct array *, void *key, array_cmp_fn cmp);

/* arr_sorted_find_i • O(log n) search in a sorted array,
 *      returning index of the smallest element larger than the key */
int
arr_sorted_find_i(struct array *, void *key, array_cmp_fn cmp);

/***************************
 * POINTER ARRAY FUNCTIONS *
 ***************************/

/* parr_adjust • shrinks the allocated memory to fit exactly the needs */
int
parr_adjust(struct parray *);

/* parr_free • frees the structure contents (buf NOT the struct itself) */
void
parr_free(struct parray *);

/* parr_grow • increases the array size to fit the given number of elements */
int
parr_grow(struct parray *, int);

/* parr_init • initialization of the struct (which is equivalent to zero) */
void
parr_init(struct parray *);

/* parr_insert • inserting nb elements before the nth one */
int
parr_insert(struct parray *, int nb, int n);

/* parr_pop • pops the last item of the array and returns it */
void *
parr_pop(struct parray *);

/* parr_push • pushes a pointer at the end of the array (= append) */
int
parr_push(struct parray *, void *);

/* parr_remove • removes the n-th element of the array and returns it */
void *
parr_remove(struct parray *, int);

/* parr_sorted_find • O(log n) search in a sorted array, returning entry */
void *
parr_sorted_find(struct parray *, void *key, array_cmp_fn cmp);

/* parr_sorted_find_i • O(log n) search in a sorted array,
 *      returning index of the smallest element larger than the key */
int
parr_sorted_find_i(struct parray *, void *key, array_cmp_fn cmp);

/* parr_top • returns the top the stack (i.e. the last element of the array) */
void *
parr_top(struct parray *);

#endif /* ndef LITHIUM_ARRAY_H */

/* vim: set filetype=c: */


text:
<?php

namespace Yandex\Tests\Metrica;

use Yandex\Metrica\Management\Models;
use Yandex\Metrica\Management\AccountsClient;
use Yandex\Tests\TestCase;
use Yandex\Tests\Metrica\Fixtures\Accounts;
use GuzzleHttp\Psr7\Response;

class AccountsClientTest extends TestCase
{

    public function testGetAccounts()
    {
        $fixtures = Accounts::$accountsFixtures;

        $mock = $this->getMock('Yandex\Metrica\Management\AccountsClient', ['sendGetRequest']);
        $mock->expects($this->any())
            ->method('sendGetRequest')
            ->will($this->returnValue($fixtures));

        $table = $mock->getAccounts();

        $this->assertEquals($fixtures["accounts"][0]["user_login"], $table->current()->getUserLogin());
        $this->assertEquals($fixtures["accounts"][0]["created_at"], $table->current()->getCreatedAt());
    }

    public function testUpdateAccounts()
    {
        $fixtures             = Accounts::$accountsFixtures;
        $token                = 'test';
        $response             = new Response(200, [], \GuzzleHttp\Psr7\stream_for(json_encode($fixtures)));
        $guzzleHttpClientMock = $this->getMock('GuzzleHttp\Client', ['request']);
        $guzzleHttpClientMock->expects($this->any())
            ->method('request')
            ->will($this->returnValue($response));
        /** @var AccountsClient $accountsClientMock */
        $accountsClientMock = $this->getMock('Yandex\Metrica\Management\AccountsClient', ['getClient'], [$token]);
        $accountsClientMock->expects($this->any())
            ->method('getClient')
            ->will($this->returnValue($guzzleHttpClientMock));

        $accounts = new Models\Accounts();
        $accounts->fromArray($fixtures);
        $table = $accountsClientMock->updateAccounts($accounts);

        $this->assertEquals($fixtures["accounts"][0]["user_login"], $table->current()->getUserLogin());
        $this->assertEquals($fixtures["accounts"][0]["created_at"], $table->current()->getCreatedAt());
    }

    public function testDeleteAccounts()
    {
        $fixtures             = Accounts::$accountsFixtures;
        $token                = 'test';
        $response             = new Response(200, [], \GuzzleHttp\Psr7\stream_for(json_encode($fixtures)));
        $guzzleHttpClientMock = $this->getMock('GuzzleHttp\Client', ['request']);
        $guzzleHttpClientMock->expects($this->any())
            ->method('request')
            ->will($this->returnValue($response));
        /** @var AccountsClient $accountsClientMock */
        $accountsClientMock = $this->getMock('Yandex\Metrica\Management\AccountsClient', ['getClient'], [$token]);
        $accountsClientMock->expects($this->any())
            ->method('getClient')
            ->will($this->returnValue($guzzleHttpClientMock));

        $accounts = new Models\Accounts();
        $accounts->fromArray($fixtures);
        $result = $accountsClientMock->deleteAccount('test');
        $this->assertArrayHasKey('accounts', $result);
    }
}


text:
package io.zbus.rpc.biz.generic;

import io.zbus.rpc.annotation.RequestMapping;

@RequestMapping
public class GenericMethodImpl implements GenericMethod{

	@Override
	public <T> void test(T t) {
		System.out.println(t);
	}

}


text:
using namespace Microsoft::WindowsAPICodePack::DirectX::Direct3D10;

SamplerDescription SamplerState::Description::get()
{
    D3D10_SAMPLER_DESC tempoutDescription;
    CastInterface<ID3D10SamplerState>()->GetDesc(&tempoutDescription);

    return SamplerDescription(tempoutDescription);
}


text:
from bottle import route, run, template, request
import rrb3 as rrb
import time

# Change these for your setup.
IP_ADDRESS = '192.168.1.13' # of your Pi
BATTERY_VOLTS = 9
MOTOR_VOLTS = 6

# Configure the RRB
rr = rrb.RRB3(BATTERY_VOLTS, MOTOR_VOLTS)

# Handler for the home page
@route('/')
def index():
    cmd = request.GET.get('command', '')
    if cmd == 'f':
        rr.forward()
    elif cmd == 'l':
        rr.left(0, 0.5) # turn at half speed
    elif cmd == 's':
        rr.stop()
    elif cmd == 'r':
        rr.right(0, 0.5)
    elif cmd == 'b':
        rr.reverse(0, 0.3) # reverse slowly
    return template('home.tpl')

# Start the webserver running on port 80
try:
    run(host=IP_ADDRESS, port=80)
finally:
    rr.cleanup()


text:
import traceback
from core import debug
debug.warning("The use of core.modules.constant_configuration is deprecated.  "
              "Please use gui.modules.constant_configuration.",
              ''.join(traceback.format_stack()))

from gui.modules.constant_configuration import *


text:
var db = require("org/arangodb").db;
var internal = require("internal");
var jsunity = require("jsunity");

function runSetup () {
  internal.debugClearFailAt();

  db._drop("UnitTestsRecovery");
  var c = db._create("UnitTestsRecovery"), i;

  for (i = 0; i < 1000; ++i) {
    c.save({ _key: "test" + i, value1: "test" + i });
  }

  // make sure the next operations go into a separate log
  internal.wal.flush(true, true);

  db._drop("UnitTestsRecovery");
  c = db._create("UnitTestsRecovery");
  for (i = 0; i < 100; ++i) {
    c.save({ _key: "test" + i, value1: i });
  }

  c.save({ _key: "foo" }, true);

  internal.debugSegfault("crashing server");
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite
////////////////////////////////////////////////////////////////////////////////

function recoverySuite () {
  jsunity.jsUnity.attachAssertions();

  return {
    setUp: function () {
    },
    tearDown: function () {
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test whether we can restore the trx data
////////////////////////////////////////////////////////////////////////////////

    testCollectionRecreate : function () {
      var c = db._collection("UnitTestsRecovery"), i;
      assertEqual(101, c.count());

      for (i = 0; i < 100; ++i) {
        assertEqual(i, c.document("test" + i).value1);
      }
    }

  };
}

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suite
////////////////////////////////////////////////////////////////////////////////

function main (argv) {
  if (argv[1] === "setup") {
    runSetup();
    return 0;
  }
  else {
    jsunity.run(recoverySuite);
    return jsunity.done() ? 0 : 1;
  }
}


text:
import numpy as np
import matplotlib.pyplot as plt
import cv2

# https://gist.github.com/CannedYerins/11be0c50c4f78cad9549
def draw_matches(img1, kp1, img2, kp2, matches, color=None):
    """Draws lines between matching keypoints of two images.
    Keypoints not in a matching pair are not drawn.
    Places the images side by side in a new image and draws circles
    around each keypoint, with line segments connecting matching pairs.
    You can tweak the r, thickness, and figsize values as needed.
    Args:
        img1: An openCV image ndarray in a grayscale or color format.
        kp1: A list of cv2.KeyPoint objects for img1.
        img2: An openCV image ndarray of the same format and with the same
        element type as img1.
        kp2: A list of cv2.KeyPoint objects for img2.
        matches: A list of DMatch objects whose trainIdx attribute refers to
        img1 keypoints and whose queryIdx attribute refers to img2 keypoints.
        color: The color of the circles and connecting lines drawn on the images.
        A 3-tuple for color images, a scalar for grayscale images.  If None, these
        values are randomly generated.
    """
    # We're drawing them side by side.  Get dimensions accordingly.
    # Handle both color and grayscale images.
    if len(img1.shape) == 3:
        new_shape = (max(img1.shape[0], img2.shape[0]), img1.shape[1]+img2.shape[1], img1.shape[2])
    elif len(img1.shape) == 2:
        new_shape = (max(img1.shape[0], img2.shape[0]), img1.shape[1]+img2.shape[1])
    new_img = np.zeros(new_shape, type(img1.flat[0]))
    # Place images onto the new image.
    new_img[0:img1.shape[0],0:img1.shape[1]] = img1
    new_img[0:img2.shape[0],img1.shape[1]:img1.shape[1]+img2.shape[1]] = img2

    # Draw lines between matches.  Make sure to offset kp coords in second image appropriately.
    r = 15
    thickness = 2
    if color:
        c = color
    for m in matches:
        # Generate random color for RGB/BGR and grayscale images as needed.
        if not color:
            c = np.random.randint(0,256,3) if len(img1.shape) == 3 else np.random.randint(0,256)
        # So the keypoint locs are stored as a tuple of floats.  cv2.line(), like most other things,
        # wants locs as a tuple of ints.
        end1 = tuple(np.round(kp1[m.queryIdx].pt).astype(int))
        end2 = tuple(np.round(kp2[m.trainIdx].pt).astype(int) + np.array([img1.shape[1], 0]))
        cv2.line(new_img, end1, end2, c, thickness)
        cv2.circle(new_img, end1, r, c, thickness)
        cv2.circle(new_img, end2, r, c, thickness)

    plt.figure(figsize=(15,15))
    plt.imshow(new_img)
    plt.show()