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

'-----------------------------------------------------------------------------------------------------------
' This is the code that actually outputs the VB code that defines the tree. It is passed a read and validated
' ParseTree, and outputs the code to defined the node classes for that tree, and also additional data
' structures like the kinds, visitor, etc.
'-----------------------------------------------------------------------------------------------------------

Imports System.IO

' Class to write out the names in the tree as a CSV file for Excel.

Friend Class WriteCsvNames
    Inherits WriteUtils

    Private _writer As TextWriter    'output is sent here.

    ' Initialize the class with the parse tree to write.
    Public Sub New(parseTree As ParseTree)
        MyBase.New(parseTree)
    End Sub

    ' Write out the CSV with the names.
    Public Sub WriteCsv(filename As String)
        _writer = New StreamWriter(New FileStream(filename, FileMode.Create, FileAccess.Write))

        Using _writer
            WriteEnums()
            WriteNodeStructures()
            WriteFactories()
        End Using
    End Sub

    Private Sub WriteCsvLine(val1 As String, val2 As String, val3 As String)
        _writer.WriteLine("{0},{1},{2}", val1, val2, val3)
    End Sub

    Private Sub WriteBlankLine()
        WriteCsvLine("", "", "")
    End Sub

    Private Sub WriteEnums()
        For Each enumeration In _parseTree.Enumerations.Values
            WriteEnum(enumeration)
        Next
    End Sub

    Private Sub WriteNodeStructures()
        For Each nodeStructure In _parseTree.NodeStructures.Values
            WriteNodeStructure(nodeStructure)
        Next
    End Sub

    ' Generate an enumeration type
    Private Sub WriteEnum(enumeration As ParseEnumeration)
        WriteCsvLine("enum", EnumerationTypeName(enumeration), "")

        For Each enumerator In enumeration.Enumerators
            WriteEnumeratorVariable(enumerator, enumeration)
        Next

        WriteBlankLine()
    End Sub

    Private Sub WriteEnumeratorVariable(enumerator As ParseEnumerator, enumeration As ParseEnumeration)
        WriteCsvLine(NameOf(enumerator), EnumerationTypeName(enumeration), enumerator.Name)
    End Sub

    Private Sub WriteNodeStructure(nodeStructure As ParseNodeStructure)
        WriteCsvLine("class", StructureTypeName(nodeStructure), "")

        For Each kind In nodeStructure.NodeKinds
            WriteKind(kind)
        Next

        Dim allFields = GetAllFieldsOfStructure(nodeStructure)
        For i = 0 To allFields.Count - 1
            WriteField(allFields(i))
        Next

        Dim allChildren = GetAllChildrenOfStructure(nodeStructure)
        For i = 0 To allChildren.Count - 1
            WriteChild(allChildren(i))
        Next

        WriteBlankLine()
    End Sub

    Private Sub WriteKind(kind As ParseNodeKind)
        WriteCsvLine(NameOf(kind), StructureTypeName(kind.NodeStructure), Ident(kind.Name))
    End Sub

    Private Sub WriteField(field As ParseNodeField)
        WriteCsvLine(NameOf(field), StructureTypeName(field.ContainingStructure), FieldPropertyName(field))
    End Sub

    Private Sub WriteChild(child As ParseNodeChild)
        WriteCsvLine(NameOf(child), StructureTypeName(child.ContainingStructure), ChildPropertyName(child))
    End Sub

    Private Sub WriteFactories()
        WriteCsvLine("class", Ident(_parseTree.FactoryClassName), "")
        For Each nodeStructure In _parseTree.NodeStructures.Values
            GenerateFactoryMethodsForStructure(nodeStructure)
        Next
    End Sub

    Private Sub GenerateFactoryMethodsForStructure(nodeStructure As ParseNodeStructure)
        If _parseTree.IsAbstract(nodeStructure) Then Return ' abstract structures don't have factory methods

        For Each nodeKind In nodeStructure.NodeKinds
            GenerateFactoryMethods(nodeStructure, nodeKind)
        Next

        ' Only generate one a structure-level factory method if >= 2 kinds, and the nodeStructure name doesn't conflict with a kind name.
        If nodeStructure.NodeKinds.Count >= 2 And Not _parseTree.NodeKinds.ContainsKey(FactoryName(nodeStructure)) Then
            GenerateFactoryMethods(nodeStructure, Nothing)
        End If
    End Sub

    Private Sub GenerateFactoryMethods(nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind)
        GenerateFactoryMethod(nodeStructure, nodeKind, False)
        If HasSimplifiedFactory(nodeStructure, nodeKind) Then
            GenerateFactoryMethod(nodeStructure, nodeKind, True)
        End If
    End Sub

    ' Should we generator a simplified factory method also?
    Private Function HasSimplifiedFactory(nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind) As Boolean
        ' Currently, all tokens have simplified factories.
        Return nodeStructure.IsToken
    End Function

    ' Generate the factory method for a node structure, possibly customized to a particular kind.
    ' If kind is Nothing, generate a factory method that takes a Kind parameter, and can create any kind.
    ' If kind is not Nothing, generator a factory method customized to that particular kind.
    ' The simplified form is:
    '   Defaults the text for any token with token-text defined
    '   Defaults the trivia to a single trailing space for any token
    Private Sub GenerateFactoryMethod(nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind, simplifiedForm As Boolean)
        Dim factoryFunctionName As String       ' name of the factory method.

        If nodeKind IsNot Nothing Then
            If nodeKind.NoFactory Then Return

            factoryFunctionName = FactoryName(nodeKind)
        Else
            If nodeStructure.NoFactory Then Return

            factoryFunctionName = FactoryName(nodeStructure)
        End If

        WriteCsvLine("factory", Ident(_parseTree.FactoryClassName), Ident(factoryFunctionName))

    End Sub

End Class


text: require "rack/mongoid"

redpajama_set_name: RedPajamaGithub


text:
package org.apache.servicecomb.faultinjection;

import org.apache.servicecomb.core.Invocation;
import org.apache.servicecomb.swagger.invocation.AsyncResponse;
import org.apache.servicecomb.swagger.invocation.exception.CommonExceptionData;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AbortFault extends AbstractFault {
  private static final Logger LOGGER = LoggerFactory.getLogger(AbortFault.class);

  @Override
  public void injectFault(Invocation invocation, FaultParam faultParam, AsyncResponse asynResponse) {
    // get the config values related to abort.
    int abortPercent = FaultInjectionUtil.getFaultInjectionConfig(invocation,
        "abort.percent");

    if (abortPercent == FaultInjectionConst.FAULT_INJECTION_DEFAULT_VALUE) {
      LOGGER.debug("Fault injection: Abort percentage is not configured");
      asynResponse.success("success");
      return;
    }

    // check fault abort condition.
    boolean isAbort = FaultInjectionUtil.isFaultNeedToInject(faultParam.getReqCount(), abortPercent);
    if (isAbort) {
      // get the config values related to abort percentage.
      int errorCode = FaultInjectionUtil.getFaultInjectionConfig(invocation,
          "abort.httpStatus");

      if (errorCode == FaultInjectionConst.FAULT_INJECTION_DEFAULT_VALUE) {
        LOGGER.debug("Fault injection: Abort error code is not configured");
        asynResponse.success("success");
        return;
      }
      // if request need to be abort then return failure with given error code
      CommonExceptionData errorData = new CommonExceptionData("aborted by fault inject");
      asynResponse.consumerFail(new InvocationException(errorCode, "aborted by fault inject", errorData));
      return;
    }

    asynResponse.success("success");
  }

  @Override
  public int getOrder() {
    return 200;
  }
}


text:
package stroom.config.global.client.presenter;

import stroom.alert.client.event.AlertEvent;
import stroom.config.global.shared.ConfigProperty;
import stroom.config.global.shared.GlobalConfigCriteria;
import stroom.config.global.shared.GlobalConfigResource;
import stroom.config.global.shared.ListConfigResponse;
import stroom.data.grid.client.MyDataGrid;
import stroom.data.grid.client.PagerView;
import stroom.dispatch.client.Rest;
import stroom.dispatch.client.RestFactory;
import stroom.node.client.NodeManager;
import stroom.svg.client.Preset;
import stroom.util.client.DataGridUtil;
import stroom.util.client.DelayedUpdate;
import stroom.util.shared.PageRequest;
import stroom.widget.button.client.ButtonView;
import stroom.widget.util.client.MultiSelectionModelImpl;

import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.client.Timer;
import com.google.gwt.view.client.Range;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.HandlerRegistration;
import com.gwtplatform.mvp.client.MyPresenterWidget;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

