text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IMessageHandlerProvider.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
//   Declares the IMessageHandlerProvider interface.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Messaging.HandlerProviders
{
    using System;
    using System.Collections.Generic;

    using Kephas.Composition;
    using Kephas.Messaging.Composition;
    using Kephas.Services;

    /// <summary>
    /// Interface for message handler provider.
    /// </summary>
    [SingletonAppServiceContract(AllowMultiple = true)]
    public interface IMessageHandlerProvider
    {
        /// <summary>
        /// Indicates whether the selector can handle the indicated message type.
        /// </summary>
        /// <remarks>
        /// This is the method by which the selectors are requested to indicate
        /// whether they are in charge of providing the handlers
        /// for a specific message type and ID.
        /// </remarks>
        /// <param name="envelopeType">The type of the envelope. This is typically the adapter type, if the message does not implement <see cref="IMessage"/>.</param>
        /// <param name="messageType">The type of the message.</param>
        /// <param name="messageId">The ID of the message.</param>
        /// <returns>
        /// True if the selector can handle the message type, false if not.
        /// </returns>
        bool CanHandle(Type envelopeType, Type messageType, object messageId);

        /// <summary>
        /// Gets a factory which retrieves the components handling messages of the given type.
        /// </summary>
        /// <param name="handlerFactories">The handler factories.</param>
        /// <param name="envelopeType">The type of the envelope. This is typically the adapter type, if
        ///                            the message does not implement <see cref="IMessage"/>.</param>
        /// <param name="messageType">The type of the message.</param>
        /// <param name="messageId">The ID of the message.</param>
        /// <returns>
        /// A factory of an enumeration of message handlers.
        /// </returns>
        Func<IEnumerable<IMessageHandler>> GetHandlersFactory(
            IEnumerable<IExportFactory<IMessageHandler, MessageHandlerMetadata>> handlerFactories,
            Type envelopeType,
            Type messageType,
            object messageId);
    }
}


text:
using System.Collections.Generic;
using System.Linq;
using EventSourcing.Library;
using EventSourcing.Server.Data;
using EventSourcing.Server.Events;

namespace EventSourcing.Server.Commands
{
  public class SellCommand : Command
  {
    public SellCommand(string name, string qty)
    {
      this.name = name;
      this.qty = qty;
    }

    public override Event Process(ServiceLocator locator)
    {
      var products = locator.Get<List<Product>>();
      var existing = products.FirstOrDefault(it => it.HasName(name));
      if (existing == null)
        return new UnknownProductEvent(name);

      decimal q;
      if (!decimal.TryParse(qty, out q))
        return new InvalidQuantityEvent(qty);

      if (!existing.CanSell(q))
        return new InsufficientStockEvent(name, q);

      return new SoldEvent(name, q);
    }

    //

    private readonly string name;
    private readonly string qty;
  }
}

redpajama_set_name: RedPajamaGithub


text:
//
// FastTemplate
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Jeff Panici

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

using System;
using System.Reflection.Emit;
using Antlr.Runtime.Tree;
using PaniciSoftware.FastTemplate.Common;

namespace PaniciSoftware.FastTemplate.Compiler
{
    internal class Statement : Emitter
    {
        public Statement(ITree tree)
            : base(tree)
        {
        }

        public ErrorList GenerateSet(Context ctx, Expression exp)
        {
            return GenerateSet(ctx, c => Errors.AddRange(exp.Generate(c)));
        }

        public ErrorList GenerateSet(Context ctx, int localIndex)
        {
            return GenerateSet(
                ctx,
                c => c.Sink.FastEmitLoadLocal(
                    localIndex));
        }

        public ErrorList GenerateSet(Context ctx, Action<Context> exp)
        {
            Ctx = ctx;
            Errors.Clear();
            var errors = new ErrorList();
            if (T.Type == 0)
            {
                var error = (CommonErrorNode) T;
                errors.ErrorParse(error);
                return Errors;
            }
            var child = (CommonTree) T.Children[0];
            switch (child.Type)
            {
                case 0:
                {
                    var error = (CommonErrorNode) child;
                    errors.ErrorParse(error);
                    break;
                }
                case TemplateLexer.MStart:
                case TemplateLexer.EStart:
                {
                    EmitSet(child, exp);
                    //pop off voidtype from final function in chain
                    break;
                }
                default:
                {
                    break;
                }
            }
            return Errors;
        }

        protected override void OnGenerate()
        {
            var errors = new ErrorList();
            if (T.Type == 0)
            {
                var error = (CommonErrorNode) T;
                errors.ErrorParse(error);
                Ctx.EmitNullRef();
                return;
            }
            var child = (CommonTree) T.Children[0];
            switch (child.Type)
            {
                case 0:
                {
                    var error = (CommonErrorNode) child;
                    errors.ErrorParse(error);
                    Ctx.EmitNullRef();
                    break;
                }
                case TemplateLexer.MStart:
                case TemplateLexer.EStart:
                {
                    EmitStatement(child);
                    if (child.Type == TemplateLexer.MStart)
                    {
                        EmitDoMacro();
                    }
                    break;
                }
                default:
                {
                    break;
                }
            }
        }

        private void EmitDoMacro()
        {
            var swap = Ctx.Sink.DeclareLocal(typeof (ITemplateType));
            Ctx.Sink.FastEmitStoreLocal(swap.LocalIndex);
            Ctx.Sink.Emit(OpCodes.Ldarg_0);
            Ctx.Sink.FastEmitLoadLocal(swap.LocalIndex);
            Ctx.EmitVTFunctionCall("EvalMacro");
        }

        private void EmitSet(CommonTree s, Action<Context> emitRVal)
        {
            var root = s.Children[0].Text;
            if (s.Children.Count < 2)
            {
                Ctx.Sink.Emit(OpCodes.Ldarg_0);
                Ctx.Sink.Emit(OpCodes.Ldstr, root);
                emitRVal(Ctx);
                Ctx.EmitVTFunctionCall("SetState");
                return;
            }
            Ctx.Sink.Emit(OpCodes.Ldarg_0);
            Ctx.Sink.Emit(OpCodes.Ldstr, root);
            Ctx.EmitVTFunctionCall("GetRootObject");
            var swapSpace = Ctx.Sink.DeclareLocal(typeof (ITemplateType));
            for (var i = 1; i < s.Children.Count; i++)
            {
                var current = (CommonTree) s.Children[i];
                switch (current.Type)
                {
                    case 0:
                    {
                        Errors.ErrorParse((CommonErrorNode) current);
                        break;
                    }
                    case TemplateParser.Invoke:
                    {
                        if (i == s.Children.Count - 1)
                        {
                            Errors.ErrorUnableToSetIntoFunctionResult(
                                "unknown type", current.Text);
                            return;
                        }
                        EmitFunctionInvoke(swapSpace, "Invoke", current);
                        break;
                    }
                    case TemplateParser.Indexer:
                    {
                        if (i == s.Children.Count - 1)
                        {
                            EmitFunctionInvoke(swapSpace, "set_Item", current, emitRVal);
                            Ctx.Sink.Emit(OpCodes.Pop);
                            return;
                        }
                        EmitFunctionInvoke(swapSpace, "get_Item", current);
                        break;
                    }
                    case TemplateParser.Prop:
                    {
                        if (i == s.Children.Count - 1)
                        {
                            EmitFunctionInvoke(
                                swapSpace,
                                string.Format("set_{0}",
                                    current.Text),
                                null,
                                emitRVal);
                            Ctx.Sink.Emit(OpCodes.Pop);
                            return;
                        }
                        var next = (CommonTree) s.Children[i + 1];
                        switch (next.Type)
                        {
                            case TemplateParser.Invoke:
                            {
                                EmitFunctionInvoke(swapSpace, current.Text, next);
                                i++;
                                break;
                            }
                            default:
                            {
                                EmitFunctionInvoke(
                                    swapSpace,
                                    string.Format("get_{0}",
                                        current.Text),
                                    null);
                                break;
                            }
                        }
                        break;
                    }
                }
            }
            Errors.ErrorUnableToSetIntoFunctionResult(
                "type only known at runtime",
                s.Children[s.Children.Count - 2].Text);
        }

        private void EmitStatement(CommonTree s)
        {
            var root = s.Children[0].Text;
            Ctx.Sink.Emit(OpCodes.Ldarg_0);
            Ctx.Sink.Emit(OpCodes.Ldstr, root);
            Ctx.EmitVTFunctionCall("GetRootObject");
            var swapSpace = Ctx.Sink.DeclareLocal(typeof (ITemplateType));
            for (var i = 1; i < s.Children.Count; i++)
            {
                var current = (CommonTree) s.Children[i];
                switch (current.Type)
                {
                    case 0:
                    {
                        Errors.ErrorParse((CommonErrorNode) current);
                        Ctx.EmitNullRef();
                        break;
                    }
                    case TemplateParser.Invoke:
                    {
                        EmitFunctionInvoke(swapSpace, "Invoke", current);
                        break;
                    }
                    case TemplateParser.Indexer:
                    {
                        EmitFunctionInvoke(swapSpace, "get_Item", current);
                        break;
                    }
                    case TemplateParser.Prop:
                    {
                        if (i == s.Children.Count - 1)
                        {
                            EmitFunctionInvoke(
                                swapSpace,
                                string.Format("get_{0}",
                                    current.Text),
                                null);
                            break;
                        }
                        var next = (CommonTree) s.Children[i + 1];
                        switch (next.Type)
                        {
                            case TemplateParser.Invoke:
                            {
                                EmitFunctionInvoke(swapSpace, current.Text, next);
                                i++;
                                break;
                            }
                            default:
                            {
                                EmitFunctionInvoke(
                                    swapSpace,
                                    string.Format("get_{0}",
                                        current.Text),
                                    null);
                                break;
                            }
                        }
                        break;
                    }
                }
            }
        }

        private void EmitFunctionInvoke(
            LocalBuilder swapSpace,
            string name,
            CommonTree next)
        {
            EmitFunctionInvoke(swapSpace, name, next, null);
        }

