text:
package net.java.sip.communicator.impl.protocol.jabber;

import java.beans.*;
import java.util.*;
import java.util.regex.*;

import net.java.sip.communicator.service.argdelegation.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;

import org.osgi.framework.*;

/**
 * The jabber implementation of the URI handler. This class handles xmpp URIs by
 * trying to establish a chat with them or add you to a chatroom.
 *
 * @author Emil Ivov
 * @author Damian Minkov
 */
public class UriHandlerJabberImpl
    implements UriHandler, ServiceListener, AccountManagerListener
{
    /**
     * The logger of this class.
     */
    private static final Logger logger =
        Logger.getLogger(UriHandlerJabberImpl.class);

    /**
     * The protocol provider factory that created us.
     */
    private final ProtocolProviderFactory protoFactory;

    /**
     * A reference to the OSGi registration we create with this handler.
     */
    private ServiceRegistration ourServiceRegistration = null;

    /**
     * The object that we are using to synchronize our service registration.
     */
    private final Object registrationLock = new Object();

    /**
     * The AccountManager which loads the stored accounts of
     * {@link #protoFactory} and to be monitored when the mentioned loading is
     * complete so that any pending {@link #uris} can be handled
     */
    private AccountManager accountManager;

    /**
     * The indicator (and its synchronization lock) which determines whether the
     * stored accounts of {@link #protoFactory} have already been loaded.
     *

     * Before the loading of the stored accounts (even if there're none) of the
     * protoFactory is complete, no handling of URIs is to be
     * performed because there's neither information which account to handle the
     * URI in case there're stored accounts available nor ground for warning the
     * user a registered account is necessary to handle URIs at all in case
     * there're no stored accounts.
     *

     */
    private final boolean[] storedAccountsAreLoaded = new boolean[1];

    /**
     * The list of URIs which have received requests for handling before the
     * stored accounts of the {@link #protoFactory} have been loaded. They will
     * be handled as soon as the mentioned loading completes.
     */
    private List<String> uris;

    /**
     * Marks network fails in order to avoid endless loops.
     */
    private boolean networkFailReceived = false;

    /**
     * Creates an instance of this uri handler, so that it would start handling
     * URIs by passing them to the providers registered by <tt>protoFactory</tt>
     * .
     *
     * @param protoFactory the provider that created us.
     *
     * @throws NullPointerException if <tt>protoFactory</tt> is <tt>null</tt>.
     */
    public UriHandlerJabberImpl(ProtocolProviderFactory protoFactory)
        throws NullPointerException
    {
        if (protoFactory == null)
        {
            throw new NullPointerException(
                "The ProtocolProviderFactory that a UriHandler is created with "
                    + " cannot be null.");
        }

        this.protoFactory = protoFactory;

        hookStoredAccounts();

        this.protoFactory.getBundleContext().addServiceListener(this);
        /*
         * Registering the UriHandler isn't strictly necessary if the
         * requirement to register the protoFactory after creating this instance
         * is met.
         */
        registerHandlerService();
    }

    /**
     * Disposes of this UriHandler by, for example, removing the
     * listeners it has added in its constructor (in order to prevent memory
     * leaks, for one).
     */
    public void dispose()
    {
        protoFactory.getBundleContext().removeServiceListener(this);
        unregisterHandlerService();

        unhookStoredAccounts();
    }

    /**
     * Sets up (if not set up already) listening for the loading of the stored
     * accounts of {@link #protoFactory} in order to make it possible to
     * discover when the prerequisites for handling URIs are met.
     */
    private void hookStoredAccounts()
    {
        if (accountManager == null)
        {
            BundleContext bundleContext = protoFactory.getBundleContext();

            accountManager =
                (AccountManager) bundleContext.getService(bundleContext
                    .getServiceReference(AccountManager.class.getName()));
            accountManager.addListener(this);
        }
    }

    /**
     * Reverts (if not reverted already) the setup performed by a previous chat
     * to {@link #hookStoredAccounts()}.
     */
    private void unhookStoredAccounts()
    {
        if (accountManager != null)
        {
            accountManager.removeListener(this);
            accountManager = null;
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * net.java.sip.communicator.service.protocol.event.AccountManagerListener
     * #handleAccountManagerEvent
     * (net.java.sip.communicator.service.protocol.event.AccountManagerEvent)
     */
    public void handleAccountManagerEvent(AccountManagerEvent event)
    {

        /*
         * When the loading of the stored accounts of protoFactory is complete,
         * the prerequisites for handling URIs have been met so it's time to
         * load any handling requests which have come before the loading and
         * were thus delayed in uris.
         */
        if ((AccountManagerEvent.STORED_ACCOUNTS_LOADED == event.getType())
            && (protoFactory == event.getFactory()))
        {
            List<String> uris = null;

            synchronized (storedAccountsAreLoaded)
            {
                storedAccountsAreLoaded[0] = true;

                if (this.uris != null)
                {
                    uris = this.uris;
                    this.uris = null;
                }
            }

            unhookStoredAccounts();

            if (uris != null)
            {
                for (Iterator<String> uriIter = uris.iterator(); uriIter
                    .hasNext();)
                {
                    handleUri(uriIter.next());
                }
            }
        }
    }

    /**
     * Registers this UriHandler with the bundle context so that it could start
     * handling URIs
     */
    public void registerHandlerService()
    {
        synchronized (registrationLock)
        {
            if (ourServiceRegistration != null)
            {
                // ... we are already registered (this is probably
                // happening during startup)
                return;
            }

            Hashtable<String, String> registrationProperties =
                new Hashtable<String, String>();

            for (String protocol : getProtocol())
            {
                registrationProperties.put(UriHandler.PROTOCOL_PROPERTY,
                    protocol);
            }

            ourServiceRegistration =
                JabberActivator.bundleContext.registerService(UriHandler.class
                    .getName(), this, registrationProperties);
        }

    }

    /**
     * Unregisters this UriHandler from the bundle context.
     */
    public void unregisterHandlerService()
    {
        synchronized (registrationLock)
        {
            if (ourServiceRegistration != null)
            {
                ourServiceRegistration.unregister();
                ourServiceRegistration = null;
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String[] getProtocol()
    {
        return new String[]
        { "xmpp" };
    }

    /**
     * Parses the specified URI and creates a chat with the currently active
     * im operation set.
     *
     * @param uri the xmpp URI that we have to handle.
     */
    public void handleUri(String uri)
    {
        /*
         * TODO If the requirement to register the factory service after
         * creating this instance is broken, we'll end up not handling the URIs.
         */
        synchronized (storedAccountsAreLoaded)
        {
            if (!storedAccountsAreLoaded[0])
            {
                if (uris == null)
                {
                    uris = new LinkedList<String>();
                }
                uris.add(uri);
                return;
            }
        }

        ProtocolProviderService provider;
        try
        {
            provider = selectHandlingProvider(uri);
        }
        catch (OperationFailedException exc)
        {
            // The operation has been canceled by the user. Bail out.
            if (logger.isTraceEnabled())
                logger.trace("User canceled handling of uri " + uri);
            return;
        }

        // if provider is null then we need to tell the user to create an
        // account
        if (provider == null)
        {
            showErrorMessage(
                "You need to configure at least one XMPP account \n"
                    + "to be able to call " + uri, null);
            return;
        }

        if(!uri.contains("?"))
        {
            OperationSetPersistentPresence presenceOpSet
                = provider
                    .getOperationSet(OperationSetPersistentPresence.class);

            String contactId = uri.substring(uri.indexOf(':') + 1);

            //todo check url!!
            //Set the email pattern string
            Pattern p = Pattern.compile(".+@.+");
            if(!p.matcher(contactId).matches())
            {
                showErrorMessage(
                "Wrong contact id : " + uri, null);
                return;
            }

            Contact contact = presenceOpSet.findContactByID(contactId);
            if(contact == null)
            {
                Object result =
                    JabberActivator.getUIService().getPopupDialog()
                            .showConfirmPopupDialog(
                                    "Do you want to add the contact : "
                                        + contactId + " ?",
                                    "Add contact",
                                    PopupDialog.YES_NO_OPTION);

                if(result.equals(PopupDialog.YES_OPTION))
                {
                    ExportedWindow ex = JabberActivator.getUIService().
                            getExportedWindow(ExportedWindow.ADD_CONTACT_WINDOW,
                                new String[]{contactId});
                    ex.setVisible(true);
                }

                return;
            }

            JabberActivator.getUIService().
                    getChat(contact).setChatVisible(true);
        }
        else
        {
            String croom = uri.replaceFirst(getProtocol() + ":", "");
            int ix = croom.indexOf("?");
            String param = croom.substring(ix + 1, croom.length());
            croom = croom.substring(0, ix);

            if(param.equalsIgnoreCase("join"))
            {
                OperationSetMultiUserChat mchatOpSet
                    = provider
                        .getOperationSet(OperationSetMultiUserChat.class);

                try
                {
                    ChatRoom room = mchatOpSet.findRoom(croom);

                    if(room != null)
                    {
                        room.join();
                    }
                }
                catch (OperationFailedException exc)
                {
                    // if we are not online we get this error
                    // will wait for it and then will try to handle once again
                    if((exc.getErrorCode()
                                == OperationFailedException.NETWORK_FAILURE)
                            && !networkFailReceived)
                    {
                        networkFailReceived = true;
                        OperationSetPresence presenceOpSet
                            = provider
                                .getOperationSet(OperationSetPresence.class);
                        presenceOpSet.addProviderPresenceStatusListener(
                                new ProviderStatusListener(uri, presenceOpSet));
                    }
                    else
                        showErrorMessage("Error joining to  " + croom, exc);
                }
                catch (OperationNotSupportedException exc)
                {
                    showErrorMessage(
                            "Join to " + croom + ", not supported!",
                            exc);
                }
            }
            else
                showErrorMessage(
                "Unknown param : " + param, null);
        }
    }

    /**
     * The point of implementing a service listener here is so that we would
     * only register our own uri handling service and thus only handle URIs
     * while the factory is available as an OSGi service. We remove ourselves
     * when our factory unregisters its service reference.
     *
     * @param event the OSGi <tt>ServiceEvent</tt>
     */
    public void serviceChanged(ServiceEvent event)
    {
        Object sourceService =
            JabberActivator.bundleContext.
                getService(event.getServiceReference());

        // ignore anything but our protocol factory.
        if (sourceService != protoFactory)
        {
            return;
        }

        switch (event.getType())
        {
            case ServiceEvent.REGISTERED:
                // our factory has just been registered as a service ...
                registerHandlerService();
                break;
            case ServiceEvent.UNREGISTERING:
                // our factory just died - seppuku.
                unregisterHandlerService();
                break;
            default:
                // we don't care.
                break;
        }
    }

    /**
     * Uses the <tt>UIService</tt> to show an error <tt>message</tt> and log and
     * <tt>exception</tt>.
     *
     * @param message the message that we'd like to show to the user.
     * @param exc the exception that we'd like to log
     */
    private void showErrorMessage(String message, Exception exc)
    {
        JabberActivator.getUIService().getPopupDialog().showMessagePopupDialog(
            message, "Failed to create chat!", PopupDialog.ERROR_MESSAGE);
        logger.error(message, exc);
    }

    /**
     * Returns the default provider that we are supposed to handle URIs through
     * or null if there aren't any. Depending on the implementation this method
     * may require user intervention so make sure you don't rely on a quick
     * outcome when chatting it.
     *
     * @param uri the uri that we'd like to handle with the provider that we are
     *            about to select.
     *
     * @return the provider that we should handle URIs through.
     *
     * @throws OperationFailedException with code <tt>OPERATION_CANCELED</tt> if
     *             the users.
     */
    public ProtocolProviderService selectHandlingProvider(String uri)
        throws OperationFailedException
    {
        ArrayList<AccountID> registeredAccounts =
            protoFactory.getRegisteredAccounts();

        // if we don't have any providers - return null.
        if (registeredAccounts.size() == 0)
        {
            return null;
        }

        // if we only have one provider - select it
        if (registeredAccounts.size() == 1)
        {
            ServiceReference<?> providerReference =
                protoFactory.getProviderForAccount(registeredAccounts.get(0));

            ProtocolProviderService provider =
                (ProtocolProviderService) JabberActivator.bundleContext
                    .getService(providerReference);

            return provider;
        }

        // otherwise - ask the user.
        ArrayList<ProviderComboBoxEntry> providers =
            new ArrayList<ProviderComboBoxEntry>();
        for (AccountID accountID : registeredAccounts)
        {
            ServiceReference<?> providerReference =
                protoFactory.getProviderForAccount(accountID);

            ProtocolProviderService provider =
                (ProtocolProviderService) JabberActivator.bundleContext
                    .getService(providerReference);

            providers.add(new ProviderComboBoxEntry(provider));
        }

        Object result
            = JabberActivator.getUIService().getPopupDialog()
                    .showInputPopupDialog(
                            "Please select the account that you would like \n"
                                + "to use to chat with " + uri,
                            "Account Selection",
                            PopupDialog.OK_CANCEL_OPTION,
                            providers.toArray(),
                            providers.get(0));

        if (result == null)
        {
            throw new OperationFailedException("Operation cancelled",
                OperationFailedException.OPERATION_CANCELED);
        }

        return ((ProviderComboBoxEntry) result).provider;
    }

    /**
     * A class that we use to wrap providers before showing them to the user
     * through a selection popup dialog from the UIService.
     */
    private static class ProviderComboBoxEntry
    {
        public final ProtocolProviderService provider;

        public ProviderComboBoxEntry(ProtocolProviderService provider)
        {
            this.provider = provider;
        }

        /**
         * Returns a human readable <tt>String</tt> representing the provider
         * encapsulated by this class.
         *
         * @return a human readable string representing the provider.
         */
        @Override
        public String toString()
        {
            return provider.getAccountID().getAccountAddress();
        }
    }

    /**
     * Waiting for the provider to become online and then handle the uri.
     */
    private class ProviderStatusListener
        implements ProviderPresenceStatusListener
    {
        private final String uri;
        private final OperationSetPresence parentOpSet;

        public ProviderStatusListener(
                String uri,
                OperationSetPresence parentOpSet)
        {
            this.uri = uri;
            this.parentOpSet = parentOpSet;
        }

        public void providerStatusChanged(ProviderPresenceStatusChangeEvent ev)
        {
            if(ev.getNewStatus().isOnline())
            {
                parentOpSet.removeProviderPresenceStatusListener(this);
                handleUri(uri);
            }
        }

        public void providerStatusMessageChanged(PropertyChangeEvent ev) {}
    }
}


text:
title: How to Change PageViewMode for the Nested Levels in RadGridView
description: Learn how to change the PageViewMode for the nested levels in RadGridView.
type: how-to
page_title: How to Change PageViewMode for the Nested Levels in RadGridView
slug: pageview-mode-in-nested-gridview-levels
position: 5
tags: grid, nested, hierarchy
ticketid: 1500326
res_type: kb
---

## Environment
|Product Version|Product|Author|
|----|----|----|
|2021.2.615|RadGridView|[Desislava Yordanova](https://www.telerik.com/blogs/author/desislava-yordanova)|

## Description

The hierarchy in **RadGridView** consists of a parent and a child template and a relation between them (e.g. linking parent's ID with a ParentID field in the child template). Hence, for the parent level you need to have any rows which will display the expander ("+") according to the child records the parent has.

When you add two or more child templates at the same level, they are displayed in tabbed view by default:

![pageview-mode-in-nested-gridview-levels 001](images/pageview-mode-in-nested-gridview-levels001.png)

**RadGridView** internally uses a page view element for displaying the child templates. The TableElement.**PageViewMode** property gives you control over the page view mode used in child views, e.g. *Strip*, *Stack*, *Outlook*, *ExplorerBar*.

![pageview-mode-in-nested-gridview-levels 002](images/pageview-mode-in-nested-gridview-levels002.png)

Since **RadGridView** creates its **TableElements** for the child levels on demand, you don't have access to the n-level **TableElements** until you expand a n-1 parent row. That is why the **PageViewMode** changes the mode only for the first hierarchical level. The inner hierarchical levels have the default strip mode:

![pageview-mode-in-nested-gridview-levels 003](images/pageview-mode-in-nested-gridview-levels003.png)

This article demonstrates a sample approach how to change the **PageViewMode** for the inner levels as well.

## Solution

It is necessary to create a derivative of the **GridDetailViewCellElement** class and override its **CreatePageViewProvider** method. Then, return the desired **IRadPageViewProvider**, e.g. **RadPageViewExplorerBarProvider**.

````C#

public RadForm1()
{
    InitializeComponent();

    this.radGridView1.CreateCell += RadGridView1_CreateCell;

    Random rand = new Random();
    DataTable dt1 = new DataTable();
    dt1.Columns.Add("Id", typeof(int));
    dt1.Columns.Add("Name", typeof(string));
    dt1.Columns.Add("IsActive", typeof(bool));
    for (int i = 0; i < 5; i++)
    {
        dt1.Rows.Add(i, "Row" + i);
    }

    this.radGridView1.MasterTemplate.DataSource = dt1;
    this.radGridView1.MasterTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;

    //level 1-1

    DataTable dt2 = new DataTable();
    dt2.Columns.Add("Id", typeof(int));
    dt2.Columns.Add("ParentId", typeof(int));
    dt2.Columns.Add("Name", typeof(string));
    dt2.Columns.Add("IsActive", typeof(bool));
    for (int i = 0; i < 20; i++)
    {
        dt2.Rows.Add(i, rand.Next(0, 5), "Row" + i);
    }

    GridViewTemplate template = new GridViewTemplate();
    template.Caption = "Child 1-1";
    template.DataSource = dt2;
    template.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
    radGridView1.MasterTemplate.Templates.Add(template);

    GridViewRelation relation = new GridViewRelation(radGridView1.MasterTemplate);
    relation.ChildTemplate = template;
    relation.RelationName = "Relation1";
    relation.ParentColumnNames.Add("Id");
    relation.ChildColumnNames.Add("ParentId");
    radGridView1.Relations.Add(relation);

    //level 1-2

    DataTable dt3 = new DataTable();
    dt3.Columns.Add("Id", typeof(int));
    dt3.Columns.Add("ParentId", typeof(int));
    dt3.Columns.Add("Name", typeof(string));
    for (int i = 0; i < 20; i++)
    {
        dt3.Rows.Add(i, rand.Next(0, 5), "Row" + i);
    }

    GridViewTemplate template2 = new GridViewTemplate();
    template2.Caption = "Child 1-2";
    template2.DataSource = dt3;
    template2.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
    radGridView1.MasterTemplate.Templates.Add(template2);

    GridViewRelation relation2 = new GridViewRelation(radGridView1.MasterTemplate);
    relation2.ChildTemplate = template2;
    relation2.RelationName = "Relation2";
    relation2.ParentColumnNames.Add("Id");
    relation2.ChildColumnNames.Add("ParentId");
    radGridView1.Relations.Add(relation2);

    this.radGridView1.TableElement.PageViewMode = PageViewMode.ExplorerBar;

    //level 2-1

    DataTable dt4 = new DataTable();
    dt4.Columns.Add("Id", typeof(int));
    dt4.Columns.Add("ParentId", typeof(int));
    dt4.Columns.Add("Name", typeof(string));
    for (int i = 0; i < 20; i++)
    {
        dt4.Rows.Add(i, rand.Next(0, 20), "Row" + i);
    }

    GridViewTemplate template3 = new GridViewTemplate();
    template3.Caption = "Child 2-1";
    template3.DataSource = dt4;
    template3.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
    template.Templates.Add(template3);

    GridViewRelation relation3 = new GridViewRelation(template);
    relation3.ChildTemplate = template3;
    relation3.RelationName = "Relation3";
    relation3.ParentColumnNames.Add("Id");
    relation3.ChildColumnNames.Add("ParentId");
    radGridView1.Relations.Add(relation3);

    //level 2-2

    DataTable dt5 = new DataTable();
    dt5.Columns.Add("Id", typeof(int));
    dt5.Columns.Add("ParentId", typeof(int));
    dt5.Columns.Add("Name", typeof(string));
    for (int i = 0; i < 20; i++)
    {
        dt5.Rows.Add(i, rand.Next(0, 20), "Row" + i);
    }

    GridViewTemplate template4 = new GridViewTemplate();
    template4.Caption = "Child 2-2";
    template4.DataSource = dt3;
    template4.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
    template.Templates.Add(template4);

    GridViewRelation relation4 = new GridViewRelation(template);
    relation4.ChildTemplate = template4;
    relation4.RelationName = "Relation4";
    relation4.ParentColumnNames.Add("Id");
    relation4.ChildColumnNames.Add("ParentId");
    radGridView1.Relations.Add(relation4);

}

private void RadGridView1_CreateCell(object sender, GridViewCreateCellEventArgs e)
{
    if (e.CellType == typeof(GridDetailViewCellElement))
    {
         e.CellElement = new CustomGridDetailViewCellElement(e.Column, e.Row);
    }
}
public class CustomGridDetailViewCellElement : GridDetailViewCellElement
{
    public CustomGridDetailViewCellElement(GridViewColumn column, GridRowElement row) : base(column, row)
    {
    }
    protected override Type ThemeEffectiveType
    {
        get
        {
            return typeof(GridDetailViewCellElement);
        }
    }

    protected override IRadPageViewProvider CreatePageViewProvider()
    {
        IRadPageViewProvider provider = base.CreatePageViewProvider();
        provider = new RadPageViewExplorerBarProvider();
        return provider;
    }
}

````
````VB.NET

 Public Sub New()
    InitializeComponent()
    AddHandler Me.RadGridView1.CreateCell, AddressOf RadGridView1_CreateCell
    Dim rand As Random = New Random()
    Dim dt1 As DataTable = New DataTable()
    dt1.Columns.Add("Id", GetType(Integer))
    dt1.Columns.Add("Name", GetType(String))
    dt1.Columns.Add("IsActive", GetType(Boolean))

    For i As Integer = 0 To 5 - 1
        dt1.Rows.Add(i, "Row" & i)
    Next

    Me.RadGridView1.MasterTemplate.DataSource = dt1
    Me.RadGridView1.MasterTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill
    Dim dt2 As DataTable = New DataTable()
    dt2.Columns.Add("Id", GetType(Integer))
    dt2.Columns.Add("ParentId", GetType(Integer))
    dt2.Columns.Add("Name", GetType(String))
    dt2.Columns.Add("IsActive", GetType(Boolean))

    For i As Integer = 0 To 20 - 1
        dt2.Rows.Add(i, rand.[Next](0, 5), "Row" & i)
    Next

    Dim template As GridViewTemplate = New GridViewTemplate()
    template.Caption = "Child 1-1"
    template.DataSource = dt2
    template.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill
    RadGridView1.MasterTemplate.Templates.Add(template)
    Dim relation As GridViewRelation = New GridViewRelation(RadGridView1.MasterTemplate)
    relation.ChildTemplate = template
    relation.RelationName = "Relation1"
    relation.ParentColumnNames.Add("Id")
    relation.ChildColumnNames.Add("ParentId")
    RadGridView1.Relations.Add(relation)
    Dim dt3 As DataTable = New DataTable()
    dt3.Columns.Add("Id", GetType(Integer))
    dt3.Columns.Add("ParentId", GetType(Integer))
    dt3.Columns.Add("Name", GetType(String))

    For i As Integer = 0 To 20 - 1
        dt3.Rows.Add(i, rand.[Next](0, 5), "Row" & i)
    Next

    Dim template2 As GridViewTemplate = New GridViewTemplate()
    template2.Caption = "Child 1-2"
    template2.DataSource = dt3
    template2.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill
    RadGridView1.MasterTemplate.Templates.Add(template2)
    Dim relation2 As GridViewRelation = New GridViewRelation(RadGridView1.MasterTemplate)
    relation2.ChildTemplate = template2
    relation2.RelationName = "Relation2"
    relation2.ParentColumnNames.Add("Id")
    relation2.ChildColumnNames.Add("ParentId")
    RadGridView1.Relations.Add(relation2)
    Me.RadGridView1.TableElement.PageViewMode = PageViewMode.ExplorerBar
    Dim dt4 As DataTable = New DataTable()
    dt4.Columns.Add("Id", GetType(Integer))
    dt4.Columns.Add("ParentId", GetType(Integer))
    dt4.Columns.Add("Name", GetType(String))

    For i As Integer = 0 To 20 - 1
        dt4.Rows.Add(i, rand.[Next](0, 20), "Row" & i)
    Next

    Dim template3 As GridViewTemplate = New GridViewTemplate()
    template3.Caption = "Child 2-1"
    template3.DataSource = dt4
    template3.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill
    template.Templates.Add(template3)
    Dim relation3 As GridViewRelation = New GridViewRelation(template)
    relation3.ChildTemplate = template3
    relation3.RelationName = "Relation3"
    relation3.ParentColumnNames.Add("Id")
    relation3.ChildColumnNames.Add("ParentId")
    RadGridView1.Relations.Add(relation3)
    Dim dt5 As DataTable = New DataTable()
    dt5.Columns.Add("Id", GetType(Integer))
    dt5.Columns.Add("ParentId", GetType(Integer))
    dt5.Columns.Add("Name", GetType(String))

    For i As Integer = 0 To 20 - 1
        dt5.Rows.Add(i, rand.[Next](0, 20), "Row" & i)
    Next

    Dim template4 As GridViewTemplate = New GridViewTemplate()
    template4.Caption = "Child 2-2"
    template4.DataSource = dt3
    template4.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill
    template.Templates.Add(template4)
    Dim relation4 As GridViewRelation = New GridViewRelation(template)
    relation4.ChildTemplate = template4
    relation4.RelationName = "Relation4"
    relation4.ParentColumnNames.Add("Id")
    relation4.ChildColumnNames.Add("ParentId")
    RadGridView1.Relations.Add(relation4)
End Sub

Private Sub RadGridView1_CreateCell(ByVal sender As Object, ByVal e As GridViewCreateCellEventArgs)
    If e.CellType = GetType(GridDetailViewCellElement) Then
        e.CellElement = New CustomGridDetailViewCellElement(e.Column, e.Row)
    End If
End Sub

Public Class CustomGridDetailViewCellElement
Inherits GridDetailViewCellElement

    Public Sub New(ByVal column As GridViewColumn, ByVal row As GridRowElement)
        MyBase.New(column, row)
    End Sub

    Protected Overrides ReadOnly Property ThemeEffectiveType As Type
        Get
            Return GetType(GridDetailViewCellElement)
        End Get
    End Property

    Protected Overrides Function CreatePageViewProvider() As IRadPageViewProvider
        Dim provider As IRadPageViewProvider = MyBase.CreatePageViewProvider()
        provider = New RadPageViewExplorerBarProvider()
        Return provider
    End Function
End Class

````

# See Also

* [Binding to Hierarchical Data Programmatically]({%slug winforms/barcode/overview%})
* [Creating Custom Cells]({%slug winforms/gridview/hierarchical-grid/binding-to-hierarchical-data-programmatically%})

redpajama_set_name: RedPajamaGithub


text:
package com.example.me.notificationsample;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class ResultActivity extends AppCompatActivity {
    private int noID=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        Button bt1=(Button)findViewById(R.id.bt1);
        Button bt2=(Button)findViewById(R.id.bt2);
        Button bt3=(Button)findViewById(R.id.bt3);
        bt1.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(ResultActivity.this)
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setContentTitle("My notification")
                                .setContentText("Hello World!")
                                .setNumber(noID++);
                // Creates an explicit intent for an Activity in your app
                Intent resultIntent = new Intent(ResultActivity.this, MainActivity.class);

                // The stack builder object will contain an artificial back stack for the
                // started Activity.
                // This ensures that navigating backward from the Activity leads out of
                // your application to the Home screen.
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(ResultActivity.this);
                // Adds the back stack for the Intent (but not the Intent itself)
                stackBuilder.addParentStack(ResultActivity.class);
                // Adds the Intent that starts the Activity to the top of the stack
                stackBuilder.addNextIntent(resultIntent);
                PendingIntent resultPendingIntent =
                        stackBuilder.getPendingIntent(
                                0,
                                PendingIntent.FLAG_UPDATE_CURRENT
                        );
                mBuilder.setContentIntent(resultPendingIntent);

                NotificationCompat.InboxStyle inboxStyle =
                        new NotificationCompat.InboxStyle();
                String[] events = new String[6];
                // Sets a title for the Inbox style big view
                inboxStyle.setBigContentTitle("Event tracker details:");
                // Moves events into the big view
                for (int i=0; i < events.length; i++) {
                    events[i]="rrrrrrrr";
                    inboxStyle.addLine(events[i]);
                }
                // Moves the big view style object into the notification object.
                mBuilder.setStyle(inboxStyle);

                NotificationManager mNotificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                // mId allows you to update the notification later on.
                mNotificationManager.notify(noID, mBuilder.build());
            }

        });

        bt2.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                final NotificationManager mNotifyManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ResultActivity.this);
                mBuilder.setContentTitle("Picture Download")
                        .setContentText("Download in progress")
                        .setSmallIcon(R.mipmap.ic_launcher);
                // Start a lengthy operation in a background thread
                new Thread(
                        new Runnable() {
                            @Override
                            public void run() {
                                int incr;
                                // Do the "lengthy" operation 20 times
                                for (incr = 0; incr <= 100; incr+=5) {
                                    // Sets the progress indicator to a max value, the
                                    // current completion percentage, and "determinate"
                                    // state
                                    mBuilder.setProgress(100, incr, false);
                                    // Displays the progress bar for the first time.
                                    mNotifyManager.notify(0, mBuilder.build());
                                    // Sleeps the thread, simulating an operation
                                    // that takes time
                                    try {
                                        // Sleep for 5 seconds
                                        Thread.sleep(1*1000);
                                    } catch (InterruptedException e) {
                                        Log.d("MainActivity", "sleep failure");
                                    }
                                }
                                // When the loop is finished, updates the notification
                                mBuilder.setContentText("Download complete")
                                        // Removes the progress bar
                                        .setProgress(0,0,false);
                                mNotifyManager.notify(noID++, mBuilder.build());
                            }
                        }
                        // Starts the thread by calling the run() method in its Runnable
                ).start();
            }

        });

        bt3.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                final NotificationManager mNotifyManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ResultActivity.this);
                mBuilder.setContentTitle("Picture Download")
                        .setContentText("Download in progress")
                        .setSmallIcon(R.mipmap.ic_launcher);
                // Start a lengthy operation in a background thread
                new Thread(
                        new Runnable() {
                            @Override
                            public void run() {
                                int incr;
                                // Do the "lengthy" operation 20 times
                                for (incr = 0; incr <= 100; incr+=5) {
                                    // Sets the progress indicator to a max value, the
                                    // current completion percentage, and "determinate"
                                    // state
                                    mBuilder.setProgress(0, 0, true);
                                    // Displays the progress bar for the first time.
                                    mNotifyManager.notify(0, mBuilder.build());
                                    // Sleeps the thread, simulating an operation
                                    // that takes time
                                    try {
                                        // Sleep for 5 seconds
                                        Thread.sleep(1*100);
                                    } catch (InterruptedException e) {
                                        Log.d("MainActivity", "sleep failure");
                                    }
                                }
                                // When the loop is finished, updates the notification
                                mBuilder.setContentText("Download complete")
                                        // Removes the progress bar
                                        .setProgress(0,0,false);
                                mNotifyManager.notify(noID++, mBuilder.build());
                            }
                        }
                        // Starts the thread by calling the run() method in its Runnable
                ).start();
            }

        });
    }
}


