问:
Send MIDI events to a stand-alone sampler/synth
I'd like to develop a very simple program to map PC keyboard to a piano keyboard: each time the user press a key a MIDI event is generated and a stand-alone sampler/synth (such as SFZ+ or other) receives these events and plays a sound.

I am able to generate MIDI events (using midiOutShortMsg), but they are sent directly to the FM synth (and so played by it), I'd like to send them to an external software. The code must be in C/C++.

Could you help me?

Tnx.

答:
You should look at JACK

JACK is system for handling real-time,
  low latency audio (and MIDI). It runs
  on GNU/Linux, Solaris, FreeBSD, OS X
  and Windows (and can be ported to
  other POSIX-conformant platforms). It
  can connect a number of different
  applications to an audio device, as
  well as allowing them to share audio
  between themselves. Its clients can
  run in their own processes (ie. as
  normal applications), or can they can
  run within the JACK server (ie. as a
  "plugin"). JACK also has support for
  distributing audio processing across a
  network, both fast & reliable LANs as
  well as slower, less reliable WANs.

JACK was designed from the ground up
  for professional audio work, and its
  design focuses on two key areas:
  synchronous execution of all clients,
  and low latency operation. More
  background information is available.

Available as source or binaries here.


来源: stackexchange

问:
How to remove \n from json object literal
When I write console.log(input), i get the below code but I don,t want to format it in this manner:

```<code>var contacts = { json: ' "book": {\n
"person": [\n
{\n
    "firstName": "Jane",\n
    "lastName": "Doe",\n
    "age": "25",\n
    "address": {\n
        "streetAddress": "21 2nd Street",\n
        "city": "Las Vegas",\n
        "state": "NV",\n
        "postalCode": "10021-3100"\n
    }\n
},\n
{\n
    "firstName": "Agatha",\n
    "lastName": "Doe",\n
    "age": "25",\n
    "address": {\n
        "streetAddress": "21 2nd Street",\n
        "city": "Las Vegas",\n
        "state": "NV",\n
        "postalCode": "10021-3100"\n
        }\n
    }\n
  ]\n
}' }
</code>```

How to convert above code in the below format?

```<code>var contacts = {
    "book": {
        "person": [
            {
                "firstName": "Jane",
                "lastName": "Doe",
                "age": "25",
                "address": {
                    "streetAddress": "21 2nd Street",
                    "city": "Las Vegas",
                    "state": "NV",
                    "postalCode": "10021-3100"
                }
            },
            {
                "firstName": "Agatha",
                "lastName": "Doe",
                "age": "25",
                "address": {
                    "streetAddress": "21 2nd Street",
                    "city": "Las Vegas",
                    "state": "NV",
                    "postalCode": "10021-3100"
                }
            }
        ]
    }
}
</code>```

答:
json = ' "book": {
    "person": [
        {
            "firstName": "Jane",
            "lastName": "Doe",
            "age": "25",
            "address": {
                "streetAddress": "21 2nd Street",
                "city": "Las Vegas",
                "state": "NV",
                "postalCode": "10021-3100"
            }
        },
        {
            "firstName": "Agatha",
            "lastName": "Doe",
            "age": "25",
            "address": {
                "streetAddress": "21 2nd Street",
                "city": "Las Vegas",
                "state": "NV",
                "postalCode": "10021-3100"
            }
        }
    ]
}'

var contact  = JSON.parse(JSON.stringify(json));
    console.log(contact);

ContentLicense: CC BY-SA 3.0

Body:
When I write console.log(input), i get the below code but I don,t want to format it in this manner:

var contacts = { json: ' "book": {\n
"person": [\n
{\n
    "firstName": "Jane",\n
    "lastName": "Doe",\n
    "age": "25",\n
    "address": {\n
        "streetAddress": "21 2nd Street",\n
        "city": "Las Vegas",\n
        "state": "NV",\n
        "postalCode": "10021-3100"\n
    }\n
},\n
{\n
    "firstName": "Agatha",\n
    "lastName": "Doe",\n
    "age": "25",\n
    "address": {\n
        "streetAddress": "21 2nd Street",\n
        "city": "Las Vegas",\n
        "state": "NV",\n
        "postalCode": "10021-3100"\n
        }\n
    }\n
  ]\n
}' }

How to convert above code in the below format?

var contacts = {
    "book": {
        "person": [
            {
                "firstName": "Jane",
                "lastName": "Doe",
                "age": "25",
                "address": {
                    "streetAddress": "21 2nd Street",
                    "city": "Las Vegas",
                    "state": "NV",
                    "postalCode": "10021-3100"
                }
            },
            {
                "firstName": "Agatha",
                "lastName": "Doe",
                "age": "25",
                "address": {
                    "streetAddress": "21 2nd Street",
                    "city": "Las Vegas",
                    "state": "NV",
                    "postalCode": "10021-3100"
                }
            }
        ]
    }
}


问:
Goal checking in BFS
I tried to implement BFS algorithm in JAVA based on what I study but I'm confused a little, I'm not sure if I'm checking if the node is goal or I'm adding nodes to explored list in the appropriate place. Here's the code:

```<code>frontier.add(nodes.getFirst());//node.isGoal is only true if the node is desired node
    if(frontier.getFirst().isGoal)//Checking if the root node is goal
    {
        explored.add(frontier.getFirst());
        prev.put(frontier.getFirst(), null);
        goalNode = explored.getFirst();
        frontier.poll();
    }
    while (!frontier.isEmpty())
    {
        currentNode = frontier.poll();
        explored.add(currentNode);
        for (Node node : currentNode.children) {//adding node children to fronier and checking if they are goal
            if (!frontier.contains(node) || !explored.contains(node)) {
                frontier.add(node);
                prev.put(node, currentNode);//mapping nodes to parent node to return sequence of nodes
                if (node.isGoal) {
                    goalNode = node;
                    break;
                }
            }
        }
    }
</code>```

Thanks in advance.

答:
Based on how I understand your code it seems you're doing it wrong: you check the first node in your initial set (e.g. tree level) and if it is not the goal node you add any children that are not already in frontier and that have not been visited yet. That's ok but probably unnecessary. What's wrong is that you're checking the child before checking any of the parent's siblings so your search is not exactly breadth-first.

So what could/should you do?

Let's assume your data represents a tree (breadth-first indicates that) and you're starting at some level (e.g. the root node). Since the data is a tree in a breadth-first approach any child not cannot have been visited already and is also probably not in your frontier list so there's no need to check for that (if you have a more general graph that might not be the case).

Thus the algorithm could look like this:

```<code>LinkedList<Node> frontier = new LinkedList<>();

//assuming you always have a root node just add it
frontier.add( root );

Node goal = null;

//loop until the list is empty, if we found a goal node we'll break the loop from the inside
while( !frontier.isEmpty() ) {
  //get the node at the start of the list and remove it
  //in the first iteration this will be the root node
  Node node = frontier.pop();

  //found a goal so we're done
  if( node.isGoal ) {
    goal = node ;
    break; //this breaks the while loop
  }

  //didn't find a goal yet so add the children at the end
  if( node.children != null ) {
    frontier.addAll( node.children );
  }
}
</code>```

Doing it this way means you add the nodes of the next level (children) at the end and pop the nodes higher up the tree from the front until you've found what you're searching for. That means you should always have only one or two levels of your tree in the list, i.e. the current level as well as the immediate children of any already processed current level node.

As you also can see there's no need to keep a explored set since we're operating on a tree.

Additionally you might want to think about whether you really need to build that prev map during iteration since you might have to remove elements again and a map is not really suited to get the path from your goal node to the root. You might want to keep a link to the parent in each node instead and thus once you've found the goal node you'd just iterate up until you reach the root.

Title: Goal checking in BFS

Body:
I tried to implement BFS algorithm in JAVA based on what I study but I'm confused a little, I'm not sure if I'm checking if the node is goal or I'm adding nodes to explored list in the appropriate place. Here's the code:

frontier.add(nodes.getFirst());//node.isGoal is only true if the node is desired node
    if(frontier.getFirst().isGoal)//Checking if the root node is goal
    {
        explored.add(frontier.getFirst());
        prev.put(frontier.getFirst(), null);
        goalNode = explored.getFirst();
        frontier.poll();
    }
    while (!frontier.isEmpty())
    {
        currentNode = frontier.poll();
        explored.add(currentNode);
        for (Node node : currentNode.children) {//adding node children to fronier and checking if they are goal
            if (!frontier.contains(node) || !explored.contains(node)) {
                frontier.add(node);
                prev.put(node, currentNode);//mapping nodes to parent node to return sequence of nodes
                if (node.isGoal) {
                    goalNode = node;
                    break;
                }
            }
        }
    }

Thanks in advance.

Body:
Based on how I understand your code it seems you're doing it wrong: you check the first node in your initial set (e.g. tree level) and if it is not the goal node you add any children that are not already in frontier and that have not been visited yet. That's ok but probably unnecessary. What's wrong is that you're checking the child before checking any of the parent's siblings so your search is not exactly breadth-first.

So what could/should you do?

Let's assume your data represents a tree (breadth-first indicates that) and you're starting at some level (e.g. the root node). Since the data is a tree in a breadth-first approach any child not cannot have been visited already and is also probably not in your frontier list so there's no need to check for that (if you have a more general graph that might not be the case).

Thus the algorithm could look like this:

LinkedList<Node> frontier = new LinkedList<>();

//assuming you always have a root node just add it
frontier.add( root );

Node goal = null;