        private void EmitFunctionInvoke(
            LocalBuilder swapSpace,
            string name,
            CommonTree next,
            Action<Context> lastArg)
        {
            Ctx.Sink.FastEmitStoreLocal(swapSpace.LocalIndex);
            Ctx.Sink.Emit(OpCodes.Ldarg_0);
            Ctx.Sink.FastEmitLoadLocal(swapSpace.LocalIndex);
            Ctx.Sink.Emit(OpCodes.Ldstr, name);
            var args = next;
            if (args != null
                && args.Children != null
                && args.Children.Count > 0)
            {
                var fnArgs = (CommonTree) args.Children[0];
                if ((Ctx.OptimizeLevel & OptimizeLevel.FixArgList) == OptimizeLevel.FixArgList)
                {
                    if (fnArgs.Type == 0)
                    {
                        Errors.ErrorParse((CommonErrorNode) fnArgs);
                        Ctx.EmitNullRef();
                        Ctx.EmitVTFunctionCall("InvokeFunction1");
                        return;
                    }
                    var hasLast = lastArg != null;
                    var argCount = hasLast ? fnArgs.Children.Count + 1 : fnArgs.Children.Count;
                    switch (argCount)
                    {
                        case 0:
                            Ctx.EmitVTFunctionCall("InvokeFunction0");
                            break;
                        case 1:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction1");
                            break;
                        case 2:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction2");
                            break;
                        case 3:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction3");
                            break;
                        case 4:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction4");
                            break;
                        case 5:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction5");
                            break;
                        case 6:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction6");
                            break;
                        case 7:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction7");
                            break;
                        case 8:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction8");
                            break;
                        case 9:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction9");
                            break;
                        case 10:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction10");
                            break;
                        case 11:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction11");
                            break;
                        case 12:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction12");
                            break;
                        case 13:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction13");
                            break;
                        case 14:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction14");
                            break;
                        case 15:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction15");
                            break;
                        case 16:
                            Errors.AddRange(Ctx.EmitFlatArgList(fnArgs));
                            if (lastArg != null)
                                lastArg(Ctx);
                            Ctx.EmitVTFunctionCall("InvokeFunction16");
                            break;
                        default:
                        {
                            ErrorList e;
                            if (lastArg == null)
                            {
                                e = Ctx.EmitArgList(fnArgs);
                            }
                            else
                            {
                                e = Ctx.EmitArgList(fnArgs, lastArg);
                            }
                            Errors.AddRange(e);
                            Ctx.EmitVTFunctionCall("InvokeFunction");
                            break;
                        }
                    }
                }
                else
                {
                    if (lastArg == null)
                    {
                        var e = Ctx.EmitArgList(fnArgs);
                        Errors.AddRange(e);
                    }
                    else
                    {
                        var e = Ctx.EmitArgList(fnArgs, lastArg);
                        Errors.AddRange(e);
                    }
                    Ctx.EmitVTFunctionCall("InvokeFunction");
                }
            }
            else
            {
                if ((Ctx.OptimizeLevel & OptimizeLevel.FixArgList) == OptimizeLevel.FixArgList)
                {
                    if (lastArg != null)
                    {
                        lastArg(Ctx);
                        Ctx.EmitVTFunctionCall("InvokeFunction1");
                    }
                    else
                    {
                        Ctx.EmitVTFunctionCall("InvokeFunction0");
                    }
                }
                else
                {
                    if (lastArg == null)
                    {
                        Ctx.EmitEmptyArgList();
                        Ctx.EmitVTFunctionCall("InvokeFunction");
                    }
                    else
                    {
                        Errors.AddRange(Ctx.EmitSingleArgList(lastArg));
                        Ctx.EmitVTFunctionCall("InvokeFunction");
                    }
                }
            }
        }
    }
}


text:
(function() {
    'use strict';

    /**
     * Module      : alto.projects
     * Description : This module allow user to see his projects and open projects
     */
    angular.module('alto.projects', [

    ]);

})();


text:
package org.drools.workbench.screens.scorecardxls.client.editor;

import javax.annotation.PostConstruct;
import javax.enterprise.event.Event;
import javax.inject.Inject;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Widget;
import org.drools.workbench.screens.scorecardxls.client.resources.i18n.ScoreCardXLSEditorConstants;
import org.drools.workbench.screens.scorecardxls.client.type.ScoreCardXLSResourceType;
import org.gwtbootstrap3.client.ui.Button;
import org.jboss.errai.bus.client.api.ClientMessageBus;
import org.kie.workbench.common.widgets.client.resources.i18n.CommonConstants;
import org.kie.workbench.common.widgets.client.widget.AttachmentFileWidget;
import org.kie.workbench.common.widgets.metadata.client.KieEditorViewImpl;
import org.uberfire.backend.vfs.ObservablePath;
import org.uberfire.backend.vfs.Path;
import org.uberfire.ext.widgets.common.client.common.BusyPopup;
import org.uberfire.workbench.events.NotificationEvent;

import static org.uberfire.ext.widgets.common.client.common.ConcurrentChangePopup.newConcurrentUpdate;

public class ScoreCardXLSEditorViewImpl
        extends KieEditorViewImpl
        implements ScoreCardXLSEditorView {

    interface ScoreCardXLSEditorViewBinder
            extends
            UiBinder<Widget, ScoreCardXLSEditorViewImpl> {

    }

    private static ScoreCardXLSEditorViewBinder uiBinder = GWT.create( ScoreCardXLSEditorViewBinder.class );

    @UiField(provided = true)
    AttachmentFileWidget uploadWidget;

    @UiField
    Button downloadButton;

    @Inject
    private Event<NotificationEvent> notificationEvent;

    @Inject
    private ScoreCardXLSResourceType resourceType;

    @Inject
    private ClientMessageBus clientMessageBus;

    private ScoreCardXLSEditorView.Presenter presenter;
    private ObservablePath.OnConcurrentUpdateEvent concurrentUpdateSessionInfo;

    @PostConstruct
    public void init() {
        uploadWidget = new AttachmentFileWidget( new String[]{ resourceType.getSuffix() }, true );
        initWidget( uiBinder.createAndBindUi( this ) );
    }

    @Override
    public void init( final ScoreCardXLSEditorView.Presenter presenter ) {
        this.presenter = presenter;
    }

    @Override
    public void setConcurrentUpdateSessionInfo( final ObservablePath.OnConcurrentUpdateEvent eventInfo ) {
        this.concurrentUpdateSessionInfo = eventInfo;
    }

    public void setPath( final Path path ) {
        uploadWidget.addClickHandler( new ClickHandler() {
            @Override
            public void onClick( final ClickEvent event ) {
                BusyPopup.showMessage( ScoreCardXLSEditorConstants.INSTANCE.Uploading() );

                if ( concurrentUpdateSessionInfo != null ) {
                    newConcurrentUpdate( concurrentUpdateSessionInfo.getPath(),
                                         concurrentUpdateSessionInfo.getIdentity(),
                                         new org.uberfire.mvp.Command() {
                                             @Override
                                             public void execute() {
                                                 submit( path );
                                             }
                                         },
                                         new org.uberfire.mvp.Command() {
                                             @Override
                                             public void execute() {
                                                 //cancel?
                                             }
                                         },
                                         new org.uberfire.mvp.Command() {
                                             @Override
                                             public void execute() {
                                                 concurrentUpdateSessionInfo = null;
                                                 presenter.reload();
                                             }
                                         }
                                       ).show();
                } else {
                    submit( path );
                }
            }
        } );

        downloadButton.addClickHandler( new ClickHandler() {
            @Override
            public void onClick( final ClickEvent event ) {
                Window.open( getDownloadUrl( path ),
                             "downloading",
                             "resizable=no,scrollbars=yes,status=no" );
            }
        } );
    }

    private void submit( final Path path ) {
        uploadWidget.submit( path,
                             getServletUrl(),
                             new Command() {

                                 @Override
                                 public void execute() {
                                     BusyPopup.close();
                                     notifySuccess();
                                 }

                             },
                             new Command() {

                                 @Override
                                 public void execute() {
                                     BusyPopup.close();
                                 }

                             }
                           );
        concurrentUpdateSessionInfo = null;
    }

    String getServletUrl() {
        return URLHelper.getServletUrl( getClientId() );
    }

    String getDownloadUrl( final Path path ) {
        return URLHelper.getDownloadUrl( path, getClientId() );
    }

    String getClientId() {
        return clientMessageBus.getClientId();
    }

    @Override
    public void setReadOnly( final boolean isReadOnly ) {
        uploadWidget.setEnabled( !isReadOnly );
    }

    private void notifySuccess() {
        notificationEvent.fire( new NotificationEvent( CommonConstants.INSTANCE.ItemCreatedSuccessfully() ) );
    }

}


text:
package main

import "bytes"
import "fmt"

func restartServer(server Raspberry) {
	session := sshConnectR(server)

	var b bytes.Buffer
	session.Stdout = &b
	if err := session.Run("sudo reboot"); err != nil {
		panic("Failed to run: " + err.Error())
	}

	fmt.Println(b.String())
}

func restartAirPlay(server Raspberry) {
	session := sshConnectR(server)

	var b bytes.Buffer
	session.Stdout = &b
	if err := session.Run("sudo /etc/init.d/shairport-sync stop;sudo /etc/init.d/shairport-sync start"); err != nil {
		panic("Failed to run: " + err.Error())
	}

	fmt.Println(b.String())
}


text:
Biligrab-Danmaku2ASS
====================

Play videos on Bilibili.com with MPV and Danmaku2ASS

Requirements
------------