text:
package worms.gui.game.commands;

import worms.gui.GUIConstants;
import worms.gui.game.PlayGameScreen;
import worms.gui.game.sprites.WormSprite;
import worms.gui.messages.MessageType;
import worms.model.IFacade;
import worms.model.ModelException;
import worms.model.Worm;

public class Move extends Command {

	private double startX;
	private double startY;

	private double finalX;
	private double finalY;

	private boolean isFalling;
	private double fallingStartTime = -1;

	private final Worm worm;

	public Move(IFacade facade, Worm worm, PlayGameScreen screen) {
		super(facade, screen);
		this.worm = worm;
	}

	public Worm getWorm() {
		return worm;
	}

	@Override
	protected boolean canStart() {
		return getWorm() != null && getFacade().canMove(getWorm());
	}

	private double getDuration() {
		return GUIConstants.MOVE_DURATION;
	}

	protected boolean canFall() {
		return getFacade().canFall(getWorm());
	}

	@Override
	protected void doUpdate(double dt) {
		WormSprite sprite = getScreen().getWormSprite(getWorm());
		if (sprite != null) {
			sprite.setIsMoving(true);
			if (getElapsedTime() < getDuration()) {
				double t = getElapsedTime() / getDuration();
				t = t * t * (3 - 2 * t); // smooth-step interpolation
				double x = (1.0 - t) * startX + t * finalX;
				double y = (1.0 - t) * startY + t * finalY;
				sprite.setCenterLocation(x, y);
			} else {
				fall(dt);
			}
		} else {
			cancelExecution();
		}
	}