//loop until the list is empty, if we found a goal node we'll break the loop from the inside
while( !frontier.isEmpty() ) {
  //get the node at the start of the list and remove it
  //in the first iteration this will be the root node
  Node node = frontier.pop();

  //found a goal so we're done
  if( node.isGoal ) {
    goal = node ;
    break; //this breaks the while loop
  }

  //didn't find a goal yet so add the children at the end
  if( node.children != null ) {
    frontier.addAll( node.children );
  }
}

Doing it this way means you add the nodes of the next level (children) at the end and pop the nodes higher up the tree from the front until you've found what you're searching for. That means you should always have only one or two levels of your tree in the list, i.e. the current level as well as the immediate children of any already processed current level node.

As you also can see there's no need to keep a explored set since we're operating on a tree.

Additionally you might want to think about whether you really need to build that prev map during iteration since you might have to remove elements again and a map is not really suited to get the path from your goal node to the root. You might want to keep a link to the parent in each node instead and thus once you've found the goal node you'd just iterate up until you reach the root.


问:
Combine vectors of list in R
I have a list contains number of vectors with different length as below:

```<code>lst <- list(c(1,2), c(1,2), c(4,5,10,11,12,13), c(7,8,9))
lst

[[1]]
[1] 1 2

[[2]]
[1] 1 2

[[3]]
[1]  4  5 10 11 12 13

[[4]]
[1] 7 8 9

[[5]]
[1] 7 8 9
</code>```

how can I combine and remove repeated vectors to be  similar to the list below:

```<code>[[1]]
[1] 1 2

[[2]]
[1]  4  5 10 11 12 13

[[3]]
[1] 7 8 9
</code>```

for repeated vectors I can use unique function.

答:
Here is one option.  We unlist the list, get a logical vector with duplicated, relist it to a list having the same skeleton as the original list, subset the 'l1' based on the logical list with Map and Filter out the list elements having 0 elements.