- [Python](https://www.python.org/) at least version 3.0
- [mpv Media Player](http://mpv.io/), a fork of MPlayer with features
  Biligrab-Danmaku2ASS requires
- [FFmpeg](https://www.ffmpeg.org/) with ffprobe installed. [Do not use Libav](https://github.com/mpv-player/mpv/wiki/FFmpeg-versus-Libav/9fc3989d00b2df54f7bc92f5de8442fc223091a2).
- [Danmaku2ASS](https://github.com/m13253/danmaku2ass), automatically installed

Note that [Libav](https://www.libav.org/) does not work. See [why FFmpeg is preferred](https://github.com/mpv-player/mpv/wiki/FFmpeg-versus-Libav).

Example
-----

```
./bilidan.py http://www.bilibili.com/video/av899574/
./bilidan.py http://www.bilibili.com/video/av314/     # High density comments!
./bilidan.py http://www.bilibili.com/video/av332732/index_7.html # Extreme density!
./bilidan.py http://www.bilibili.com/video/av297197/  # Even Toukome (advanced comments)!
```
Use option `--source overseas` if your are outside China. And `--source html5`  to use the the experimental HTML5 API.
Use `--fakeip` if you can't get valid media URLs due to ip restrictions.

Why Biligrab-Danmaku2ASS?
-------------------------

- Bilibili uses a Flash-based video player. Flash is unavailable since
  **Chromium** 35 to Linux users.
- Chrome Pepper Flash has a font-related bug on Linux, which causes the whole
  page crash when Flash tries to render certain CJK fonts so that you have no
  chance to switch to another font. This caused Bilibili Flash player unusable
  to **Google Chrome** users on Linux.
- **Mozilla Firefox** users on Linux never receives a newer Flash player than
  11.2 from Adobe. It is certain that Adobe has abandoned Flash.
- Flash consumes too much energy. Flash causes a burning laptop.
- Experiments show that Danmaku2ASS renders a lot faster than the native
  Bilibili player and even similar software such as
  [ABPlayerHTML5](https://github.com/jabbany/ABPlayerHTML5). Thanks to libass,
  Danmaku2ASS has passed a
  [extreme density test](http://www.bilibili.com/video/av332732/index_7.html) at
  60 fps on a Intel Core i5 laptop.

Tips
----

- Use key V to switch comment visibility.
- Some videos require logging in your account. Import your Cookie at bilibili.tv
  with `--cookie` option.
- If you have difficulties connecting to video server, try `--overseas`.
- If your computer is not fast enough, try `--mpvflags '--framedrop yes'`.
- Use `--d2aflags 'duration_marquee=5'` to set comment flow speed.
- Use `--d2aflags 'text_opacity=0.8'` to set comment opacity.
- Try to fast forward or rewind when streaming is stuck, or to tweak cache
  parameters of mpv.
- For issue related to URL parsing (especially the experimental HTML5 API),
  please report directly to Biligrab, the upstream parser:
  https://github.com/cnbeining/Biligrab/issues

License
-------

Like the original Biligrab, Biligrab-Danmaku2ASS is licensed under MIT license
as well. This program is provided **as is**, with absolutely no warranty.


text:
lock '3.2.1'

set :application, 'your_app_name'
set :repo_url, 'your_repo_url.git'

set :user, 'deployer'  # your server SSH user
set :use_sudo, false

# Default branch is :master
# ask :branch, proc { `git rev-parse --abbrev-ref HEAD`.chomp }.call

# Default deploy_to directory is /var/www/my_app

# Default value for :scm is :git
set :scm, :git

set :deploy_via, :remote_cache # off while it is first deployment

# Default value for :format is :pretty
# set :format, :pretty
set :rvm1_ruby_version, "ruby-2.1.5"

# Default value for :log_level is :debug
# set :log_level, :debug

# Default value for :pty is false
# set :pty, true

# Default value for :linked_files is []
set :linked_files, %w{config/database.yml}

# Default value for linked_dirs is []
set :linked_dirs, %w{log tmp/pids tmp/cache tmp/sockets vendor/bundle}
set :linked_dirs, fetch(:linked_dirs) + %w{public/system public/uploads}

# Default value for default_env is {}
# set :default_env, { path: "/opt/ruby/bin:$PATH" }

set :pty, true

# Default value for keep_releases is 5
set :keep_releases, 5

# set config unicorn.rb, unicorn_init.sh, nginx.conf file permission after deployment
set :file_permissions_roles, :all
set :file_permissions_users, ['deployer']
set :file_permissions_chmod_mode, "0777"

namespace :deploy do

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 1 do
      # Your restart mechanism here, for example:
      execute :touch, release_path.join('tmp/restart.txt')
      # execute "sudo service nginx restart"
      # execute "sudo service unicorn restart"
    end
  end

  before "deploy:updated", "deploy:set_permissions:chmod"

  after :publishing, :restart

  after :restart, :clear_cache do
    on roles(:web), in: :groups, limit: 3, wait: 10 do
      # Here we can do anything such as:
      # within release_path do
      #   execute :rake, 'cache:clear'
      # end
    end
  end
end


text:
package com.allihoopa.sdk.openin;

import android.support.annotation.Nullable;

import com.allihoopa.sdk.AllihoopaPiece;

/**
 * Asynchronous callback interface for the
 * {@link com.allihoopa.sdk.AllihoopaSDK#getPiece(android.support.v7.app.AppCompatActivity, String, OpenInCallback)}
 *
 * The interface has two method calls of which the {@link this#onQueryComplete(AllihoopaPiece)}
 * is called in the normal operation and {@link this#onQueryError(Exception)} is called on
 * error.
 */

public interface OpenInCallback {

    /**
     * Called as a result of normal operation. In case of successful query, an object of
     * {@link AllihoopaPiece} is returned.
     *
     * @param allihoopaPiece
     */
    void onQueryComplete(@Nullable AllihoopaPiece allihoopaPiece);

    /**
     * Called as a result of failed operation. The {@link Exception} causing the failure
     * is passed as a parameter.
     *
     * @param e
     */
    void onQueryError(Exception e);
}


text:
class VolumeController : public ash::VolumeControlDelegate,
                         public chromeos::CrasAudioHandler::AudioObserver {
 public:
  VolumeController();
  ~VolumeController() override;

  // Overridden from ash::VolumeControlDelegate:
  void HandleVolumeMute(const ui::Accelerator& accelerator) override;
  void HandleVolumeDown(const ui::Accelerator& accelerator) override;
  void HandleVolumeUp(const ui::Accelerator& accelerator) override;

  // Overridden from chromeos::CrasAudioHandler::AudioObserver.
  void OnOutputNodeVolumeChanged(uint64_t node_id, int volume) override;
  void OnOutputMuteChanged(bool mute_on, bool system_adjust) override;

 private:

  DISALLOW_COPY_AND_ASSIGN(VolumeController);
};

#endif  // CHROME_BROWSER_UI_ASH_VOLUME_CONTROLLER_CHROMEOS_H_


text:
package com.base2.kagura.shared;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author aubels
 *         Date: 27/08/13
 */
public class ResourcesUtils {
    public static InputStream getFaviconPng()
    {
        return ResourcesUtils.class.getResourceAsStream("/favicon.png");
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.bounswe.group7.services (services-api 1.0-SNAPSHOT API)</title>
<meta name="date" content="2016-12-22">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.bounswe.group7.services

Class Summary

Class
Description

CommentsService

This class is the service class of the Comments Class.

QuestionsService

This is the service class of the questions of the quiz.

QuizesService

This is the service class of the quiz object.

ReviewsService

This is the service class of the Review Model.

SearchService

SearchService.Pair<K,V>

TagsService

This is the service of the Tags Model

TopicsService

This is the service class of the Topic Model.

UsersService

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2016 Pivotal Software, Inc.. All rights reserved.


text:
<form action="{{ action }}" method="post" id="paysto-payment-form">
    {{ form }}
    <button type="submit" class="btn btn-lg btn-flt3" formtarget="__blank">Оплатить</button>
</form>


text:
<?php
//Parsonline/ZF/Form/Common.php

/**
 * @uses    Parsonline_ZF_Form
 */
require_once('Parsonline/ZF/Form.php');

/**
 * Parsonline_ZF_Form_Common
 *
 * A preconfigured subclass of Parsonline_ZF_Form, with methods to
 * reconfigure its behaviour.
 * Provides a generic form with data persistence, security features (using
 * a hash to identify form submission), automatically mark invalid elements
 * via element modifiers by default.
 */
class Parsonline_ZF_Form_Common extends Parsonline_ZF_Form
{
    const APPEND = 'append';
    const PREPEND = 'prepend';
    const NONE = 'none';

    /**
     * If should automatically add a security hash element for each form.
     *
     * @staticvar bool
     * @access protected
     */
    protected static $_defaultAddHashEelement = false;

    /**
     * Array of CSS classes to add to CSS classes of invalid elements,
     * for all forms. leave empty to disable.
     *
     * @staticvar   array
     * @access  protected
     */
    protected static $_defaultInvalidElementCSSClasses = array('invalid');

    /**
     * The default TTL for persistence session
     *
     * NOTE: Overrides the parent by increasing this value.
     *
     * @staticvar int
     * @access protected
     */
    protected static $_defaultPersistenceSessionTTL = 86400;

    /**
     * Array of CSS classes to add to CSS classes of required elements,
     * for all forms. leave empty to disable.
     *
     * @staticvar   array
     * @access  protected
     */
    protected static $_defaultRequiredElementCSSClasses = array('required');

    /**
     * Placement of element errors in the titles.
     * use NONE to turn off.
     *
     * @staticvar   string
     * @access      protected
     */
    protected static $_elementErrorPlacementInTitle = self::APPEND;

    /**
     * Name of the hash element created for form security.
     *
     * @var string
     * @access protected
     */
    protected $_securityHashElementName = 'hash';

    /**
     * Returns the array of CSS classes that would be added to the
     * CSS class of invalid elements.
     *
     * @return   array
     */
    public static function getDefaultInvalidElementCSSClasses()
    {
        return self::$_defaultInvalidElementCSSClasses;
    }

    /**
     * Set the array of CSS classes that would be added to the
     * CSS class of invalid elements.
     *
     * @param   string  $classes
     */
    public static function setDefaultInvalidElementCSSClasses($classes)
    {
        if ( !is_array($classes) ) $classes = explode(' ', $classes);
        self::$_defaultInvalidElementCSSClasses = array();
        foreach($classes as $c) {
            $c = trim($c);
            if ($c) array_push(self::$_defaultInvalidElementCSSClasses, $c);
        }
    } // public static function setDefaultInvalidElementCSSClasses()

    /**
     * Returns the array of CSS classes that would be added to the
     * CSS class of required elements.
     *
     * @return   array
     */
    public static function getDefaultRequiredElementCSSClasses()
    {
        return self::$_defaultRequiredElementCSSClasses;
    }

    /**
     * Set the array of CSS classes that would be added to the
     * CSS class of required elements.
     *
     * @param   string  $classes
     */
    public static function setDefaultRequiredElementCSSClasses($classes)
    {
        if ( !is_array($classes) ) $classes = explode(' ', $classes);
        self::$_defaultRequiredElementCSSClasses = array();
        foreach($classes as $c) {
            array_push(self::$_defaultRequiredElementCSSClasses, trim($c));
        }
    } // public static function setDefaultRequiredElementCSSClasses()

    /**
     * Returns the placement of element errors in their titles.
     *
     * @return   string
     */
    public static function getElementErrorPlacementInTitle()
    {
        return self::$_elementErrorPlacementInTitle;
    }

    /**
     * Set the placement of element errors in their titles. use NONE to turn
     * off this feature.
     *
     * @param   string  $placement
     * @throws  Parsonline_Exception_ValueException on not supported placement
     */
    public static function setElementErrorPlacementInTitle($placement)
    {
        $placement = strtolower($placement);
        switch($placement) {
            case self::APPEND:
            case self::PREPEND:
            case self::NONE:
                self::$_elementErrorPlacementInTitle = $placement;
                return;
        }
        /**
         * @uses    Parsonline_Exception_ValueException
         */
        require_once('Parsonline/Exception/ValueException.php');
        throw new Parsonline_Exception_ValueException("placement '{$placement}' is invalid");
    } // public static function setElementErrorPlacementInTitle;

    /**
     * Turns off the automatically adding of a hash element to the form.
     *
     * @param   bool    $no
     */
    public static function setNoHashElement($no=false)
    {
        self::$_defaultAddHashEelement = true && $no;
    }

    /**
     * Constructor
     *
     * Registers form view helper as decorator.
     * Overrides the parent by registerring the default element modifiers.
     *
     * @param   mixed       $options
     * @return  void
     */
    public function __construct($options=null)
    {
        parent::__construct($options);
        $modifierSpecs = $this->getDefaultElementModifiers();
        foreach ($modifierSpecs as $modiSpec) {
            list ($phase, $cond, $mod, $options) = $modiSpec;
            $this->addElementModifier($mod, $phase, $cond, $options);
        }
    } // public function __construct()

    /**
     * Add a new element
     *
     * $element may be either a string element type, or an object of type
     * Zend_Form_Element. If a string element type is provided, $name must be
     * provided, and $options may be optionally provided for configuring the
     * element.
     *
     * If a Zend_Form_Element is provided, $name may be optionally provided,
     * and any provided $options will be ignored.
     *
     * NOTE: Overrides the parent class, by adding the password and hash
     * elements to the list of persistence discarded elements.
     *
     * @param  string|Zend_Form_Element $element
     * @param  string                   $name
     * @param  array|Zend_Config        $options
     * @return  Parsonline_ZF_Form_Common
     */
    public function addElement($element, $name=null, $options=null)
    {
        parent::addElement($element, $name, $options);
        $elementName = ($element instanceof Zend_Form_Element) ? $element->getName() : $name;
        $elementClass = get_class($this->getElement($elementName));
        switch ($elementClass) {
            case 'Zend_Form_Element_Password':
            case 'Zend_Form_Element_Hash':
                $this->addPersistenceDiscardedElements($elementName);
            default:
                // pass
        }
        return $this;
    } // public function addElement()

    /**
     * Setups a Zend_Form_Element_Hash object.
     *
     * @return  Zend_Form_Element_Hash
     */
    public function createSecurityHashElement()
    {
        /**
        * @uses Zend_Form_Element_Hash
        */
       $hashName = $this->getSecurityHashElementName();
       $hashElement = new Zend_Form_Element_Hash($hashName);
       $hashElement->setSalt($this->getFormUID());
       $hashElement->setSession($this->getPersistenceSession());
       return $hashElement;
    } // public function createSecurityHashElement()

    /**
     * Returns an indexed array of arrays which describe the default element
     * modifiers. each subarray is in (phase, condition, modifier, options) format.
     *
     * Default Element modifiers are:
     *      1. on render phase for invalid elements, add an ErrorsInTitle modifier
     *         with auto remove option.
     *      2. on render phase for invalid elements, add an InvalidElementCSSClass
     *          modifier, with auto remove option.
     *      3. on render phase for all elements, add a RequiredElementCSSClass
     *          modifier to elements, with auto remove option.
     *
     * @return  array
     */
    public function getDefaultElementModifiers()
    {
        $modifierSpecs = array();
        if (self::$_elementErrorPlacementInTitle !== self::NONE) {
            /**
             * @uses    Parsonline_ZF_Form_ElementModifier_ErrorsInTitle
             */
            require_once('Parsonline/ZF/Form/ElementModifier/ErrorsInTitle.php');
            $modifier = new Parsonline_ZF_Form_ElementModifier_ErrorsInTitle();
            $modifier->setPlacement(self::$_elementErrorPlacementInTitle);
            $spec = array(
                        self::PHASE_RENDER,
                        self::CONDITION_INVALID_ELEMNT,
                        $modifier,
                        array(self::ELEMNET_MODIFIER_OPTION_AUTO_REMOVE)
                    );
            array_push($modifierSpecs, $spec);
            unset($spec, $modifier);
        }

        if (self::$_defaultInvalidElementCSSClasses) {
            /**
             * @uses    Parsonline_ZF_Form_ElementModifier_InvalidElementCSSClass
             */
            require_once('Parsonline/ZF/Form/ElementModifier/InvalidElementCSSClass.php');
            $modifier = new Parsonline_ZF_Form_ElementModifier_InvalidElementCSSClass();
            $modifier->setClasses(self::$_defaultInvalidElementCSSClasses);
            $spec = array(
                        self::PHASE_RENDER,
                        self::CONDITION_INVALID_ELEMNT,
                        $modifier,
                        array(self::ELEMNET_MODIFIER_OPTION_AUTO_REMOVE)
                    );
            array_push($modifierSpecs, $spec);
            unset($spec, $modifier);
        }

        if (self::$_defaultRequiredElementCSSClasses) {
            /**
             * @uses    Parsonline_ZF_Form_ElementModifier_RequiredElementCSSClass
             */
            require_once('Parsonline/ZF/Form/ElementModifier/RequiredElementCSSClass.php');
            $modifier = new Parsonline_ZF_Form_ElementModifier_RequiredElementCSSClass();
            $modifier->setClasses(self::$_defaultRequiredElementCSSClasses);
            $spec = array(
                        self::PHASE_RENDER,
                        self::CONDITION_ALWAYS,
                        $modifier,
                        array(self::ELEMNET_MODIFIER_OPTION_AUTO_REMOVE)
                    );
            array_push($modifierSpecs, $spec);
            unset($spec, $modifier);
        }

        return $modifierSpecs;
    } // public function getDefaultElementModifiers()

    /**
     * Returns the name of the hash element used for form security.
     *
     * @return  string
     */
    public function getSecurityHashElementName()
    {
        return $this->_securityHashElementName;
    }

    /**
     * Sets the name of the hash element used for form security.
     *
     * @param  string       $name
     * @return  Parsonline_ZF_Form_Common
     */
    public function setSecurityHashElementName($name)
    {
        $this->_securityHashElementName = $name;
        return $this;
    }

    /**
     * Initialize the Form.
     *
     * Overrides the parent by:
     *  1. clearing all elements, and element modifiers.
     *  2. Adding the security hash element to the form elements.
     */
    public function init()
    {
       parent::init();
       $this->clearElements();
       $this->clearAllElementModifiers();
       /**
        * Since the '$_defaultAddHashEelement' protected property and this method are both defined in
        * this class (Parsonline_ZF_Form_Common), using the PHP construct
        * 'self' would not check if the property is overriden in child classes.
        * So I use this trick below, to get the self reference on runtime, as
        * the reference to the same class that is actually overriding the
        * property.
        */
       $self = get_class($this);
       if ($self::$_defaultAddHashEelement) {
           $hashElement = $this->createSecurityHashElement();
           $this->addElement($hashElement);
       }
    } // public function init()
}


text:
typedef enum __nfpack Handshake
{
    Handshake_None = 0,
    Handshake_XOnXOff = 1,
    Handshake_RequestToSend = 2,
    Handshake_RequestToSendXOnXOff = 3,
} Handshake;

typedef enum __nfpack Parity
{
    Parity_None = 0,
    Parity_Odd = 1,
    Parity_Even = 2,
} Parity;

typedef enum __nfpack SerialData
{
    SerialData_Chars = 1,
    SerialData_WatchChar = 2,
} SerialData;

typedef enum __nfpack SerialMode
{
    SerialMode_Normal = 0,
    SerialMode_RS485 = 1,
} SerialMode;

typedef enum __nfpack StopBits
{
    StopBits_One = 1,
    StopBits_Two = 2,
    StopBits_OnePointFive = 3,
} StopBits;

struct Library_sys_io_ser_native_System_IO_Ports_SerialDataEvent
{
    static const int FIELD__SerialDeviceIndex = 3;
    static const int FIELD__Event = 4;

    //--//
};

struct Library_sys_io_ser_native_System_IO_Ports_SerialDataReceivedEventArgs
{
    static const int FIELD___data = 1;

    //--//
};

struct Library_sys_io_ser_native_System_IO_Ports_SerialDeviceController
{
    static const int FIELD_STATIC___syncLock = 0;
    static const int FIELD_STATIC__s_deviceCollection = 1;

    //--//
};

struct Library_sys_io_ser_native_System_IO_Ports_SerialPort
{
    static const int FIELD_STATIC__s_eventListener = 2;

    static const int FIELD___disposed = 1;
    static const int FIELD___syncLock = 2;
    static const int FIELD___opened = 3;
    static const int FIELD___writeTimeout = 4;
    static const int FIELD___readTimeout = 5;
    static const int FIELD___receivedBytesThreshold = 6;
    static const int FIELD___baudRate = 7;
    static const int FIELD___handshake = 8;
    static const int FIELD___stopBits = 9;
    static const int FIELD___dataBits = 10;
    static const int FIELD___parity = 11;
    static const int FIELD___mode = 12;
    static const int FIELD___deviceId = 13;
    static const int FIELD___portIndex = 14;
    static const int FIELD___watchChar = 15;
    static const int FIELD___callbacksDataReceivedEvent = 16;
    static const int FIELD___stream = 17;
    static const int FIELD___newLine = 18;
    static const int FIELD___bufferSize = 19;

    NANOCLR_NATIVE_DECLARE(get_BytesToRead___I4);
    NANOCLR_NATIVE_DECLARE(get_InvertSignalLevels___BOOLEAN);
    NANOCLR_NATIVE_DECLARE(set_InvertSignalLevels___VOID__BOOLEAN);
    NANOCLR_NATIVE_DECLARE(Read___I4__SZARRAY_U1__I4__I4);
    NANOCLR_NATIVE_DECLARE(ReadExisting___STRING);
    NANOCLR_NATIVE_DECLARE(ReadLine___STRING);
    NANOCLR_NATIVE_DECLARE(Write___VOID__SZARRAY_U1__I4__I4);
    NANOCLR_NATIVE_DECLARE(NativeDispose___VOID);
    NANOCLR_NATIVE_DECLARE(NativeInit___VOID);
    NANOCLR_NATIVE_DECLARE(NativeConfig___VOID);
    NANOCLR_NATIVE_DECLARE(NativeSetWatchChar___VOID);
    NANOCLR_NATIVE_DECLARE(NativeWriteString___VOID__STRING__BOOLEAN);
    NANOCLR_NATIVE_DECLARE(NativeReceivedBytesThreshold___VOID__I4);
    NANOCLR_NATIVE_DECLARE(GetDeviceSelector___STATIC__STRING);

    //--//

    static HRESULT SetupWriteLine(CLR_RT_StackFrame &stack, char **buffer, uint32_t *length, bool *isNewAllocation);
    static bool GetLineFromRxBuffer(
        CLR_RT_HeapBlock *serialDevice,
        HAL_RingBuffer<uint8_t> *ringBuffer,
        uint8_t *&line);
};

struct Library_sys_io_ser_native_System_IO_Ports_SerialDeviceEventListener
{
    static const int FIELD___serialDevicesMap = 1;

    //--//
};

struct Library_sys_io_ser_native_System_IO_Ports_SerialStream
{
    static const int FIELD___serial = 2;

    //--//
};

extern const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_System_IO_Ports;

#endif // SYS_IO_SER_NATIVE_H


text:
class FixInvalidMysqlIndices < ActiveRecord::Migration[4.2]
  def up
    if index_exists?("settings", ["target_type", "target_id", "var"])
      remove_index "settings", ["target_type", "target_id", "var"]

      add_index "settings", ["target_type", "target_id"],
                  name: "index_settings_on_target_type_and_target_id",
                  unique: true
    end
  end

  def down
    if index_exists?("settings", ["target_type", "target_id"])
      remove_index "settings", ["target_type", "target_id"]
      add_index "settings", ["target_type", "target_id", "var"],
                  name: "index_settings_on_target_type_and_target_id_and_var",
                  unique: true
    end
  end
end


text:
"use strict";

/**
 * StrelkiJS module
 * @module StrelkiJS
 * @author A. Maximov amaksr
 */
(function(exports){

    /**
     * Create new IndexArray object
     * @class
     * IndexedArray is a hybrid array with multiple hash indexes.
     * It can have additional "indexes": hash objects that point to elements and that can be quickly accessed by index value.
     * Elements also can be accessed by position.
     * @name IndexedArray
     * @constructor
     */
    var IndexedArray = function() {
        this.data = {};
        this.data_ids = null;
        this.indexData = {};
        this.ordered = false;
    }

    /**
     * Set flag that indicates whether array should be ordered by "id" or not
     * @param {boolean} ordered
     */
    IndexedArray.prototype.setOrdered = function(ordered) {
        this.ordered = ordered;
        if(this.ordered && this.data_ids)
            this.data_ids.sort();
    };

    IndexedArray.prototype._getDataIds = function() {
        if(!this.data_ids) {
            this.data_ids = Object.keys(this.data);
            if(this.ordered)
                this.data_ids.sort();
        }
        return this.data_ids;
    };

    /**
     * Creates hash index on array using fieldName property of the elements
     * @param {String} fieldName
     */
    IndexedArray.prototype.createIndex = function(fieldName) {
        if(fieldName === 'id')
            return;

        var idxData = {};
        var dataKeys = this._getDataIds();
        for(var i=0; i<dataKeys.length; i++) {
            var id = dataKeys[i];
            var e = this.data[id];
            var fv = e[fieldName];
            if(!idxData[fv])
                idxData[fv] = {};

            idxData[fv][id] = 1;
        }
        this.indexData[fieldName] = idxData;
    };

    /**
     * Returns hash array of objects
     * @returns {{}|*}
     */
    IndexedArray.prototype.getData = function() {
        return this.data;
    };

    /**
     * Puts all the elements from array
     * @param {Array} array
     */
    IndexedArray.prototype.loadArray = function(array) {
        if(!array || !array.length)
            return;
        for(var i=0; i<array.length; i++)
            this.put(array[i]);
    };

    /**
     * Drops index fieldName
     * @param {String} fieldName
     */
    IndexedArray.prototype.dropIndex = function(fieldName) {
        delete this.indexData[fieldName];
    };

    /**
     * Drops all indexes
     * @param fieldName
     */
    IndexedArray.prototype.dropAllIndexes = function(fieldName) {
        this.indexData={};
    };

    /**
     * Returns number of elements in the array
     * @returns {Number}
     */
    IndexedArray.prototype.length = function() {
        return this._getDataIds().length;
    };

    /**
     * Delete all data in the array
     */
    IndexedArray.prototype.empty = function() {
        this.data = {};
        this.data_ids = null;
        var indexes = Object.keys(this.indexData);
        for(var i = 0; i < indexes.length; i++)
            this.indexData[indexes[i]] = {};
    };

    /**
     * Returns record by "id" field
     * @param id
     * @returns {*}
     */
    IndexedArray.prototype.get = function(id) {
        return this.data[id];
    };

    /**
     * Returns record at given position
     * @param {Number} pos - position of element
     * @returns {*}
     */
    IndexedArray.prototype.getAt = function(pos) {
        return this.data[this._getDataIds()[pos]];
    };

    /**
     * Stores element with unique "id" to array. If element with given "id" was already there, it will be overriden with the new element
     * @param element
     */
    IndexedArray.prototype.put = function(element) {
        this.del(element.id);
        this.data_ids = null;
        this.data[element.id] = element;

        var indexes = Object.keys(this.indexData);
        for(var i = 0; i < indexes.length; i++) {
            var fld = element[indexes[i]];
            var idxData = this.indexData[indexes[i]];
            if(!idxData[fld])
                idxData[fld] = {};

            idxData[fld][element.id] = 1;
        }
    };

    /**
     * Delete element by "id"
     * @param id
     */
    IndexedArray.prototype.del = function(id) {
        var e = this.data[id];
        if(!e)
            return;
        var indexes = Object.keys(this.indexData);
        for(var i = 0; i < indexes.length; i++) {
            var idxData = this.indexData[indexes[i]];
            var idxElements  = idxData[e[indexes[i]]];
            if(idxElements) {
                delete idxElements[id];
                if(Object.keys(idxElements).length === 0)
                    delete idxData[e[indexes[i]]];
            }
        }
        delete this.data[id];
        this.data_ids = null;
    };

    /**
     * Delete multimple elements by array of ids
     * @param {Array} ids
     */
    IndexedArray.prototype.delMany = function(ids) {
        for(var i=0; i<ids.length; i++)
            this.del(ids[i]);
    };

    /**
     * Returns IndexedArray converted to regular Array
     * @returns {Array}
     */
    IndexedArray.prototype.toArray = function() {
        var res = [];
        var ids = this._getDataIds();
        for(var i =0; i<ids.length; i++)
            res.push(this.get(ids[i]));
        return res;
    };

    /**
     * Find elements by index value, and return their ids
     * @param {String} filedName - index name
     * @param {String} value - index value
     * @returns {Array} - array of ids, empty array if not found
     */
    IndexedArray.prototype.findIdsByIndex = function(filedName,value) {
        if(filedName === 'id') {
            var val = this.data[value];
            if(val)
                return [val.id];
            else
                return [];
        }
        else {
            var idxData = this.indexData[filedName];
            if(!idxData)
                throw "Index " + filedName + " does not exist";
            if(!idxData[value])
                return [];

            return Object.keys(idxData[value]);
        }
    };

    IndexedArray.prototype.dump = function() {
        console.log("dump: indexes="+JSON.stringify(this.indexData));
        console.log("dump: data="+JSON.stringify(this.data));
    };

    /**
     * For element el perform lookups according to joinInfoArray, and return all related records
     * @param el - element
     * @param {Array} joinInfoArray
     */
    IndexedArray.doLookups = function(el, joinInfoArray) {
        var res=[];
        for(var i=0; i<joinInfoArray.length; i++) {
            var ji = joinInfoArray[i];
            var joins = IndexedArray.doLookup(el, ji);
            res = IndexedArray._merge(res,joins);
        }
        return res;
    };

    IndexedArray.doLookup = function(el, joinInfo) {
        var res = [];
        var from_col = joinInfo.from_col;
        var to_table = joinInfo.to_table;
        var to_col = joinInfo.to_col;
        var to_ids = el?to_table.findIdsByIndex(to_col,el[from_col]):[];

        if(to_ids.length == 0 && joinInfo.type === 'outer')
            to_ids.push(null);

        for(var i=0; i < to_ids.length; i++) {
            var to_id = to_ids[i];
            var to_el = to_id?to_table.getData()[to_id]:null;
            if(joinInfo['join']) {
                var joins = IndexedArray.doLookups(to_el,joinInfo['join']);
                for(var j=0; j<joins.length; j++)
                    res.push([to_el].concat(joins[j]));
            }
            else
                res.push([to_el]);
        }

        return res;
    };

    /**
     * Join other IndexedArrays according to joinInfoArray
     * <pre>
     * joinInfoArray = [
     *  	{
	 *  		from_col:   mandatory field name in 'el' element
	 *  		to_table:   mandatory reference to IndexedArray
	 *  		to_col:     mandatory id or other indexed field in referenced IndexedArray
	 *  	        type:       'outer' for outer join, null for inner join
	 *  	        join:       optional nested joinInfoArray structure
	 *  	},
     *
     *  ]
     *  </pre>
     * @param joinInfoArray
     * @returns {Array} - array of records, where each record is an array of joined elements
     */
    IndexedArray.prototype.query = function(joinInfoArray) {
        var res = [];
        var mainKeys = this._getDataIds();
        for(var i=0; i < mainKeys.length; i++) {
            var el = this.data[mainKeys[i]];
            var joins = IndexedArray.doLookups(el,joinInfoArray);

            for(var j=0; j<joins.length; j++)
                res.push([el].concat(joins[j]));
        }
        return res;
    };

    /**
     * Search array by index, and then by filterCallback function
     * @param fieldName - name of the index, null to select all elements
     * @param value - value of the index
     * @param filterCallback - filter function that eccepts element as a parameter, and returns true or false
     * @returns {IndexedArray} - new IndexedArray with selected records
     */
    IndexedArray.prototype.where = function(fieldName, value, filterCallback) {
        var res = new IndexedArray();

        var ids;

        if(fieldName)
            ids = this.findIdsByIndex(fieldName, value);
        else
            ids = this._getDataIds();

        for(var i = 0; i < ids.length; i++) {
            var el = this.get(ids[i]);
            if(!filterCallback || filterCallback && filterCallback(el))
                res.put(el);
        }
        return res;
    };

    IndexedArray._merge = function(arr1, arr2) {
        if(arr1.length === 0)
            return arr2;
        var res=[];
        for(var i=0; i < arr1.length; i++) {
            for(var j=0; j < arr2.length; j++) {
                res.push(arr1[i].concat(arr2[j]));
            }
        }
        return res;
    };

	exports.IndexedArray = IndexedArray;

})(typeof exports === 'undefined'? this['StrelkiJS']={} : exports);


text:
Investigate and detect slow methods within the stack trace of your Ruby (optionally Sinatra) application

## Introduction

StackTracy is created for simply investigating your stack trace for called methods and its corresponding duration. You can filter modules / classes / methods within the output tree.

The gem is partly written in C to reduce the application performance as minimal as possible.

[![Dick .. Stack Tracy](https://slack-imgs.com/?c=1&o1=wi400.he250&url=http%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F330722020.jpg)](https://vimeo.com/archan937/stacktracy)

Watch the ["**Using StackTracy within a small Sinatra application**"](https://vimeo.com/archan937/stacktracy) **screencast** to see StackTracy in action!

## Installation

### Add `StackTracy` to your Gemfile

    gem "stack_tracy"

### Install the gem dependencies

    $ bundle

## Usage

### Recording stack events

Using `StackTracy` is pretty straightforward. You can either `start` and `stop` stack events recording.

    [1] pry(main)> StackTracy.start
    [2] pry(main)> puts "testing"
    [3] pry(main)> StackTracy.stop

Or you can use the `stack_tracy` convenience method which records stack events within the passed block.

    [1] pry(main)> stack_tracy do
    [1] pry(main)*   puts "testing"
    [1] pry(main)* end

### Reducing recorded stack events

As StackTracy records every `call` and `return` event, the resulted stack tree can get immense huge. Especially when dealing with complicated or extensive applications. If this is the case, I **really** recommend using following options which instructs StackTracy to reduce the recorded stack events.

It accepts an options `Hash` with at least one of the following keys:

* `:only` - Only matching events will be recorded
* `:exclude` - Matching events will be ignored

The value can be either a String (optionally whitespace-delimited) or an array of strings containing `class` and/or `module` names. You can use the wildcard (`*`) for matching classes and/or modules within that namespace.

#### Some examples

You can pass options as follows:

    [1] pry(main)> StackTracy.start :only => ["Foo"]
    [2] pry(main)> StackTracy.start :exclude => [:core]

When using the convenience method:

    [3] pry(main)> stack_tracy(:only => "Foo") { puts "testing" }
    [4] pry(main)> stack_tracy(:dump, {:only => "Foo*"}) { puts "testing" }
    [5] pry(main)> stack_tracy(:open, {:exclude => ["Array", "Hash"]}) { puts "testing" }

Let's say that you have the following code:

    class Foo
      class Bar; end
      module CandyBar; end
    end

    class FooBar; end

A couple of examples:

* `:only => "Foo"` records `Foo`
* `:only => "Foo*"` records `Foo`, `Foo::Bar` and `Foo::CandyBar`
* `:only => "Foo*", :exclude => "Foo::Bar"` records `Foo` and `Foo::CandyBar`
* `:exclude => ["Foo*", "FooBar"]` records everything except for `Foo`, `Foo::Bar`, `Foo::CandyBar` and `FooBar`
* `:only => "Foo* Kernel"` records `Foo`, `Foo::Bar`, `Foo::CandyBar` and `Kernel`
* `:exclude => :core` records everything except for Ruby core classes and modules (see [stack_tracy.rb](https://github.com/archan937/stack_tracy/blob/master/lib/stack_tracy.rb#L16) for more details)

### Adding trace messages

Sometimes you want to add marks to the stack tree in order to recognize certain events. You can do this by adding trace messages with the `String#tracy` method:

    [1] pry(main)> stack_tracy(:print) do
    [1] pry(main)*   "Putting string".tracy
    [1] pry(main)*   puts "Hello world!"
    [1] pry(main)*   "Done putting string".tracy
    [1] pry(main)* end
    Hello world!
    "Putting string" <0.000007>
    Kernel#puts <0.000038>
       IO#puts <0.000034>
          IO#write <0.000017>
          IO#write <0.000009>
    "Done putting string" <0.000003>
    => nil

You can also encapsulate trace messages by executing code within a block:

    [1] pry(main)> stack_tracy(:print) do
    [1] pry(main)*   "Doing things".tracy do
    [1] pry(main)*     "" * 10
    [1] pry(main)*     "Putting string".tracy do
    [1] pry(main)*       puts "Hello world!"
    [1] pry(main)*     end
    [1] pry(main)*   end
    [1] pry(main)* end
    Hello world!
    "Doing things" <0.000057>
       String#* <0.000003>
       "Putting string" <0.000043>
          Kernel#puts <0.000038>
             IO#puts <0.000033>
                IO#write <0.000017>
                IO#write <0.000009>
    => nil

### Configure StackTracy

You can configure `StackTracy` regarding the default stack tree reduction behaviour, its dump directory and whether to include the source location when dumping recorded stack events:

    StackTracy.config do |c|
      c.dump_dir             = "."                        #=> default: Dir::tmpdir
      c.dump_source_location = "."                        #=> default: false
      c.limit                = 1000                       #=> default: 7500
      c.threshold            = 0.005                      #=> default: 0.001
      c.messages_only        = true                       #=> default: false
      c.slows_only           = false                      #=> default: false
      c.only                 = "Foo*"                     #=> default: nil
      c.exclude              = %w(Foo::Bar Foo::CandyBar) #=> default: nil
    end

As already mentioned, recorded stack traces can easily get very huge. So StackTracy will use the `:limit` and `:threshold` options when generating the HTML stack trace page (after having invoked `StackTracy.open`).

When the amount of calls within the stack trace exceeds the specified `:limit`, StackTracy will automatically filter out Ruby core classes and modules calls and it will also apply the `:threshold` option.

When applying the `:threshold`, calls with a duration **below** the `:threshold` will be folded at default within the stack tree which saves **a lot** of heavy browser rendering on page load as the 'child calls' will be rendered as comment. See [this commit](https://github.com/archan937/stack_tracy/commit/0bb49669015b44cd24715988bf9f7e4cf03a5dad) for more information.

As of version v0.1.5, `StackTracy.open` (and thus the CLI) is provided with the options `:messages_only` and `:slows_only`. When having set `:messages_only` to `true`, the stack tree will only include trace messages. If you have set `:slows_only` to `true`, then the stack tree will only include slow calls (duration > threshold) **and** trace messages.

### Using recorded stack events

Once you have recorded stack events, you can call the following methods:

`StackTracy.stack_trace` - returns all recorded stack events (`array` of `StackTracy::EventInfo` instances)

    [2] pry(main)> StackTracy.stack_trace.inspect
    => [
      #<StackTracy::EventInfo:0x0000010154b418 @event="c-call", @file="(pry)", @line=2, @singleton=false, @object=Kernel, @method="puts", @nsec=1344465432463251968>,
      #<StackTracy::EventInfo:0x0000010154b350 @event="c-call", @file="(pry)", @line=2, @singleton=false, @object=IO, @method="puts", @nsec=1344465432463272960>,
      #<StackTracy::EventInfo:0x0000010154b1c0 @event="c-call", @file="(pry)", @line=2, @singleton=false, @object=IO, @method="write", @nsec=1344465432463288064>,
      #<StackTracy::EventInfo:0x0000010154b0a8 @event="c-return", @file="(pry)", @line=2, @singleton=false, @object=IO, @method="write", @nsec=1344465432463331072>,
      #<StackTracy::EventInfo:0x0000010154af68 @event="c-call", @file="(pry)", @line=2, @singleton=false, @object=IO, @method="write", @nsec=1344465432463344896>,
      #<StackTracy::EventInfo:0x0000010154ae50 @event="c-return", @file="(pry)", @line=2, @singleton=false, @object=IO, @method="write", @nsec=1344465432463365888>,
      #<StackTracy::EventInfo:0x0000010154ad38 @event="c-return", @file="(pry)", @line=2, @singleton=false, @object=IO, @method="puts", @nsec=1344465432463378944>,
      #<StackTracy::EventInfo:0x0000010154ac20 @event="c-return", @file="(pry)", @line=2, @singleton=false, @object=Kernel, @method="puts", @nsec=1344465432463390976>]
    ]

`StackTracy.select` - returns (optionally filtered) recorded stack events for printing purposes (`array` of `Hash` instances)

    [3] pry(main)> StackTracy.select.inspect
    => [
      {:event=>"c-call", :file=>"(pry)", :line=>2, :singleton=>false, :object=>Kernel, :method=>"puts", :nsec=>1344464282852728064, :call=>"Kernel#puts", :depth=>0, :duration=>0.000129024},
      {:event=>"c-call", :file=>"(pry)", :line=>2, :singleton=>false, :object=>IO, :method=>"puts", :nsec=>1344464282852748032, :call=>"IO#puts", :depth=>1, :duration=>9.7024e-05},
      {:event=>"c-call", :file=>"(pry)", :line=>2, :singleton=>false, :object=>IO, :method=>"write", :nsec=>1344464282852762112, :call=>"IO#write", :depth=>2, :duration=>3.4816e-05},
      {:event=>"c-call", :file=>"(pry)", :line=>2, :singleton=>false, :object=>IO, :method=>"write", :nsec=>1344464282852811008, :call=>"IO#write", :depth=>2, :duration=>2.0992e-05}
    ]
    [4] pry(main)> StackTracy.select(%w(Kernel)).inspect
    => [
      {:event=>"c-call", :file=>"(pry)", :line=>2, :singleton=>false, :object=>Kernel, :method=>"puts", :nsec=>1344464282852728064, :call=>"Kernel#puts", :depth=>0, :duration=>0.000129024}
    ]
    [5] pry(main)> StackTracy.select("Kernel IO#puts").inspect
    => [
      {:event=>"c-call", :file=>"(pry)", :line=>2, :singleton=>false, :object=>Kernel, :method=>"puts", :nsec=>1344464282852728064, :call=>"Kernel#puts", :depth=>0, :duration=>0.000129024},
      {:event=>"c-call", :file=>"(pry)", :line=>2, :singleton=>false, :object=>IO, :method=>"puts", :nsec=>1344464282852748032, :call=>"IO#puts", :depth=>1, :duration=>9.7024e-05}
    ]

`StackTracy.print` - prints (optionally filtered) recorded stack events as a tree

    [6] pry(main)> StackTracy.print
    Kernel#puts <0.000094>
       IO#puts <0.000069>
          IO#write <0.000018>
          IO#write <0.000016>
    => nil

### Writing data to CSV files

You can dump (optionally filtered) recorded stack events to a CSV file.

    [1] pry(main)> StackTracy.start
    [2] pry(main)> puts "testing"
    => testing
    [3] pry(main)> StackTracy.stop
    [4] pry(main)> StackTracy.print
    Kernel#puts <0.000121>
       IO#puts <0.000091>
          IO#write <0.000032>
          IO#write <0.000020>
    => nil
    [5] pry(main)> StackTracy.dump "result.csv"
    => true

#### CSV sample file

This is what the contents of `result.csv` would look like:

    event;;;singleton;object;method;nsec;call;depth;duration
    c-call;;;false;Kernel;puts;1344466943040581120;Kernel#puts;0;0.000120832
    c-call;;;false;IO;puts;1344466943040599040;IO#puts;1;9.1904e-05
    c-call;;;false;IO;write;1344466943040613120;IO#write;2;3.2768e-05
    c-call;;;false;IO;write;1344466943040658944;IO#write;2;1.9968e-05

When invoking `StackTracy.dump "result.csv", true` and thus including the source location:

    event;file;line;singleton;object;method;nsec;call;depth;duration
    c-call;(pry);2;false;Kernel;puts;1344466943040581120;Kernel#puts;0;0.000120832
    c-call;(pry);2;false;IO;puts;1344466943040599040;IO#puts;1;9.1904e-05
    c-call;(pry);2;false;IO;write;1344466943040613120;IO#write;2;3.2768e-05
    c-call;(pry);2;false;IO;write;1344466943040658944;IO#write;2;1.9968e-05

### Viewing stack events in your browser

You can easily view the dumped stack events within your browser by either calling the following within Ruby:

    [1] pry(main)> StackTracy.open "some/dir/file.csv"

Your default browser will be launched in which the stack events will be displayed.

When passing no path, StackTracy will look for `stack_events-<random generated postfix>.csv` in either the default dump directory, the current directory or `Dir::tmpdir` and display it in the browser. When not found, it will display the last compiled stack tree when available:

    [2] pry(main)> StackTracy.open

### Using the CLI (command line interface)

Another way for viewing stack events in your browser is using the CLI `tracy` within the Terminal:

    $ tracy             #=> let StackTracy auto-determine which file to display
    $ tracy .           #=> display the last data file within the current directory
    $ tracy foo/bar.csv #=> display foo/bar.csv

To get info about its options, type `tracy help open`:

    $ tracy help open
    Usage:
      tracy open [PATH]

    Options:
      -l, [--limit=N]
      -t, [--threshold=N]
      -m, [--messages-only=MESSAGES_ONLY]
      -s, [--slows-only=SLOWS_ONLY]

    Display StackTracy data within the browser (PATH is optional)

### Kernel#stack_tracy

As already mentioned, there is a convenience method called `stack_tracy` convenience method. The following shows a couple variants with its equivalent "normal implementation".

#### Without passing an argument

Record stack events executed within a block:

    [1] pry(main)> stack_tracy do
    [1] pry(main)*   puts "testing"
    [1] pry(main)* end

Its equivalent:

    [1] pry(main)> StackTracy.start
    [2] pry(main)> puts "testing"
    [3] pry(main)> StackTracy.stop

#### Passing `:print`

Record stack events executed within a block and print the stack tree:

    [1] pry(main)> stack_tracy :print do
    [1] pry(main)*   puts "testing"
    [1] pry(main)* end

Its equivalent:

    [1] pry(main)> StackTracy.start
    [2] pry(main)> puts "testing"
    [3] pry(main)> StackTracy.stop
    [4] pry(main)> StackTracy.print

#### Passing `:dump`

Record stack events executed within a block and write the obtained data to `<default dump directory>/stack_events-<random generated postfix>.csv`:

    [1] pry(main)> stack_tracy :dump do
    [1] pry(main)*   puts "testing"
    [1] pry(main)* end

Its equivalent:

    [1] pry(main)> StackTracy.start
    [2] pry(main)> puts "testing"
    [3] pry(main)> StackTracy.stop
    [4] pry(main)> StackTracy.dump

#### Passing a target directory

Record stack events executed within a block and write the obtained data to `<passed directory>/stack_events-<random generated postfix>.csv`:

    [1] pry(main)> stack_tracy Dir::tmpdir do
    [1] pry(main)*   puts "testing"
    [1] pry(main)* end

Its equivalent:

    [1] pry(main)> StackTracy.start
    [2] pry(main)> puts "testing"
    [3] pry(main)> StackTracy.stop
    [4] pry(main)> StackTracy.dump Dir::tmpdir

#### Passing a CSV file path

Record stack events executed within a block and write the obtained data to the passed file path:

    [1] pry(main)> stack_tracy "some/file.csv" do
    [1] pry(main)*   puts "testing"
    [1] pry(main)* end

Its equivalent:

    [1] pry(main)> StackTracy.start
    [2] pry(main)> puts "testing"
    [3] pry(main)> StackTracy.stop
    [4] pry(main)> StackTracy.dump "some/file.csv"

#### Passing `:open`

Record stack events executed within a block and open the stack tree in your browser:

    [1] pry(main)> stack_tracy :open do
    [1] pry(main)*   puts "testing"
    [1] pry(main)* end

Its equivalent:

    [1] pry(main)> StackTracy.start
    [2] pry(main)> puts "testing"
    [3] pry(main)> StackTracy.stop
    [4] pry(main)> StackTracy.dump do |file|
    [4] pry(main)*   StackTracy.open file, true
    [4] pry(main)* end

## Hooking into Sinatra requests

You can easily hook `StackTracy` into [Sinatra](http://www.sinatrarb.com) requests. This is a complete working example:

    require "sinatra"
    require "stack_tracy"

    use StackTracy::Sinatra, :open

    get "/" do
      "Hello world!"
    end

**Note**: Make sure you have the `sinatra` and `stack_tracy` gems installed.

Open the Sinatra application in your browser at [http://localhost:4567](http://localhost:4567) and the complete stack tree will be displayed in your browser! ^^

You can also open [http://localhost:4567/tracy](http://localhost:4567/tracy) afterwards by the way.

### Taking more control

I can imagine that you don't want to hook into every Sinatra request. So you can pass a block which will be yielded before every request. The request will only be traced when the block does **not** return either `false` or `nil`:

    use StackTracy::Sinatra do |path, params|
      path == "/" #=> only trace "http://localhost:4567"
    end

Also, you can determine what StackTracy has to do after the request has finished. It resembles the invocation of `stack_tracy`. The following will dump every request into the current directory:

    use StackTracy::Sinatra, "."

This will immediately open the stack tree in your default browser after every traced request:

    use StackTracy::Sinatra, :open do |path, params|
      path == "/paul/engel" #=> only trace and open stack tree when opening "http://localhost:4567/paul/engel"
    end

Reduce the stack tree and open it immediately:

    use StackTracy::Sinatra, :open, :only => "Foo*"

## Using the console

The StackTracy repo is provided with `script/console` which you can use for development / testing purposes.

Run the following command in your console:

    $ script/console
    Loading development environment (StackTracy 0.1.9)
    [1] pry(main)> stack_tracy :print do
    [1] pry(main)*   puts "testing"
    [1] pry(main)* end
    testing
    Kernel#puts <0.000121>
       IO#puts <0.000091>
          IO#write <0.000032>
          IO#write <0.000020>
    => nil
    [2] pry(main)>

## Testing

Run the following command for testing:

    $ rake

You can also run a single test file:

    $ ruby test/unit/test_tracy.rb

## TODO

* Optimize C implementation performance when converting C data to Ruby objects within `stack_tracy_stop`
* Improve stack tree reduction by checking on method level
* Correct `StackTracy::PRESETS` regarding `:active_record` and `:data_mapper`
* Easily hook into Rails requests?

## Contact me

For support, remarks and requests, please mail me at [paul.engel@holder.nl](mailto:paul.engel@holder.nl).

## Credit

* Two functions within the StackTracy C implementation are taken from [ruby-prof](https://github.com/rdp/ruby-prof).
* The table sort within the Cumulatives tab is implemented with [TinySort](http://tinysort.sjeiti.com/).
* Being able to improve browser performance when loading heavy HTML stack trace pages using Ravi Raj's ([@raviraj4u](https://twitter.com/raviraj4u)) blog post: [http://ravirajsblog.blogspot.nl/2010/12/another-hack-to-render-heavy-html-pages.html](http://ravirajsblog.blogspot.nl/2010/12/another-hack-to-render-heavy-html-pages.html)

## License

Copyright (c) 2012 Paul Engel, released under the MIT license

[http://holder.nl](http://holder.nl) - [http://codehero.es](http://codehero.es) - [http://gettopup.com](http://gettopup.com) - [http://github.com/archan937](http://github.com/archan937) - [http://twitter.com/archan937](http://twitter.com/archan937) - [paul.engel@holder.nl](mailto:paul.engel@holder.nl)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
package org.mvcspec.ozark.bootstrap;

import javax.ws.rs.core.FeatureContext;

/**
 * SPI used to register providers when Ozark is initialized. Implementations are discovered
 * using the JDK's ServiceLoader mechanism.
 *
 * @author Christian Kaltepoth
 */
public interface ConfigProvider {

    void configure(FeatureContext context);

}


text:
package org.dev4u.hv.my_diagnostic.MyPlacesUI;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Http {

    public String read(String httpUrl) throws IOException {
        String httpData = "";
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(httpUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();
            inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer stringBuffer = new StringBuffer();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            httpData = stringBuffer.toString();
            bufferedReader.close();
        } catch (Exception e) {

        } finally {
            inputStream.close();
            httpURLConnection.disconnect();
        }
        return httpData;
    }
}


text:
'use strict';

// Environment variables that grunt will set when the server starts locally. Use for your api keys, secrets, etc.
// You will need to set these on the server you deploy to.
//
// This file should not be tracked by git.

module.exports = {
  SESSION_SECRET: "tester-secret",
  FACEBOOK_ID: "app-id",
  FACEBOOK_SECRET: "secret",
  TWITTER_ID: "app-id",
  TWITTER_SECRET: "secret",
  GOOGLE_ID: "app-id",
  GOOGLE_SECRET: "secret"
};


text:
// Reference: http://karma-runner.github.io/0.12/config/configuration-file.html
module.exports = function karmaConfig (config) {
  config.set({

    // base path that will be used to resolve all patterns (e.g. files, exclude)
    basePath: __dirname,

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: [
      // Reference: https://github.com/karma-runner/karma-jasmine
      // Set framework to jasmine
      'jasmine'
    ],

    // list of files to exclude
    exclude: [ ],

    /*
     * test results reporter to use
     *
     * possible values: 'dots', 'progress'
     * available reporters: https://npmjs.org/browse/keyword/karma-reporter
     */
    reporters: [ 'mocha', 'coverage' ], //, 'karma-remap-istanbul' ],

    // list of files / patterns to load in the browser
    // we are building the test environment in ./spec-bundle.js
    files: [ { pattern: 'spec-bundle.js', watched: false } ],

    preprocessors: {
      // Reference: http://webpack.github.io/docs/testing.html
      // Reference: https://github.com/webpack/karma-webpack
      // Convert files with webpack and load sourcemaps
      'spec-bundle.js': ['coverage', 'webpack', 'sourcemap']
    },

    browsers: [
      // Run tests using PhantomJS
      'PhantomJS',
      //'Chrome'
    ],

    autoWatch: true,
    singleRun: true,

    // Configure code coverage reporter
    coverageReporter: {
      reporters: [{
        type: 'json',
        subdir: '.',
        file: 'coverage-final.json'
      }]
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    /*
     * level of logging
     * possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
     */
    logLevel: config.LOG_INFO,

    /**
     * Load webpack config
     */
    webpack: require('../../webpack.config'),

    // Webpack please don't spam the console when running in karma!
    webpackServer: { noInfo: true }

  });
};


text:
package firestore

import (
	"testing"

	"golang.org/x/net/context"
	pb "google.golang.org/genproto/googleapis/firestore/v1beta1"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
)

var testClient = &Client{
	projectID:  "projectID",
	databaseID: "(default)",
}

func TestClientCollectionAndDoc(t *testing.T) {
	coll1 := testClient.Collection("X")
	db := "projects/projectID/databases/(default)"
	wantc1 := &CollectionRef{
		c:          testClient,
		parentPath: db,
		Parent:     nil,
		ID:         "X",
		Path:       "projects/projectID/databases/(default)/documents/X",
		Query:      Query{c: testClient, collectionID: "X", parentPath: db},
	}
	if !testEqual(coll1, wantc1) {
		t.Fatalf("got\n%+v\nwant\n%+v", coll1, wantc1)
	}
	doc1 := testClient.Doc("X/a")
	wantd1 := &DocumentRef{
		Parent: coll1,
		ID:     "a",
		Path:   "projects/projectID/databases/(default)/documents/X/a",
	}

	if !testEqual(doc1, wantd1) {
		t.Fatalf("got %+v, want %+v", doc1, wantd1)
	}
	coll2 := testClient.Collection("X/a/Y")
	parentPath := "projects/projectID/databases/(default)/documents/X/a"
	wantc2 := &CollectionRef{
		c:          testClient,
		parentPath: parentPath,
		Parent:     doc1,
		ID:         "Y",
		Path:       "projects/projectID/databases/(default)/documents/X/a/Y",
		Query:      Query{c: testClient, collectionID: "Y", parentPath: parentPath},
	}
	if !testEqual(coll2, wantc2) {
		t.Fatalf("\ngot  %+v\nwant %+v", coll2, wantc2)
	}
	doc2 := testClient.Doc("X/a/Y/b")
	wantd2 := &DocumentRef{
		Parent: coll2,
		ID:     "b",
		Path:   "projects/projectID/databases/(default)/documents/X/a/Y/b",
	}
	if !testEqual(doc2, wantd2) {
		t.Fatalf("got %+v, want %+v", doc2, wantd2)
	}
}

func TestClientCollDocErrors(t *testing.T) {
	for _, badColl := range []string{"", "/", "/a/", "/a/b", "a/b/", "a//b"} {
		coll := testClient.Collection(badColl)
		if coll != nil {
			t.Errorf("coll path %q: got %+v, want nil", badColl, coll)
		}
	}
	for _, badDoc := range []string{"", "a", "/", "/a", "a/", "a/b/c", "a//b/c"} {
		doc := testClient.Doc(badDoc)
		if doc != nil {
			t.Errorf("doc path %q: got %+v, want nil", badDoc, doc)
		}
	}
}

func TestGetAll(t *testing.T) {
	ctx := context.Background()
	const dbPath = "projects/projectID/databases/(default)"
	c, srv := newMock(t)
	defer c.Close()
	wantPBDocs := []*pb.Document{
		{
			Name:       dbPath + "/documents/C/a",
			CreateTime: aTimestamp,
			UpdateTime: aTimestamp,
			Fields:     map[string]*pb.Value{"f": intval(2)},
		},
		nil,
		{
			Name:       dbPath + "/documents/C/c",
			CreateTime: aTimestamp,
			UpdateTime: aTimestamp,
			Fields:     map[string]*pb.Value{"f": intval(1)},
		},
	}
	srv.addRPC(
		&pb.BatchGetDocumentsRequest{
			Database: dbPath,
			Documents: []string{
				dbPath + "/documents/C/a",
				dbPath + "/documents/C/b",
				dbPath + "/documents/C/c",
			},
		},
		[]interface{}{
			// deliberately put these out of order
			&pb.BatchGetDocumentsResponse{
				Result: &pb.BatchGetDocumentsResponse_Found{wantPBDocs[2]},
			},
			&pb.BatchGetDocumentsResponse{
				Result: &pb.BatchGetDocumentsResponse_Found{wantPBDocs[0]},
			},
			&pb.BatchGetDocumentsResponse{
				Result: &pb.BatchGetDocumentsResponse_Missing{dbPath + "/documents/C/b"},
			},
		},
	)
	coll := c.Collection("C")
	var docRefs []*DocumentRef
	for _, name := range []string{"a", "b", "c"} {
		docRefs = append(docRefs, coll.Doc(name))
	}
	docs, err := c.GetAll(ctx, docRefs)
	if err != nil {
		t.Fatal(err)
	}
	if got, want := len(docs), len(wantPBDocs); got != want {
		t.Errorf("got %d docs, wanted %d", got, want)
	}
	for i, got := range docs {
		var want *DocumentSnapshot
		if wantPBDocs[i] != nil {
			want, err = newDocumentSnapshot(docRefs[i], wantPBDocs[i], c)
			if err != nil {
				t.Fatal(err)
			}
		}
		if diff := testDiff(got, want); diff != "" {
			t.Errorf("#%d: got=--, want==++\n%s", i, diff)
		}
	}
}

func TestGetAllErrors(t *testing.T) {
	ctx := context.Background()
	const (
		dbPath  = "projects/projectID/databases/(default)"
		docPath = dbPath + "/documents/C/a"
	)
	c, srv := newMock(t)
	if _, err := c.GetAll(ctx, []*DocumentRef{nil}); err != errNilDocRef {
		t.Errorf("got %v, want errNilDocRef", err)
	}

	// Internal server error.
	srv.addRPC(
		&pb.BatchGetDocumentsRequest{
			Database:  dbPath,
			Documents: []string{docPath},
		},
		[]interface{}{grpc.Errorf(codes.Internal, "")},
	)
	_, err := c.GetAll(ctx, []*DocumentRef{c.Doc("C/a")})
	codeEq(t, "GetAll #1", codes.Internal, err)

	// Doc appears as both found and missing (server bug).
	srv.reset()
	srv.addRPC(
		&pb.BatchGetDocumentsRequest{
			Database:  dbPath,
			Documents: []string{docPath},
		},
		[]interface{}{
			&pb.BatchGetDocumentsResponse{
				Result: &pb.BatchGetDocumentsResponse_Found{&pb.Document{Name: docPath}},
			},
			&pb.BatchGetDocumentsResponse{
				Result: &pb.BatchGetDocumentsResponse_Missing{docPath},
			},
		},
	)
	if _, err := c.GetAll(ctx, []*DocumentRef{c.Doc("C/a")}); err == nil {
		t.Error("got nil, want error")
	}

	// Doc never appears (server bug).
	srv.reset()
	srv.addRPC(
		&pb.BatchGetDocumentsRequest{
			Database:  dbPath,
			Documents: []string{docPath},
		},
		[]interface{}{},
	)
	if _, err := c.GetAll(ctx, []*DocumentRef{c.Doc("C/a")}); err == nil {
		t.Error("got nil, want error")
	}
}


text:
@interface ASPOSETASKSGetProjectResourcesResponse : ASPOSEBaseResponse

@property(nonatomic, strong) ASPOSETASKSResourceItems<Optional> *resources;

@end


text:
define('ember-data/-private/system/record-arrays/filtered-record-array', ['exports', 'ember', 'ember-data/-private/system/record-arrays/record-array'], function (exports, _ember, _emberDataPrivateSystemRecordArraysRecordArray) {
  'use strict';

  /**
    @module ember-data
  */

  var get = _ember['default'].get;

  /**
    Represents a list of records whose membership is determined by the
    store. As records are created, loaded, or modified, the store
    evaluates them to determine if they should be part of the record
    array.

    @class FilteredRecordArray
    @namespace DS
    @extends DS.RecordArray
  */
  exports['default'] = _emberDataPrivateSystemRecordArraysRecordArray['default'].extend({
    init: function init() {
      this._super.apply(this, arguments);

      this.set('filterFunction', this.get('filterFunction') || null);
      this.isLoaded = true;
    },
    /**
      The filterFunction is a function used to test records from the store to
      determine if they should be part of the record array.
       Example
       ```javascript
      var allPeople = store.peekAll('person');
      allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"]
       var people = store.filter('person', function(person) {
        if (person.get('name').match(/Katz$/)) { return true; }
      });
      people.mapBy('name'); // ["Yehuda Katz"]
       var notKatzFilter = function(person) {
        return !person.get('name').match(/Katz$/);
      };
      people.set('filterFunction', notKatzFilter);
      people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"]
      ```
       @method filterFunction
      @param {DS.Model} record
      @return {Boolean} `true` if the record should be in the array
    */

    replace: function replace() {
      var type = get(this, 'type').toString();
      throw new Error('The result of a client-side filter (on ' + type + ') is immutable.');
    },

    /**
      @method updateFilter
      @private
    */
    _updateFilter: function _updateFilter() {
      if (get(this, 'isDestroying') || get(this, 'isDestroyed')) {
        return;
      }
      get(this, 'manager').updateFilter(this, get(this, 'type'), get(this, 'filterFunction'));
    },

    updateFilter: _ember['default'].observer('filterFunction', function () {
      _ember['default'].run.once(this, this._updateFilter);
    })
  });
});


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="raw" name="Export raw">
    <property environment="env"/>
    <property name="ECLIPSE_HOME" value="../../../../Program Files/eclipse"/>
    <property name="debuglevel" value="source,lines,vars"/>
    <property name="target" value="1.6"/>
    <property name="source" value="1.6"/>
    <target name="raw">
        <copy todir="./res/raw" overwrite="true">
            <fileset dir="./res/layout">
                <include name="*.xml"/>
            </fileset>
        </copy>
        <copy todir="./res/raw" overwrite="true">
            <fileset dir="./res/xml">
                <include name="*.xml"/>
            </fileset>
        </copy>
        <copy todir="./res/raw" overwrite="true">
            <fileset dir="./src">
                <include name="**/viewModels/*.java"/>
            </fileset>
            <chainedmapper>
            	<mapper type="flatten"/>
            	<scriptmapper language="javascript">
            	    var str = source.substring(0, source.indexOf(".java"));
            	    self.addMappedName(str.toLowerCase() + "_code");
            	</scriptmapper>
            </chainedmapper>
        </copy>
    </target>
</project>