	protected boolean isFalling() {
		return isFalling;
	}

	protected void ensureFalling() {
		if (fallingStartTime == -1) {
			fallingStartTime = getElapsedTime();
		}
		isFalling = true;
	}

	protected void fall(double dt) {
		if (!isFalling) {
			startFalling();
		} else {
			updateFalling();
		}
	}

	protected void updateFalling() {
		WormSprite sprite = getScreen().getWormSprite(worm);
		if (sprite != null) {
			double duration = getScreen().screenToWorldDistance(
					Math.abs(finalY - startY))
					/ GUIConstants.FALL_VELOCITY;
			double timeElapsedFalling = getElapsedTime() - fallingStartTime;
			if (timeElapsedFalling <= duration) {
				double t = timeElapsedFalling / duration;
				t = t * t;
				double x = (1.0 - t) * startX + t * finalX;
				double y = (1.0 - t) * startY + t * finalY;
				sprite.setCenterLocation(x, y);
			} else {
				sprite.setCenterLocation(finalX, finalY);
				completeExecution();
			}
		} else {
			cancelExecution();
		}
	}

	protected void startFalling() {
		this.startX = getScreen().getScreenX(getObjectX());
		this.startY = getScreen().getScreenY(getObjectY());

		if (canFall()) {
			ensureFalling();
			getFacade().fall(getWorm());
			if (isObjectStillActive()) {
				this.finalX = getScreen().getScreenX(getObjectX());
				this.finalY = getScreen().getScreenY(getObjectY());
			} else {
				this.finalX = startX;
				try {
					this.finalY = getScreen().getScreenY(getObjectY());
				} catch (ModelException e) {
					this.finalY = getScreen().getScreenY(0);
				}
			}
		} else {
			completeExecution();
		}
		WormSprite sprite = getScreen().getWormSprite(worm);
		if (sprite != null) {
			sprite.setCenterLocation(startX, startY);
		} else {
			cancelExecution();
		}
	}