public class ManageGlobalPropertyListPresenter
        extends MyPresenterWidget<PagerView>
        implements ColumnSortEvent.Handler {

    private static final String NODES_UNAVAILABLE_MSG = "[Error getting values]";
    private static final String NODES_UNAVAILABLE_SHORT_MSG = "[Error]";
    private static final String MULTIPLE_VALUES_MSG = "[Multiple values]";
    private static final String MULTIPLE_SOURCES_MSG = "[Multiple]";
    private static final String ERROR_CSS_COLOUR = "red";

    // This is the delay between getting the list of props and hitting all the other nodes
    // to get their specific values.  Too low and we pepper the nodes for each key press of the filter.
    // Too high and there is too big a delay in showing props with mixed source
    private static final int REFRESH_ALL_NODES_TIMER_DELAY_MS = 500;

    private static final int UPDATE_MAPS_TIMER_DELAY_MS = 50;

    private static final GlobalConfigResource GLOBAL_CONFIG_RESOURCE_RESOURCE = GWT.create(GlobalConfigResource.class);

    private final MyDataGrid<ConfigPropertyRow> dataGrid;
    private final MultiSelectionModelImpl<ConfigPropertyRow> selectionModel;
    private final ListDataProvider<ConfigPropertyRow> dataProvider;
    private final RestFactory restFactory;
    private final NodeManager nodeManager;
    private final Set<String> unreachableNodes = new HashSet<>();

    // propName => (node => effectiveValue)
    private final Map<String, Map<String, String>> nodeToClusterEffectiveValuesMap = new HashMap<>();
    // propName => (effectiveValues)
    private Map<String, Set<String>> propertyToUniqueEffectiveValuesMap = new HashMap<>();
    // propName => (node => source)
    private final Map<String, Map<String, String>> nodeToClusterSourcesMap = new HashMap<>();
    // propName => (sources)
    private Map<String, Set<String>> propertyToUniqueSourcesMap = new HashMap<>();

    private final DelayedUpdate refreshAllNodesTimer = new DelayedUpdate(REFRESH_ALL_NODES_TIMER_DELAY_MS,
            this::refreshPropertiesForAllNodes);

    // This is node that responded to the top level request
    private String lastNodeName;

    private final DelayedUpdate updateChildMapsTimer = new DelayedUpdate(UPDATE_MAPS_TIMER_DELAY_MS,
            this::updatePropertyKeyedMaps);

    private final NameFilterTimer nameFilterTimer = new NameFilterTimer();

    private final GlobalConfigCriteria criteria = new GlobalConfigCriteria(
            new PageRequest(0, Integer.MAX_VALUE),
            new ArrayList<>(),
            null);

    @Inject
    public ManageGlobalPropertyListPresenter(final EventBus eventBus,
                                             final PagerView view,
                                             final RestFactory restFactory,
                                             final NodeManager nodeManager) {
        super(eventBus, view);

        dataGrid = new MyDataGrid<>();
        selectionModel = dataGrid.addDefaultSelectionModel(false);
        view.setDataWidget(dataGrid);

        this.restFactory = restFactory;
        this.nodeManager = nodeManager;

        initColumns();

        dataProvider = new ListDataProvider<>();
        dataProvider.addDataDisplay(dataGrid);
        dataProvider.setListUpdater(this::refreshTable);
    }

    private void resetLocalState() {
        refreshAllNodesTimer.reset();
        updateChildMapsTimer.reset();

        nodeToClusterEffectiveValuesMap.clear();
        propertyToUniqueEffectiveValuesMap.clear();
        nodeToClusterSourcesMap.clear();
        propertyToUniqueSourcesMap.clear();
        unreachableNodes.clear();
    }

    private void refreshTable(final Range range) {

        criteria.setPageRequest(new PageRequest(range.getStart(), range.getLength()));

        resetLocalState();

//        GWT.log("Refresh table called");

        final Rest<ListConfigResponse> rest = restFactory.create();
        rest
                .onSuccess(listConfigResponse -> {

                    lastNodeName = listConfigResponse.getNodeName();

                    // Build the table based on what we know from one node
                    final List<ConfigPropertyRow> rows = listConfigResponse.getValues().stream()
                            .map(ConfigPropertyRow::new)
                            .collect(Collectors.toList());

//                GWT.log("Offset: " + listConfigResponse.getPageResponse().getOffset()
//                    + " total: " + listConfigResponse.getPageResponse().getTotal());

                    dataProvider.setPartialList(
                            rows,
                            listConfigResponse.getPageResponse()
                                    .getTotal()
                                    .intValue());

                    // The timer will fetch the node specific values for the other nodes
                    // so we need to process the values for this node
                    handleNodeResponse(listConfigResponse);

                    // now we have the props from one node, go off and get all the values/sources
                    // from all the nodes. Use a timer to delay it a bit
                    refreshAllNodesTimer.update();
                })
                .onFailure(caught ->
                        AlertEvent.fireError(
                                ManageGlobalPropertyListPresenter.this,
                                caught.getMessage(),
                                null))
                .call(GLOBAL_CONFIG_RESOURCE_RESOURCE)
                .list(criteria);
    }

    private void refreshPropertiesForAllNodes() {
        // Only care about enabled nodes
        unreachableNodes.clear();
        // No point hitting the node that we hit at the top level again as we already have its data
        nodeManager.listEnabledNodes(
                nodeNames ->
                        nodeNames
                                .stream()
                                .filter(nodeName -> !nodeName.equals(lastNodeName))
                                .forEach(this::refreshPropertiesForNode),
                throwable ->
                        showError(
                                throwable,
                                "Error getting list of all nodes. Only properties for one node will be shown"));
    }

    private void refreshPropertiesForNode(final String nodeName) {
//        GWT.log("Refreshing " + nodeName);
        final Rest<ListConfigResponse> listPropertiesRest = restFactory.create();

        criteria.setPageRequest(new PageRequest(
                dataGrid.getVisibleRange().getStart(),
                dataGrid.getVisibleRange().getLength()));

        listPropertiesRest
                .onSuccess(this::handleNodeResponse)
                .onFailure(throwable -> {
                    unreachableNodes.add(nodeName);

                    nodeToClusterEffectiveValuesMap.keySet().forEach(
                            propName -> {
                                nodeToClusterEffectiveValuesMap.computeIfAbsent(
                                        propName,
                                        k -> new HashMap<>())
                                        .remove(nodeName);

                                nodeToClusterSourcesMap.computeIfAbsent(
                                        propName,
                                        k -> new HashMap<>())
                                        .remove(nodeName);
                            });

                    // kick off the delayed action to update the maps keyed on prop name,
                    // unless another node has already kicked it off
                    updateChildMapsTimer.update();
                })
                .call(GLOBAL_CONFIG_RESOURCE_RESOURCE)
                .listByNode(nodeName, criteria);
    }

    private void handleNodeResponse(final ListConfigResponse listConfigResponse) {
//        GWT.log("Handling response for node " + listConfigResponse.getNodeName());
        unreachableNodes.remove(listConfigResponse.getNodeName());

        // Add the node's result to our maps
        listConfigResponse.getValues().forEach(configProperty -> {
            final String effectiveValue = configProperty.getEffectiveValue().orElse(null);
            final String source = configProperty.getSource().getName();

//            if (configProperty.getNameAsString().equals("stroom.statistics.sql.db.connectionPool.maxPoolSize")) {
//                GWT.log(listConfigResponse.getNodeName() + " - eff: " + effectiveValue + " source " + source);
//            }

            updateNodeKeyedMaps(
                    listConfigResponse.getNodeName(),
                    configProperty.getNameAsString(),
                    effectiveValue,
                    source);

            // kick off the delayed action to update the maps keyed on prop name,
            // unless another node has already kicked it off
            updateChildMapsTimer.update();
        });
    }

    private void updateNodeKeyedMaps(final String nodeName,
                                     final String propName,
                                     final String effectiveValue,
                                     final String source) {

        nodeToClusterEffectiveValuesMap.computeIfAbsent(
                propName,
                k -> new HashMap<>())
                .put(nodeName, effectiveValue);

//        if (propName.equals("stroom.statistics.sql.db.connectionPool.maxPoolSize")) {
//            GWT.log(nodeName + " - " + effectiveValue + " - "
//                    + nodeToClusterEffectiveValuesMap.get(propName).get(nodeName));
//        }

        nodeToClusterSourcesMap.computeIfAbsent(
                propName,
                k -> new HashMap<>())
                .put(nodeName, source);
    }

    private void populateDataProviderFromMaps() {
        final List<ConfigPropertyRow> newRows = dataProvider.getList()
                .stream()
                .map(row -> {
                    final String effectiveValueStr;
                    final Set<String> effectiveValues = propertyToUniqueEffectiveValuesMap.get(row.getNameAsString());

                    if (effectiveValues == null) {
                        effectiveValueStr = NODES_UNAVAILABLE_MSG;
                    } else {
                        if (effectiveValues.size() <= 1) {
                            effectiveValueStr = row.getEffectiveValueAsString();
                        } else {
//                            GWT.log(row.configProperty.getNameAsString() + effectiveValues);
                            effectiveValueStr = MULTIPLE_VALUES_MSG;
                        }
                    }

                    final String sourceStr;
                    final Set<String> sources = propertyToUniqueSourcesMap.get(row.getNameAsString());
                    if (sources == null) {
                        sourceStr = NODES_UNAVAILABLE_SHORT_MSG;
                    } else {
                        if (sources.size() <= 1) {
                            sourceStr = row.getSourceAsString();
                        } else {
                            sourceStr = MULTIPLE_SOURCES_MSG;
                        }
                    }

                    return new ConfigPropertyRow(row.getConfigProperty(), effectiveValueStr, sourceStr);
                })
                .collect(Collectors.toList());
        // We are not changing the total so re-use the existing one
        dataProvider.setPartialList(newRows, dataGrid.getRowCount());
    }

    private void updatePropertyKeyedMaps() {
        // Walk the node keyed maps to rebuild the property keyed maps
        // to build a picture of all values over the cluster for each prop
        propertyToUniqueEffectiveValuesMap = nodeToClusterEffectiveValuesMap.entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry ->
                                new HashSet<>(entry.getValue().values())
                ));

        propertyToUniqueSourcesMap = nodeToClusterSourcesMap.entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry ->
                                new HashSet<>(entry.getValue().values())
                ));

        populateDataProviderFromMaps();

        // Set errors.
        final String errors = unreachableNodes
                .stream()
                .sorted(Comparator.naturalOrder())
                .collect(Collectors.joining("\n"));
        ErrorEvent.fire(this, errors);
    }

    private void initColumns() {
        // Name.
        dataGrid.addResizableColumn(
                DataGridUtil.htmlColumnBuilder(ConfigPropertyRow::getNameAsString, SafeHtmlUtils::fromString)
                        .topAligned()
                        .withSorting(GlobalConfigResource.FIELD_DEF_NAME.getDisplayName())
                        .withStyleName(MyDataGrid.RESOURCES.dataGridStyle().dataGridCellVerticalTop())
                        .build(),
                GlobalConfigResource.FIELD_DEF_NAME.getDisplayName(),
                450);

        // Effective Value
        dataGrid.addResizableColumn(
                DataGridUtil.htmlColumnBuilder(
                        DataGridUtil.highlightedCellExtractor(
                                ConfigPropertyRow::getEffectiveValueAsString,
                                (ConfigPropertyRow row) ->
                                        MULTIPLE_VALUES_MSG.equals(row.getEffectiveValueAsString()),
                                ERROR_CSS_COLOUR))
                        .withSorting(GlobalConfigResource.FIELD_DEF_VALUE.getDisplayName())
                        .withStyleName(MyDataGrid.RESOURCES.dataGridStyle().dataGridCellVerticalTop())
                        .build(),
                GlobalConfigResource.FIELD_DEF_VALUE.getDisplayName(),
                300);

        // Source
        dataGrid.addResizableColumn(
                DataGridUtil.htmlColumnBuilder(
                        DataGridUtil.highlightedCellExtractor(
                                ConfigPropertyRow::getSourceAsString,
                                (ConfigPropertyRow row) ->
                                        MULTIPLE_SOURCES_MSG.equals(row.getSourceAsString()),
                                ERROR_CSS_COLOUR))
                        .withSorting(GlobalConfigResource.FIELD_DEF_SOURCE.getDisplayName())
                        .withStyleName(MyDataGrid.RESOURCES.dataGridStyle().dataGridCellVerticalTop())
                        .build(),
                GlobalConfigResource.FIELD_DEF_SOURCE.getDisplayName(),
                75);

        // Description
        dataGrid.addResizableColumn(
                DataGridUtil.htmlColumnBuilder(ConfigPropertyRow::getDescription, SafeHtmlUtils::fromString)
                        .topAligned()
                        .withStyleName(MyDataGrid.RESOURCES.dataGridStyle().dataGridCellWrapText())
                        .withStyleName(MyDataGrid.RESOURCES.dataGridStyle().dataGridCellVerticalTop())
                        .build(),
                GlobalConfigResource.FIELD_DEF_DESCRIPTION.getDisplayName(),
                750);

        DataGridUtil.addEndColumn(dataGrid);
        DataGridUtil.addColumnSortHandler(dataGrid, criteria, this::refresh);
    }

    public ButtonView addButton(final Preset preset) {
        return getView().addButton(preset);
    }

    @Override
    protected void onReveal() {
        super.onReveal();
        refresh();
    }

    public void refresh() {
        dataProvider.refresh(false);
    }

    public ConfigProperty getSelectedItem() {
        return selectionModel.getSelected().getConfigProperty();
    }

    void setPartialName(final String partialName) {
        nameFilterTimer.setName(partialName);
        nameFilterTimer.cancel();
        nameFilterTimer.schedule(400);
    }

    void clearFilter() {
        this.criteria.setQuickFilterInput(null);

        if (!(lastNodeName == null || lastNodeName.isEmpty())) {
            refresh();
        }
        lastNodeName = null;
    }

    private void showError(final Throwable throwable, final String message) {
        AlertEvent.fireError(
                ManageGlobalPropertyListPresenter.this,
                message + " - " + throwable.getMessage(),
                null,
                null);
    }

    @Override
    public void onColumnSort(final ColumnSortEvent event) {
        // TODO implement sorting for Name and Source
    }

    public HandlerRegistration addErrorHandler(final ErrorEvent.Handler handler) {
        return this.addHandlerToSource(ErrorEvent.getType(), handler);
    }

    public MultiSelectionModelImpl<ConfigPropertyRow> getSelectionModel() {
        return selectionModel;
    }

    public static class ConfigPropertyRow {

        private final ConfigProperty configProperty;
        private final String effectiveValue;
        private final String source;

        public ConfigPropertyRow(final ConfigProperty configProperty,
                                 final String effectiveValue,
                                 final String source) {
            this.configProperty = configProperty;
            this.effectiveValue = effectiveValue;
            this.source = source;
        }

        public ConfigPropertyRow(final ConfigProperty configProperty) {
            this.configProperty = configProperty;
            this.effectiveValue = null;
            this.source = null;
        }

        public ConfigProperty getConfigProperty() {
            return configProperty;
        }

        public String getEffectiveValueAsString() {
            return effectiveValue != null
                    ? effectiveValue
                    : configProperty.getEffectiveValueMasked().orElse(null);
        }

        public String getSourceAsString() {
            return source != null
                    ? source
                    : configProperty.getSource().getName();
        }

        public String getNameAsString() {
            return configProperty.getNameAsString();
        }

        public String getDescription() {
            return configProperty.getDescription();
        }
    }

    private class NameFilterTimer extends Timer {

        private String name;

        @Override
        public void run() {
            String filter = name;
            if (filter != null) {
                filter = filter.trim();
                if (filter.length() == 0) {
                    filter = null;
                }
            }

            if (!Objects.equals(filter, criteria.getQuickFilterInput())) {
                criteria.setQuickFilterInput(filter);
                // Need to reset the range else the name criteria can push us outside the page we are on
                Range range = dataGrid.getVisibleRange();
                dataGrid.setVisibleRange(0, range.getLength());
                refresh();
            }
        }

        public void setName(final String name) {
            this.name = name;
        }
    }
}