```<code>Filter(length, Map(`[`, l1, relist(!duplicated(unlist(l1)), skeleton = l1)))
#[[1]]
#[1] 1 2

#[[2]]
#[1]  4  5 10 11 12 13

#[[3]]
#[1] 7 8 9

#[[4]]
#[1] 14 15

#[[5]]
#[1] 19 20
</code>```

data

```<code>l1 <- list(1:2, 1:2, c(4, 5, 10, 11, 12, 13), 7:9, 7:9, 10:13, 10:13,
  c(4, 10, 11, 12, 13), 14:15, 19:20)
</code>```

Title: Combine vectors of list in R

Body:
I have a list contains number of vectors with different length as below:

lst <- list(c(1,2), c(1,2), c(4,5,10,11,12,13), c(7,8,9))
lst

[[1]]
[1] 1 2

[[2]]
[1] 1 2

[[3]]
[1]  4  5 10 11 12 13

[[4]]
[1] 7 8 9

[[5]]
[1] 7 8 9

how can I combine and remove repeated vectors to be  similar to the list below:

[[1]]
[1] 1 2

[[2]]
[1]  4  5 10 11 12 13

[[3]]
[1] 7 8 9

for repeated vectors I can use unique function.

Body:
Here is one option.  We unlist the list, get a logical vector with duplicated, relist it to a list having the same skeleton as the original list, subset the 'l1' based on the logical list with Map and Filter out the list elements having 0 elements.

Filter(length, Map(`[`, l1, relist(!duplicated(unlist(l1)), skeleton = l1)))
#[[1]]
#[1] 1 2

#[[2]]
#[1]  4  5 10 11 12 13

#[[3]]
#[1] 7 8 9

#[[4]]
#[1] 14 15

#[[5]]
#[1] 19 20

data

l1 <- list(1:2, 1:2, c(4, 5, 10, 11, 12, 13), 7:9, 7:9, 10:13, 10:13,
  c(4, 10, 11, 12, 13), 14:15, 19:20)


问:
WPF ListView Virtualization Grouping
Does anyone know of a ListView implementation that support UI Virtualization when grouping is enabled?  By default the VirtualizingStackPanel is disabled when grouping is setup.

It seems that Microsoft is not going to implement this within v4.0 of the .NET Framework so I am look for alternate solutions.

答:
I hope its not too much off topic but I had recently a similar problem. As stated above it is only .NET 4.0 issue. I would even agree that in most cases with combo box you should not normally need virtualization because it should not have that many items and if there is need for grouping then some kind of master-detail solution should be implemented. But there might be some gray areas.

The link provided by Luke about Grouping and Virtualization on MSDN helped me a lot. In my case that was the only approach which I was able to come up or find anywhere that is in a direction i need. It does not support all functionality from ListViewCollection. I had to override few methods otherwise selection of items would not work correctly. There are obviously more work to do.

So here is an updated solution of FlatGroupListCollectionView from here :

```<code>/// <summary>
///     Provides a view that flattens groups into a list
///     This is used to avoid limitation that ListCollectionView has in .NET 4.0, if grouping is used then Virtialuzation would not work
///     It assumes some appropriate impelmentation in view(XAML) in order to support this way of grouping
///     Note: As implemented, it does not support nested grouping
///     Note: Only overriden properties and method behaves correctly, some of methods and properties related to selection of item might not work as expected and would require new implementation
/// </summary>
public class FlatGroupListCollectionView : ListCollectionView
{
    /// <summary>
    /// Initializes a new instance of the <see cref="FlatGroupListCollectionView"/> class.
    /// </summary>
    /// <param name="list">A list used in this collection</param>
    public FlatGroupListCollectionView(IList list)
        : base(list)
    {
    }

    /// <summary>
    ///     This currently only supports one level of grouping
    ///     Returns CollectionViewGroups if the index matches a header
    ///     Otherwise, maps the index into the base range to get the actual item
    /// </summary>
    /// <param name="index">Index from which get an item</param>
    /// <returns>Item that was found on given index</returns>
    public override object GetItemAt(int index)
    {
        int delta = 0;
        ReadOnlyObservableCollection<object> groups = this.BaseGroups;
        if (groups != null)
        {
            int totalCount = 0;
            for (int i = 0; i < groups.Count; i++)
            {
                CollectionViewGroup group = groups[i] as CollectionViewGroup;
                if (group != null)
                {
                    if (index == totalCount)
                    {
                        return group;
                    }

                    delta++;
                    int numInGroup = group.ItemCount;
                    totalCount += numInGroup + 1;

                    if (index < totalCount)
                    {
                        break;
                    }
                }
            }
        }

        object item = base.GetItemAt(index - delta);
        return item;
    }

    /// <summary>
    ///     In the flat list, the base count is incremented by the number of groups since there are that many headers
    ///     To support nested groups, the nested groups must also be counted and added to the count
    /// </summary>
    public override int Count
    {
        get
        {
            int count = base.Count;

            if (this.BaseGroups != null)
            {
                count += this.BaseGroups.Count;
            }

            return count;
        }
    }

    /// <summary>
    ///     By returning null, we trick the generator into thinking  that we are not grouping
    ///     Thus, we avoid the default grouping code
    /// </summary>
    public override ReadOnlyObservableCollection<object> Groups
    {
        get
        {
            return null;
        }
    }

    /// <summary>
    ///     Gets the Groups collection from the base class
    /// </summary>
    private ReadOnlyObservableCollection<object> BaseGroups
    {
        get
        {
            return base.Groups;
        }
    }

    /// <summary>
    ///     DetectGroupHeaders is a way to get access to the containers by setting the value to true in the container style
    ///     That way, the change handler can hook up to the container and provide a value for IsHeader
    /// </summary>
    public static readonly DependencyProperty DetectGroupHeadersProperty =
        DependencyProperty.RegisterAttached("DetectGroupHeaders", typeof(bool), typeof(FlatGroupListCollectionView), new FrameworkPropertyMetadata(false, OnDetectGroupHeaders));

    /// <summary>
    /// Gets the Detect Group Headers property
    /// </summary>
    /// <param name="obj">Dependency Object from which the property is get</param>
    /// <returns>Value of Detect Group Headers property</returns>
    public static bool GetDetectGroupHeaders(DependencyObject obj)
    {
        return (bool)obj.GetValue(DetectGroupHeadersProperty);
    }

    /// <summary>
    /// Sets the Detect Group Headers property
    /// </summary>
    /// <param name="obj">Dependency Object on which the property is set</param>
    /// <param name="value">Value to set to property</param>
    public static void SetDetectGroupHeaders(DependencyObject obj, bool value)
    {
        obj.SetValue(DetectGroupHeadersProperty, value);
    }

    /// <summary>
    ///     IsHeader can be used to style the container differently when it is a header
    ///     For instance, it can be disabled to prevent selection
    /// </summary>
    public static readonly DependencyProperty IsHeaderProperty =
        DependencyProperty.RegisterAttached("IsHeader", typeof(bool), typeof(FlatGroupListCollectionView), new FrameworkPropertyMetadata(false));

    /// <summary>
    /// Gets the Is Header property
    /// </summary>
    /// <param name="obj">Dependency Object from which the property is get</param>
    /// <returns>Value of Is Header property</returns>
    public static bool GetIsHeader(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsHeaderProperty);
    }

    /// <summary>
    /// Sets the Is Header property
    /// </summary>
    /// <param name="obj">Dependency Object on which the property is set</param>
    /// <param name="value">Value to set to property</param>
    public static void SetIsHeader(DependencyObject obj, bool value)
    {
        obj.SetValue(IsHeaderProperty, value);
    }

    /// <summary>
    /// Raises the System.Windows.Data.CollectionView.CollectionChanged event.
    /// </summary>
    /// <param name="args">The System.Collections.Specialized.NotifyCollectionChangedEventArgs object to pass to the event handler</param>
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs args)
    {
        switch (args.Action)
        {
            case NotifyCollectionChangedAction.Add:
                {
                    int flatIndex = this.ConvertFromItemToFlat(args.NewStartingIndex, false);
                    int headerIndex = Math.Max(0, flatIndex - 1);
                    object o = this.GetItemAt(headerIndex);
                    CollectionViewGroup group = o as CollectionViewGroup;
                    if ((group != null) && (group.ItemCount == args.NewItems.Count))
                    {
                        // Notify that a header was added
                        base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new object[] { group }, headerIndex));
                    }

                    base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, args.NewItems, flatIndex));
                }

                break;

            case NotifyCollectionChangedAction.Remove:
                // TODO: Implement this action
                break;

            case NotifyCollectionChangedAction.Move:
                // TODO: Implement this action
                break;

            case NotifyCollectionChangedAction.Replace:
                // TODO: Implement this action
                break;

            default:
                base.OnCollectionChanged(args);
                break;
        }
    }

    /// <summary>
    /// Sets the specified item to be the System.Windows.Data.CollectionView.CurrentItem in the view
    /// This is an override of base method, an item index is get first and its needed to convert that index to flat version which includes groups
    /// Then adjusted version of MoveCurrentToPosition base method is called
    /// </summary>
    /// <param name="item">The item to set as the System.Windows.Data.CollectionView.CurrentItem</param>
    /// <returns>true if the resulting System.Windows.Data.CollectionView.CurrentItem is within the view; otherwise, false</returns>
    public override bool MoveCurrentTo(object item)
    {
        int index = this.IndexOf(item);

        int newIndex = this.ConvertFromItemToFlat(index, false);

        return this.MoveCurrentToPositionBase(newIndex);
    }

    /// <summary>
    /// Sets the item at the specified index to be the System.Windows.Data.CollectionView.CurrentItem in the view
    /// This is an override of base method, Its called when user selects new item from this collection
    /// A delta is get of which is the possition shifted because of groups and we shift this position by this delta and then base method is called
    /// </summary>
    /// <param name="position">The index to set the System.Windows.Data.CollectionView.CurrentItem to</param>
    /// <returns>true if the resulting System.Windows.Data.CollectionView.CurrentItem is an item within the view; otherwise, false</returns>
    public override bool MoveCurrentToPosition(int position)
    {
        int delta = this.GetDelta(position);

        int newPosition = position - delta;

        return base.MoveCurrentToPosition(newPosition);
    }

    private static void OnDetectGroupHeaders(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // This assumes that a container will not change between being a header and not
        // If using ContainerRecycling this may not be the case
        ((FrameworkElement)d).Loaded += OnContainerLoaded;
    }

    private static void OnContainerLoaded(object sender, RoutedEventArgs e)
    {
        FrameworkElement element = (FrameworkElement)sender;
        element.Loaded -= OnContainerLoaded; // If recycling, remove this line

        // CollectionViewGroup is the type of the header in this sample
        // Add more types or change the type as necessary
        if (element.DataContext is CollectionViewGroup)
        {
            SetIsHeader(element, true);
        }
    }

    private int ConvertFromItemToFlat(int index, bool removed)
    {
        ReadOnlyObservableCollection<object> groups = this.BaseGroups;
        if (groups != null)
        {
            int start = 1;
            for (int i = 0; i < groups.Count; i++)
            {
                CollectionViewGroup group = groups[i] as CollectionViewGroup;
                if (group != null)
                {
                    index++;
                    int end = start + group.ItemCount;

                    if ((start <= index) && ((!removed && index < end) || (removed && index <= end)))
                    {
                        break;
                    }

                    start = end + 1;
                }
            }
        }

        return index;
    }

    /// <summary>
    /// Move <seealso cref="CollectionView.CurrentItem"/> to the item at the given index.
    /// This is a replacement for base method
    /// </summary>
    /// <param name="position">Move CurrentItem to this index</param>
    /// <returns>true if <seealso cref="CollectionView.CurrentItem"/> points to an item within the view.</returns>
    private bool MoveCurrentToPositionBase(int position)
    {
        // VerifyRefreshNotDeferred was removed
        bool result = false;

        // Instead of property InternalCount we use Count property
        if (position < -1 || position > this.Count)
        {
            throw new ArgumentOutOfRangeException("position");
        }

        if (position != this.CurrentPosition || !this.IsCurrentInSync)
        {
            // Instead of property InternalCount we use Count property from this class
            // Instead of InternalItemAt we use GetItemAt from this class
            object proposedCurrentItem = (0 <= position && position < this.Count) ? this.GetItemAt(position) : null;

            // ignore moves to the placeholder
            if (proposedCurrentItem != CollectionView.NewItemPlaceholder)
            {
                if (this.OKToChangeCurrent())
                {
                    bool oldIsCurrentAfterLast = this.IsCurrentAfterLast;
                    bool oldIsCurrentBeforeFirst = this.IsCurrentBeforeFirst;

                    this.SetCurrent(proposedCurrentItem, position);

                    this.OnCurrentChanged();

                    // notify that the properties have changed.
                    if (this.IsCurrentAfterLast != oldIsCurrentAfterLast)
                    {
                        this.OnPropertyChanged(PropertySupport.ExtractPropertyName(() => this.IsCurrentAfterLast));
                    }

                    if (this.IsCurrentBeforeFirst != oldIsCurrentBeforeFirst)
                    {
                        this.OnPropertyChanged(PropertySupport.ExtractPropertyName(() => this.IsCurrentBeforeFirst));
                    }

                    this.OnPropertyChanged(PropertySupport.ExtractPropertyName(() => this.CurrentPosition));
                    this.OnPropertyChanged(PropertySupport.ExtractPropertyName(() => this.CurrentItem));

                    result = true;
                }
            }
        }

        // Instead of IsCurrentInView we return result
        return result;
    }

    private int GetDelta(int index)
    {
        int delta = 0;
        ReadOnlyObservableCollection<object> groups = this.BaseGroups;
        if (groups != null)
        {
            int totalCount = 0;
            for (int i = 0; i < groups.Count; i++)
            {
                CollectionViewGroup group = groups[i] as CollectionViewGroup;
                if (group != null)
                {
                    if (index == totalCount)
                    {
                        break;
                    }

                    delta++;
                    int numInGroup = group.ItemCount;
                    totalCount += numInGroup + 1;

                    if (index < totalCount)
                    {
                        break;
                    }
                }
            }
        }

        return delta;
    }

    /// <summary>
    /// Helper to raise a PropertyChanged event
    /// </summary>
    /// <param name="propertyName">Name of the property</param>
    private void OnPropertyChanged(string propertyName)
    {
        base.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

XAML part stays as it is in sample code. View model stays as it is as well which means using FlatGroupListCollectionView and set up GroupDescriptions.

I prefer this solution because it separates grouping logic from my list of data in view model. Other solution would be to implement support of grouping on original list of items in view model which means somehow identify headers. For a one time usage it should be fine but the collection might need to be recreated for a purpose of different or no grouping which is not so nice.

ContentLicense: CC BY-SA 2.5

Title: WPF ListView Virtualization Grouping

Body:
I hope its not too much off topic but I had recently a similar problem. As stated above it is only .NET 4.0 issue. I would even agree that in most cases with combo box you should not normally need virtualization because it should not have that many items and if there is need for grouping then some kind of master-detail solution should be implemented. But there might be some gray areas.

The link provided by Luke about Grouping and Virtualization on MSDN helped me a lot. In my case that was the only approach which I was able to come up or find anywhere that is in a direction i need. It does not support all functionality from ListViewCollection. I had to override few methods otherwise selection of items would not work correctly. There are obviously more work to do.

So here is an updated solution of FlatGroupListCollectionView from here :

/// <summary>
///     Provides a view that flattens groups into a list
///     This is used to avoid limitation that ListCollectionView has in .NET 4.0, if grouping is used then Virtialuzation would not work
///     It assumes some appropriate impelmentation in view(XAML) in order to support this way of grouping
///     Note: As implemented, it does not support nested grouping
///     Note: Only overriden properties and method behaves correctly, some of methods and properties related to selection of item might not work as expected and would require new implementation
/// </summary>
public class FlatGroupListCollectionView : ListCollectionView
{
    /// <summary>
    /// Initializes a new instance of the <see cref="FlatGroupListCollectionView"/> class.
    /// </summary>
    /// <param name="list">A list used in this collection</param>
    public FlatGroupListCollectionView(IList list)
        : base(list)
    {
    }

    /// <summary>
    ///     This currently only supports one level of grouping
    ///     Returns CollectionViewGroups if the index matches a header
    ///     Otherwise, maps the index into the base range to get the actual item
    /// </summary>
    /// <param name="index">Index from which get an item</param>
    /// <returns>Item that was found on given index</returns>
    public override object GetItemAt(int index)
    {
        int delta = 0;
        ReadOnlyObservableCollection<object> groups = this.BaseGroups;
        if (groups != null)
        {
            int totalCount = 0;
            for (int i = 0; i < groups.Count; i++)
            {
                CollectionViewGroup group = groups[i] as CollectionViewGroup;
                if (group != null)
                {
                    if (index == totalCount)
                    {
                        return group;
                    }

                    delta++;
                    int numInGroup = group.ItemCount;
                    totalCount += numInGroup + 1;

                    if (index < totalCount)
                    {
                        break;
                    }
                }
            }
        }

        object item = base.GetItemAt(index - delta);
        return item;
    }

    /// <summary>
    ///     In the flat list, the base count is incremented by the number of groups since there are that many headers
    ///     To support nested groups, the nested groups must also be counted and added to the count
    /// </summary>
    public override int Count
    {
        get
        {
            int count = base.Count;

            if (this.BaseGroups != null)
            {
                count += this.BaseGroups.Count;
            }

            return count;
        }
    }

    /// <summary>
    ///     By returning null, we trick the generator into thinking  that we are not grouping
    ///     Thus, we avoid the default grouping code
    /// </summary>
    public override ReadOnlyObservableCollection<object> Groups
    {
        get
        {
            return null;
        }
    }

    /// <summary>
    ///     Gets the Groups collection from the base class
    /// </summary>
    private ReadOnlyObservableCollection<object> BaseGroups
    {
        get
        {
            return base.Groups;
        }
    }

    /// <summary>
    ///     DetectGroupHeaders is a way to get access to the containers by setting the value to true in the container style
    ///     That way, the change handler can hook up to the container and provide a value for IsHeader
    /// </summary>
    public static readonly DependencyProperty DetectGroupHeadersProperty =
        DependencyProperty.RegisterAttached("DetectGroupHeaders", typeof(bool), typeof(FlatGroupListCollectionView), new FrameworkPropertyMetadata(false, OnDetectGroupHeaders));

    /// <summary>
    /// Gets the Detect Group Headers property
    /// </summary>
    /// <param name="obj">Dependency Object from which the property is get</param>
    /// <returns>Value of Detect Group Headers property</returns>
    public static bool GetDetectGroupHeaders(DependencyObject obj)
    {
        return (bool)obj.GetValue(DetectGroupHeadersProperty);
    }

    /// <summary>
    /// Sets the Detect Group Headers property
    /// </summary>
    /// <param name="obj">Dependency Object on which the property is set</param>
    /// <param name="value">Value to set to property</param>
    public static void SetDetectGroupHeaders(DependencyObject obj, bool value)
    {
        obj.SetValue(DetectGroupHeadersProperty, value);
    }

    /// <summary>
    ///     IsHeader can be used to style the container differently when it is a header
    ///     For instance, it can be disabled to prevent selection
    /// </summary>
    public static readonly DependencyProperty IsHeaderProperty =
        DependencyProperty.RegisterAttached("IsHeader", typeof(bool), typeof(FlatGroupListCollectionView), new FrameworkPropertyMetadata(false));

    /// <summary>
    /// Gets the Is Header property
    /// </summary>
    /// <param name="obj">Dependency Object from which the property is get</param>
    /// <returns>Value of Is Header property</returns>
    public static bool GetIsHeader(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsHeaderProperty);
    }

    /// <summary>
    /// Sets the Is Header property
    /// </summary>
    /// <param name="obj">Dependency Object on which the property is set</param>
    /// <param name="value">Value to set to property</param>
    public static void SetIsHeader(DependencyObject obj, bool value)
    {
        obj.SetValue(IsHeaderProperty, value);
    }

    /// <summary>
    /// Raises the System.Windows.Data.CollectionView.CollectionChanged event.
    /// </summary>
    /// <param name="args">The System.Collections.Specialized.NotifyCollectionChangedEventArgs object to pass to the event handler</param>
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs args)
    {
        switch (args.Action)
        {
            case NotifyCollectionChangedAction.Add:
                {
                    int flatIndex = this.ConvertFromItemToFlat(args.NewStartingIndex, false);
                    int headerIndex = Math.Max(0, flatIndex - 1);
                    object o = this.GetItemAt(headerIndex);
                    CollectionViewGroup group = o as CollectionViewGroup;
                    if ((group != null) && (group.ItemCount == args.NewItems.Count))
                    {
                        // Notify that a header was added
                        base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new object[] { group }, headerIndex));
                    }

                    base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, args.NewItems, flatIndex));
                }

                break;

            case NotifyCollectionChangedAction.Remove:
                // TODO: Implement this action
                break;

            case NotifyCollectionChangedAction.Move:
                // TODO: Implement this action
                break;

            case NotifyCollectionChangedAction.Replace:
                // TODO: Implement this action
                break;

            default:
                base.OnCollectionChanged(args);
                break;
        }
    }

    /// <summary>
    /// Sets the specified item to be the System.Windows.Data.CollectionView.CurrentItem in the view
    /// This is an override of base method, an item index is get first and its needed to convert that index to flat version which includes groups
    /// Then adjusted version of MoveCurrentToPosition base method is called
    /// </summary>
    /// <param name="item">The item to set as the System.Windows.Data.CollectionView.CurrentItem</param>
    /// <returns>true if the resulting System.Windows.Data.CollectionView.CurrentItem is within the view; otherwise, false</returns>
    public override bool MoveCurrentTo(object item)
    {
        int index = this.IndexOf(item);

        int newIndex = this.ConvertFromItemToFlat(index, false);

        return this.MoveCurrentToPositionBase(newIndex);
    }

    /// <summary>
    /// Sets the item at the specified index to be the System.Windows.Data.CollectionView.CurrentItem in the view
    /// This is an override of base method, Its called when user selects new item from this collection
    /// A delta is get of which is the possition shifted because of groups and we shift this position by this delta and then base method is called
    /// </summary>
    /// <param name="position">The index to set the System.Windows.Data.CollectionView.CurrentItem to</param>
    /// <returns>true if the resulting System.Windows.Data.CollectionView.CurrentItem is an item within the view; otherwise, false</returns>
    public override bool MoveCurrentToPosition(int position)
    {
        int delta = this.GetDelta(position);

        int newPosition = position - delta;

        return base.MoveCurrentToPosition(newPosition);
    }

    private static void OnDetectGroupHeaders(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // This assumes that a container will not change between being a header and not
        // If using ContainerRecycling this may not be the case
        ((FrameworkElement)d).Loaded += OnContainerLoaded;
    }

    private static void OnContainerLoaded(object sender, RoutedEventArgs e)
    {
        FrameworkElement element = (FrameworkElement)sender;
        element.Loaded -= OnContainerLoaded; // If recycling, remove this line

        // CollectionViewGroup is the type of the header in this sample
        // Add more types or change the type as necessary
        if (element.DataContext is CollectionViewGroup)
        {
            SetIsHeader(element, true);
        }
    }

    private int ConvertFromItemToFlat(int index, bool removed)
    {
        ReadOnlyObservableCollection<object> groups = this.BaseGroups;
        if (groups != null)
        {
            int start = 1;
            for (int i = 0; i < groups.Count; i++)
            {
                CollectionViewGroup group = groups[i] as CollectionViewGroup;
                if (group != null)
                {
                    index++;
                    int end = start + group.ItemCount;

                    if ((start <= index) && ((!removed && index < end) || (removed && index <= end)))
                    {
                        break;
                    }

                    start = end + 1;
                }
            }
        }

        return index;
    }

    /// <summary>
    /// Move <seealso cref="CollectionView.CurrentItem"/> to the item at the given index.
    /// This is a replacement for base method
    /// </summary>
    /// <param name="position">Move CurrentItem to this index</param>
    /// <returns>true if <seealso cref="CollectionView.CurrentItem"/> points to an item within the view.</returns>
    private bool MoveCurrentToPositionBase(int position)
    {
        // VerifyRefreshNotDeferred was removed
        bool result = false;

        // Instead of property InternalCount we use Count property
        if (position < -1 || position > this.Count)
        {
            throw new ArgumentOutOfRangeException("position");
        }

        if (position != this.CurrentPosition || !this.IsCurrentInSync)
        {
            // Instead of property InternalCount we use Count property from this class
            // Instead of InternalItemAt we use GetItemAt from this class
            object proposedCurrentItem = (0 <= position && position < this.Count) ? this.GetItemAt(position) : null;

            // ignore moves to the placeholder
            if (proposedCurrentItem != CollectionView.NewItemPlaceholder)
            {
                if (this.OKToChangeCurrent())
                {
                    bool oldIsCurrentAfterLast = this.IsCurrentAfterLast;
                    bool oldIsCurrentBeforeFirst = this.IsCurrentBeforeFirst;

                    this.SetCurrent(proposedCurrentItem, position);

                    this.OnCurrentChanged();

                    // notify that the properties have changed.
                    if (this.IsCurrentAfterLast != oldIsCurrentAfterLast)
                    {
                        this.OnPropertyChanged(PropertySupport.ExtractPropertyName(() => this.IsCurrentAfterLast));
                    }

                    if (this.IsCurrentBeforeFirst != oldIsCurrentBeforeFirst)
                    {
                        this.OnPropertyChanged(PropertySupport.ExtractPropertyName(() => this.IsCurrentBeforeFirst));
                    }

                    this.OnPropertyChanged(PropertySupport.ExtractPropertyName(() => this.CurrentPosition));
                    this.OnPropertyChanged(PropertySupport.ExtractPropertyName(() => this.CurrentItem));

                    result = true;
                }
            }
        }

        // Instead of IsCurrentInView we return result
        return result;
    }

    private int GetDelta(int index)
    {
        int delta = 0;
        ReadOnlyObservableCollection<object> groups = this.BaseGroups;
        if (groups != null)
        {
            int totalCount = 0;
            for (int i = 0; i < groups.Count; i++)
            {
                CollectionViewGroup group = groups[i] as CollectionViewGroup;
                if (group != null)
                {
                    if (index == totalCount)
                    {
                        break;
                    }

                    delta++;
                    int numInGroup = group.ItemCount;
                    totalCount += numInGroup + 1;

                    if (index < totalCount)
                    {
                        break;
                    }
                }
            }
        }

        return delta;
    }

    /// <summary>
    /// Helper to raise a PropertyChanged event
    /// </summary>
    /// <param name="propertyName">Name of the property</param>
    private void OnPropertyChanged(string propertyName)
    {
        base.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }
}

XAML part stays as it is in sample code. View model stays as it is as well which means using FlatGroupListCollectionView and set up GroupDescriptions.

I prefer this solution because it separates grouping logic from my list of data in view model. Other solution would be to implement support of grouping on original list of items in view model which means somehow identify headers. For a one time usage it should be fine but the collection might need to be recreated for a purpose of different or no grouping which is not so nice.


问:
Cannot find name require Angular2
am trying to learn angular doing a schedulerApp.
here is my code :

app.component.ts

```<code>import {Component} from '@angular/core';
import {Routes, ROUTER_DIRECTIVES} from '@angular/router';
import {AboutComponent} from './about/about.component';
import {ExperimentsComponent} from './experiments/experiments.component';
import {HomeComponent} from './home/home.component';
import {calendrierComponent} from './calendrier/calendrier.component';
import {StateService} from './common/state.service';
import {ExperimentsService} from './common/experiments.service';

@Component({
  selector: 'app',
  template: require('./app.component.html'),
  styles: [ require('./app.component.css')],
  directives: [ ROUTER_DIRECTIVES ],
  providers: [StateService, ExperimentsService],
})
@Routes([
  {path: '/',            component: HomeComponent },
  {path: '/home',        component: HomeComponent },
  {path: '/about',       component: AboutComponent },
  {path: '/experiments', component: ExperimentsComponent },
  {path: '/calendrier',  component: calendrierComponent },
  {path: '/*',           component: HomeComponent }
])
export class AppComponent {}
</code>```

when i add these lines :

```<code>import {calendrierComponent} from './calendrier/calendrier.component';

@Routes([
  {path: '/calendrier',  component: calendrierComponent },
])
</code>```

i have these errors :

```<code>Error   Typescript  Cannot find name 'require'. 12:13
Error   Typescript  Cannot find name 'require'. 13:13
</code>```

i tried to add "   "types": [ "node" ] " on my ts.config.json but it didn't do anything... Did you have some idea to unstuck me ? thanks you very much

答:
your component should be like that. you can not use require in angular 4. also directives depreciate in angular 2 & 4. see (app.module.ts) so you need to pass it in providers in component or declarations in module

```<code> import {Component} from '@angular/core';
    import {Routes, ROUTER_DIRECTIVES} from '@angular/router';
    import {AboutComponent} from './about/about.component';
    import {ExperimentsComponent} from './experiments/experiments.component';
    import {HomeComponent} from './home/home.component';
    import {calendrierComponent} from './calendrier/calendrier.component';
    import {StateService} from './common/state.service';
    import {ExperimentsService} from './common/experiments.service';

    @Component({
      selector: 'app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      providers: [StateService, ExperimentsService, ROUTER_DIRECTIVES],
    })
    @Routes([
      {path: '/',            component: HomeComponent },
      {path: '/home',        component: HomeComponent },
      {path: '/about',       component: AboutComponent },
      {path: '/experiments', component: ExperimentsComponent },
      {path: '/calendrier',  component: calendrierComponent },
      {path: '/*',           component: HomeComponent }
    ])
    export class AppComponent {}
</code>```

Title: Cannot find name require Angular2

Body:
am trying to learn angular doing a schedulerApp.
here is my code :

app.component.ts

import {Component} from '@angular/core';
import {Routes, ROUTER_DIRECTIVES} from '@angular/router';
import {AboutComponent} from './about/about.component';
import {ExperimentsComponent} from './experiments/experiments.component';
import {HomeComponent} from './home/home.component';
import {calendrierComponent} from './calendrier/calendrier.component';
import {StateService} from './common/state.service';
import {ExperimentsService} from './common/experiments.service';

@Component({
  selector: 'app',
  template: require('./app.component.html'),
  styles: [ require('./app.component.css')],
  directives: [ ROUTER_DIRECTIVES ],
  providers: [StateService, ExperimentsService],
})
@Routes([
  {path: '/',            component: HomeComponent },
  {path: '/home',        component: HomeComponent },
  {path: '/about',       component: AboutComponent },
  {path: '/experiments', component: ExperimentsComponent },
  {path: '/calendrier',  component: calendrierComponent },
  {path: '/*',           component: HomeComponent }
])
export class AppComponent {}

when i add these lines :

import {calendrierComponent} from './calendrier/calendrier.component';

@Routes([
  {path: '/calendrier',  component: calendrierComponent },
])

i have these errors :

Error   Typescript  Cannot find name 'require'. 12:13
Error   Typescript  Cannot find name 'require'. 13:13

i tried to add "   "types": [ "node" ] " on my ts.config.json but it didn't do anything... Did you have some idea to unstuck me ? thanks you very much

Body:
your component should be like that. you can not use require in angular 4. also directives depreciate in angular 2 & 4. see (app.module.ts) so you need to pass it in providers in component or declarations in module

 import {Component} from '@angular/core';
    import {Routes, ROUTER_DIRECTIVES} from '@angular/router';
    import {AboutComponent} from './about/about.component';
    import {ExperimentsComponent} from './experiments/experiments.component';
    import {HomeComponent} from './home/home.component';
    import {calendrierComponent} from './calendrier/calendrier.component';
    import {StateService} from './common/state.service';
    import {ExperimentsService} from './common/experiments.service';

    @Component({
      selector: 'app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      providers: [StateService, ExperimentsService, ROUTER_DIRECTIVES],
    })
    @Routes([
      {path: '/',            component: HomeComponent },
      {path: '/home',        component: HomeComponent },
      {path: '/about',       component: AboutComponent },
      {path: '/experiments', component: ExperimentsComponent },
      {path: '/calendrier',  component: calendrierComponent },
      {path: '/*',           component: HomeComponent }
    ])
    export class AppComponent {}


问:
Numpy Linalg norm behaving oddly (wrongly)
I have a large vector F with a few million entries that gives this inconsistent behaviour when taking norms.

```<code>np.linalg.norm(F,2.000001)=3225.96..
np.linalg.norm(F,2)=inf
np.linalg.norm(F,1.999999)=3226.01..
np.linalg.norm(F,1)=inf
---------
np.linalg.norm(F)=inf
np.linalg.norm(F/12)=inf
np.linalg.norm(F/13)=246.25
---------
np.sum(F*F)=inf
np.sum(F*F/169)=60639
np.sum(F*F/144)=inf
---------
np.all(np.isfinite(F))=True
np.max(np.abs(F))=11
---------
F.dtype=dtype('float16')
</code>```

Aside from some sort of hacky solution, does anyone have any idea what's going on?

答:
There seems to be no fix from Numpy yet. So, for completeness, another (quite obvious) solution from my side for calculating a norm:

```<code>def calcNorm(vector):
    if (vector.dtype == np.float16):
        vector = vector.astype(np.float32)
    return np.linalg.norm(vector)
</code>```

Or, as I needed it, in the use case of normalizing a vector:

```<code>def normalize(vector):
    prevType = vector.dtype
    if (vector.dtype == np.float16):
        vector = vector.astype(np.float32)
    norm = np.linalg.norm(vector)
    if (norm != 0 and np.isfinite(norm)):
        vector /= norm
    return vector.astype(prevType)
</code>```

Body:
I have a large vector F with a few million entries that gives this inconsistent behaviour when taking norms.

np.linalg.norm(F,2.000001)=3225.96..
np.linalg.norm(F,2)=inf
np.linalg.norm(F,1.999999)=3226.01..
np.linalg.norm(F,1)=inf
---------
np.linalg.norm(F)=inf
np.linalg.norm(F/12)=inf
np.linalg.norm(F/13)=246.25
---------
np.sum(F*F)=inf
np.sum(F*F/169)=60639
np.sum(F*F/144)=inf
---------
np.all(np.isfinite(F))=True
np.max(np.abs(F))=11
---------
F.dtype=dtype('float16')

Aside from some sort of hacky solution, does anyone have any idea what's going on?

Body:
There seems to be no fix from Numpy yet. So, for completeness, another (quite obvious) solution from my side for calculating a norm:

def calcNorm(vector):
    if (vector.dtype == np.float16):
        vector = vector.astype(np.float32)
    return np.linalg.norm(vector)

Or, as I needed it, in the use case of normalizing a vector:

def normalize(vector):
    prevType = vector.dtype
    if (vector.dtype == np.float16):
        vector = vector.astype(np.float32)
    norm = np.linalg.norm(vector)
    if (norm != 0 and np.isfinite(norm)):
        vector /= norm
    return vector.astype(prevType)


问:
How do I open a dialog or page to a specific record in Google App Maker?
I have an "edit" button on each row in a table of records in Google App Maker.

When the user clicks this button I would like the dialog/page that opens to be editing the record the user clicked on.

Ideally, the answer would work with the showDialog() function.

答:
Try creating a page fragment (say, named "EditDialog") that uses the same datasource as your table. Then set this page fragment to be opened as when you click the edit button:

```<code>app.showDialog(app.pageFragments.EditDialog);
</code>```

Table clicks should automatically select that row of data, so this should be enough. In some cases, I've noticed that the selection happens too late, and the previously selected record might get used in the dialog.

In this case, you might have to make sure that the selection actually happens before the dialog is opened. If I recall correctly, something in the sense of the following (as onClick) made it work for me (this might not be that smart of a solution though):

```<code>var key = widget.datasource.item._key;
widget.datasource.selectKey(key);
app.showDialog(app.pageFragments.EditDialog);
</code>```

Hope this helps!

EDIT: I found out that actually this work better when you make the selection to the datasource not through that widget you're clicking, but through its parents or straight to the datasource (app.datasources.ArbitraryDatasource.selectKey(key);).

ContentLicense: CC BY-SA 4.0

Body:
Try creating a page fragment (say, named "EditDialog") that uses the same datasource as your table. Then set this page fragment to be opened as when you click the edit button:

app.showDialog(app.pageFragments.EditDialog);

Table clicks should automatically select that row of data, so this should be enough. In some cases, I've noticed that the selection happens too late, and the previously selected record might get used in the dialog.

In this case, you might have to make sure that the selection actually happens before the dialog is opened. If I recall correctly, something in the sense of the following (as onClick) made it work for me (this might not be that smart of a solution though):

var key = widget.datasource.item._key;
widget.datasource.selectKey(key);
app.showDialog(app.pageFragments.EditDialog);

Hope this helps!

EDIT: I found out that actually this work better when you make the selection to the datasource not through that widget you're clicking, but through its parents or straight to the datasource (app.datasources.ArbitraryDatasource.selectKey(key);).


问:
How to do a COUNT(*) with GROUP BY in Kotlin?
Let's say that I have a List of objects of the following class.

```<code>class Contact(
    val name: String
    // ...
)
</code>```

I would like to retrieve a Map<String, Int> which maps a name to its number of occurences.

On a SQL-based database I would query:

```<code>SELECT name, count(*) FROM Contact GROUP BY name;
</code>```

What is the best way to do this in Kotlin with higher order functions?

答:
If contacts is of type List<Contact> you can do the following:

```<code>val numOccurencesMap = contacts.groupingBy { it.name }.eachCount()
</code>```

numOccurencesMap will be of type Map<String, Int>.

Body:
Let's say that I have a List of objects of the following class.

class Contact(
    val name: String
    // ...
)

I would like to retrieve a Map<String, Int> which maps a name to its number of occurences.

On a SQL-based database I would query:

SELECT name, count(*) FROM Contact GROUP BY name;

What is the best way to do this in Kotlin with higher order functions?

Body:
If contacts is of type List<Contact> you can do the following:

val numOccurencesMap = contacts.groupingBy { it.name }.eachCount()

numOccurencesMap will be of type Map<String, Int>.


问:
How do we enforce privacy while providing tracing of provenance using multiple channels in Hyperledger Fabric v1.0?
In Hyperledger Fabric v0.6, a supply chain app can be implemented that allows tracing of provenance and avoids double-spending (i.e., distributing/selling items more than it has) and thus avoids counterfeit.  As an example, when a supplier supplies 500 units of an item to a distributor, this data is stored in the ledger.  The distributor can distribute a specified quantity of an item to a particular reseller  by calling a "transfer" function.  The transfer function does the following:

checks if the distributor has enough quantity of an item to distribute to a particular reseller (i.e., if quantity to transfer <= current quantity)

updates the ledger (i.e., deducts the current quantity of the distributor and adds this to the current quantity of the reseller)

With this approach, the distributor cannot distribute more (i.e., double spend) than what it has (e.g., distributing counterfeit/smuggled items).

In addition, a consumer can trace the provenance (e.g., an item was purchased from reseller1, which came from a distributor, which came from a supplier) by looking at the ledger.

However, since it uses a single ledger, privacy is an issue (e.g., reseller2 can see the quantity of items ordered by reseller1, etc.)

A proposed solution to impose privacy is to use multiple channels in Hyperledger Fabric v1.0.  In this approach, a separate channel/ledger is used by the supplier and distributor.  Similarly, a separate channel/ledger is used by the distributor and reseller1, and another separate channel/ledger for the distributor and reseller2.

However, since the resellers (i.e., reseller1 and reseller2) have no access the the channel/ledger of the supplier and distributor, the resellers have no idea of the real quantity supplied by the supplier to the distributor.  For example, if the supplier supplied only 500 quantities to the distributor, the distributor can claim to the resellers that it procured 1000 quantities from the supplier.  With this approach, double spending / counterfeiting will not be avoided.

In addition, how will tracing of provenance be implemented?  Will a consumer be given access to all the channels/ledgers?  If this is the case, then privacy becomes an issue again.

Given this, how can we use multiple channels in Hyperledger Fabric v1.0 while allowing tracing of provenance and prohibiting double spending?

答:
At the moment there is no straight forward way of providing provenance across two different channels within Hyperledger Fabric 1.0. There few directions to support such scenarios:

First one is to have an ability to keep portions of the data of the ledger and provide discrete segregation within the channel, the work item described here: FAB-1151.

Additionally there is proposal of adding support for private data while maintaining the ability to proof existence and ownership of claimed asset was posted in mailing list.

What you can do currently is to leverage application side encryption to provide privacy and keep all related transactions on the same channel, e.g. same ledger (pretty much similar to approach you had back in v0.6).


问:
Web config - redirect specific url with domain to another url
I would like to redirect testdomain.com/diamonds/silver to testdomain.com/diamonds.

I need to have the domain specified because the website has several domains attached to it.

This is what i have now, but it does not seem to do anything.

```<code><rule name="testredirect" stopProcessing="true">
        <match url=".*" />
         <conditions logicalGrouping="MatchAny">
           <add input="{HTTP_HOST}" pattern="^testdomain.com/diamonds/silver" />
         </conditions>
         <action type="Redirect" url="/diamonds" redirectType="Permanent" />
 </rule>
</code>```

I have also tried this, but that did not work either.

```<code><rule name="testredirect" stopProcessing="true">
    <match url="^testdomain.com/diamonds/silver" ignoreCase="true" />
    <action type="Redirect" url="/diamonds" redirectType="Permanent"/>
</rule>
</code>```

Any suggestions?

I have figured it out. Answer below!

答:
Finally.

This worked:

```<code><rule name="redirect diamonds" stopProcessing="true">
            <match url="^diamonds/diamondrings" ignoreCase="true" />
            <conditions>
                <add input="{HTTP_HOST}" pattern="^(www.)?mywebshop.azurewebsites.net" />
            </conditions>
            <action type="Redirect" url="/diamondrings" redirectType="Permanent" />
        </rule>
</code>```

Body:
I would like to redirect testdomain.com/diamonds/silver to testdomain.com/diamonds.

I need to have the domain specified because the website has several domains attached to it.

This is what i have now, but it does not seem to do anything.

<rule name="testredirect" stopProcessing="true">
        <match url=".*" />
         <conditions logicalGrouping="MatchAny">
           <add input="{HTTP_HOST}" pattern="^testdomain.com/diamonds/silver" />
         </conditions>
         <action type="Redirect" url="/diamonds" redirectType="Permanent" />
 </rule>

I have also tried this, but that did not work either.

<rule name="testredirect" stopProcessing="true">
    <match url="^testdomain.com/diamonds/silver" ignoreCase="true" />
    <action type="Redirect" url="/diamonds" redirectType="Permanent"/>
</rule>

Any suggestions?

I have figured it out. Answer below!

Body:
Finally.

This worked:

<rule name="redirect diamonds" stopProcessing="true">
            <match url="^diamonds/diamondrings" ignoreCase="true" />
            <conditions>
                <add input="{HTTP_HOST}" pattern="^(www.)?mywebshop.azurewebsites.net" />
            </conditions>
            <action type="Redirect" url="/diamondrings" redirectType="Permanent" />
        </rule>


问:
How to publish an image to a Facebook Page's albums via CURL along with getting new Page Access Tokens?
Currently, I have a website that allows users to upload images and at the same time I would like all these uploaded images to be published automatically to a Facebook page's albums. I used this CURL code below:

```<code>    $args = array(
       'message' => $imageDescription,
        'access_token'=>$accesstoken,
        'url' => $img
    );

    $ch = curl_init();
    $url = 'https://graph.facebook.com/' . $albumid . '/photos';
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

    $data = curl_exec($ch);

    $response = json_decode($data,true);
</code>```

From my test, this code works, but only for an hour, because I use the access token generated from the Graph API. This expiration is mentioned in https://developers.facebook.com/docs/pages/access-tokens#expire .

I have been looking around on Stack Overflow, and majority of the questions and answers mentioned the use of app ID and app secret to generate a new token, but this is a page and not an app. There is no app ID and app secret, so I am stuck.

So in this case, what can I do? Or is it not possible to use CURL in this case?

答:
An app in this case doesn't refer to something like a game, it is referring to an API app. This is common for APIs that use OAuth to authenticate users. You create an app for your account and it allows you to access the Facebook API using your user account as the user accessing it. </p>

<p>The following post explains the entire thing and even has info about how the facebook API works https://stormpath.com/blog/what-the-heck-is-oauth </p>

Body:
Currently, I have a website that allows users to upload images and at the same time I would like all these uploaded images to be published automatically to a Facebook page's albums. I used this CURL code below:

    $args = array(
       'message' => $imageDescription,
        'access_token'=>$accesstoken,
        'url' => $img
    );

    $ch = curl_init();
    $url = 'https://graph.facebook.com/' . $albumid . '/photos';
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

    $data = curl_exec($ch);

    $response = json_decode($data,true);

From my test, this code works, but only for an hour, because I use the access token generated from the Graph API. This expiration is mentioned in https://developers.facebook.com/docs/pages/access-tokens#expire .

I have been looking around on Stack Overflow, and majority of the questions and answers mentioned the use of app ID and app secret to generate a new token, but this is a page and not an app. There is no app ID and app secret, so I am stuck.

So in this case, what can I do? Or is it not possible to use CURL in this case?

Body:
An app in this case doesn't refer to something like a game, it is referring to an API app. This is common for APIs that use OAuth to authenticate users. You create an app for your account and it allows you to access the Facebook API using your user account as the user accessing it.

The following post explains the entire thing and even has info about how the facebook API works https://stormpath.com/blog/what-the-heck-is-oauth


问:
Passing python function from python3 to jython 2.2
I have a python 3 code, which internally starts a jython process, as shown:

```<code>from multiprocessing import Process
import subprocess

def startJython(arg1, arg2, arg3):
    jythonProc = Process(target=initJython, args=(arg1,arg2,arg3,))
    jythonProc.start()

def initJython(arg1,arg2,arg3):
    command = 'java -jar /pathTo/jython.jar /pathTo/myJython.py '+arg1+' '+arg2+' '+arg3
    subprocess.call(command,shell=True)
</code>```

This works well when the arguments are strings.
However, python allows us to pass functions as arguments.

How can I send a function as an argument in this scenario ?

I understand that it cannot be done via a shell command, hence I'm also looking for alternate approaches to this process.

Please note that I cannot run the whole process in jython or python3 alone, because python3 uses imports that jython 2.2 cannot import, vice versa.

I considered passing the function name as a string using the __name__ object, but then my jython code may not be able to import that function since it won't know where to import it from.

What is the most optimum solution to this ? Thanks

答:
I solved this problem by passing the following as arguments:

arg1 - the name of the function I want to call

arg2 - the name of the module that contains the method

arg3 - the absolute path to the module

I ran the startJython function, as defined in my question.

in the target myJython.py, I imported the method from arg1, arg2 and arg3 as shown:

```<code>import sys
testmethod_name = sys.argv[1]
testmethod_module = sys.argv[2]
module_path = sys.argv[3]

sys.path.append(module_path) #append full path to the file to sys.path
testmodule = __import__(testmethod_module) #import the module that contains the method
testmethod = getattr(testmodule, testmethod_name) #type: function
</code>```

Body:
I have a python 3 code, which internally starts a jython process, as shown:

from multiprocessing import Process
import subprocess

def startJython(arg1, arg2, arg3):
    jythonProc = Process(target=initJython, args=(arg1,arg2,arg3,))
    jythonProc.start()

def initJython(arg1,arg2,arg3):
    command = 'java -jar /pathTo/jython.jar /pathTo/myJython.py '+arg1+' '+arg2+' '+arg3
    subprocess.call(command,shell=True)

This works well when the arguments are strings.
However, python allows us to pass functions as arguments.

How can I send a function as an argument in this scenario ?

I understand that it cannot be done via a shell command, hence I'm also looking for alternate approaches to this process.

Please note that I cannot run the whole process in jython or python3 alone, because python3 uses imports that jython 2.2 cannot import, vice versa.

I considered passing the function name as a string using the __name__ object, but then my jython code may not be able to import that function since it won't know where to import it from.

What is the most optimum solution to this ? Thanks

Body:
I solved this problem by passing the following as arguments:

arg1 - the name of the function I want to call

arg2 - the name of the module that contains the method

arg3 - the absolute path to the module

I ran the startJython function, as defined in my question.

in the target myJython.py, I imported the method from arg1, arg2 and arg3 as shown:

import sys
testmethod_name = sys.argv[1]
testmethod_module = sys.argv[2]
module_path = sys.argv[3]

sys.path.append(module_path) #append full path to the file to sys.path
testmodule = __import__(testmethod_module) #import the module that contains the method
testmethod = getattr(testmodule, testmethod_name) #type: function


问:
Play one song at a time
I am a beginner in html. I made my website and it contains various audio elements. I want that only one audio element should be played at a time I got jquery code from another question. But when I play first song for 10s and then move on to next one and when I again play the first song then it starts from 10s. I want that it should start from the begining.
Can anyone help me.
Give me the jquery code
Thanx in advance</p>

答:
There is no .stop() function for audio elements. We can only pause them. And when we want to start from the beginning of the audio file we change its .currentTime. We will use this line in our example audioElement.currentTime = 0;. To achieve .stop() function we first pause the file then reset its time.

We may want to know the length of the audio file and the current playing time. We already learnt .currentTimeabove, to learn its length we use .duration.

use the following snippet to set the timing of the audio file from starting.

```<code> $('#restart').click(function() {
        audioElement.currentTime = 0;
 });
</code>```

Source: Play an audio file using jQuery when a button is clicked

Title: Play one song at a time

Body:
There is no .stop() function for audio elements. We can only pause them. And when we want to start from the beginning of the audio file we change its .currentTime. We will use this line in our example audioElement.currentTime = 0;. To achieve .stop() function we first pause the file then reset its time.

We may want to know the length of the audio file and the current playing time. We already learnt .currentTimeabove, to learn its length we use .duration.

use the following snippet to set the timing of the audio file from starting.

 $('#restart').click(function() {
        audioElement.currentTime = 0;
 });

Source: Play an audio file using jQuery when a button is clicked


问:
How to set data in recyclerView with Retrofit in Android
I want to show some data into recyclerview and for this I am using the code displayed below.

When I run the application, it's not showing me any data into recyclerview and ListData.size() is 0, but in PostMan

I write below code for set into recyclerView :

```<code>InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<CommentResponse> call = api.getComments(sendData);

call.enqueue(new Callback<CommentResponse>() {
    @Override
    public void onResponse(Call<CommentResponse> call, Response<CommentResponse> response) {
        if (response.body().getData() != null) {
            commentModel.clear();
            commentModel.addAll(response.body().getData());
            commentsListAdapter.notifyDataSetChanged();
            content_newsCommentsRecyclerView.setAdapter(commentsListAdapter);
        }
    }

    @Override
    public void onFailure(Call<CommentResponse> call, Throwable t) {

    }
});
</code>```

My Adapter codes:

```<code>public class CommentsListAdapter extends RecyclerView.Adapter<CommentsListAdapter.ViewHolder> {

    private Context context;
    private List<CommentData> model;

    public CommentsListAdapter(Context context, List<CommentData> model) {
        this.context = context;
        this.model = model;
    }

    @Override
    public CommentsListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_comment, parent, false);

        return new CommentsListAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final CommentsListAdapter.ViewHolder holder, final int position) {

        holder.row_commentNameTxt.setText(Html.fromHtml(model.get(position).getOwner().getName()));
        holder.row_commentCommentTxt.setText(Html.fromHtml(model.get(position).getText()));
        Glide.with(context)
                .load(model.get(position).getOwner().getImageUrl())
                .placeholder(R.drawable.default_image)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(holder.row_commentProfileImage);
        holder.row_commentLikeTxt.setText(model.get(position).getLikeCount() + "");
        holder.row_commentReplayTxt.setText(model.get(position).getRepliesCount() + "");
        holder.row_commentDateTxt.setText(model.get(position).getSubmitDate() + " " + model.get(position).getSubmitTime());
    }

    @Override
    public int getItemCount() {
        return model.size();
    }

    public void addNewItem(List<CommentData> newContent) {
        int start = this.model.size();
        int end = newContent.size();
        model.addAll(newContent);
        notifyDataSetChanged();
    }

    public void clear() {
        model.clear();
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private CircleImageView row_commentProfileImage;
        private TextView row_commentNameTxt, row_commentCommentTxt, row_commentLikeTxt, row_commentReplayTxt, row_commentDateTxt;

        public ViewHolder(View itemView) {
            super(itemView);

            row_commentProfileImage = (CircleImageView) itemView.findViewById(R.id.row_commentProfileImage);
            row_commentNameTxt = (TextView) itemView.findViewById(R.id.row_commentNameTxt);
            row_commentCommentTxt = (TextView) itemView.findViewById(R.id.row_commentCommentTxt);
            row_commentLikeTxt = (TextView) itemView.findViewById(R.id.row_commentLikeTxt);
            row_commentReplayTxt = (TextView) itemView.findViewById(R.id.row_commentReplayTxt);
            row_commentDateTxt = (TextView) itemView.findViewById(R.id.row_commentDateTxt);

        }
    }
}
</code>```

How can I display the data into recyclerView?

答:
Create a method inside your Adapter class

```<code>       //This will add all the items in the adapter's list
       public  void addAllItems(List<CommentData> items) {
                model.addAll(items);
                notifyDataSetChanged();
            }