	@Override
	protected void afterExecutionCompleted() {
		WormSprite sprite = getScreen().getWormSprite(getWorm());
		if (sprite != null) {
			sprite.setIsMoving(false);
		}
	}

	@Override
	protected void afterExecutionCancelled() {
		WormSprite sprite = getScreen().getWormSprite(getWorm());
		if (sprite != null) {
			sprite.setIsMoving(false);
		}
		getScreen().addMessage("This worm cannot move like that :(",
				MessageType.ERROR);
	}

	@Override
	protected void doStartExecution() {
		try {
			this.startX = getScreen().getScreenX(getFacade().getX(getWorm()));
			this.startY = getScreen().getScreenY(getFacade().getY(getWorm()));
			getFacade().move(getWorm());
			this.finalX = getScreen().getScreenX(getFacade().getX(getWorm()));
			this.finalY = getScreen().getScreenY(getFacade().getY(getWorm()));
		} catch (ModelException e) {
			e.printStackTrace();
			cancelExecution();
		}
	}

	protected boolean isObjectStillActive() {
		return getFacade().isAlive(getWorm());
	}

	protected double getObjectX() {
		return getFacade().getX(getWorm());
	}

	protected double getObjectY() {
		return getFacade().getY(getWorm());
	}
}


text:
package com.simplifiedlogic.nitro.jlink.calls.simprep;

import com.ptc.cipjava.jxthrowable;
import com.ptc.pfc.pfcSimpRep.SimpRepAction;
import com.ptc.pfc.pfcSimpRep.SimpRepSubstitute;
import com.ptc.pfc.pfcSimpRep.Substitution;
import com.simplifiedlogic.nitro.jlink.impl.NitroConstants;
import com.simplifiedlogic.nitro.jlink.intf.DebugLogging;

/**
 * Wrapper for JLink's com.ptc.pfc.pfcSimpRep.SimpRepSubstitute
 *
 * @author Adam Andrews
 *
 */
public class CallSimpRepSubstitute extends CallSimpRepAction {

	public CallSimpRepSubstitute(SimpRepSubstitute action) {
		super((SimpRepAction)action);
	}

	public CallSubstitution getSubstituteData() throws jxthrowable {
        if (NitroConstants.DEBUG_JLINK) DebugLogging.sendTimerMessage("SimpRepSubstitute,GetSubstituteData", 0, NitroConstants.DEBUG_JLINK_KEY);
        Substitution subst = getAction().GetSubstituteData();
		if (subst==null)
			return null;
		return CallSubstitution.create(subst);
	}

	public SimpRepSubstitute getAction() {
		return (SimpRepSubstitute)action;
	}

}


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

    <android.support.v7.widget.CardView
        app:cardBackgroundColor="?attr/pingCardBackgroundColor"
        style="@style/statistic_fragment_frame_layout">

        <include layout="@layout/card_host_name"/>
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        app:cardBackgroundColor="?attr/pingCardBackgroundColor"
        style="@style/statistic_fragment_frame_layout">

        <include layout="@layout/card_ip_address"/>
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        app:cardBackgroundColor="?attr/pingCardBackgroundColor"
        style="@style/statistic_fragment_frame_layout" >

        <include layout="@layout/card_count_value"/>
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        app:cardBackgroundColor="?attr/pingCardBackgroundColor"
        style="@style/statistic_fragment_frame_layout"
        android:layout_weight="1.5" >

        <include layout="@layout/card_last_value"/>
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        app:cardBackgroundColor="?attr/pingCardBackgroundColor"
        style="@style/statistic_fragment_frame_layout" >

        <include layout="@layout/card_mean_value"/>
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        app:cardBackgroundColor="?attr/pingCardBackgroundColor"
        style="@style/statistic_fragment_frame_layout">

        <include layout="@layout/card_max_value"/>
    </android.support.v7.widget.CardView>

</merge>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  <meta content="text/html; charset=ISO-8859-1"
 http-equiv="content-type">
  <title>Test Command Error</title>

      Test Command Error

      open
      ../tests/html/test_verifications.html

      verifyErrorOnNext
      Element notALink not found

      click
      notALink

      verifyErrorOnNext
      Element noSuchSelect not found

      select
      noSuchSelect
      somelabel

      verifyErrorOnNext
      Option with label 'noSuchLabel' not found

      select
      theSelect
      label=noSuchLabel

      verifyErrorOnNext
      Specified element is not a Select (has no options)

      select
      theText
      label=noSuchLabel


text:
package source

import (
	"bytes"
	"io"
	"regexp"
	"strings"
	"unicode"
	"unicode/utf8"
)

// CommentToMarkdown converts comment text to formatted markdown.
// The comment was prepared by DocReader,
// so it is known not to have leading, trailing blank lines
// nor to have trailing spaces at the end of lines.
// The comment markers have already been removed.
//
// Each line is converted into a markdown line and empty lines are just converted to
// newlines. Heading are prefixed with `### ` to make it a markdown heading.
//
// A span of indented lines retains a 4 space prefix block, with the common indent
// prefix removed unless empty, in which case it will be converted to a newline.
//
// URLs in the comment text are converted into links.
func CommentToMarkdown(text string) string {
	buf := &bytes.Buffer{}
	commentToMarkdown(buf, text)
	return buf.String()
}

var (
	mdNewline   = []byte("\n")
	mdHeader    = []byte("### ")
	mdIndent    = []byte("    ")
	mdLinkStart = []byte("[")
	mdLinkDiv   = []byte("](")
	mdLinkEnd   = []byte(")")
)

func commentToMarkdown(w io.Writer, text string) {
	blocks := blocks(text)
	for i, b := range blocks {
		switch b.op {
		case opPara:
			for _, line := range b.lines {
				emphasize(w, line, true)
			}
		case opHead:
			// The header block can consist of only one line.
			// However, check the number of lines, just in case.
			if len(b.lines) == 0 {
				// Skip this block.
				continue
			}
			header := b.lines[0]

			w.Write(mdHeader)
			commentEscape(w, header, true)
			// Header doesn't end with \n unlike the lines of other blocks.
			w.Write(mdNewline)
		case opPre:
			for _, line := range b.lines {
				if isBlank(line) {
					w.Write(mdNewline)
					continue
				}
				w.Write(mdIndent)
				w.Write([]byte(line))
			}
		}

		if i < len(blocks)-1 {
			w.Write(mdNewline)
		}
	}
}

const (
	ulquo = """
	urquo = """
)