text:
{-# OPTIONS_GHC -cpp  #-}
{-# OPTIONS -fglasgow-exts #-}
{-# LANGUAGE MultiParamTypeClasses, OverlappingInstances, UndecidableInstances, FunctionalDependencies, NoMonomorphismRestriction #-}
{-+
This module defines a number of classes that captures various forms of IO.
This allows code to specify IO operations without being tied directly to
the standard #IO# monad.

Instances for the standard #IO# type as well as for all monad transformers
(for all classes except one) are provided. This allows the IO operations to
be used without explicit lifting in monads that extend the IO monad by
an arbitrary number of monad transformers.

Note that we redefine some functions exported from the #Prelude#. To be able
to use these, you need to refer to them by a qualified name, or exclude the
Prelude functions from the unqualified name space by explicitly importing
the #Prelude# and hiding them (as shown below, for example).

By the way, it *is* annoying that #Functor# isn't a superclass of
 #Monad#, isn't it!
-}
module AbstractIO(module AbstractIO,
		  IOError,ClockTime,S.ExitCode(..)) where
import Prelude hiding (readFile,writeFile, appendFile,
		       putStr,putStrLn,print,
		       getLine,readLn,getContents,
		       catch,ioError,userError)
import qualified Prelude
import qualified System.Directory as D
-- import qualified System as S
import qualified System.Exit as S
import qualified System.Cmd as S
import qualified System.Environment as S

import qualified System.IO as IO
import qualified System.IO.Error as IO

import qualified System.Time as Time
import System.Time(ClockTime,CalendarTime)
import MT(MT(..))

{-+
Reading and writing files
-------------------------
-}
class (Functor io,Monad io) => FileIO io where
  readFile :: FilePath -> io String
  writeFile :: FilePath -> String -> io ()
  appendFile :: FilePath -> String -> io ()

instance FileIO IO where
  readFile = Prelude.readFile
  writeFile = Prelude.writeFile
  appendFile = Prelude.appendFile

instance (MT t,Functor (t m),Monad (t m),FileIO m) => FileIO (t m) where
  readFile             = lift . readFile
  writeFile path       = lift . writeFile path
  appendFile path      = lift . appendFile path

{-+
Standard IO
-----------
(For messages in the terminal window and user input.)
-}
class (Functor io,Monad io) => StdIO io where
  putStr,putStrLn,ePutStr,ePutStrLn :: String -> io ()
  getLine :: io String -- blocking IO is considered bad by some... :-)
  getContents :: io String

  putStrLn s = putStr s >> putStr "\n"
  ePutStrLn s = ePutStr s >> ePutStr "\n"

print x = putStrLn (show x)

readIO s =  case [x | (x,t) <- reads s, ("","") <- lex t] of
              [x] -> return x
              []  -> ioError (userError "Prelude.readIO: no parse")
              _   -> ioError (userError "Prelude.readIO: ambiguous parse")

instance StdIO IO where
  putStr    = Prelude.putStr
  putStrLn  = Prelude.putStrLn
  ePutStr   = IO.hPutStr IO.stderr
  ePutStrLn = IO.hPutStrLn IO.stderr
  getLine  = Prelude.getLine
  getContents = Prelude.getContents

instance (MT t,Functor (t m),Monad (t m),StdIO m) => StdIO (t m) where
  putStr   = lift . putStr
  putStrLn = lift . putStrLn
  ePutStr   = lift . ePutStr
  ePutStrLn = lift . ePutStrLn
  getLine  = lift getLine
  getContents = lift getContents

{-+
System interaction
------------------
Operations corresponding to the standard library module #System#.
(Executing shell commands and other interaction with command line shells.)
-}

class (Functor io,Monad io) => SystemIO io where
  system :: String -> io S.ExitCode
  getEnv :: String -> io String
  getProgName :: io String
  getArgs :: io [String]
  -- ... exitWith

instance SystemIO IO where
  system = S.system
  getEnv = S.getEnv
  getProgName = S.getProgName
  getArgs = S.getArgs

instance (MT t,Functor (t m),Monad (t m),SystemIO m) => SystemIO (t m) where
  system = lift . system
  getEnv = lift . getEnv
  getProgName = lift getProgName
  getArgs = lift getArgs

{-+
Directory manipulation
----------------------
Operations corresponding to the standard library module #Directory#.
-}

class (Functor io,Monad io) => DirectoryIO io where
  createDirectory,removeFile :: FilePath -> io ()
  getModificationTime :: FilePath -> io ClockTime
  doesFileExist, doesDirectoryExist :: FilePath -> io Bool
  getDirectoryContents :: FilePath -> io [FilePath]

-- Base case:
instance DirectoryIO IO where
  createDirectory = D.createDirectory
  getModificationTime = D.getModificationTime
  doesFileExist = D.doesFileExist
  doesDirectoryExist = D.doesDirectoryExist . dropFinalSlash
  getDirectoryContents = D.getDirectoryContents
  removeFile = D.removeFile

-- Quick workaround for a Cygwin problem:
dropFinalSlash = reverse . dropit . reverse
  where dropit ('/':s) = s
	dropit s = s

-- Inductive case:
instance (MT t,Functor (t m),Monad (t m),DirectoryIO m)
      => DirectoryIO (t m) where
  createDirectory      = lift . createDirectory
  getModificationTime  = lift . getModificationTime
  doesFileExist        = lift . doesFileExist
  doesDirectoryExist   = lift . doesDirectoryExist
  getDirectoryContents = lift . getDirectoryContents
  removeFile           = lift . removeFile

{-+
Time functions
----------------------
Operations corresponding to the standard library module #Time#.
(Only the subset requiring IO.)
-}

class (Functor m,Monad m) => TimeIO m where
  getClockTime :: m ClockTime
  toCalendarTime :: ClockTime -> m CalendarTime

instance TimeIO IO where
  getClockTime = Time.getClockTime
  toCalendarTime = Time.toCalendarTime

instance (MT t,Functor (t m),Monad (t m),TimeIO m) => TimeIO (t m) where
  getClockTime = lift getClockTime
  toCalendarTime = lift . toCalendarTime

{-+
Catching errors
---------------

This is the only class that lacks a general instance for monad transformers.
(It is probably a good idea to try to survive without relying on error
handlers...)
-}

class (Functor io,Monad io) => CatchIO ioerror io | io->ioerror where
  catch :: io a -> (ioerror -> io a) -> io a
  ioError :: ioerror -> io a

try m = fmap Right m `catch` (return . Left)
maybeM m = (Just `fmap` m) `catch` const (return Nothing)

bracket before after m =
  do x <- before
     r <- try (m x)
     after x
     returnTry r

bracket_ before after m =
  do x <- before
     r <- try m
     after x
     returnTry r

tryThen m after =
  do r <- try m
     after
     returnTry r

returnTry r = either ioError return r

instance CatchIO IOError IO where
  catch = Prelude.catch
  ioError = Prelude.ioError

--instance (MT t,Functor (t m),Monad (t m),CatchIO m) => CatchIO (t m) where
  -- !! How do you lift operations with negative occurences of m?

class IOErr ioerror where
  userError :: String -> ioerror
  isDoesNotExistError,isUserError :: ioerror -> Bool
  ioeGetErrorString :: ioerror -> String
  -- ..., ioeGetFileName, ...

instance IOErr IOError where
  userError = IO.userError
  isDoesNotExistError = IO.isDoesNotExistError
  isUserError = IO.isUserError
  ioeGetErrorString = IO.ioeGetErrorString


text:
module Azure::OperationalInsights::Mgmt::V2020_03_01_preview
  module Models
    #
    # Defines values for DataSourceType
    #
    module DataSourceType
      CustomLogs = "CustomLogs"
      AzureWatson = "AzureWatson"
      Query = "Query"
      Ingestion = "Ingestion"
      Alerts = "Alerts"
    end
  end
end


text:
/*!
  \file aqfp_resynthesis.hpp
  \brief Resynthesis of path balanced networks

  \author Dewmini Sudara Marakkalage
  \author Siang-Yun (Sonia) Lee
*/

#pragma once

#include <iostream>
#include <unordered_map>

#include <fmt/format.h>

#include "../../traits.hpp"
#include "../../utils/node_map.hpp"
#include "../../utils/stopwatch.hpp"
#include "../../views/depth_view.hpp"
#include "../../views/topo_view.hpp"

namespace mockturtle
{

/*! \brief Parameters for aqfp_resynthesis.
 *
 * The data structure `aqfp_resynthesis_params` holds configurable parameters
 * with default arguments for `node_resynthesis`.
 */
struct aqfp_resynthesis_params
{
  bool verbose{ false };
};

/*! \brief Statistics of aqfp_resynthesis.
 *
 * The data structure `aqfp_resynthesis_stats` holds data collected during AQFP re-synthesis.
 */
struct aqfp_resynthesis_stats
{
  stopwatch<>::duration time_total{ 0 };

  void report() const
  {
    std::cout << fmt::format( "[i] total time = {:>8.2f} secs\n", to_seconds( time_total ) );
  }
};

/*! \brief Results of aqfp_resynthesis.
 *
 * The data structure `aqfp_resynthesis_result` holds the resulting level assignment of nodes
 * and the level of the critical primary output.
 */
template<typename NtkDest>
struct aqfp_resynthesis_result
{
  std::unordered_map<node<NtkDest>, uint32_t> node_level;
  std::unordered_map<node<NtkDest>, uint32_t> po_level;

  uint32_t critical_po_level()
  {
    return max_element( po_level.begin(), po_level.end(), [&]( auto n1, auto n2 ) { return n1.second < n2.second; } )
        ->second;
  }
};

namespace detail
{

/*! \brief Implementation of the AQFP re-synthesis algorithm. */
template<typename NtkDest, typename NtkSrc, typename NodeResynFn, typename FanoutResynFn>
class aqfp_resynthesis_impl
{
public:
  aqfp_resynthesis_impl(
      NtkDest& ntk_dest,
      NtkSrc const& ntk_src,
      NodeResynFn&& node_resyn_fn,
      FanoutResynFn&& fanout_resyn_fn,
      aqfp_resynthesis_params const& ps,
      aqfp_resynthesis_stats& st )
      : ntk_dest( ntk_dest ),
        ntk_src( ntk_src ),
        node_resyn_fn( node_resyn_fn ),
        fanout_resyn_fn( fanout_resyn_fn ),
        ps( ps ),
        st( st )
  {
  }

  aqfp_resynthesis_result<NtkDest> run()
  {
    stopwatch t( st.time_total );

    node_map<signal<NtkDest>, NtkSrc> node2new( ntk_src );
    node_map<uint32_t, NtkSrc> level_of_src_node( ntk_src );

    std::unordered_map<node<NtkDest>, uint32_t> level_of_node;
    std::unordered_map<node<NtkDest>, uint32_t> po_level_of_node;
    std::map<std::pair<node<NtkSrc>, node<NtkSrc>>, uint32_t> level_for_fanout;

    std::unordered_map<node<NtkSrc>, std::vector<node<NtkSrc>>> fanouts;
    ntk_src.foreach_gate( [&]( auto n ) { ntk_src.foreach_fanin( n, [&]( auto fi ) { fanouts[ntk_src.get_node( fi )].push_back( n ); } ); } );

    depth_view ntk_depth{ ntk_src };
    topo_view ntk_topo{ ntk_depth };

    /* map constants */
    auto c0 = ntk_dest.get_constant( false );
    node2new[ntk_src.get_node( ntk_src.get_constant( false ) )] = c0;
    level_of_node[ntk_dest.get_node( c0 )] = 0u;

    if ( ntk_src.get_node( ntk_src.get_constant( true ) ) != ntk_src.get_node( ntk_src.get_constant( false ) ) )
    {
      auto c1 = ntk_dest.get_constant( true );
      node2new[ntk_src.get_node( ntk_src.get_constant( true ) )] = c1;
      level_of_node[ntk_dest.get_node( c1 )] = 0u;
    }

    /* map primary inputs */
    ntk_src.foreach_pi( [&]( auto n ) {
      auto pi = ntk_dest.create_pi();
      node2new[n] = pi;
      level_of_node[ntk_dest.get_node( pi )] = 0u;

      if constexpr ( has_has_name_v<NtkSrc> && has_get_name_v<NtkSrc> && has_set_name_v<NtkDest> )
      {
        if ( ntk_src.has_name( ntk_src.make_signal( n ) ) )
          ntk_dest.set_name( node2new[n], ntk_src.get_name( ntk_src.make_signal( n ) ) );
      }

      /* synthesize fanout net of `n`*/
      auto fanout_node_callback = [&]( const auto& f, const auto& level ) {
        level_for_fanout[{ n, f }] = level;
      };

      auto fanout_po_callback = [&]( const auto& index, const auto& level ) {
        (void)index;
        auto node = ntk_dest.get_node(node2new[n]);
        po_level_of_node[node] = std::max(po_level_of_node[node], level);
      };

      fanout_resyn_fn( ntk_topo, n, fanouts[n], ntk_dest, node2new[n], 0u, fanout_node_callback, fanout_po_callback ); } );

    /* map register outputs */
    if constexpr ( has_foreach_ro_v<NtkSrc> && has_create_ro_v<NtkDest> )
    {
      ntk_src.foreach_ro( [&]( auto n, auto i ) {
        auto ro = ntk_dest.create_ro();
        node2new[n] = ro;
        level_of_node[ntk_dest.get_node( ro )] = 0u;

        ntk_dest.set_register( i, ntk_src.register_at( i ) );
        if constexpr ( has_has_name_v<NtkSrc> && has_get_name_v<NtkSrc> && has_set_name_v<NtkDest> )
        {
          if ( ntk_src.has_name( ntk_src.make_signal( n ) ) )
            ntk_dest.set_name( node2new[n], ntk_src.get_name( ntk_src.make_signal( n ) ) );
        }

        auto fanout_node_callback = [&]( const auto& f, const auto& level ) {
          level_for_fanout[{ n, f }] = level;
        };

        auto fanout_po_callback = [&]( const auto& index, const auto& level ) {
          (void)index;
          auto node = ntk_dest.get_node(node2new[n]);
          po_level_of_node[node] = std::max(po_level_of_node[node], level);
        };

        fanout_resyn_fn( ntk_topo, n, fanouts[n], ntk_dest, node2new[n], 0u, fanout_node_callback, fanout_po_callback ); } );
    }

    /* map nodes */
    ntk_topo.foreach_node( [&]( auto n ) {
      if ( ntk_topo.is_constant( n ) || ntk_topo.is_ci( n ) )
        return;

      /* synthesize node `n` */
      std::vector<std::pair<signal<NtkDest>, uint32_t>> children;
      ntk_topo.foreach_fanin( n, [&]( auto const& f ) {
        children.push_back( { ntk_topo.is_complemented( f ) ? ntk_dest.create_not( node2new[f] ) : node2new[f], level_for_fanout[{ ntk_topo.get_node( f ), n }] } );
      } );

      auto performed_resyn = false;

      auto level_update_callback =
          [&]( const auto& n, uint32_t level ) {
            if ( !level_of_node.count( n ) )
            {
              level_of_node[n] = level;
            }
          };

      auto resyn_performed_callback =
          [&]( const auto& f, auto new_level ) {
            node2new[n] = f;
            level_of_src_node[n] = new_level;

            if constexpr ( has_has_name_v<NtkSrc> && has_get_name_v<NtkSrc> && has_set_name_v<NtkDest> )
            {
              if ( ntk_topo.has_name( ntk_topo.make_signal( n ) ) )
                ntk_dest.set_name( f, ntk_topo.get_name( ntk_topo.make_signal( n ) ) );
            }

            performed_resyn = true;
          };

      node_resyn_fn( ntk_dest, ntk_topo.node_function( n ), children.begin(), children.end(), level_update_callback, resyn_performed_callback );

      if ( !performed_resyn )
      {
        fmt::print( "[e] could not perform resynthesis for node {} in node_resynthesis\n", ntk_topo.node_to_index( n ) );
        std::abort();
      }

      /* synthesize fanout net of `n` */
      auto fanout_node_callback = [&]( const auto& f, const auto& level ) {
        level_for_fanout[{ n, f }] = std::max(level_for_fanout[{n, f}], level);
      };

      auto fanout_po_callback = [&]( const auto& index, const auto& level ) {
        (void)index;
        auto node = ntk_dest.get_node(node2new[n]);
        po_level_of_node[node] = std::max(po_level_of_node[node], level);
      };

      fanout_resyn_fn( ntk_topo, n, fanouts[n], ntk_dest, node2new[n], level_of_src_node[n], fanout_node_callback, fanout_po_callback ); } );

    /* map primary outputs */
    ntk_src.foreach_po( [&]( auto const& f, auto index ) {
      (void)index;

      auto const o = ntk_src.is_complemented( f ) ? ntk_dest.create_not( node2new[f] ) : node2new[f];
      ntk_dest.create_po( o );

      assert(ntk_dest.is_constant(ntk_dest.get_node(o)) || po_level_of_node.count(ntk_dest.get_node(o)) > 0);
      assert(ntk_dest.is_constant(ntk_dest.get_node(o)) || po_level_of_node.at(ntk_dest.get_node(o)) >= level_of_node.at(ntk_dest.get_node(o)));

      if constexpr ( has_has_output_name_v<NtkSrc> && has_get_output_name_v<NtkSrc> && has_set_output_name_v<NtkDest> )
      {
        if ( ntk_src.has_output_name( index ) )
        {
          ntk_dest.set_output_name( index, ntk_src.get_output_name( index ) );
        }
      } } );

    /* map register inputs */
    if constexpr ( has_foreach_ri_v<NtkSrc> && has_create_ri_v<NtkDest> )
    {
      ntk_src.foreach_ri( [&]( auto const& f, auto index ) {
        (void)index;

        auto const o = ntk_src.is_complemented( f ) ? ntk_dest.create_not( node2new[f] ) : node2new[f];
        ntk_dest.create_ri( o );

        if constexpr ( has_has_output_name_v<NtkSrc> && has_get_output_name_v<NtkSrc> && has_set_output_name_v<NtkDest> )
        {
          if ( ntk_src.has_output_name( index ) )
          {
            ntk_dest.set_output_name( index + ntk_src.num_pos(), ntk_src.get_output_name( index + ntk_src.num_pos() ) );
          }
        } } );
    }

    return { level_of_node, po_level_of_node };
  }

private:
  NtkDest& ntk_dest;
  NtkSrc const& ntk_src;
  NodeResynFn&& node_resyn_fn;
  FanoutResynFn&& fanout_resyn_fn;
  aqfp_resynthesis_params const& ps;
  aqfp_resynthesis_stats& st;
};

} /* namespace detail */

/*! \brief Re-synthesize a given source network as a path-balanced AQFP network.
 *
 * The algorithm outputs an AQFP network with level assignments to its nodes and combinational outputs.
 *
   \verbatim embed:rst

   Example

   .. code-block:: c++

     aqfp_assumptions assume = { false, false, true, 4u };
     aqfp_fanout_resyn fanout_resyn{ assume };

     std::unordered_map<uint32_t, double> gate_costs = { { 3u, 6.0 }, { 5u, 10.0 } };
     std::unordered_map<uint32_t, double> splitters = { { 1u, 2.0 }, { assume.splitter_capacity, 2.0 } };
     aqfp_node_resyn_param ps{ assume, splitters, aqfp_node_resyn_strategy::delay };

     aqfp_db<> db( gate_costs, splitters );
     db.load_db( ... ); // from an input-stream (e.g., std::ifstream or std::stringstream)

     aqfp_node_resyn node_resyn( db, ps );

     klut_network src_ntk = ...;
     aqfp_network dst_ntk;
     auto res = aqfp_resynthesis( dst_ntk, src_ntk, node_resyn, fanout_resyn );

   \endverbatim
 */
template<class NtkDest, class NtkSrc, class NodeResynFn, class FanoutResynFn>
aqfp_resynthesis_result<NtkDest> aqfp_resynthesis(
    NtkDest& ntk_dest,
    NtkSrc const& ntk_src,
    NodeResynFn&& node_resyn_fn,
    FanoutResynFn&& fanout_resyn_fn,
    aqfp_resynthesis_params const& ps = { false },
    aqfp_resynthesis_stats* pst = nullptr )
{
  static_assert( is_network_type_v<NtkSrc>, "NtkSrc is not a network type" );
  static_assert( is_network_type_v<NtkDest>, "NtkDest is not a network type" );

  static_assert( has_get_node_v<NtkSrc>, "NtkSrc does not implement the get_node method" );
  static_assert( has_get_constant_v<NtkSrc>, "NtkSrc does not implement the get_constant method" );
  static_assert( has_foreach_pi_v<NtkSrc>, "NtkSrc does not implement the foreach_pi method" );
  static_assert( has_foreach_node_v<NtkSrc>, "NtkSrc does not implement the foreach_node method" );
  static_assert( has_is_constant_v<NtkSrc>, "NtkSrc does not implement the is_constant method" );
  static_assert( has_is_pi_v<NtkSrc>, "NtkSrc does not implement the is_pi method" );
  static_assert( has_is_complemented_v<NtkSrc>, "NtkSrc does not implement the is_complemented method" );
  static_assert( has_foreach_fanin_v<NtkSrc>, "NtkSrc does not implement the foreach_fanin method" );
  static_assert( has_node_function_v<NtkSrc>, "NtkSrc does not implement the node_function method" );
  static_assert( has_foreach_po_v<NtkSrc>, "NtkSrc does not implement the foreach_po method" );

  static_assert( has_get_constant_v<NtkDest>, "NtkDest does not implement the get_constant method" );
  static_assert( has_create_pi_v<NtkDest>, "NtkDest does not implement the create_pi method" );
  static_assert( has_create_not_v<NtkDest>, "NtkDest does not implement the create_not method" );
  static_assert( has_create_po_v<NtkDest>, "NtkDest does not implement the create_po method" );

  aqfp_resynthesis_stats st;

  detail::aqfp_resynthesis_impl<NtkDest, NtkSrc, NodeResynFn, FanoutResynFn> p( ntk_dest, ntk_src, node_resyn_fn, fanout_resyn_fn, ps, st );
  auto result = p.run();

  if ( ps.verbose )
  {
    st.report();
  }

  if ( pst )
  {
    *pst = st;
  }

  return result;
}

} // namespace mockturtle


text:
[![NPM](https://nodei.co/npm/react-sortable-tree.png)](https://npmjs.org/package/react-sortable-tree)

[![tree200](https://cloud.githubusercontent.com/assets/4413963/18860410/26f64de8-84b8-11e6-9284-350308eed30a.png)](https://fritz-c.github.io/react-sortable-tree/)

### [Demo](https://fritz-c.github.io/react-sortable-tree/)
[![demo](https://cloud.githubusercontent.com/assets/4413963/19334888/2be8261c-913a-11e6-9508-4b347ae114b4.gif)](https://fritz-c.github.io/react-sortable-tree/)

### Features

- Works right out of the box, but is highly customizable

## Example

```jsx
import React, { Component } from 'react';
import SortableTree from 'react-sortable-tree';

export default class Tree extends Component {
    constructor(props) {
        super(props);

        this.state = {
            treeData: [{ title: 'Chicken', children: [ { title: 'Egg' } ] }],
        };
    }

    render() {
        return (
            <div style={{ height: 400 }}>
                <SortableTree
                    treeData={this.state.treeData}
                    onChange={treeData => this.setState({ treeData })}
                />
            </div>
        );
    }
}

```

## Options

Property                  | Type           | Default             | Required | Description
:-------------------------|:--------------:|:-------------------:|:--------:|:----------------------------------------
treeData                  | object[]       |                     |   yes    | Tree data with the following keys:
`title` is the primary label for the node.

`subtitle` is a secondary label for the node.

`expanded` shows children of the node if true, or hides them if false. Defaults to false.

`children` is an array of child nodes belonging to the node.

__Example__: `[{title: 'main', subtitle: 'sub'}, { title: 'value2', expanded: true, children: [{ title: 'value3') }] }]`
onChange                  | func           |                     |   yes    | Called whenever tree data changed. Just like with React input elements, you have to update your own component's data to see the changes reflected.
`( treeData: object[] ): void`

style                     | object         | `{}`                |          | Style applied to the container wrapping the tree (style defaults to {height: '100%'})
className                 | string         |                     |          | Class name for the container wrapping the tree
innerStyle                | object         | `{}`                |          | Style applied to the inner, scrollable container (for padding, etc.)
maxDepth                  | number         |                     |          | Maximum depth nodes can be inserted at. Defaults to infinite.
searchMethod              | func           |                     |          | The method used to search nodes. Defaults to a function that uses the `searchQuery` string to search for nodes with matching `title` or `subtitle` values. NOTE: Changing `searchMethod` will not update the search, but changing the `searchQuery` will.
`({ node: object, path: number[] or string[], treeIndex: number, searchQuery: any }): bool`

searchQuery               | string or any  | `null`              |          | Used by the `searchMethod` to highlight and scroll to matched nodes. Should be a string for the default `searchMethod`, but can be anything when using a custom search.
searchFocusOffset         | number         |                     |          | Outline the <`searchFocusOffset`>th node and scroll to it.
searchFinishCallback      | func           |                     |          | Get the nodes that match the search criteria. Used for counting total matches, etc.
`(matches: { node: object, path: number[] or string[], treeIndex: number }[]): void`

generateNodeProps         | func           |                     |          | Generate an object with additional props to be passed to the node renderer. Use this for adding buttons via the `buttons` key, or additional `style` / `className` settings.
`({ node: object, path: number[] or string[], treeIndex: number, lowerSiblingCounts: number[], isSearchMatch: bool, isSearchFocus: bool }): object`

getNodeKey                | func           | defaultGetNodeKey   |          | Determine the unique key used to identify each node and generate the `path` array passed in callbacks. By default, returns the index in the tree (omitting hidden nodes).
`({ node: object, treeIndex: number }): string or number`

onMoveNode                | func           |                     |          | Called after node move operation.
`({ treeData: object[], node: object, treeIndex: number, path: number[] or string[] }): void`

onVisibilityToggle        | func           |                     |          | Called after children nodes collapsed or expanded.
`({ treeData: object[], node: object, expanded: bool }): void`

reactVirtualizedListProps | object         |                     |          | Custom properties to hand to the [react-virtualized list](https://github.com/bvaughn/react-virtualized/blob/master/docs/List.md#prop-types)
rowHeight                 | number or func | `62`                |          | Used by react-virtualized. Either a fixed row height (number) or a function that returns the height of a row given its index: `({ index: number }): number`
slideRegionSize           | number         | `100`               |          | Size in px of the region near the edges that initiates scrolling on dragover.
scaffoldBlockPxWidth      | number         | `44`                |          | The width of the blocks containing the lines representing the structure of the tree.
isVirtualized             | bool           | `true`              |          | Set to false to disable virtualization. __NOTE__: Auto-scrolling while dragging, and scrolling to the `searchFocusOffset` will be disabled.
nodeContentRenderer       | any            | NodeRendererDefault |          | Override the default component for rendering nodes (but keep the scaffolding generator) This is an advanced option for complete customization of the appearance. It is best to copy the component in `node-renderer-default.js` to use as a base, and customize as needed.

## Data Helper Functions

Need a hand turning your flat data into nested tree data?
Want to perform add/remove operations on the tree data without creating your own recursive function?
Check out the helper functions exported from [`tree-data-utils.js`](https://github.com/fritz-c/react-sortable-tree/blob/master/src/utils/tree-data-utils.js).

Notable among the available functions:

- __`getTreeFromFlatData`__: Convert flat data (like that from a database) into nested tree data
- __`getFlatDataFromTree`__: Convert tree data back to flat data
- __`addNodeUnderParent`__: Add a node under the parent node at the given path
- __`removeNodeAtPath`__: Remove the node at the given path
- __`map`__: Perform a change on every node in the tree
- __`walk`__: Visit every node in the tree in order

Documentation for each method is only available in the code at this time.
If your hobbies happen to include writing documentation, by all means submit a pull request. It would really help out.

## Browser Compatibility

| Browser | Works? |
|:-----|:-----|
| Chrome | Yes |
| Firefox | Yes |
| Safari | Yes |
| IE >= 10 | Yes |
| IE 9 | Broken due to flexbox issues. [Plan to fix.](https://github.com/fritz-c/react-sortable-tree/issues/6)  |

## Troubleshooting

### If it doesn't work with other components that use react-dnd

react-dnd only allows for one DragDropContext at a time (see: https://github.com/gaearon/react-dnd/issues/186). To get around this, you can import the context-less tree component via `SortableTreeWithoutDndContext`.
```js
// before
import SortableTree from 'react-sortable-tree';

// after
import { SortableTreeWithoutDndContext as SortableTree } from 'react-sortable-tree';
```

## Contributing

After cloning the repository and running `npm install` inside, you can use the following commands to develop and build the project.

```sh
# Starts a webpack dev server that hosts a demo page with the component.
# It uses react-hot-loader so changes are reflected on save.
npm start

# Lints the code with eslint and my custom rules.
npm run lint

# Lints and builds the code, placing the result in the dist directory.
# This build is necessary to reflect changes if you're
#  `npm link`-ed to this repository from another local project.
npm run build
```

Pull requests are welcome!

## License

MIT


text:
class ApplicationMailer < ActionMailer::Base
  default from: AppConfig.emails.default_from
  layout 'mailer'
end


text:
{% extends "admin/base_site.html" %}
{% load i18n l10n static %}
{% load url from future %}
{% load admin_urls %}

{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/forms.css" %}" />{% endblock %}

{% block breadcrumbs %}

		{% trans 'Home' %}
		› {{ app_label|capfirst|escape }}
		› {{ opts.verbose_name_plural|capfirst }}
		› {% trans 'Set the domain name of the cloned zone' %}

{% endblock %}

{% block title %}{% trans 'Set the domain name of the cloned zone' %}{% endblock %}

{% block content %}

        <form action="" method="post">{% csrf_token %}

            {% if form.errors %}

                {% blocktrans count counter=form.errors.items|length %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}

            {% endif %}

{% trans 'Set the domain name of the cloned zone' %}

{% trans "Enter a domain name for the cloned zone." %}

            <fieldset class="module aligned">

                    {{ form.clone_domain_name.errors }}
                    {% trans 'Domain Name' %}:{{ form.clone_domain_name }}

{{ form.clone_domain_name.help_text }}

                    {{ form.option_clone_dynamic.errors }}
                    {% trans 'Clone dynamic setting' %}:{{ form.option_clone_dynamic }}

{{ form.option_clone_dynamic.help_text }}

                    {{ form.option_clone_metadata.errors }}
                    {% trans 'Clone zone metadata' %}:{{ form.option_clone_metadata }}

{{ form.option_clone_metadata.help_text }}

            </fieldset>

            {# Special Fields #}
            {# These are needed for the action code to work. This an undocumented Django feature #}
            {% for obj in queryset %}
                <input type="hidden" name="{{ action_checkbox_name }}" value="{{ obj.pk|unlocalize }}" />
            {% endfor %}
            <input type="hidden" name="action" value="clone_zone" />
            <input type="hidden" name="post" value="yes" />

                <input type="submit" value="{% trans 'Clone' %}" class="default" />

        </form>

{% endblock %}


text:
/***
* Inferno Engine v4 2015-2017
* Written by Tomasz "Rex Dex" Jonarski
*
* [#filter: io\system\watcher #]
***/

#pragma once

#include "absolutePath.h"

namespace base
{
    namespace io
    {
        enum class DirectoryWatcherEventType : Uint8
        {
            FileAdded,
            DirectoryAdded,
            FileRemoved,
            DirectoryRemoved,
            FileContentChanged,
            FileMetadataChanged,
        };

        // directory watcher event, sent to the listener interface
        struct BASE_IO_API DirectoryWatcherEvent
        {
            DirectoryWatcherEventType m_type;
            AbsolutePath m_path;
        };

        // directory watcher callback
        // NOTE: this may be called at any time and from any thread (sometimes a deep OS thread)
        class BASE_IO_API IDirectoryWatcherListener : public base::NoCopy
        {
        public:
            virtual ~IDirectoryWatcherListener();

            /// handle file event
            virtual void handleEvent(const DirectoryWatcherEvent& evt) = 0;
        };

        // an abstract directory watcher interface
        // NOTE: the directory watcher watches the specified directory and all sub directories
        class BASE_IO_API IDirectoryWatcher : public base::NoCopy
        {
        public:
            virtual ~IDirectoryWatcher();

            //! attach listener
            virtual void attachListener(IDirectoryWatcherListener* listener) = 0;

            //! detach event listener
            virtual void dettachListener(IDirectoryWatcherListener* listener) = 0;

        protected:
            IDirectoryWatcher();
        };

    } // io
} // base


text:
namespace ledger { namespace core { namespace api {

std::string to_string(const TezosCurve& tezosCurve) {
    switch (tezosCurve) {
        case TezosCurve::ED25519: return "ED25519";
        case TezosCurve::SECP256K1: return "SECP256K1";
        case TezosCurve::P256: return "P256";
    };
};
template <>
TezosCurve from_string(const std::string& tezosCurve) {
    if (tezosCurve == "ED25519") return TezosCurve::ED25519;
    else if (tezosCurve == "SECP256K1") return TezosCurve::SECP256K1;
    else return TezosCurve::P256;
};

std::ostream &operator<<(std::ostream &os, const TezosCurve &o)
{
    switch (o) {
        case TezosCurve::ED25519:  return os << "ED25519";
        case TezosCurve::SECP256K1:  return os << "SECP256K1";
        case TezosCurve::P256:  return os << "P256";
    }
}

} } }  // namespace ledger::core::api


text:
'''
# Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
#
#  This file was generated and any changes will be overwritten.
'''

from __future__ import unicode_literals
from datetime import datetime
from ..one_drive_object_base import OneDriveObjectBase

class UploadSession(OneDriveObjectBase):

    def __init__(self, prop_dict=None):
        self._prop_dict = prop_dict if prop_dict is not None else {}

    @property
    def upload_url(self):
        """Gets and sets the uploadUrl

        Returns:
            str:
                The uploadUrl
        """
        if "uploadUrl" in self._prop_dict:
            return self._prop_dict["uploadUrl"]
        else:
            return None

    @upload_url.setter
    def upload_url(self, val):
        self._prop_dict["uploadUrl"] = val

    @property
    def expiration_date_time(self):
        """Gets and sets the expirationDateTime

        Returns:
            datetime:
                The expirationDateTime
        """
        if "expirationDateTime" in self._prop_dict:
            if '.' in self._prop_dict["expirationDateTime"]:
                return datetime.strptime(self._prop_dict["expirationDateTime"].replace("Z", ""), "%Y-%m-%dT%H:%M:%S.%f")
            else:
                return datetime.strptime(self._prop_dict["expirationDateTime"].replace("Z", ""), "%Y-%m-%dT%H:%M:%S")
        else:
            return None

    @expiration_date_time.setter
    def expiration_date_time(self, val):
        self._prop_dict["expirationDateTime"] = val.isoformat()+((".0" if val.time().microsecond == 0 else "")+"Z")

    @property
    def next_expected_ranges(self):
        """Gets and sets the nextExpectedRanges

        Returns:
            str:
                The nextExpectedRanges
        """
        if "nextExpectedRanges" in self._prop_dict:
            return self._prop_dict["nextExpectedRanges"]
        else:
            return None

    @next_expected_ranges.setter
    def next_expected_ranges(self, val):
        self._prop_dict["nextExpectedRanges"] = val


text:
<template name="Dropzone">

			{{> DownloadList files=this.files type=this.tp}}

Slipp {{typeDesc}} her
(eller klikk)

				{{! A hidden input field of type file. We can then simulate a mouse click on this input field, and open a OS file browser. }}
				<input type="file" id="upload-{{tp}}" name="upload-{{tp}}" style="visibility: hidden; width: 1px; height: 1px" multiple />

</template>


text:
var BaseMetrics = require('./BaseMetrics'),
	helpers = require('../helpers');

function NetworkTimings() {
	BaseMetrics.apply(this, arguments);
}
require('util').inherits(NetworkTimings, BaseMetrics);

NetworkTimings.prototype.id = 'NetworkTimings';
NetworkTimings.prototype.probes = ['NavTimingProbe'];

NetworkTimings.prototype.onData = function(data) {
	this.timing = data;
}

NetworkTimings.prototype.getResults = function(cfg, browser) {

	// More useful representation of timing information
	// Credit : https://github.com/addyosmani/timing.js
	this.addMetric('loadTime', 'loadEventEnd', 'fetchStart');
	this.addMetric('domReadyTime', 'domComplete', 'domInteractive');
	this.addMetric('readyStart', 'fetchStart', 'navigationStart');
	this.addMetric('redirectTime', 'redirectEnd', 'redirectStart');
	this.addMetric('appcacheTime', 'domainLookupStart', 'fetchStart');
	this.addMetric('unloadEventTime', 'unloadEventEnd', 'unloadEventStart');
	this.addMetric('domainLookupTime', 'domainLookupEnd', 'domainLookupStart');
	this.addMetric('connectTime', 'connectEnd', 'connectStart');
	this.addMetric('requestTime', 'responseEnd', 'requestStart');
	this.addMetric('initDomTreeTime', 'domInteractive', 'responseEnd');
	this.addMetric('loadEventTime', 'loadEventEnd', 'loadEventStart');

	return this.timing;
}

NetworkTimings.prototype.addMetric = function(prop, a, b) {
	if (typeof this.timing[a] === 'number' && typeof this.timing[b] === 'number') {
		this.timing[prop] = this.timing[a] - this.timing[b];
	}
}

module.exports = NetworkTimings;


text:
"""
Forms for contact forms
"""
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.mail import send_mail
from django.forms import ModelForm, Textarea
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _

from project.utils.context_processors import get_site_metas

from crispy_forms.helper import FormHelper
from crispy_forms_foundation.layout import Layout, Field, Fieldset, Row, Column, HTML, ButtonHolder, ButtonHolderPanel, Submit, InlineField, InlineJustifiedField

#from captcha.fields import ReCaptchaField

from .models import CIVILITY_CHOICES, ContactBase, Contact

def SimpleRowColumn(field, *args, **kwargs):
    """
    Shortcut for simple row with only a full column
    """
    if isinstance(field, basestring):
        field = Field(field, *args, **kwargs)
    return Row(
        Column(field),
    )

class ContactFormBase(ModelForm):
    """
    Contact base form, you cant use it directly because the used
    model ('ContactBase') is just an abstract model
    """
    error_css_class = 'error'
    required_css_class = 'required'
    mail_subject_template = 'contact_form/contact_form_subject.txt'
    mail_content_template = 'contact_form/contact_form.txt'

    def __init__(self, *args, **kwargs):
        super(ContactFormBase, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_action = '.'

    def save(self, commit=True):
        """Save and send"""
        contact = super(ContactFormBase, self).save()
        context = {'contact': contact}
        context.update(get_site_metas())

        subject = ''.join(render_to_string(self.mail_subject_template, context).splitlines())
        content = render_to_string(self.mail_content_template, context)

        send_mail(subject, content,
                  settings.DEFAULT_FROM_EMAIL,
                  settings.CONTACT_FORM_TO,
                  fail_silently=not settings.DEBUG)

        return contact

    class Meta:
        model = ContactBase

class ContactForm(ContactFormBase):
    """Contact Form"""
    def __init__(self, *args, **kwargs):
        super(ContactFormBase, self).__init__(*args, **kwargs)

        self.fields['civility'].choices = (('', _('civility')),) + CIVILITY_CHOICES

        self.helper = FormHelper()
        self.helper.attrs = {'data_abide': ''}
        self.helper.form_action = '.'
        self.helper.add_input(Submit('submit', _('Submit')))

    class Meta:
        model = Contact


text:
package net.jalg.hawkj.ext;

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

/**
 */
public class InputStreamBuffer extends InputStream {
	protected InputStream inputStream;
	protected ByteArrayOutputStream buffer = new ByteArrayOutputStream();

	public InputStreamBuffer(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public byte[] getBuffer() {
		return buffer.toByteArray();
	}

	@Override
	public int read() throws IOException {
		int b = inputStream.read();
		if (b > -1)
			buffer.write((byte) b);
		return b;
	}

	@Override
	public int read(byte[] bytes) throws IOException {
		int nbytes = inputStream.read(bytes);
		if (nbytes > 0) {
			buffer.write(bytes, 0, nbytes);
		}
		return nbytes;
	}

	@Override
	public int read(byte[] bytes, int off, int len) throws IOException {
		int nbytes = inputStream.read(bytes, off, len);
		if (nbytes > 0) {
			buffer.write(bytes, off, nbytes);
		}
		return nbytes;
	}

	@Override
	public long skip(long l) throws IOException {
		return inputStream.skip(l);
	}

	@Override
	public int available() throws IOException {
		return inputStream.available();
	}

	@Override
	public void close() throws IOException {
		inputStream.close();
	}

	@Override
	public void mark(int i) {
		inputStream.mark(i);
	}

	@Override
	public void reset() throws IOException {
		throw new RuntimeException("Resetting stream not permitted");
	}

	@Override
	public boolean markSupported() {
		return inputStream.markSupported();
	}
}


text:
using NUnit.Framework;
using RefactoringEssentials.CSharp.Diagnostics;

namespace RefactoringEssentials.Tests.CSharp.Diagnostics
{
    [TestFixture]
    [Ignore("TODO: Issue not ported yet")]
    public class UnusedTypeParameterTests : CSharpDiagnosticTestBase
    {

        [Test]
        public void TestUnusedTypeParameter()
        {
            var input = @"
class TestClass {
	void TestMethod<T> ()
	{
	}
}";
            Test<UnusedTypeParameterAnalyzer>(input, 1);
        }

        [Test]
        public void TestUsedTypeParameter()
        {
            var input = @"
class TestClass {
	void TestMethod<T> (T i)
	{
	}
}";
            var input2 = @"
class TestClass {
	T TestMethod<T> ()
	{
	}
}";
            Test<UnusedTypeParameterAnalyzer>(input, 0);
            Test<UnusedTypeParameterAnalyzer>(input2, 0);
        }

    }
}


text:
/**
 * @file   kvstore_nccl.h
 * @brief  NCCL implementation of KVStore
 */
#ifndef MXNET_KVSTORE_KVSTORE_NCCL_H_
#define MXNET_KVSTORE_KVSTORE_NCCL_H_

#if MXNET_USE_NCCL

#include <mxnet/kvstore.h>
#include <nccl.h>
#include <unordered_map>
#include <bitset>
#include <vector>
#include <string>
#include <utility>
#include <functional>
#include <algorithm>
#include <tuple>
#include "./comm.h"
#include "./kvstore_local.h"
#include "../common/cuda_utils.h"

// NCCL v2 introduces NCCL_MAJOR macro for versioning,
// so if there is no such macro defined in nccl.h
// then it is NCCL v1
#ifndef NCCL_MAJOR
#define NCCL_MAJOR 1
#endif

#if NCCL_MAJOR == 1
#define ncclGroupStart()
#define ncclGroupEnd()
#define ncclNumTypes nccl_NUM_TYPES
#endif  // NCCL_MAJOR == 1

namespace mxnet {
namespace kvstore {

/**
 * \brief store data in local machine using NCCL
 */
class KVStoreNCCL : public KVStoreLocal {
 public:
  KVStoreNCCL() : KVStoreLocal() {
    // Due to aggregation, we do not use the Comm interface
    comm_ = nullptr;
    pinned_ctx_ = Context::CPUPinned(0);
    inited_ = false;
  }

  virtual ~KVStoreNCCL() {
    for (auto e : nccl_data_) {
      cudaStreamDestroy(e.second.stream);
      ncclCommDestroy(e.second.comm);
    }
  }

 private:
  void InitImpl(const std::vector<int>& keys,
                const std::vector<NDArray>& values) override {
    for (size_t i = 0; i < keys.size(); ++i) {
      CHECK(local_.find(keys[i]) == local_.end())
          << "duplicate init of key " << keys[i];
      local_[keys[i]] = values[i].Copy(pinned_ctx_);
      InitKey(keys[i], values[i].storage_type(), values[i].shape(), values[i].dtype());
    }
  }

  void PushImpl(const std::vector<int>& keys,
                const std::vector<NDArray>& values,
                int priority) override {
    std::vector<int> uniq_keys;
    std::vector<std::vector<NDArray> > grouped_vals;
    // nccl kvstore doesn't support sparse ndarray
    GroupKVPairsHelper(keys, values, &uniq_keys, &grouped_vals, true);

    std::vector<const NDArray*> merged_ptrs;
    std::vector<NDArray*> local_ptrs;
    bool nccl_called = false;

    Reduce(uniq_keys, grouped_vals, priority, &merged_ptrs);

    for (size_t i = 0; i < uniq_keys.size(); ++i) {
      int key = uniq_keys[i];
      if (grouped_vals[i].size() > 1) {
        // We issued NCCL kernels, need to synchronize
        nccl_called = true;
      }
      auto& merged = *(merged_ptrs[i]);
      NDArray& local = local_[key];
      if (updater_ != nullptr) {
        CHECK(!local.is_none()) << "key " << key << " has not been inited";
        // if merged is on gpu, we may need copy weight from cpu to gpu
        if (merged.ctx().dev_mask() != cpu::kDevMask &&
            local.ctx().dev_mask() == cpu::kDevMask) {
          local = local.Copy(merged.ctx());
        }
      }
      local_ptrs.push_back(&local);
    }

    // Sync after all reductions in a group
    if (nccl_called) {
      CommSync(merged_ptrs, priority);
    }

    for (size_t i = 0; i < uniq_keys.size(); ++i) {
      int key = uniq_keys[i];
      auto& merged = *(merged_ptrs[i]);
      NDArray& local = *(local_ptrs[i]);
      if (updater_ != nullptr) {
        // call the updater with string keys
        // if string keys are used and str_updater_ is available
        // otherwise fallback to updater_ which uses int key interface
        if (key_type_ == kStringKey && str_updater_ != nullptr) {
          // after all language bindings picks up string interface changes
          const std::string &str_key = reverse_str_key_dict_[key];
          str_updater_(str_key, merged,  &local);
        } else {
          updater_(key, merged,  &local);
        }
      } else {
        local = merged;
      }
    }
  }

  void PullImpl(const std::vector<int>& keys,
                const std::vector<NDArray*>& values,
                int priority, bool ignore_sparse) override {
    CHECK(ignore_sparse) << "nccl kvstore pull doesn't support ignore_sparse=False";
    std::vector<int> uniq_keys;
    std::vector<std::vector<NDArray*> > grouped_vals;
    GroupKVPairsHelper(keys, values, &uniq_keys, &grouped_vals, true);
    std::vector<NDArray> locals;
    bool nccl_called = false;

    for (size_t i = 0; i < uniq_keys.size(); ++i) {
      int key = uniq_keys[i];
      const NDArray& local = local_[key];
      locals.push_back(local_[key]);
      CHECK(!local.is_none()) << "key " << key << " has not been inited";
      if (grouped_vals[i].size() > 1) {
        // We issued NCCL kernels, need to synchronize
        nccl_called = true;
      }
    }

    Broadcast(uniq_keys, locals, grouped_vals, priority);
    // Sync after all broadcasts in a group
    if (nccl_called) {
      const std::vector<const NDArray*> values_copy(values.begin(), values.end());
      CommSync(values_copy, priority);
    }
  }

  void PullRowSparseImpl(const std::vector<int>& keys,
                         const std::vector<std::pair<NDArray*, NDArray>>& val_rowids,
                         int priority = 0) override {
    LOG(FATAL) << "NCCL kvstore does not support sparse storage type";
  }

  void SetGradientCompression(const std::vector<std::pair<std::string, std::string> >
                                      & kwargs) override {
    LOG(FATAL) << "NCCL kvstore does not support gradient compression";
  }

 protected:
  /**
   * \brief group values on keys
   */
  template <typename T>
  void GroupKVPairsHelper(const std::vector<int>& keys,
                          const std::vector<T>& values,
                          std::vector<int> *uniq_keys,
                          std::vector<std::vector<T>> *grouped_vals,
                          bool ignore_sparse) {
    // check if the storage type of a value is valid
    auto validator = [this](const int key, const T nd, bool ignore_sparse) -> bool {
      CHECK(ignore_sparse) << "nccl kvstore pull doesn't support ignore_sparse=False";
      auto stype = ptr(nd)->storage_type();
      // valid NDArray
      if (stype == kDefaultStorage) return true;
      // invalid NDArray, abort
      LOG(FATAL) << "NCCL kvstore does not support sparse storage type";
      return false;
    };
    GroupKVPairs(keys, values, uniq_keys, grouped_vals, validator, ignore_sparse);
  }

 private:
  // Aggregated reductions
  virtual void Reduce(const std::vector<int> keys,
                      const std::vector<std::vector<NDArray>>& srcs,
                      int priority,
                      std::vector<const NDArray*>* merged_ptrs) {
    std::vector<size_t> root_ids(keys.size());
    std::vector<NDArray> reduces(keys.size());
    merged_ptrs->resize(keys.size());
    std::vector<Engine::VarHandle> const_vars;
    std::vector<Engine::VarHandle> mutate_vars;

    for (size_t k = 0; k < keys.size(); ++k) {
      auto& key = keys[k];
      auto& src = srcs[k];
      auto& root_id = root_ids[k];

      // avoid extra copy for single device, but it may bring problems for
      // abnormal usage of kvstore
      if (src.size() == 1) {
        (*merged_ptrs)[k] = &src[0];
        continue;
      }

      if (!inited_) {
        std::vector<Context> devs;
        for (const auto& a : src) {
          devs.push_back(a.ctx());
        }
        InitNCCL(devs);
        InitMergeBuffer(devs);
      }

      // Check whether we got the same set of devices
      std::vector<int> dev_ids;
      for (auto e : src) {
        dev_ids.push_back(e.ctx().dev_id);
      }
      std::sort(dev_ids.begin(), dev_ids.end());
      CHECK(device_ids_ == dev_ids) << "NCCL KVStore supports only single set of devices";

      auto& buf = merge_buf_[key];
      int root = buf.merged.ctx().dev_id;
      root_id = FindRootId(src, root);

      auto& reduce = buf.merged;
      (*merged_ptrs)[k] = &reduce;
      // Need to pass NDArrays by value to the engine
      reduces[k] = reduce;

      for (size_t i = 0; i < src.size(); ++i) {
        const_vars.push_back(src[i].var());
      }
      mutate_vars.push_back(reduce.var());
    }

    Engine::Get()->PushSync([srcs, reduces, root_ids, this](RunContext rctx) {
        std::lock_guard<std::mutex> l(Storage::Get()->GetMutex(Context::kGPU));
#if (NCCL_MAJOR > 2 || (NCCL_MAJOR == 2 && NCCL_MINOR > 1))
        ncclGroupStart();
#endif
        for (size_t k = 0; k < srcs.size(); ++k) {
          auto& src = srcs[k];
          auto& root_id = root_ids[k];
          auto& reduce = reduces[k];
          if (src.size() <= 1) {
            continue;
          }
          int root = nccl_data_[src[root_id].ctx().dev_id].rank;
          ncclGroupStart();
          for (size_t i = 0; i < src.size(); ++i) {
            NCCLEntry cur = nccl_data_[src[i].ctx().dev_id];
            if (i == root_id) {
            MSHADOW_TYPE_SWITCH(src[i].dtype(), DType,
            ncclReduce(src[i].data().dptr<DType>(),
                              reduce.data().dptr<DType>(),
                              src[i].shape().Size(),
                              GetNCCLType(src[i].dtype()),
                              ncclSum,
                              root,
                              cur.comm,
                              cur.stream););
            } else {
            MSHADOW_TYPE_SWITCH(src[i].dtype(), DType,
            ncclReduce(src[i].data().dptr<DType>(),
                              nullptr,
                              src[i].shape().Size(),
                              GetNCCLType(src[i].dtype()),
                              ncclSum,
                              root,
                              cur.comm,
                              cur.stream););
            }
          }
          ncclGroupEnd();
        }
#if (NCCL_MAJOR > 2 || (NCCL_MAJOR == 2 && NCCL_MINOR > 1))
        ncclGroupEnd();
#endif
      },
      Context::CPU(),
      const_vars,
      mutate_vars,
      FnProperty::kCPUPrioritized,
      priority,
      "KVStoreReduce");
  }

  virtual void Broadcast(const std::vector<int> keys,
      const std::vector<NDArray>& srcs,
      const std::vector<std::vector<NDArray*>>& dsts,
      int priority) {
    std::vector<size_t> root_ids(keys.size());
    std::vector<Engine::VarHandle> const_vars;
    std::vector<Engine::VarHandle> mutable_vars;

    for (size_t k = 0; k < keys.size(); ++k) {
      auto& key = keys[k];
      auto& src = srcs[k];
      auto& dst = dsts[k];
      auto& root_id = root_ids[k];

      if (!inited_) {
        // copy to a random device first
        int dev_id = key % dst.size();
        CopyFromTo(src, *dst[dev_id], priority);
        for (size_t i = 0; i < dst.size(); ++i) {
          if (i != static_cast<size_t>(dev_id)) {
            CopyFromTo(*dst[dev_id], *dst[i], priority);
          }
        }
      } else {
        auto& buf = merge_buf_[key];
        int root = src.ctx().dev_id;
        assert(root == buf.merged.ctx().dev_id);
        root_id = FindRootId(dst, root);

        // Check whether we got the same set of devices
        std::vector<int> dev_ids;
        for (size_t i = 0; i < dst.size(); ++i) {
          auto& bcast = (i == root_id) ? src : *dst[i];
          dev_ids.push_back(bcast.ctx().dev_id);
        }
        std::sort(dev_ids.begin(), dev_ids.end());
        CHECK(device_ids_ == dev_ids) << "NCCL KVStore supports only single set of devices";

        // On root perform simple copy to the output
        CopyFromTo(src, *dst[root_id], priority);
        for (size_t i = 0; i < dst.size(); ++i) {
          if ( i != root_id)
            mutable_vars.push_back(dst[i]->var());
        }
        const_vars.push_back(src.var());
      }
    }

    // If not yet inited, then all work is already scheduled
    if (!inited_) {
      return;
    }

    // We need to capture NDArrays by value
    // in order to push to the engine
    std::vector<std::vector<NDArray>> broadcasts(dsts.size());
    for (size_t i = 0; i < dsts.size(); ++i) {
      auto& broadcast = broadcasts[i];
      broadcast.resize(dsts[i].size());
      for (size_t j = 0; j < dsts[i].size(); ++j) {
        broadcast[j] = *(dsts[i][j]);
      }
    }

    Engine::Get()->PushSync([srcs, broadcasts, root_ids, this](RunContext rctx) {
        std::lock_guard<std::mutex> l(Storage::Get()->GetMutex(Context::kGPU));
#if (NCCL_MAJOR > 2 || (NCCL_MAJOR == 2 && NCCL_MINOR > 1))
        ncclGroupStart();
#endif
        for (size_t k = 0; k < srcs.size(); ++k) {
          auto& src = srcs[k];
          auto& dst = broadcasts[k];
          auto& root_id = root_ids[k];
          if (dst.size() <= 1) {
            continue;
          }

          int root = nccl_data_[src.ctx().dev_id].rank;
          ncclGroupStart();
          for (size_t i = 0; i < dst.size(); ++i) {
            auto& bcast = (i == root_id) ? src : dst[i];
            NCCLEntry cur = nccl_data_[bcast.ctx().dev_id];
            MSHADOW_TYPE_SWITCH(bcast.dtype(), DType,
                ncclBcast(bcast.data().dptr<DType>(),
                  bcast.shape().Size(),
                  GetNCCLType(bcast.dtype()),
                  root,
                  cur.comm,
                  cur.stream););
          }
          ncclGroupEnd();
        }
#if (NCCL_MAJOR > 2 || (NCCL_MAJOR == 2 && NCCL_MINOR > 1))
        ncclGroupEnd();
#endif
      },
      Context::CPU(),
      const_vars,
      mutable_vars,
      FnProperty::kCPUPrioritized,
      priority,
      "KVStoreBCast");
  }

  // Function that waits for NCCL collective to complete
  template <typename T>
  void CommSync(const std::vector<T>& dst, int priority) {
    std::vector<Engine::VarHandle> mutate_vars;
    for (size_t i = 0; i < dst.size(); ++i) {
        mutate_vars.push_back(ptr(dst[i])->var());
    }
    Engine::Get()->PushSync([this](RunContext rctx) {
        mxnet::common::cuda::DeviceStore device_store;
        for (auto cur : nccl_data_) {
          device_store.SetDevice(cur.second.dev_id);
          CUDA_CALL(cudaStreamSynchronize(cur.second.stream));
        }
      },
      Context::CPU(),
      {},
      mutate_vars,
      FnProperty::kCPUPrioritized,
      priority,
      "KVStoreStreamSync");
  }

  // Initialize single key
  void InitKey(int key, const NDArrayStorageType stype, const mxnet::TShape& shape,
            int dtype = mshadow::kFloat32) {
    if (stype == kDefaultStorage) {
      key_attrs_.push_back(std::make_tuple(key, shape, dtype));
    } else {
      LOG(FATAL) << "NCCL KVStore does not support sparse storage type";
    }
  }

  ncclDataType_t GetNCCLType(int dtype) {
    switch (dtype) {
      case mshadow::kFloat32:
        return ncclFloat;
      case mshadow::kFloat16:
        return ncclHalf;
      case mshadow::kFloat64:
        return ncclDouble;
      case mshadow::kUint8:
        return ncclChar;
      case mshadow::kInt32:
        return ncclInt;
      case mshadow::kInt64:
        return ncclInt64;
      default:
        LOG(FATAL) << "Unknown type passed to NCCL KVStore";
    }
    return ncclNumTypes;
  }

  void InitNCCL(const std::vector<Context>& devs) {
    for (size_t i = 0; i < devs.size(); ++i) {
      device_ids_.push_back(devs[i].dev_id);
    }
    std::sort(device_ids_.begin(), device_ids_.end());
    std::lock_guard<std::mutex> l(Storage::Get()->GetMutex(Context::kGPU));
    std::vector<ncclComm_t> comms(devs.size());
    ncclCommInitAll(&(comms[0]), devs.size(), &(device_ids_[0]));
    mxnet::common::cuda::DeviceStore device_store;
    for (size_t i = 0; i < devs.size(); ++i) {
      NCCLEntry e;
      e.dev_id = device_ids_[i];
      e.comm = comms[i];
      e.rank = i;
      device_store.SetDevice(e.dev_id);
      cudaStreamCreate(&(e.stream));
      nccl_data_[device_ids_[i]] = e;
    }
  }

  using KeyAttrs = std::tuple<int, mxnet::TShape, int>;
  void InitMergeBuffer(const std::vector<Context>& devs) {
    for (size_t i = 0; i < key_attrs_.size(); ++i) {
      int key  = std::get<0>(key_attrs_[i]);
      mxnet::TShape s = std::get<1>(key_attrs_[i]);
      int type = std::get<2>(key_attrs_[i]);
      auto& buf = merge_buf_[key];
      // always use devs[0] as root
      buf.merged = NDArray(s, devs[0], false, type);
    }
    inited_ = true;
  }

  // Functions that enable templates to work on both references
  // and pointers
  template<typename T>
  const T * ptr(const T & obj) { return &obj; }

  template<typename T>
  const T * ptr(T * obj) { return obj; }

  // Find which element of the vector
  // corresponds to root dev_id
  template <typename T>
  size_t FindRootId(const std::vector<T>& vec, int root) {
    size_t root_id = -1;
    for (size_t i = 0; i < vec.size(); ++i) {
      if (ptr(vec[i])->ctx().dev_id == root) {
        root_id = i;
        break;
      }
    }
    return root_id;
  }

  std::vector<KeyAttrs> key_attrs_;
  /// \brief temporal space for pushing and pulling
  struct BufferEntry {
    /// \brief the merged value
    NDArray merged;
  };
  struct NCCLEntry {
    /// \brief device ID
    int dev_id;
    /// \brief NCCL commmunicator
    ncclComm_t comm;
    /// \brief NCCL rank
    int rank;
    /// \brief GPU stream to use with NCCL
    cudaStream_t stream;
  };
  std::unordered_map<int, BufferEntry> merge_buf_;
  std::unordered_map<int, NCCLEntry> nccl_data_;
  bool inited_;
  // \brief devices used with this KVStore
  std::vector<int> device_ids_;
};
}  // namespace kvstore
}  // namespace mxnet
#endif  // MXNET_USE_NCCL
#endif  // MXNET_KVSTORE_KVSTORE_NCCL_H_


text:
package client

import (
	"fmt"
	"io"
	"os"

	"golang.org/x/net/context"

	"github.com/hyperhq/hyper-api/types"
	Cli "github.com/hyperhq/hypercli/cli"
	"github.com/hyperhq/hypercli/opts"
	"github.com/hyperhq/hypercli/pkg/jsonmessage"
	flag "github.com/hyperhq/hypercli/pkg/mflag"
	"github.com/hyperhq/hypercli/pkg/urlutil"
)

// CmdImport creates an empty filesystem image, imports the contents of the tarball into the image, and optionally tags the image.
//
// The URL argument is the address of a tarball (.tar, .tar.gz, .tgz, .bzip, .tar.xz, .txz) file or a path to local file relative to docker client. If the URL is '-', then the tar file is read from STDIN.
//
// Usage: docker import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]
func (cli *DockerCli) Import(args ...string) error {
	cmd := Cli.Subcmd("import", []string{"file|URL|- [REPOSITORY[:TAG]]"}, Cli.DockerCommands["import"].Description, true)
	flChanges := opts.NewListOpts(nil)
	cmd.Var(&flChanges, []string{"c", "-change"}, "Apply Dockerfile instruction to the created image")
	message := cmd.String([]string{"m", "-message"}, "", "Set commit message for imported image")
	cmd.Require(flag.Min, 1)

	cmd.ParseFlags(args, true)

	var (
		in      io.Reader
		tag     string
		src     = cmd.Arg(0)
		srcName = src
		ref     = cmd.Arg(1)
		changes = flChanges.GetAll()
	)

	if cmd.NArg() == 3 {
		fmt.Fprintf(cli.err, "[DEPRECATED] The format 'file|URL|- [REPOSITORY [TAG]]' has been deprecated. Please use file|URL|- [REPOSITORY[:TAG]]\n")
		tag = cmd.Arg(2)
	}

	if src == "-" {
		in = cli.in
	} else if !urlutil.IsURL(src) {
		srcName = "-"
		file, err := os.Open(src)
		if err != nil {
			return err
		}
		defer file.Close()
		in = file
	}
	source := types.ImageImportSource{
		Source:     in,
		SourceName: srcName,
	}

	options := types.ImageImportOptions{
		Message: *message,
		Tag:     tag,
		Changes: changes,
	}

	responseBody, err := cli.client.ImageImport(context.Background(), source, ref, options)
	if err != nil {
		return err
	}
	defer responseBody.Close()

	return jsonmessage.DisplayJSONMessagesStream(responseBody, cli.out, cli.outFd, cli.isTerminalOut, nil)
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>M S Prowant | Ge[o]rges Dib</title>
    <link>https://dibgerge.github.io/authors/m-s-prowant/</link>
      <atom:link href="https://dibgerge.github.io/authors/m-s-prowant/index.xml" rel="self" type="application/rss+xml" />
    <description>M S Prowant</description>
    <generator>Source Themes Academic (https://sourcethemes.com/academic/)</generator><language>en-us</language><lastBuildDate>Sun, 17 Apr 2016 00:00:00 -0700</lastBuildDate>
    <image>
      <url>https://dibgerge.github.io/images/icon_hufb0bba0b24038dd6774d907c032416d0_44829_512x512_fill_lanczos_center_2.png</url>
      <title>M S Prowant</title>
      <link>https://dibgerge.github.io/authors/m-s-prowant/</link>
    </image>

    <item>
      <title>Non-destructive Measurements for Diagnostics of Advanced Reactor Passive Components</title>
      <link>https://dibgerge.github.io/publication/2016-icapp/</link>
      <pubDate>Sun, 17 Apr 2016 00:00:00 -0700</pubDate>
      <guid>https://dibgerge.github.io/publication/2016-icapp/</guid>
      <description></description>
    </item>

  </channel>
</rss>


text:
from django.core.management import BaseCommand
from corehq.util.couch import iter_update, DocUpdate
from corehq.apps.domain.models import Domain

class Command(BaseCommand):
    help = "Change the location_restriction flag to False"

    def handle(self, *args, **options):
        def update_domain(doc):
            doc['location_restriction_for_users'] = False
            return DocUpdate(doc)
        domain_ids = [d['id'] for d in Domain.get_all(include_docs=False)]
        res = iter_update(Domain.get_db(), update_domain, domain_ids)

        print "number of domains updated:", len(res.updated_ids)
        print "Domains that already had it disabled:", res.ignored_ids
        print "Not Found:", res.not_found_ids
        print "Deleted (sure as shit better be empty):", res.deleted_ids
        print "Errored:", res.error_ids


text:
/*
 * Sensor Subsystem (SS) Timer
 *
 * This app configures a timer to expire every 0.5 seconds, at which point the
 * callback function will be invoked to increase the count and a message is
 * printed to the console.
 *
 * This app is specific to the Intel(R) Quark(TM) SE development platform.
 */

#include "qm_ss_interrupt.h"
#include "qm_ss_isr.h"
#include "qm_ss_timer.h"

#define INTERVAL (0x00F42400) /* 0.5 seconds. */
#define NUM_CALLBACK (5)

static volatile uint32_t cb_count = 0;
static volatile bool cb_fired = false;
static volatile bool complete = false;

/* Example timer callback function. */
static void timer_example_callback(void *data)
{
	/* Reset the timer if necessary. */
	if (cb_count < NUM_CALLBACK) {
		cb_count++;
		cb_fired = true;
		qm_ss_timer_set(QM_SS_TIMER_0, 0x00000000);
	} else {
		complete = true;
	}
}

int main(void)
{
	qm_ss_timer_config_t cfg;

	QM_PUTS("Starting: Sensor Timer");

	/*
	 * Request and unmask the timer interrupt. Timer interrupts and
	 * exceptions must be registered with the following function.
	 */
	qm_ss_int_vector_request(QM_ARC_TIMER_0_INT, qm_ss_timer_0_isr);
	qm_ss_irq_unmask(QM_ARC_TIMER_0_INT);

	/* Configure the timer. */
	cfg.watchdog_mode = false;
	cfg.inc_run_only = false;
	cfg.int_en = true;
	cfg.count = INTERVAL;
	cfg.callback = timer_example_callback;
	cfg.callback_data = NULL;

	if (0 != qm_ss_timer_set_config(QM_SS_TIMER_0, &cfg)) {
		QM_PUTS("Error: Set Config for TIMER0 failed");
		return 1;
	}

	/* Set the count. */
	if (0 != qm_ss_timer_set(QM_SS_TIMER_0, 0x00000000)) {
		QM_PUTS("Error: Set Count for TIMER0 failed");
		return 1;
	}

	/* Wait for the app to complete. */
	while (false == complete) {
		if (cb_fired) {
			cb_fired = false;
			QM_PUTS("Timer fired!");
		}
	}

	/* Disable the interrupt, the timer will continue to run. */
	cfg.int_en = false;
	if (0 != qm_ss_timer_set_config(QM_SS_TIMER_0, &cfg)) {
		QM_PUTS("Error: Set Config for TIMER0 failed");
		return 1;
	}

	QM_PUTS("Finished: Sensor Timer");

	return 0;
}


text:
section.light * {
  color: black !important;
}
section.dark * {
  color: white !important;
  text-shadow:
    0 0 15px black,
    0 0 10px black,
    0 0 5px black !important;
}
section.mixed * {
  color: black !important;
}
section.mixed > .wrapper {
  display: inline-block;
  padding: 30px 50px;
  background: #fff;
  border-radius: 3px;
  box-shadow: 0 0 15px black;
}

section.custom {
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
}
section.custom .top,
section.custom .left,
section.custom .right,
section.custom .bottom { position: absolute !important }

section.custom .top { top: 0 !important; }
section.custom .left { left: 0 !important; }
section.custom .right { right: 0 !important; }
section.custom .bottom { bottom: 0 !important; }

.no-margin {
  margin: 0 !important;
  padding: 0 !important;
}

.me {
  font-size: 0.6em !important;
}
.me img {
  margin: 0 !important;
  border: none !important;
  box-shadow: none !important;
}
.me .me-row {
  padding-left: 27%;
  text-align: left;
  margin-bottom: 30px;
}
.me .me-row > * {
  vertical-align: top;
}
.me .me-left {
  display: inline-block;
  width: 33%;
}
.me .me-right {
  display: inline-block;
  width: 42%;
}
.me ul {
  list-style: none;
  margin-left: 0;
}


text:
/*------------------------------------------------------------------------*/
/* Sample code of OS dependent controls for FatFs R0.10                   */
/* (C)ChaN, 2013                                                          */
/*------------------------------------------------------------------------*/

#include <stdlib.h>		/* ANSI memory controls */
#include "../ff.h"

#if _FS_REENTRANT
/*-----------------------------------------------------------------------
 Create a Synchronization Object
------------------------------------------------------------------------
 This function is called in f_mount function to create a new
 synchronization object, such as semaphore and mutex. When a zero is
 returned, the f_mount function fails with FR_INT_ERR.
*/

int ff_cre_syncobj (	/* TRUE:Function succeeded, FALSE:Could not create due to any error */
	BYTE vol,			/* Corresponding logical drive being processed */
	_SYNC_t *sobj		/* Pointer to return the created sync object */
)
{
  int ret;

  osSemaphoreDef(SEM);
  *sobj = osSemaphoreCreate(osSemaphore(SEM), 1);
  ret = (*sobj != NULL);

  return ret;
}

/*------------------------------------------------------------------------*/
/* Delete a Synchronization Object                                        */
/*------------------------------------------------------------------------*/
/* This function is called in f_mount function to delete a synchronization
/  object that created with ff_cre_syncobj function. When a zero is
/  returned, the f_mount function fails with FR_INT_ERR.
*/

int ff_del_syncobj (	/* TRUE:Function succeeded, FALSE:Could not delete due to any error */
	_SYNC_t sobj		/* Sync object tied to the logical drive to be deleted */
)
{
  osSemaphoreDelete (sobj);
  return 1;
}

/*------------------------------------------------------------------------*/
/* Request Grant to Access the Volume                                     */
/*------------------------------------------------------------------------*/
/* This function is called on entering file functions to lock the volume.
/  When a zero is returned, the file function fails with FR_TIMEOUT.
*/

int ff_req_grant (	/* TRUE:Got a grant to access the volume, FALSE:Could not get a grant */
	_SYNC_t sobj	/* Sync object to wait */
)
{
  int ret = 0;

  if(osSemaphoreWait(sobj, _FS_TIMEOUT) == osOK)
  {
    ret = 1;
  }

  return ret;
}

/*------------------------------------------------------------------------*/
/* Release Grant to Access the Volume                                     */
/*------------------------------------------------------------------------*/
/* This function is called on leaving file functions to unlock the volume.
*/

void ff_rel_grant (
	_SYNC_t sobj	/* Sync object to be signaled */
)
{
  osSemaphoreRelease(sobj);
}

#endif

#if _USE_LFN == 3	/* LFN with a working buffer on the heap */
/*------------------------------------------------------------------------*/
/* Allocate a memory block                                                */
/*------------------------------------------------------------------------*/
/* If a NULL is returned, the file function fails with FR_NOT_ENOUGH_CORE.
*/

void* ff_memalloc (	/* Returns pointer to the allocated memory block */
	UINT size		/* Number of bytes to allocate */
)
{
  return malloc(size);
}

/*------------------------------------------------------------------------*/
/* Free a memory block                                                    */
/*------------------------------------------------------------------------*/

void ff_memfree(
	void* mblock	/* Pointer to the memory block to free */
)
{
  free(mblock);
}

#endif