//In Adapter's Constructor do the following changes
 public CommentsListAdapter(Context context, List<CommentData> model) {
        this.context = context;
        this.model = new ArrayList<>;
    }
</code>```

and when you are fetching your response you can call this by

```<code>//Inside your onCreate add the below code

        mAdapter = new CommentsListAdapter (this);
        content_newsCommentsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        content_newsCommentsRecyclerView.setAdapter(mAdapter);

//Call this inside your success of onResponse
commentsListAdapter.addAllItems(commentModel);
</code>```

This will update the content of recyclerView and notify the changes made, do try this and let me know if you have any issue.

Body:
I want to show some data into recyclerview and for this I am using the code displayed below.

When I run the application, it's not showing me any data into recyclerview and ListData.size() is 0, but in PostMan

I write below code for set into recyclerView :

InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<CommentResponse> call = api.getComments(sendData);

call.enqueue(new Callback<CommentResponse>() {
    @Override
    public void onResponse(Call<CommentResponse> call, Response<CommentResponse> response) {
        if (response.body().getData() != null) {
            commentModel.clear();
            commentModel.addAll(response.body().getData());
            commentsListAdapter.notifyDataSetChanged();
            content_newsCommentsRecyclerView.setAdapter(commentsListAdapter);
        }
    }

    @Override
    public void onFailure(Call<CommentResponse> call, Throwable t) {

    }
});

My Adapter codes:

public class CommentsListAdapter extends RecyclerView.Adapter<CommentsListAdapter.ViewHolder> {

    private Context context;
    private List<CommentData> model;

    public CommentsListAdapter(Context context, List<CommentData> model) {
        this.context = context;
        this.model = model;
    }

    @Override
    public CommentsListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_comment, parent, false);

        return new CommentsListAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final CommentsListAdapter.ViewHolder holder, final int position) {

        holder.row_commentNameTxt.setText(Html.fromHtml(model.get(position).getOwner().getName()));
        holder.row_commentCommentTxt.setText(Html.fromHtml(model.get(position).getText()));
        Glide.with(context)
                .load(model.get(position).getOwner().getImageUrl())
                .placeholder(R.drawable.default_image)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(holder.row_commentProfileImage);
        holder.row_commentLikeTxt.setText(model.get(position).getLikeCount() + "");
        holder.row_commentReplayTxt.setText(model.get(position).getRepliesCount() + "");
        holder.row_commentDateTxt.setText(model.get(position).getSubmitDate() + " " + model.get(position).getSubmitTime());
    }

    @Override
    public int getItemCount() {
        return model.size();
    }

    public void addNewItem(List<CommentData> newContent) {
        int start = this.model.size();
        int end = newContent.size();
        model.addAll(newContent);
        notifyDataSetChanged();
    }

    public void clear() {
        model.clear();
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private CircleImageView row_commentProfileImage;
        private TextView row_commentNameTxt, row_commentCommentTxt, row_commentLikeTxt, row_commentReplayTxt, row_commentDateTxt;

        public ViewHolder(View itemView) {
            super(itemView);

            row_commentProfileImage = (CircleImageView) itemView.findViewById(R.id.row_commentProfileImage);
            row_commentNameTxt = (TextView) itemView.findViewById(R.id.row_commentNameTxt);
            row_commentCommentTxt = (TextView) itemView.findViewById(R.id.row_commentCommentTxt);
            row_commentLikeTxt = (TextView) itemView.findViewById(R.id.row_commentLikeTxt);
            row_commentReplayTxt = (TextView) itemView.findViewById(R.id.row_commentReplayTxt);
            row_commentDateTxt = (TextView) itemView.findViewById(R.id.row_commentDateTxt);

        }
    }
}

How can I display the data into recyclerView?

Body:
Create a method inside your Adapter class

       //This will add all the items in the adapter's list
       public  void addAllItems(List<CommentData> items) {
                model.addAll(items);
                notifyDataSetChanged();
            }

//In Adapter's Constructor do the following changes
 public CommentsListAdapter(Context context, List<CommentData> model) {
        this.context = context;
        this.model = new ArrayList<>;
    }

and when you are fetching your response you can call this by

//Inside your onCreate add the below code

        mAdapter = new CommentsListAdapter (this);
        content_newsCommentsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        content_newsCommentsRecyclerView.setAdapter(mAdapter);

//Call this inside your success of onResponse
commentsListAdapter.addAllItems(commentModel);

This will update the content of recyclerView and notify the changes made, do try this and let me know if you have any issue.


问:
Jquery button don't append elements with no errors at the console
I have this html form:

```<code>         <div class="col-sm-4 rounded" style="background-color: #D3D3D3">
          <div class="row clonedInput" id="clonedInput1">
          <div class="col-sm-6">
              <label for="diagnosis_data">Medication</label>
                <fieldset class="form-group">
                  <select class="form-control select" name="diagnosis_data" id="diagnosis_data">
                    <option value="choose">Select</option>
                  </select>
                </fieldset>
            <!-- End class="col-sm-6" -->
            </div>
            <div class="col-sm-6">
              <label for="patient_weight">Quantity</label>
                <fieldset class="form-group">
                  <input type="number" class="form-control" name="patient_weight" id="patient_weight">
                </fieldset>
            <!-- End class="col-sm-6" -->
            </div>
            <!-- End class="col-sm-6" -->
          </div>
          <div class="actions pull-right">
            <button class="btn btn-danger clone">Add More</button>
            <button class="btn btn-danger remove">Remove</button>
          </div>