var (
	markdownEscape = regexp.MustCompile(`([\\\x60*{}[\]()#+\-.!_>~|"$%&'\/:;<=?@^])`)

	unicodeQuoteReplacer = strings.NewReplacer("``", ulquo, "''", urquo)
)

// commentEscape escapes comment text for markdown. If nice is set,
// also turn double ` and ' into " and ".
func commentEscape(w io.Writer, text string, nice bool) {
	if nice {
		text = convertQuotes(text)
	}
	text = escapeRegex(text)
	w.Write([]byte(text))
}

func convertQuotes(text string) string {
	return unicodeQuoteReplacer.Replace(text)
}

func escapeRegex(text string) string {
	return markdownEscape.ReplaceAllString(text, `\$1`)
}

func emphasize(w io.Writer, line string, nice bool) {
	for {
		m := matchRx.FindStringSubmatchIndex(line)
		if m == nil {
			break
		}
		// m >= 6 (two parenthesized sub-regexps in matchRx, 1st one is urlRx)

		// write text before match
		commentEscape(w, line[0:m[0]], nice)

		// adjust match for URLs
		match := line[m[0]:m[1]]
		if strings.Contains(match, "://") {
			m0, m1 := m[0], m[1]
			for _, s := range []string{"()", "{}", "[]"} {
				open, close := s[:1], s[1:] // E.g., "(" and ")"
				// require opening parentheses before closing parentheses (#22285)
				if i := strings.Index(match, close); i >= 0 && i < strings.Index(match, open) {
					m1 = m0 + i
					match = line[m0:m1]
				}
				// require balanced pairs of parentheses (#5043)
				for i := 0; strings.Count(match, open) != strings.Count(match, close) && i < 10; i++ {
					m1 = strings.LastIndexAny(line[:m1], s)
					match = line[m0:m1]
				}
			}
			if m1 != m[1] {
				// redo matching with shortened line for correct indices
				m = matchRx.FindStringSubmatchIndex(line[:m[0]+len(match)])
			}
		}

		// Following code has been modified from go/doc since words is always
		// nil. All html formatting has also been transformed into markdown formatting

		// analyze match
		url := ""
		if m[2] >= 0 {
			url = match
		}

		// write match
		if len(url) > 0 {
			w.Write(mdLinkStart)
		}

		commentEscape(w, match, nice)

		if len(url) > 0 {
			w.Write(mdLinkDiv)
			w.Write([]byte(urlReplacer.Replace(url)))
			w.Write(mdLinkEnd)
		}

		// advance
		line = line[m[1]:]
	}
	commentEscape(w, line, nice)
}

// Everything from here on is a copy of go/doc/comment.go

const (
	// Regexp for Go identifiers
	identRx = `[\pL_][\pL_0-9]*`

	// Regexp for URLs
	// Match parens, and check later for balance - see #5043, #22285
	// Match .,:;?! within path, but not at end - see #18139, #16565
	// This excludes some rare yet valid urls ending in common punctuation
	// in order to allow sentences ending in URLs.

	// protocol (required) e.g. http
	protoPart = `(https?|ftp|file|gopher|mailto|nntp)`
	// host (required) e.g. www.example.com or [::1]:8080
	hostPart = `([a-zA-Z0-9_@\-.\[\]:]+)`
	// path+query+fragment (optional) e.g. /path/index.html?q=foo#bar
	pathPart = `([.,:;?!]*[a-zA-Z0-9$'()*+&#=@~_/\-\[\]%])*`

	urlRx = protoPart + `://` + hostPart + pathPart
)

var (
	matchRx     = regexp.MustCompile(`(` + urlRx + `)|(` + identRx + `)`)
	urlReplacer = strings.NewReplacer(`(`, `\(`, `)`, `\)`)
)

func indentLen(s string) int {
	i := 0
	for i < len(s) && (s[i] == ' ' || s[i] == '\t') {
		i++
	}
	return i
}

func isBlank(s string) bool {
	return len(s) == 0 || (len(s) == 1 && s[0] == '\n')
}

func commonPrefix(a, b string) string {
	i := 0
	for i < len(a) && i < len(b) && a[i] == b[i] {
		i++
	}
	return a[0:i]
}

func unindent(block []string) {
	if len(block) == 0 {
		return
	}

	// compute maximum common white prefix
	prefix := block[0][0:indentLen(block[0])]
	for _, line := range block {
		if !isBlank(line) {
			prefix = commonPrefix(prefix, line)
		}
	}
	n := len(prefix)

	// remove
	for i, line := range block {
		if !isBlank(line) {
			block[i] = line[n:]
		}
	}
}

// heading returns the trimmed line if it passes as a section heading;
// otherwise it returns the empty string.
func heading(line string) string {
	line = strings.TrimSpace(line)
	if len(line) == 0 {
		return ""
	}

	// a heading must start with an uppercase letter
	r, _ := utf8.DecodeRuneInString(line)
	if !unicode.IsLetter(r) || !unicode.IsUpper(r) {
		return ""
	}

	// it must end in a letter or digit:
	r, _ = utf8.DecodeLastRuneInString(line)
	if !unicode.IsLetter(r) && !unicode.IsDigit(r) {
		return ""
	}

	// exclude lines with illegal characters. we allow "(),"
	if strings.ContainsAny(line, ";:!?+*/=[]{}_^°&§~%#@<\">\\") {
		return ""
	}

	// allow "'" for possessive "'s" only
	for b := line; ; {
		i := strings.IndexRune(b, '\'')
		if i < 0 {
			break
		}
		if i+1 >= len(b) || b[i+1] != 's' || (i+2 < len(b) && b[i+2] != ' ') {
			return "" // not followed by "s "
		}
		b = b[i+2:]
	}

	// allow "." when followed by non-space
	for b := line; ; {
		i := strings.IndexRune(b, '.')
		if i < 0 {
			break
		}
		if i+1 >= len(b) || b[i+1] == ' ' {
			return "" // not followed by non-space
		}
		b = b[i+1:]
	}

	return line
}

type op int

const (
	opPara op = iota
	opHead
	opPre
)

type block struct {
	op    op
	lines []string
}

func blocks(text string) []block {
	var (
		out  []block
		para []string

		lastWasBlank   = false
		lastWasHeading = false
	)

	close := func() {
		if para != nil {
			out = append(out, block{opPara, para})
			para = nil
		}
	}

	lines := strings.SplitAfter(text, "\n")
	unindent(lines)
	for i := 0; i < len(lines); {
		line := lines[i]
		if isBlank(line) {
			// close paragraph
			close()
			i++
			lastWasBlank = true
			continue
		}
		if indentLen(line) > 0 {
			// close paragraph
			close()

			// count indented or blank lines
			j := i + 1
			for j < len(lines) && (isBlank(lines[j]) || indentLen(lines[j]) > 0) {
				j++
			}
			// but not trailing blank lines
			for j > i && isBlank(lines[j-1]) {
				j--
			}
			pre := lines[i:j]
			i = j

			unindent(pre)

			// put those lines in a pre block
			out = append(out, block{opPre, pre})
			lastWasHeading = false
			continue
		}

		if lastWasBlank && !lastWasHeading && i+2 < len(lines) &&
			isBlank(lines[i+1]) && !isBlank(lines[i+2]) && indentLen(lines[i+2]) == 0 {
			// current line is non-blank, surrounded by blank lines
			// and the next non-blank line is not indented: this
			// might be a heading.
			if head := heading(line); head != "" {
				close()
				out = append(out, block{opHead, []string{head}})
				i += 2
				lastWasHeading = true
				continue
			}
		}

		// open paragraph
		lastWasBlank = false
		lastWasHeading = false
		para = append(para, lines[i])
		i++
	}
	close()

	return out
}


text:
package io.github.jlprat.reactive.jee.rest;

import io.github.jlprat.reactive.jee.domain.Reader;
import io.github.jlprat.reactive.jee.service.ReaderService;

import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.logging.Logger;

/**
 * @author @jlprat
 */
@Path("/users/readers")
public class ReaderResource {

    Logger logger = Logger.getLogger(ReaderResource.class.getName());

    @Inject
    private ReaderService readerService;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getReaders() {
        return Response.ok(readerService.getReaders()).build();
    }

    @Path("/{id}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getReader(@PathParam("id") final String id) {
        final Reader reader = readerService.getReader(id);
        if (reader != null) {
            return Response.ok(reader).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }

    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.APPLICATION_JSON)
    public Response createReader(@FormParam("name") final String name, @FormParam("surname") final String surname) {
        logger.info("name " + name);
        final Reader reader = readerService.createReader(name, surname);
        logger.info("reader " + reader);
        return Response.ok(reader).build();
    }
}


text:
struct RenderState
{
	unsigned int meshId;
    std::vector<int> shaderEffectIds;
	unsigned int texId;

	virtual void setParameters(ShaderEffect* effect)
	{
		printf("shouldn't be here...\n");
	}
};

struct SimpleRenderState : public RenderState
{
	public:

	static glm::vec3 lightPositionWorldSpace;
	static glm::vec3 lightPositionWorldSpace2;

	virtual void setParameters(ShaderEffect* e)
	{
		SimpleShaderEffect* effect = static_cast<SimpleShaderEffect*>(e);
		// Bind our texture in Texture Unit 0
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, texId);
		// Set our "myTextureSampler" sampler to user Texture Unit 0
		glUniform1i(effect->textureSamplerId, 0);
		check_gl_error();
		glUniform3f(effect->lightPositionId, lightPositionWorldSpace.x, lightPositionWorldSpace.y, lightPositionWorldSpace.z );
		glUniform3f(effect->lightPosition2Id, lightPositionWorldSpace2.x, lightPositionWorldSpace2.y, lightPositionWorldSpace2.z);
	}
};

struct VolumeRenderingRenderState : public RenderState
{
	unsigned int volumeTexId;
	static unsigned int layerNr;

	virtual void setParameters(ShaderEffect* e)
	{
		VolumeRenderingShaderEffect* effect = static_cast<VolumeRenderingShaderEffect*>(e);
		glActiveTexture(GL_TEXTURE0);
		check_gl_error();
		glBindTexture(GL_TEXTURE_3D, volumeTexId);
		check_gl_error();
		glUniform1i(effect->volumeSamplerId, 0);
		check_gl_error();
		//glUniform1i(effect->layerId, layerNr);
		//check_gl_error();
	}
};

// DONE added the Shadow mapping render state
// it holds the application side values of the
// ShadowMappingShaderEffectr
// the id of the depth texture and
// the bias magic number
struct ShadowMappingRenderState : public SimpleRenderState
{
	unsigned int depthTexId;
	unsigned int ssaoResultTexId;

	static float shadowMagicNumber;

	virtual void setParameters(ShaderEffect* e)
	{
		SimpleRenderState::setParameters(e);
		ShadowMappingShaderEffect* effect = static_cast<ShadowMappingShaderEffect*>(e);
		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, depthTexId);
		glUniform1i(effect->depthTextureSamplerId, 1);
		glActiveTexture(GL_TEXTURE2);
		glBindTexture(GL_TEXTURE_2D, ssaoResultTexId);
		glUniform1i(effect->ssaoResultSamplerId, 2);
		check_gl_error();
		glUniform1f(effect->shadowMagicNumberId, shadowMagicNumber);
	}
};


text:
typedef void (^ViewListener)();

#pragma mark - View interface -

@interface View : UIView

@property (copy) ViewListener listener;

@end


text:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

          <title></title>
          <meta name="description" content="" />
          <meta name="keywords" content="" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../lib/ref-index.css" media="screen" type="text/css" rel="stylesheet" />

apply

LangBundle

asOpt

StringWithAnalysis StringUtil

asUrl

StringWithAnalysis


text:
package org.powlab.jeye.tests.loop;

public class LoopTest36 {

    public boolean test(boolean  a, boolean  b)
    {
        boolean res = true;
        boolean c = true;
        do {
            c = false;
            System.out.println(Boolean.valueOf(res));
        } while (res = (b && a == (c = b) && b && c));
        return c;
    }
}


text:
"""Frog and Pelican recognition module"""

class Spotter:
    """This class can tell you whether an image contains a frog or a
    pelican.  In the case of frogs, it can tell you how many there
    are."""
    def __init__(self, buffer):
        """buffer should be a PIL image buffer"""

    def contains_pelican(self):
        "does the picture depict a pelican? (boolean)"
        return answer

    def count_frogs(self, tadpoles):
        """How many frogs in the picture? If tadpoles is true, they are
        counted too."""
        return int_frogcount

def defrog(buffer, tadpoles):
    """Remove any frogs and optionally tadpoles from a given image"""


text:
'use strict';

angular.module('umm3601ursamajorApp')

    .config(function ($stateProvider) {
        $stateProvider
            .state('test', {
                url: '/test',
                templateUrl: 'app/test/test.html',
                controller: 'TestCtrl'
            });
    });

angular.module("textAngularTest", ['textAngular']);

$('mybutton').click(function(){
    $('#mytextarea').append('[b][/b]');
});


text:
/*!
 * Angular Material Design
 * https://github.com/angular/material
 * @license MIT
 * v0.6.0-rc1-master-57f10f7
 */
@-webkit-keyframes tooltipBackgroundShow {
  0% {
    -webkit-transform: scale(0.2);
            transform: scale(0.2);
    opacity: 0.25; }

  50% {
    opacity: 1; }

  100% {
    -webkit-transform: scale(1);
            transform: scale(1);
    opacity: 1; } }

@keyframes tooltipBackgroundShow {
  0% {
    -webkit-transform: scale(0.2);
            transform: scale(0.2);
    opacity: 0.25; }

  50% {
    opacity: 1; }

  100% {
    -webkit-transform: scale(1);
            transform: scale(1);
    opacity: 1; } }

@-webkit-keyframes tooltipBackgroundHide {
  0% {
    opacity: 1; }

  100% {
    opacity: 0; } }

@keyframes tooltipBackgroundHide {
  0% {
    opacity: 1; }

  100% {
    opacity: 0; } }

md-tooltip {
  position: absolute;
  font-size: 14px;
  z-index: 9;
  overflow: hidden;
  pointer-events: none;
  border-radius: 4px;
  /**
   * Depending on the tooltip's size as a multiple of 32 (set by JS),
   * change the background's animation duration.
   * The larger the tooltip, the less time the background should take to ripple outwards.
   */ }
  md-tooltip[md-direction="bottom"] {
    -webkit-transform: translate3d(0, -30%, 0);
            transform: translate3d(0, -30%, 0);
    margin-top: 8px; }
  md-tooltip[md-direction="top"] {
    -webkit-transform: translate3d(0, 30%, 0);
            transform: translate3d(0, 30%, 0);
    margin-bottom: 8px; }
  md-tooltip .md-background {
    position: absolute;
    left: 50%;
    width: 256px;
    height: 256px;
    margin-left: -128px;
    margin-top: -128px;
    border-radius: 256px;
    opacity: 0.25;
    -webkit-transform: scale(0.2);
            transform: scale(0.2); }
  md-tooltip .md-content {
    max-width: 240px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding: 8px;
    background: transparent;
    opacity: 0.3;
    transition: inherit; }
  md-tooltip.md-hide {
    transition: all 0.3s cubic-bezier(0.55, 0, 0.55, 0.2); }
  md-tooltip.md-show {
    transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
    pointer-events: auto;
    -webkit-transform: translate3d(0, 0, 0);
            transform: translate3d(0, 0, 0); }
    md-tooltip.md-show .md-background {
      -webkit-transform: scale(1);
              transform: scale(1);
      opacity: 1;
      -webkit-animation: tooltipBackgroundShow linear;
              animation: tooltipBackgroundShow linear; }
    md-tooltip.md-show .md-content {
      opacity: 0.99; }
  md-tooltip.md-hide .md-background {
    -webkit-transform: scale(1);
            transform: scale(1);
    opacity: 0;
    -webkit-animation: tooltipBackgroundHide 0.2s linear;
            animation: tooltipBackgroundHide 0.2s linear; }
  md-tooltip[width-32="1"].md-show .md-background {
    -webkit-animation-duration: 900ms;
            animation-duration: 900ms; }
  md-tooltip[width-32="2"].md-show .md-background {
    -webkit-animation-duration: 800ms;
            animation-duration: 800ms; }
  md-tooltip[width-32="3"].md-show .md-background {
    -webkit-animation-duration: 700ms;
            animation-duration: 700ms; }
  md-tooltip[width-32="4"].md-show .md-background {
    -webkit-animation-duration: 600ms;
            animation-duration: 600ms; }
  md-tooltip[width-32="5"].md-show .md-background {
    -webkit-animation-duration: 500ms;
            animation-duration: 500ms; }
  md-tooltip[width-32="6"].md-show .md-background {
    -webkit-animation-duration: 400ms;
            animation-duration: 400ms; }
  md-tooltip[width-32="7"].md-show .md-background {
    -webkit-animation-duration: 300ms;
            animation-duration: 300ms; }
  md-tooltip[width-32="8"].md-show .md-background {
    -webkit-animation-duration: 200ms;
            animation-duration: 200ms; }


text:
package com.intellij.lang.java;

import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.intellij.ide.scratch.ScratchUtil;
import com.intellij.java.JavaBundle;
import com.intellij.lang.ImportOptimizer;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.templateLanguages.TemplateLanguageUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.SlowOperations;
import org.jetbrains.annotations.NotNull;

public class JavaImportOptimizer implements ImportOptimizer {
  private static final Logger LOG = Logger.getInstance(JavaImportOptimizer.class);

  @Override
  @NotNull
  public Runnable processFile(@NotNull final PsiFile file) {
    if (!(file instanceof PsiJavaFile)) {
      return EmptyRunnable.getInstance();
    }
    Project project = file.getProject();
    final PsiImportList newImportList = JavaCodeStyleManager.getInstance(project).prepareOptimizeImportsResult((PsiJavaFile)file);
    if (newImportList == null) return EmptyRunnable.getInstance();

    return new CollectingInfoRunnable() {
      private int myImportsAdded;
      private int myImportsRemoved;

      @Override
      public void run() {
        SlowOperations.allowSlowOperations(this::doRun);
      }

      private void doRun() {
        try {
          final PsiDocumentManager manager = PsiDocumentManager.getInstance(file.getProject());
          final Document document = manager.getDocument(file);
          if (document != null) {
            manager.commitDocument(document);
          }
          final PsiImportList oldImportList = ((PsiJavaFile)file).getImportList();
          assert oldImportList != null;
          final Multiset<PsiElement> oldImports = HashMultiset.create();
          for (PsiImportStatement statement : oldImportList.getImportStatements()) {
            oldImports.add(statement.resolve());
          }

          final Multiset<PsiElement> oldStaticImports = HashMultiset.create();
          for (PsiImportStaticStatement statement : oldImportList.getImportStaticStatements()) {
            oldStaticImports.add(statement.resolve());
          }

          oldImportList.replace(newImportList);
          for (PsiImportStatement statement : newImportList.getImportStatements()) {
            if (!oldImports.remove(statement.resolve())) {
              myImportsAdded++;
            }
          }
          myImportsRemoved += oldImports.size();

          for (PsiImportStaticStatement statement : newImportList.getImportStaticStatements()) {
            if (!oldStaticImports.remove(statement.resolve())) {
              myImportsAdded++;
            }
          }
          myImportsRemoved += oldStaticImports.size();
        }
        catch (IncorrectOperationException e) {
          LOG.error(e);
        }
      }

      @Override
      public String getUserNotificationInfo() {
        if (myImportsRemoved == 0) {
          return JavaBundle.message("hint.text.rearranged.imports");
        }
        String notification = JavaBundle.message("hint.text.removed.imports", myImportsRemoved, myImportsRemoved == 1 ? 0 : 1);
        if (myImportsAdded > 0) {
          notification += JavaBundle.message("hint.text.added.imports", myImportsAdded, myImportsAdded == 1 ? 0 : 1);
        }
        return notification;
      }
    };
  }

  @Override
  public boolean supports(@NotNull PsiFile file) {
    if (file instanceof PsiJavaFile && !TemplateLanguageUtil.isTemplateDataFile(file)) {
      VirtualFile virtualFile = PsiUtilCore.getVirtualFile(file);
      return virtualFile != null && (ProjectRootManager.getInstance(file.getProject()).getFileIndex().isInSource(virtualFile) ||
                                     ScratchUtil.isScratch(virtualFile));
    }
    return false;
  }
}


text:
namespace feature_engagement {

class Event;

namespace test {

// Adds an Event count entry for |event|.
void SetEventCountForDay(Event* event, uint32_t day, uint32_t count);

// Adds a snooze count entry for |event|.
void SetSnoozeCountForDay(Event* event, uint32_t day, uint32_t count);

// Verifies that the given |event| contains a |day| with the correct |count|,
// and that the day only exists a single time.
void VerifyEventCount(const Event* event, uint32_t day, uint32_t count);

// Verifies that the event |a| and |b| contain the exact same data.
void VerifyEventsEqual(const Event* a, const Event* b);

}  // namespace test
}  // namespace feature_engagement