</code>```

And this jQuery Script from this link here:

```<code><script>
  $(document).ready(function()
  {
    $("button.clone").on("click", clone);

    $("button.remove").on("click", remove);
  })
    var regex = /^(.+?)(\d+)$/i;
    var cloneIndex = $(".clonedInput").length;
    function clone(){
        $(this).parents(".clonedInput").clone()
            .appendTo(".rounded")
            .attr("id", "clonedInput" +  cloneIndex)
            .find("*")
            .each(function() {
                var id = this.id || "";
                var match = id.match(regex) || [];
                if (match.length == 3) {
                    this.id = match[1] + (cloneIndex);
                }
            })
            .on('click', 'button.clone', clone)
            .on('click', 'button.remove', remove);
        cloneIndex++;
    }
    function remove(){
        $(this).parents(".clonedInput").remove();
    }

  </script>
</code>```

But of course with changes to html but nothing happens when I click on each of the buttons, even no errors at the console. Here is my fiddle.

I am using jQuery 3.2.1

EDIT 1

I tried this script:

```<code>$("button.clone").on("click", function()
{
   $('.clonedInput').clone().insertAfter('.clonedInput')
});
</code>```

it works but there is 2 problems:

ID of each element is not incrementing;

If I had 2 elements and clicked on the button they will be 4, then 8, then...

EDIT 2

I tried this and the problem number 2 is gone:

```<code>$("button.clone").on("click", function()
{
  $('#clonedInput1').clone().insertAfter('#clonedInput1')
});
</code>```

Now I still have to increment the id so I can send the data later using Ajax. Here is my updated fiddle.

答:
Check if below code works!

$(document).ready(function()
  {
    $("button.clone").on("click", clone);

    $("button.remove").on("click", remove);
  })
    var regex = /^(.+?)(\d+)$/i;
    var cloneIndex = $(".clonedInput").length;
    function clone(){

        $(this).closest(".rounded").clone()
            .insertAfter(".rounded:last")
            .attr("id", "rounded" +  (cloneIndex+1))
            .find("*")
            .each(function() {
                var id = this.id || "";
                var match = id.match(regex) || [];
                if (match.length == 3) {
                    this.id = match[1] + (cloneIndex+1);
                }
            })
            .on('click', 'button.clone', clone)
            .on('click', 'button.remove', remove);
        cloneIndex++;
    }
    function remove(){
        $(this).parent().parent(".rounded").remove();
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
              <div class="row clonedInput" id="clonedInput1">
              <div class="col-sm-6">
                  <label for="diagnosis_data">Medication</label>
                    <fieldset class="form-group">
                      <select class="form-control select" name="diagnosis_data" id="diagnosis_data">
                        <option value="choose">Select</option>
                      </select>
                    </fieldset>
                <!-- End class="col-sm-6" -->
                </div>
                <div class="col-sm-6">
                  <label for="patient_weight">Quantity</label>
                    <fieldset class="form-group">
                      <input type="number" class="form-control" name="patient_weight" id="patient_weight">
                    </fieldset>
                <!-- End class="col-sm-6" -->
                </div>
                <!-- End class="col-sm-6" -->
              </div>
              <div class="actions pull-right">
                <button class="btn btn-danger clone">Add More</button>
                <button class="btn btn-danger remove">Remove</button>
              </div></code>```

Body:
I have this html form:

              Medication
                <fieldset class="form-group">
                  <select class="form-control select" name="diagnosis_data" id="diagnosis_data">
                    <option value="choose">Select</option>
                  </select>
                </fieldset>

              Quantity
                <fieldset class="form-group">
                  <input type="number" class="form-control" name="patient_weight" id="patient_weight">
                </fieldset>

            <button class="btn btn-danger clone">Add More</button>
            <button class="btn btn-danger remove">Remove</button>

And this jQuery Script from this link here:

But of course with changes to html but nothing happens when I click on each of the buttons, even no errors at the console. Here is my fiddle.

I am using jQuery 3.2.1

EDIT 1

I tried this script:

$("button.clone").on("click", function()
{
   $('.clonedInput').clone().insertAfter('.clonedInput')
});

it works but there is 2 problems:

ID of each element is not incrementing;

If I had 2 elements and clicked on the button they will be 4, then 8, then...

EDIT 2

I tried this and the problem number 2 is gone:

$("button.clone").on("click", function()
{
  $('#clonedInput1').clone().insertAfter('#clonedInput1')
});

Now I still have to increment the id so I can send the data later using Ajax. Here is my updated fiddle.

Body:
Check if below code works!

$(document).ready(function()
  {
    $("button.clone").on("click", clone);

    $("button.remove").on("click", remove);
  })
    var regex = /^(.+?)(\d+)$/i;
    var cloneIndex = $(".clonedInput").length;
    function clone(){

        $(this).closest(".rounded").clone()
            .insertAfter(".rounded:last")
            .attr("id", "rounded" +  (cloneIndex+1))
            .find("*")
            .each(function() {
                var id = this.id || "";
                var match = id.match(regex) || [];
                if (match.length == 3) {
                    this.id = match[1] + (cloneIndex+1);
                }
            })
            .on('click', 'button.clone', clone)
            .on('click', 'button.remove', remove);
        cloneIndex++;
    }
    function remove(){
        $(this).parent().parent(".rounded").remove();
    }

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
              <div class="row clonedInput" id="clonedInput1">
              <div class="col-sm-6">
                  <label for="diagnosis_data">Medication</label>
                    <fieldset class="form-group">
                      <select class="form-control select" name="diagnosis_data" id="diagnosis_data">
                        <option value="choose">Select</option>
                      </select>
                    </fieldset>
                <!-- End class="col-sm-6" -->
                </div>
                <div class="col-sm-6">
                  <label for="patient_weight">Quantity</label>
                    <fieldset class="form-group">
                      <input type="number" class="form-control" name="patient_weight" id="patient_weight">
                    </fieldset>
                <!-- End class="col-sm-6" -->
                </div>
                <!-- End class="col-sm-6" -->
              </div>
              <div class="actions pull-right">
                <button class="btn btn-danger clone">Add More</button>
                <button class="btn btn-danger remove">Remove</button>
              </div>