#endif  // COMPONENTS_FEATURE_ENGAGEMENT_INTERNAL_TEST_EVENT_UTIL_H_


text:
{% extends "common/selection.html" %}
{% load staticfiles %}

{% block addon_js %}

{% endblock %}

{% block middle_column %}

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

New Features

Completely redesigned interface to be more intuitive.

Instead of extensive drop downs each methodnow open in separate windows so it is easier to manage.

General design improvements.

Snake plot has been given more space in order to give a clearer visual representation

Ability to sort suggestions by either homology level or over all frequency.

Ability to filter truncation suggestions based on Fusion Protein.

Ability to use separate sources for start and end of ICL truncations.

Separate underlying data by choosing whether to base truncations no active/inactive data set, and whether to have truncations for ICL regions from a dataset with or without fusion proteins.

Ability to export all suggestions to excel

Ability to export chosen modifications along with modified sequence (WT sequence minus truncations and with mutations inserted).

Ability to import a previously generated excel sheet.

Useful to continue a previous design, to use same modifications on a different target, or to make modifications locally and visualise using tool.

Allow ICL2 truncations for class B and C.

Do not suggestions ICL3 truncation if ICL3 is less than 9 residues.

Implemented a list of mutation suggestions from various sources

Some are rule based (devised by David)

Some are conservation based - e.g. Mutate to conserved residue in crystallised receptors.

Some are from literature data set for thermostability.

Some are from annotated crystal mutations.

Ability to create custom modifications (Mutation or truncation)

Dataset has been cleaned up to more correctly identify fusion proteins and sites.

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

            {% if filters %}

Filter

                    {% include 'common/selection_filters_species.html' %}

                    {% include 'common/selection_filters_annotation.html' %}

            {% endif %}

Search

                        <input id="selection-autocomplete" class="form-control" size="15">

{% endblock %}


text:
package io.quarkus.deployment.builditem;

import java.io.Closeable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.jboss.logging.Logger;

import io.quarkus.builder.item.SimpleBuildItem;

public final class QuarkusBuildCloseablesBuildItem extends SimpleBuildItem implements Closeable {

    private static final Logger log = Logger.getLogger(QuarkusBuildCloseablesBuildItem.class);

    private final List<Closeable> closeables = Collections.synchronizedList(new ArrayList<>());

    public <T extends Closeable> T add(T closeable) {
        closeables.add(closeable);
        return closeable;
    }

    @Override
    public void close() {
        for (Closeable c : closeables) {
            try {
                c.close();
            } catch (Throwable e) {
                log.debugf(e, "Failed to close %s", c);
            }
        }
    }
}


text:
"""Outputs on both stderr and stdout."""

import re
import sys
import time

def main():
  for command in sys.argv[1:]:
    if re.match(r'^[0-9\.]+$', command):
      time.sleep(float(command))
      continue

    if command.startswith('out_'):
      pipe = sys.stdout
    elif command.startswith('err_'):
      pipe = sys.stderr
    else:
      return 1

    command = command[4:]
    if command == 'print':
      pipe.write('printing')
    elif command == 'sleeping':
      pipe.write('Sleeping.\n')
    elif command == 'slept':
      pipe.write('Slept.\n')
    elif command == 'lf':
      pipe.write('\n')
    elif command == 'flush':
      pipe.flush()
    else:
      return 1
  return 0

if __name__ == '__main__':
  sys.exit(main())


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.todolist"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Email"
            android:label="@string/title_activity_email" >
        </activity>
        <activity
            android:name=".Summary"
            android:label="@string/title_activity_summary" >
        </activity>
    </application>

</manifest>


text:
export interface NavbarTab {
  name: string;
  filter: (number) => boolean;
}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Remotus.Base;
using RestSharp;

namespace Remotus.API.v1
{
    public partial class FullCtrlAPI
    {
        public async Task<IResponseBase<IEnumerable<IPlugin>>> GetLocalPlugins()
        {
            var uri = new Uri("local/plugins", UriKind.Relative);
            var request = BuildRequest(uri, Method.GET);

            var response = await GetResponse<IEnumerable<IPlugin>>(request);
            return response;
        }

        public async Task<IResponseBase<IEnumerable<IFunctionPlugin>>> GetLocalFunctionPlugins()
        {
            var uri = new Uri("local/plugins/function", UriKind.Relative);
            var request = BuildRequest(uri, Method.GET);

            var response = await GetResponse<IEnumerable<IFunctionPlugin>>(request);
            return response;
        }

        public async Task<IResponseBase<IEnumerable<IServicePlugin>>> GetLocalServicePlugins()
        {
            var uri = new Uri("local/plugins/service", UriKind.Relative);
            var request = BuildRequest(uri, Method.GET);

            var response = await GetResponse<IEnumerable<IServicePlugin>>(request);
            return response;
        }

        public async Task<IResponseBase<IFunctionResult>> ExecuteLocalFunction(string pluginID, string functionID, IFunctionArguments arguments)
        {
            var uri = new Uri("local/execute/function", UriKind.Relative);
            var request = BuildRequest(uri, Method.POST);
            request.AddQueryParameter("pluginID", pluginID);
            request.AddQueryParameter("functionID", functionID);
            request.AddJsonBody(arguments);

            var response = await GetResponse<IFunctionResult>(request);
            return response;
        }

    }
}


text:
function Get(obj, options, cb) {
    obj = this.clone(obj);

    const self = this;
    const optType = this.type(options);

    // options parametresi function olarak geçirilmişse callback olarak bunu seçiyoruz
    const _cb = (optType === '[object Function]') ? options : cb;

    // cache key'i belirliyoruz
    // cache key direkt obje içinde veya options içinde belirtilebilir
    let cacheKey;
    if(obj.cacheKey) {
        cacheKey = obj.cacheKey;
        delete obj.cacheKey;
    } else if(optType === '[object Object]') {
        cacheKey = options.cacheKey;
    }

    // core cache ve cache key varsa cache'i çalıştırıyoruz
    if(this._app.core.cache && cacheKey) {
        // objeyi ve class'ı cache-stampede içinde kullanılabilmesi için
        // parametre olarak geçiriyoruz
        const params = {params: [obj, self]};
        if(obj.expiry) { // in ms
            params.expiry = obj.expiry;
            delete obj.expiry;
        }

        if(obj.cacheNotFound) {
            params.params.push(true);
            delete obj.cacheNotFound;
        }

        this._app.core.cache.cached(`api:${cacheKey}`, this.getPromise, params)
        .then(doc => {
            self.log('CACHE', cacheKey);
            return _cb ? _cb(null, doc) : self._http.OK({doc}, self._res);
        }, err => {
            self.log(`CACHE:${cacheKey}`, err);
            self.errors(err, _cb);
        });
    } else {
        this.getFunc(obj, null, _cb);
    }
}

module.exports = Get;


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>StormEngineC 1.2 API DOC Source: StormCamera.class.js</title>

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.stormenginec.css">

			StormEngineC 1.2 API DOC

					Classes

							ActionHelpers

							StormBufferObject

							StormCamera

							StormControllerFollow

							StormControllerPlayer

							StormControllerPlayerCar

							StormControllerTargetCam

							StormEngineC

							StormEngineC_PanelAnimationTimeline

							StormForceField

							StormGI

							StormGLContext

							StormGraph

							StormGrid

							StormGroupNodes

							StormLight

							StormLine

							StormLineSceneCollision

							StormM16

							StormMaterial

							StormNode

							StormPolarityPoint

							StormTriangleBox

							StormUtils

							StormV3

							StormVoxelizator

							WebCLGL

							WebCLGLBuffer

							WebCLGLBufferItem

							WebCLGLKernel

							WebCLGLKernelProgram

							WebCLGLUtils

							WebCLGLVertexFragmentProgram

							WebCLGLWork

					Global

							$M16

							$V3

Source: StormCamera.class.js

/**
* @class
* @constructor
* @augments StormNode

* @property {String} objectType
* @property {StomrNode} nodePivot
* @property {StomrNode} nodeGoal
* @property {StormControllerTargetCam|StormControllerPlayer|StormControllerPlayerCar|StormControllerFollow} controller Camera controller
*/
StormCamera = function(sec) { StormNode.call(this);
	this._sec = sec;

	this.objectType = 'camera';

	this.controller; // camera controller
	this.nodeGoal;
	this.nodePivot;

	this.usedByGLContext = false;
	this.enableAnimFrames = false;
	this.lockRotX = false;
	this.lockRotY = false;

	this.posCamera;
	this.posCameraPivot;
	this.vecView;
	this.vecXPlanoProyeccion;//◄
	this.vecYPlanoProyeccion;//▲
	this.distanciaAlPlano = 1.0;
	this.centroPlanoProyeccion;

	// lens
	this.autofocus = true;
	this.focusExtern = 20.0;
	this.fNumber = 90.0/128.0; // solo profCampo
	this.DOFenable = false;

	this.widthLens = 0.5;
	this.refIndex = 1.46;
	this.focusIntern = 2.135105374746873;// EMR RENDER
};
StormCamera.prototype = Object.create(StormNode.prototype);

/**
* Remove this object
* @type Void
*/
StormCamera.prototype.remove = function() {
	var idToRemove = undefined;
	for(var n = 0, f = this._sec.nodesCam.length; n < f; n++) {
		if(this._sec.nodesCam[n].idNum == this.idNum) idToRemove = n;
	}
	this._sec.nodesCam.splice(idToRemove,1);
};
/**
* Look rotation x
* @type Void
 */
StormCamera.prototype.lockRotationX = function() {
	this.lockRotX = true;
};
/**
* Look rotation y
* @type Void
 */
StormCamera.prototype.lockRotationY = function() {
	this.lockRotY = true;
};
/**
* UnLook rotation x
* @type Void
 */
StormCamera.prototype.unlockRotationX = function() {
	this.lockRotX = false;
};
/**
* UnLook rotation y
* @type Void
 */
StormCamera.prototype.unlockRotationY = function() {
	this.lockRotY = false;
};

/**
* Set side view. This change the projection to orthographic.
* @type Void
* @param {String} view 'LEFT','RIGHT','FRONT','BACK','TOP','BOTTOM'
 */
StormCamera.prototype.setView = function(view) {
	this.setProjectionType('o');
	this.nodePivot.resetAxis();
	this.resetAxis();
	switch(view) {
		case 'LEFT':
			this.nodePivot.setRotation(this._sec.utils.degToRad(-90),false,$V3([0.0,1.0,0.0]));
			break;
		case 'RIGHT':
			this.nodePivot.setRotation(this._sec.utils.degToRad(-90-180),false,$V3([0.0,1.0,0.0]));
			break;
		case 'FRONT':
			this.nodePivot.setRotation(this._sec.utils.degToRad(0),false,$V3([0.0,1.0,0.0]));
			break;
		case 'BACK':
			this.nodePivot.setRotation(this._sec.utils.degToRad(180),false,$V3([0.0,1.0,0.0]));
			break;
		case 'TOP':
			this.nodePivot.setRotation(this._sec.utils.degToRad(-90),false,$V3([1.0,0.0,0.0]));
			break;
		case 'BOTTOM':
			this.nodePivot.setRotation(this._sec.utils.degToRad(90),false,$V3([1.0,0.0,0.0]));
			break;
	}
};

/**
* Switch cam controller
* @type Void
* @param {Object} jsonIn
* 	@param {String} jsonIn.mode 'targetcam'|'follow'|'player'|'nodeCar'.
* 	@param {Float} [jsonIn.distance] Distance to camera target.
* 	@param {StormNode} [jsonIn.node] For attach a node to the camera target. Only type 'targetcam'|'follow'|'player'.
* 	@param {StormNode} [jsonIn.nodeCar] If mode is 'nodeCar'.
* 	@param {String} [jsonIn.view='node'] 'camera' | 'node'.
 */
StormCamera.prototype.setController = function(jsonIn) {
	var view =(jsonIn.view != undefined) ? jsonIn.view : 'node';

	if(jsonIn.mode == 'targetcam') {
		this.controller = new StormControllerTargetCam(this._sec, jsonIn.distance);

		if(jsonIn.node != undefined) {
			if(view == 'node') this.nodePivot.setPosition(jsonIn.node.getPosition());
			if(view == 'camera') jsonIn.node.setPosition(this.nodePivot.getPosition());
		}

		this.controller.cameraSetupFC(this, jsonIn.node); // cameraNode, meshNode
	}
	if(jsonIn.mode == 'player') {
		this.controller = new StormControllerPlayer(this._sec, jsonIn.distance);

		if(jsonIn.node != undefined) {
			if(view == 'node') this.nodePivot.setPosition(jsonIn.node.getPosition());
			if(view == 'camera') jsonIn.node.setPosition(this.nodePivot.getPosition());
		}

		this.controller.cameraSetupFC(this, jsonIn.node); // cameraNode, meshNode
	}
	if(jsonIn.mode == 'nodeCar') {
		this.controller = new StormControllerPlayerCar(this._sec, jsonIn.distance);

		if(jsonIn.node != undefined) {
			if(view == 'node') this.nodePivot.setPosition(jsonIn.node.getPosition());
			if(view == 'camera') jsonIn.node.setPosition(this.nodePivot.getPosition());
		}

		this.controller.cameraSetupFC(this, jsonIn.node, jsonIn.nodeCar); // cameraNode, meshNode, nodeCar
	}
	if(jsonIn.mode == 'follow') {
		this.controller = new StormControllerFollow(this._sec, jsonIn.distance);

		if(jsonIn.node != undefined) {
			if(view == 'node') this.nodePivot.setPosition(jsonIn.node.getPosition());
			if(view == 'camera') jsonIn.node.setPosition(this.nodePivot.getPosition());
		}

		this.controller.cameraSetupFC(this, jsonIn.node); // cameraNode, meshNode
		this.enableAnimFrames = false;
	}
};

/**
 * @private
 */
StormCamera.prototype.setFocusIntern = function() {
	var etaAir = 1.00029;

	var lineOrigin = this.posCameraPivot.add(this.vecView.x(this.focusExtern));
	var lineEnd = this.posCameraPivot.add(this.vecYPlanoProyeccion.x(this.widthLens));

	var rayLens = new StormRayLens(this._sec);
	var rl = rayLens.setRayLens(lineOrigin, lineEnd, etaAir, this.refIndex);
	if(rl[0] != -1.0) {
		var outRay = $V3([rl[4], rl[5], rl[6]]);

		var angle = 1.0-(outRay.dot(this.vecYPlanoProyeccion.x(-1.0)));
		angle *= 90.0;
		var distFocus = Math.tan(this._sec.utils.degToRad(angle));
		this.focusIntern = distFocus*0.786;

	}
};
/**
* Enable depth of field.
* @type Void
* @param {Object} jsonIn
* 	@param {Bool} [jsonIn.autofocus=true] Use auto focus.
 */
StormCamera.prototype.enableDOF = function(jsonIn) {
	this.DOFenable = true;
	if(jsonIn != undefined && jsonIn.autofocus != undefined) this.autofocus = jsonIn.autofocus;
};
/**
* Disable depth of field.
* @type Void
 */
StormCamera.prototype.disableDOF = function() {
	this.DOFenable = false;
};

/**
* Enable auto focus if DOF is enabled.
* @type Void
 */
StormCamera.prototype.enableAutofocus = function() {
	this.autofocus = true;
};
/**
* Disable auto focus if DOF is enabled.
* @type Void
 */
StormCamera.prototype.disableAutofocus = function() {
	this.autofocus = false;
};

/**
* Set the focus distance and F-Stop.
* @type Void
* @param	{Object} jsonIn
* 	@param {Float} [jsonIn.distance=20.0] Focus distance.
* 	@param {Float} [jsonIn.fStop=90.0] Aperture (0.3 - 128.0).
 */
StormCamera.prototype.focus = function(jsonIn) {
	this.focusExtern = parseFloat(jsonIn.distance);
	if(this.focusExtern < 0.1) this.focusExtern = 0.1;

	if(jsonIn.fStop != undefined) {
		if(jsonIn.fStop > 128.0) jsonIn.fStop = 128.0; if(jsonIn.fStop <= 0.0) jsonIn.fStop = 0.3;
		this.fNumber = (128.0-jsonIn.fStop)/128.0;
	}
};

					StormEngineC 1.2 API DOC

		2010 Roberto Gonzalez. http://stormcolour.appspot.com

		Documentation generated by JSDoc 3.3.0-alpha2
		on Wed Nov 25 2015 23:11:10 GMT+0100 (CET) using the DocStrap template.


text:
<?php

namespace Bazinga\Bundle\GeocoderBundle\DataCollector;

use Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * @author Michal Dabrowski <dabrowski@brillante.pl>
 */
class GeocoderDataCollector extends DataCollector
{
    /**
     * @var GeocoderLogger
     */
    protected $logger;

    /**
     *
     * @param GeocoderLogger $logger
     */
    public function __construct(GeocoderLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * {@inheritdoc}
     */
    public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        $this->data = array(
            'requests' => null !== $this->logger ? $this->logger->getRequests() : array(),
        );
    }

    /**
     * Returns an array of collected requests.
     *
     * @return array
     */
    public function getRequests()
    {
        return $this->data['requests'];
    }

    /**
     * Returns the number of collected requests.
     *
     * @return integer
     */
    public function getRequestsCount()
    {
        return count($this->data['requests']);
    }

    /**
     * Returns the execution time of all collected requests in seconds.
     *
     * @return float
     */
    public function getTime()
    {
        $time = 0;
        foreach ($this->data['requests'] as $command) {
            $time += $command['duration'];
        }

        return $time;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'geocoder';
    }
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.plugins.newui;

import com.intellij.ide.plugins.PluginManagerConfigurableNew;
import com.intellij.util.ui.AbstractLayoutManager;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.util.List;

/**
 * @author Alexander Lobas
 */
public class PluginsListLayout extends AbstractLayoutManager {
  int myLineHeight;

  @Override
  public Dimension preferredLayoutSize(@NotNull Container parent) {
    calculateLineHeight(parent);

    java.util.List<UIPluginGroup> groups = ((PluginsGroupComponent)parent).getGroups();
    int height = 0;

    for (UIPluginGroup group : groups) {
      height += group.panel.getPreferredSize().height;
      height += group.plugins.size() * myLineHeight;
    }

    return new Dimension(0, height);
  }

  @Override
  public void layoutContainer(@NotNull Container parent) {
    calculateLineHeight(parent);

    java.util.List<UIPluginGroup> groups = ((PluginsGroupComponent)parent).getGroups();
    int width = parent.getWidth();
    int y = 0;

    for (UIPluginGroup group : groups) {
      Component component = group.panel;
      int height = component.getPreferredSize().height;
      component.setBounds(0, y, width, height);
      y += height;

      for (CellPluginComponent plugin : group.plugins) {
        plugin.setBounds(0, y, width, myLineHeight);
        y += myLineHeight;
      }
    }
  }

  private void calculateLineHeight(@NotNull Container parent) {
    List<UIPluginGroup> groups = ((PluginsGroupComponent)parent).getGroups();
    int width = PluginManagerConfigurableNew.getParentWidth(parent) - parent.getInsets().right;

    myLineHeight = 0;

    for (UIPluginGroup group : groups) {
      for (CellPluginComponent plugin : group.plugins) {
        JEditorPane description = plugin.myDescription;
        if (description != null) {
          plugin.doLayout();
          int parentWidth = width - SwingUtilities.convertPoint(description.getParent(), description.getLocation(), plugin).x;
          if (parentWidth > 0) {
            description.putClientProperty("parent.width", new Integer(parentWidth));
          }
        }

        plugin.doLayout();
        myLineHeight = Math.max(myLineHeight, plugin.getPreferredSize().height);
      }
    }
  }
}


text:
<?php
/**
 * Single applicant view page
 */
$page->getJazzeePage()->setApplicant($applicant);
?>
<div class='page' id='page<?php print $page->getPage()->getId() ?>'>

<?php print $page->getTitle(); ?>

    <?php
    foreach ($page->getJazzeePage()->getAnswers() as $answer) {
      $class = $answer->getPayment()->getType()->getClass();
      $this->renderElement($class::APPLICANTS_SINGLE_ELEMENT, array('answer' => $answer));
    }?>

<?php
  if ($this->controller->checkIsAllowed('applicants_single', 'addAnswer')) { ?>
    <a class='actionForm' href='<?php print $this->path('applicants/single/' . $applicant->getId() . '/addAnswer/' . $page->getPage()->getId()); ?>'>Record new payment<?php
  } ?>