问:
Set row of csr_matrix
I have a sparse csr_matrix, and I want to change the values of a single row to different values. I can't find an easy and efficient implementation however. This is what it has to do:

```<code>A = csr_matrix([[0, 1, 0],
                [1, 0, 1],
                [0, 1, 0]])
new_row = np.array([-1, -1, -1])
print(set_row_csr(A, 2, new_row).todense())

>>> [[ 0,  1, 0],
     [ 1,  0, 1],
     [-1, -1, -1]]
</code>```

This is my current implementation of set_row_csr:

```<code>def set_row_csr(A, row_idx, new_row):
    A[row_idx, :] = new_row
    return A
</code>```

But this gives me a SparseEfficiencyWarning. Is there a way of getting this done without manual index juggling, or is this my only way out?

答:
physicalattraction's answer is indeed significantly quicker. It's much faster than my solution, which was to just add a separate matrix with that single row set. Though the addition solution was faster than the slicing solution.

The take away for me is that the fastest way to set rows in a csr_matrix or columns in a csc_matrix is to modify the underlying data yourself.

```<code>def time_copy(A, num_tries = 10000):
    start = time.time()
    for i in range(num_tries):
        B = A.copy()
    end = time.time()
    return end - start

def test_method(func, A, row_idx, new_row, num_tries = 10000):
    start = time.time()
    for i in range(num_tries):
        func(A.copy(), row_idx, new_row)
    end = time.time()
    copy_time = time_copy(A, num_tries)
    print("Duration {}".format((end - start) - copy_time))

def set_row_csr_slice(A, row_idx, new_row):
    A[row_idx,:] = new_row

def set_row_csr_addition(A, row_idx, new_row):
    indptr = np.zeros(A.shape[1] + 1)
    indptr[row_idx +1:] = A.shape[1]
    indices = np.arange(A.shape[1])
    A += csr_matrix((new_row, indices, indptr), shape=A.shape)

>>> A = csr_matrix((np.ones(1000), (np.random.randint(0,1000,1000), np.random.randint(0, 1000, 1000))))
>>> test_method(set_row_csr_slice, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 4.938395977020264

>>> test_method(set_row_csr_addition, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 2.4161765575408936

>>> test_method(set_row_csr, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 0.8432261943817139
</code>```

The slice solution also scales much worse with the size and sparsity of the matrix.

```<code># Larger matrix, same fraction sparsity
>>> A = csr_matrix((np.ones(10000), (np.random.randint(0,10000,10000), np.random.randint(0, 10000, 10000))))
>>> test_method(set_row_csr_slice, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 18.335174798965454

>>> test_method(set_row_csr, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 1.1089558601379395

# Super sparse matrix
>>> A = csr_matrix((np.ones(100), (np.random.randint(0,10000,100), np.random.randint(0, 10000, 100))))
>>> test_method(set_row_csr_slice, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 13.371600151062012

>>> test_method(set_row_csr, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 1.0454308986663818
</code>```

Title: Set row of csr_matrix

Body:
I have a sparse csr_matrix, and I want to change the values of a single row to different values. I can't find an easy and efficient implementation however. This is what it has to do:

A = csr_matrix([[0, 1, 0],
                [1, 0, 1],
                [0, 1, 0]])
new_row = np.array([-1, -1, -1])
print(set_row_csr(A, 2, new_row).todense())

>>> [[ 0,  1, 0],
     [ 1,  0, 1],
     [-1, -1, -1]]

This is my current implementation of set_row_csr:

def set_row_csr(A, row_idx, new_row):
    A[row_idx, :] = new_row
    return A

But this gives me a SparseEfficiencyWarning. Is there a way of getting this done without manual index juggling, or is this my only way out?

Body:
physicalattraction's answer is indeed significantly quicker. It's much faster than my solution, which was to just add a separate matrix with that single row set. Though the addition solution was faster than the slicing solution.

The take away for me is that the fastest way to set rows in a csr_matrix or columns in a csc_matrix is to modify the underlying data yourself.

def time_copy(A, num_tries = 10000):
    start = time.time()
    for i in range(num_tries):
        B = A.copy()
    end = time.time()
    return end - start

def test_method(func, A, row_idx, new_row, num_tries = 10000):
    start = time.time()
    for i in range(num_tries):
        func(A.copy(), row_idx, new_row)
    end = time.time()
    copy_time = time_copy(A, num_tries)
    print("Duration {}".format((end - start) - copy_time))

def set_row_csr_slice(A, row_idx, new_row):
    A[row_idx,:] = new_row

def set_row_csr_addition(A, row_idx, new_row):
    indptr = np.zeros(A.shape[1] + 1)
    indptr[row_idx +1:] = A.shape[1]
    indices = np.arange(A.shape[1])
    A += csr_matrix((new_row, indices, indptr), shape=A.shape)

>>> A = csr_matrix((np.ones(1000), (np.random.randint(0,1000,1000), np.random.randint(0, 1000, 1000))))
>>> test_method(set_row_csr_slice, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 4.938395977020264

>>> test_method(set_row_csr_addition, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 2.4161765575408936

>>> test_method(set_row_csr, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 0.8432261943817139

The slice solution also scales much worse with the size and sparsity of the matrix.

# Larger matrix, same fraction sparsity
>>> A = csr_matrix((np.ones(10000), (np.random.randint(0,10000,10000), np.random.randint(0, 10000, 10000))))
>>> test_method(set_row_csr_slice, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 18.335174798965454

>>> test_method(set_row_csr, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 1.1089558601379395

# Super sparse matrix
>>> A = csr_matrix((np.ones(100), (np.random.randint(0,10000,100), np.random.randint(0, 10000, 100))))
>>> test_method(set_row_csr_slice, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 13.371600151062012

>>> test_method(set_row_csr, A, 200, np.ones(A.shape[1]), num_tries = 10000)
Duration 1.0454308986663818


来源: stackexchange

问:
Ruby reverse iterate array but not index
How to convert this code to Ruby involving reversed array iteration and but not indexing?

```<code>    out = 0
    for index,x in enumerate(reversed(d)):
        out += x*pow(2,index)
</code>```

From what I can understand from the Python code, the array d is reversed but the index of the elements are not?

Twisting!

How to do this in Ruby?

答:
Considering the next output in Python:

```<code>for index, string in enumerate(reversed(['zero', 'one', 'two'])):
    print index, string
# 0 two
# 1 one
# 2 zero
</code>```

Then you can use reverse before applying the enumerator, in this case each, so, it'll take your array as ['two', 'one', 'zero'], and the index for each iteration will remain intact:

```<code>['zero', 'one', 'two'].reverse.each_with_index do |word, index|
  puts "#{index} #{word}"
end
# 0 two
# 1 one
# 2 zero
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to convert this code to Ruby involving reversed array iteration and but not indexing?

    out = 0
    for index,x in enumerate(reversed(d)):
        out += x*pow(2,index)

From what I can understand from the Python code, the array d is reversed but the index of the elements are not?

Twisting!

How to do this in Ruby?

Body:
Considering the next output in Python:

for index, string in enumerate(reversed(['zero', 'one', 'two'])):
    print index, string
# 0 two
# 1 one
# 2 zero

Then you can use reverse before applying the enumerator, in this case each, so, it'll take your array as ['two', 'one', 'zero'], and the index for each iteration will remain intact:

['zero', 'one', 'two'].reverse.each_with_index do |word, index|
  puts "#{index} #{word}"
end
# 0 two
# 1 one
# 2 zero


问:
WPF Enter Keystroke Simulating Click on Button
How do I make the user enter return have the same effect as click the button?</p>

答:
You need to set IsDefault to true:</p>

```<code><Button IsDefault="True"></Button>
</code>```

Body:
You need to set IsDefault to true:

<Button IsDefault="True"></Button>

ContentLicense: CC BY-SA 2.5


问:
Many docker volumes, each for different user (swarm mode)
I have users that each will each have a directory for storing arbitrary php code. Each user can execute their code in a Docker container - this means I don't want user1 to be able to see the directory for user2.

I'm not sure how to set this up.

I've read about bind-mounts vs named-volumes. I'm using swarm-mode so I don't know on which host a particular container will run. This means I'm not sure how to connect the container to the volume mount and subdirectory.

Any ideas?

答:
Have you considered having an external server for storage and mounting it on each Docker host?
If you need the data to exist and you don't want to mount external storage you can try looking into something like Gluster for syncing files across multiple hosts
As for not wanting users to share directories you can just set the rights on the folder.</p>


问:
How to perform an integer division, and separately get the remainder, in JavaScript?
In JavaScript, how do I get:

The whole number of times a given integer goes into another?

The remainder?

答:
Alex Moore-Niemi's comment as an answer:

For Rubyists here from Google in search of divmod, you can implement it as such:

```<code>function divmod(x, y) {
  var div = Math.trunc(x/y);
  var rem = x % y;
  return [div, rem];
}
</code>```

Result:

```<code>// [2, 33]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Alex Moore-Niemi's comment as an answer:

For Rubyists here from Google in search of divmod, you can implement it as such:

function divmod(x, y) {
  var div = Math.trunc(x/y);
  var rem = x % y;
  return [div, rem];
}

Result:

// [2, 33]


问:
How does the StringBuilder decide how large its capacity should be?
I know that the StringBuilder object allocates more memory when you use sb.Append(..) when the sb is already at capacity. But how much does that capacity increase?

```<code>    StringBuilder sb = new StringBuilder(5);
    sb.Append("0123456789");
</code>```

Now what is the capacity of sb and why? What is the multiplier?

Just for clarity. I am asking about capacity and not length.

Thanks!

答: It's exponential growth (specifically, doubling with each reallocation), in order to allow a series of appends to take O(N) time instead of O(N²) time.</p>

Body:
I know that the StringBuilder object allocates more memory when you use sb.Append(..) when the sb is already at capacity. But how much does that capacity increase?

    StringBuilder sb = new StringBuilder(5);
    sb.Append("0123456789");

Now what is the capacity of sb and why? What is the multiplier?

Just for clarity. I am asking about capacity and not length.

Thanks!


问:
Sort three numbers in array from least to greatest
I have to create a function that takes 3 numbers. The function should return an array containing the numbers from least to greatest. So far I have this.I know it isn't correct but it's a start.I'm not using native functions as well. Can anyone give me some tips? Appreciate any help.</p>

```<code>   function leastToGreatest (num) {
        var array = [];
        var num1 = 0;
        var num2 = 0;
        var num3 = 0;
        for (var i = 0; i < num.length; i++) {
           if(num[i] < num[i] && num[i] < num[i]) {
                  num[i] = num1;
                  array.push(num1);
           }
           else if(num[i] > num[i] && num[i] < num[i]) {
             num[i] = num2;
             array.push(num2);
           }
           else if(num[i] > num[i] && num[i] > num[i])
             num[i] = num3;
             array.push(num3);
           }
           return array;
     }
     leastToGreatest(2,1,3);
</code>```

答:
I would suggest using two for loops to solve this problem. For example,

function sortArray(array) {
  var temp = 0;
  for (var i = 0; i < array.length; i++) {
    for (var j = i; j < array.length; j++) {
      if (array[j] < array[i]) {
        temp = array[j];
        array[j] = array[i];
        array[i] = temp;
      }
    }
  }
  return array;
}

console.log(sortArray([3,1,2]));```

With this function, no matter what size the array is it will always sort it.

The reason your function is not working (as is stated by @WashingtonGuedes) is that you are comparing the same value each time. As they said, you will reach the last statement and receive two false's, which causes you to test false for all three if statements. Your returned array, then, will be empty.

One suggestion is to not hard-code for three values, as you have done, but instead assume nothing and let the program do the hard work. As put in my code snippet, you can enter an array of any length and it will be sorted, not just where length is 3.

Body:
I have to create a function that takes 3 numbers. The function should return an array containing the numbers from least to greatest. So far I have this.I know it isn't correct but it's a start.I'm not using native functions as well. Can anyone give me some tips? Appreciate any help.

   function leastToGreatest (num) {
        var array = [];
        var num1 = 0;
        var num2 = 0;
        var num3 = 0;
        for (var i = 0; i < num.length; i++) {
           if(num[i] < num[i] && num[i] < num[i]) {
                  num[i] = num1;
                  array.push(num1);
           }
           else if(num[i] > num[i] && num[i] < num[i]) {
             num[i] = num2;
             array.push(num2);
           }
           else if(num[i] > num[i] && num[i] > num[i])
             num[i] = num3;
             array.push(num3);
           }
           return array;
     }
     leastToGreatest(2,1,3);

Body:
I would suggest using two for loops to solve this problem. For example,

function sortArray(array) {
  var temp = 0;
  for (var i = 0; i < array.length; i++) {
    for (var j = i; j < array.length; j++) {
      if (array[j] < array[i]) {
        temp = array[j];
        array[j] = array[i];
        array[i] = temp;
      }
    }
  }
  return array;
}

console.log(sortArray([3,1,2]));

With this function, no matter what size the array is it will always sort it.

The reason your function is not working (as is stated by @WashingtonGuedes) is that you are comparing the same value each time. As they said, you will reach the last statement and receive two false's, which causes you to test false for all three if statements. Your returned array, then, will be empty.

One suggestion is to not hard-code for three values, as you have done, but instead assume nothing and let the program do the hard work. As put in my code snippet, you can enter an array of any length and it will be sorted, not just where length is 3.


问:
Error on add to source control - Unable to transfer a file: error detected by clearcase subsystem
We are setting up new servers at CC 8.1.1.11 and going through basic tests.

From a CC Explorer client we try and add a simple .txt file to source control and get the error

```<code>Error adding "path to filename.txt" to source control Unable to transfer file :
error detected by Clearcase Subsystem.
</code>```

Selecting Ok on the error pop-up we can then see the "Green Tick" against the file showing it checked out but when we try to check in we get the same error.

In the mvfs log on the client machine we see the following

```<code>Fetch cleartext view=viewname vob=\vobname dbid=0x43 - I/O error
See view log on  view server for more info.
</code>```

View Log on view Server -

```<code>Error: view_server.exe error unable to construct cleartext for object "0x43" in vob "path to vob"
Error detected by clearcase subsystem
Error unable to transfer a file.
</code>```

Client machine and view server are windows. Vob server aix

No significant errors when running ClearCase doctor.

How can I avoid this error?

答:
The phrase "unable to transfer" is a key indication that the client application (cleartool.exe) and the view server process are using CCFS to get to the pools.

If this just started happening, please verify that your user account still maps to the unix server correctly. (...\clearcase\etc\utils\credmap server_name) @Vonc's lsview option will also tell you the view's user and group credentials, which can also be an issue -- particularly for CCFS transfers.

You may also want to see what happens on disabling CCFS on the client host and view server host (ClearCase control panel, options page). Be aware that this may merely change the nature of the failure if the albd account on Windows is not able to directly access the pools.

Body:
We are setting up new servers at CC 8.1.1.11 and going through basic tests.

From a CC Explorer client we try and add a simple .txt file to source control and get the error

Error adding "path to filename.txt" to source control Unable to transfer file :
error detected by Clearcase Subsystem.

Selecting Ok on the error pop-up we can then see the "Green Tick" against the file showing it checked out but when we try to check in we get the same error.

In the mvfs log on the client machine we see the following

Fetch cleartext view=viewname vob=\vobname dbid=0x43 - I/O error
See view log on  view server for more info.

View Log on view Server -

Error: view_server.exe error unable to construct cleartext for object "0x43" in vob "path to vob"
Error detected by clearcase subsystem
Error unable to transfer a file.

Client machine and view server are windows. Vob server aix

No significant errors when running ClearCase doctor.

How can I avoid this error?


问:
How do I connect my iPhone to the virtual machine (VMware macOS)?
my virtual machine (VMware macOS) doesn't see my iPhone when I connect my iPhone to the computer. Anyone knows how to handle this ? I want to connect just for using my iPhone as simulator.</p>

答:
I think that your iPhone with the lightning connector would be perceived by VMWare as a USB Device, so you could refer to their USB Device documentation.  The TL;DR is essentially:

Add the physical usb port to what the vm can "see".

Choose VM > Removable Devices to connect specific USB devices to your virtual machine.

Find the menu item for the usb port the iPhone is plugged into and mouse over it to see the iPhone, then click its name.

I found some additional instructions here which may provide more useful, granular details on how to do this.  Pleas note that you will have to take into account the OS of both the host and the guest when following the documentation.  Additionally, you may need specific drivers to let the guest addition recognize the iOS device.

Good luck!


问:
How to use single function to multiple classes?
I've got this following code:

```<code><script type="text/javascript">
    $(document).ready(function(){
        $('.sample1').click(function(){
            $('.dropdown-content').toggleClass('visible-dropdown');
        })
    })
</script>
</code>```

It adds class so I can get some animations with mouse click event.
I have some more classes in HTML like 'sample2', 'sample3', etc. and would like to add exactly the same animations (classes of course has different content).

I know one solution, namely just add in same code n-times, but change class for each block of code. Is there a shorter way? I thought maybe something with arrays, not sure. I'm not really good in JS, it's like my first time ;)

答:
You can use css selectors:

Catch the elements which have classes started with 'sample':

```<code>$('[class^=sample]').on('click',function(){

    //Do something
});
</code>```

Catch the elements which have classes ended with 'sample':

```<code>    $('[class$=sample]').on('click',function(){

    //Do something
    });
</code>```

To find more information about css selectors:
https://www.w3schools.com/cssref/css_selectors.asp

Body:
I've got this following code:

It adds class so I can get some animations with mouse click event.
I have some more classes in HTML like 'sample2', 'sample3', etc. and would like to add exactly the same animations (classes of course has different content).

I know one solution, namely just add in same code n-times, but change class for each block of code. Is there a shorter way? I thought maybe something with arrays, not sure. I'm not really good in JS, it's like my first time ;)

Body:
You can use css selectors:

Catch the elements which have classes started with 'sample':

$('[class^=sample]').on('click',function(){

    //Do something
});

Catch the elements which have classes ended with 'sample':

    $('[class$=sample]').on('click',function(){

    //Do something
    });

To find more information about css selectors:
https://www.w3schools.com/cssref/css_selectors.asp


问:
C# function uses extension function but VB equivalent does not?
So I have the following code in C#:

```<code>public Container ConfigureSimpleInjector(IAppBuilder app)
{
    var container = new Container();

    container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

    container.RegisterPackages();

    app.Use(async (context, next) =>
    {
        using (AsyncScopedLifestyle.BeginScope(container))
        {
            await next();
        }
    });

    container.Verify();

    return container;
}
</code>```

The app.Use() is defined as Owin.AppBuilderUserExtensions.Use() and looks like this:

public static IAppBuilder Use(this IAppBuilder app, Func<IOwinContext, Func<Task>, Task> handler);

The VB equivalent is as follows:

Public Function ConfigureSimpleInjector(app As IAppBuilder) As Container
    Dim container = New Container()

    container.Options.DefaultScopedLifestyle = New AsyncScopedLifestyle()

    container.RegisterPackages()

    app.Use(Async Sub(context, [next])
                Using AsyncScopedLifestyle.BeginScope(container)
                    Await [next]()
                End Using
            End Sub)

    container.Verify()

    Return container
End Function
```

For some reason, in the VB version, the app.Use() doesn't use the extension function that's available and simply uses IAppBuilder.Use() instead, as follows:

Function Use(middleware As Object, ParamArray args() As Object) As IAppBuilder

Why does the VB code not use the same extension function that C# does and how can I make it use that?

Edit

For clarity, the extension methods are not my own. They are from the Owin 3rd party library. So there is no option of renaming the extension methods.

答:
In the C# code because next is Func and await returns a task, there is no return statement, but actualy a Task object is returned.

IMO the VB.NET code does not return a Task object, because the lambda is specified as Sub (= Action in C#).

Changing the Sub to Func in the VB.NET code should call the wanted method.

Body:
So I have the following code in C#:

public Container ConfigureSimpleInjector(IAppBuilder app)
{
    var container = new Container();

    container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

    container.RegisterPackages();

    app.Use(async (context, next) =>
    {
        using (AsyncScopedLifestyle.BeginScope(container))
        {
            await next();
        }
    });

    container.Verify();

    return container;
}

The app.Use() is defined as Owin.AppBuilderUserExtensions.Use() and looks like this:

public static IAppBuilder Use(this IAppBuilder app, Func<IOwinContext, Func<Task>, Task> handler);

The VB equivalent is as follows:

Public Function ConfigureSimpleInjector(app As IAppBuilder) As Container
    Dim container = New Container()

    container.Options.DefaultScopedLifestyle = New AsyncScopedLifestyle()

    container.RegisterPackages()

    app.Use(Async Sub(context, [next])
                Using AsyncScopedLifestyle.BeginScope(container)
                    Await [next]()
                End Using
            End Sub)

    container.Verify()

    Return container
End Function

For some reason, in the VB version, the app.Use() doesn't use the extension function that's available and simply uses IAppBuilder.Use() instead, as follows:

Function Use(middleware As Object, ParamArray args() As Object) As IAppBuilder

Why does the VB code not use the same extension function that C# does and how can I make it use that?

Edit

For clarity, the extension methods are not my own. They are from the Owin 3rd party library. So there is no option of renaming the extension methods.


问:
How to update repository location in Git Tower
I have reorganized the folder structure for my repositories in the Mac Finder and now when I open up Git Tower it is informing me that those repositories can't be located. This I understand however I"m trying to figure out how I can update the location of the repository from inside the application. I've looked on the Tower website and researched using Google however I have not come up with any possible solutions. </p>

<p>Does anyone have any suggestions? </p>

答:
This is quite hacky, but I was able to edit Tower's sqlite file directly and change all broken repo paths at once.

On my system, the file was located here:
~/Library/Application Support/com.fournova.Tower2/Tower.sqlite3. And OF COURSE make a backup before you proceed.

I then used DB Browser for SQLite to run the following SQL queries (all at once):

```<code>UPDATE ZGTGITREPOSITORY SET ZFILEURLSTRING = REPLACE (
ZFILEURLSTRING,
'/OldPath/',
'/NewPath/');

UPDATE ZGTGITREPOSITORY SET ZGITDIRECTORYURLSTRING = REPLACE (
ZGITDIRECTORYURLSTRING,
'/OldPath/',
'/NewPath/');

UPDATE ZGTGITREPOSITORY SET ZWORKINGTREEDIRECTORYURLSTRING = REPLACE (
ZWORKINGTREEDIRECTORYURLSTRING,
'/OldPath/',
'/NewPath/');
</code>```

A few notes:

That's basically doing a "find and replace" so your old path needs to be exactly accurate or else it won't be found.

You need to URL encode the path, so /my path with spaces/ becomes /my%20path%20with%20spaces/

Did I mention make a backup of the file before you proceed?

Body:
I have reorganized the folder structure for my repositories in the Mac Finder and now when I open up Git Tower it is informing me that those repositories can't be located. This I understand however I"m trying to figure out how I can update the location of the repository from inside the application. I've looked on the Tower website and researched using Google however I have not come up with any possible solutions.

Does anyone have any suggestions?

Body:
This is quite hacky, but I was able to edit Tower's sqlite file directly and change all broken repo paths at once.

On my system, the file was located here:
~/Library/Application Support/com.fournova.Tower2/Tower.sqlite3. And OF COURSE make a backup before you proceed.

I then used DB Browser for SQLite to run the following SQL queries (all at once):

UPDATE ZGTGITREPOSITORY SET ZFILEURLSTRING = REPLACE (
ZFILEURLSTRING,
'/OldPath/',
'/NewPath/');

UPDATE ZGTGITREPOSITORY SET ZGITDIRECTORYURLSTRING = REPLACE (
ZGITDIRECTORYURLSTRING,
'/OldPath/',
'/NewPath/');

UPDATE ZGTGITREPOSITORY SET ZWORKINGTREEDIRECTORYURLSTRING = REPLACE (
ZWORKINGTREEDIRECTORYURLSTRING,
'/OldPath/',
'/NewPath/');

A few notes:

That's basically doing a "find and replace" so your old path needs to be exactly accurate or else it won't be found.

You need to URL encode the path, so /my path with spaces/ becomes /my%20path%20with%20spaces/

Did I mention make a backup of the file before you proceed?


问:
How to get other pages titles with same sys_category of the current page
I use TYPO3 8.7, I want to display on the current page footer the title of other pages with the same sys_category of the current page. When the user reach the bottom of the page he will find "related pages", those pages have the same sys_category uid of the current page. Can this be done with typoscript ?

I have tried this code but this didn't work:

```<code>temp.relatedCAT = CONTENT
temp.relatedCAT {
  table = pages
  select {
    // dontCheckPid doesn't exist for CONTENT objects, so make it recursive from root page (or pidInList.data = leveluid:-2
    pidInList = {$pidRoot}
    recursive = 99
    selectFields = sys_category.uid as catUid
    join = sys_category_record_mm ON pages.uid = sys_category_record_mm.uid_foreign JOIN sys_category ON sys_category.uid = sys_category_record_mm.uid_local
    where = sys_category_record_mm.tablenames = 'pages' AND sys_category_record_mm.uid_foreign = {TSFE:id}
    where.insertData = 1
    // not necessary for this use case
    // orderBy = sys_category.sorting
  }
  renderObj = TEXT
  renderObj {
    field = catUid
    // Hack: if there are no cats selected for a page, all news are displayed
    // so I just pass a catUid that's quite unlikely
    wrap = |
  }
}
lib.related >
lib.related= TEXT
lib.related {

                table = pages
                select {
                        # pid de la racine du site
                        pidInList = 1
                        # récursivité jusqu'au maximum de niveau
                        recursive = 99
                        # jointure sur la sys_cat_mm
                        leftjoin = sys_category_record_mm ON (pages.uid = sys_category_record_mm.uid_foreign)
                        # condition de recherche
                        where = sys_category_record_mm.tablenames =  "pages" AND sys_category_record_mm.uid_local = {$temp.relatedCAT}
                        where.insertData = 1

}
}
</code>```

答:
What about using a HMENU object with special = categories?
See: https://docs.typo3.org/typo3cms/TyposcriptReference/ContentObjects/Hmenu/Index.html#special-categories

Body:
I use TYPO3 8.7, I want to display on the current page footer the title of other pages with the same sys_category of the current page. When the user reach the bottom of the page he will find "related pages", those pages have the same sys_category uid of the current page. Can this be done with typoscript ?

I have tried this code but this didn't work:

temp.relatedCAT = CONTENT
temp.relatedCAT {
  table = pages
  select {
    // dontCheckPid doesn't exist for CONTENT objects, so make it recursive from root page (or pidInList.data = leveluid:-2
    pidInList = {$pidRoot}
    recursive = 99
    selectFields = sys_category.uid as catUid
    join = sys_category_record_mm ON pages.uid = sys_category_record_mm.uid_foreign JOIN sys_category ON sys_category.uid = sys_category_record_mm.uid_local
    where = sys_category_record_mm.tablenames = 'pages' AND sys_category_record_mm.uid_foreign = {TSFE:id}
    where.insertData = 1
    // not necessary for this use case
    // orderBy = sys_category.sorting
  }
  renderObj = TEXT
  renderObj {
    field = catUid
    // Hack: if there are no cats selected for a page, all news are displayed
    // so I just pass a catUid that's quite unlikely
    wrap = |
  }
}
lib.related >
lib.related= TEXT
lib.related {

                table = pages
                select {
                        # pid de la racine du site
                        pidInList = 1
                        # récursivité jusqu'au maximum de niveau
                        recursive = 99
                        # jointure sur la sys_cat_mm
                        leftjoin = sys_category_record_mm ON (pages.uid = sys_category_record_mm.uid_foreign)
                        # condition de recherche
                        where = sys_category_record_mm.tablenames =  "pages" AND sys_category_record_mm.uid_local = {$temp.relatedCAT}
                        where.insertData = 1

}
}


问:
Responsive JQGRID converts action icons to be a button, but not paging information
I have this JQGRID:

```<code>$(document).ready(function () {
    $.jgrid.defaults.width = 780;
    $.jgrid.defaults.responsive = true;
    $.jgrid.defaults.styleUI = 'Bootstrap';
    $.jgrid.styleUI.Bootstrap.base.rowTable = "table table-bordered table-striped";
            $("#gridUsuario").jqGrid({
                url: '@Url.Action("GetUsers", "Account", new { area = "Security" })',
                mtype: "GET",
                datatype: "json",
                colModel: [
                    { label: 'ID', name: 'ID', key: true, width: 70 },
                    { label: 'Vigente', name: 'UsuarioVigente', hidden: true },
                    { label: 'Nombre Completo', name: 'FullName', width: 200, edittype: 'text', editable: true, editrules: { required: true }, editoptions: { size: 50, maxlength: 100 }, formoptions: { elmprefix: '(*)' } },
                    { label: 'Login', name: 'UserName', width: 120, edittype: 'text', editable: true, editrules: { required: true }, editoptions: { size: 30, maxlength: 50 }, formoptions: { elmprefix: '(*)' } },
                    { label: 'Password', name: 'Password', width: 100, edittype: 'password', editable: true, hidden: true, editrules: { required: true, edithidden: true }, editoptions: { size: 30, maxlength: 50 }, formoptions: { elmprefix: '(*)' } },
                    { label: 'E-mail', name: 'Email', width: 240, edittype: 'text', editable: true, editrules: { required: true, email: true }, editoptions: { size: 50, maxlength: 100 }, formoptions: { elmprefix: '(*)' } },
                    { label: 'Teléfono', name: 'PhoneNumber', width: 120, edittype: 'text', editable: true, editoptions: { size: 30, maxlength: 50 } },
                    { label: 'Ciudad', name: 'Hometown', width: 150, edittype: 'text', editable: true, editoptions: { size: 30, maxlength: 50 } },
                    { label: 'Fecha Registro', name: 'UsuarioCreadoEn', width: 120, formatter: "date", formatoptions: { srcformat: "ISO8601Long", newformat: "d/m/Y H:i" } }
                ],
                viewrecords: true,
                shrinkToFit: false,
                autowidth: true,
                multiselect: true,
                rowNum: 20,
                rowList: [10, 20, 30],
                gridview: true,
                pager: "#gridPager",
                sortname: "FullName",
                sortorder: "asc",
                beforeRequest: function () {
                    var $PANEL = $('#pnlGrid'),
                        $FOOTER = $('footer');

                    // 125 = otros altos, como paddings y la fila de paginación
                    $("#gridUsuario").jqGrid('setGridHeight', $FOOTER.offset().top - $PANEL.offset().top - 125);
                },
                rowattr: function (rd) {
                    if (!rd.UsuarioVigente) {
                        return { "class": "no-vigente" };
                    }
                }
            });
</code>```

All works perfect but responsive behaviour.

At bottom toolbar, I have several actions created with navButtonAdd method.

When I test responsiveness, the action icons at bottom toolbar are replaced by a button with "Actions..." label. When clicked, all action items pop up. That is perfect, however, the paging does not behave the same, causing paging icons to appear over the "Actions..." button.

Is this a bug in JQGRID? is there a way to solve this?

答:
Before to comment if certain component does not support some feature it is good idea to check the example. From the example provided I can not see any problem. The author of the request should post full example, and the suggester should check it before to suggest his component.

Kind Regards

Body:
I have this JQGRID:

$(document).ready(function () {
    $.jgrid.defaults.width = 780;
    $.jgrid.defaults.responsive = true;
    $.jgrid.defaults.styleUI = 'Bootstrap';
    $.jgrid.styleUI.Bootstrap.base.rowTable = "table table-bordered table-striped";
            $("#gridUsuario").jqGrid({
                url: '@Url.Action("GetUsers", "Account", new { area = "Security" })',
                mtype: "GET",
                datatype: "json",
                colModel: [
                    { label: 'ID', name: 'ID', key: true, width: 70 },
                    { label: 'Vigente', name: 'UsuarioVigente', hidden: true },
                    { label: 'Nombre Completo', name: 'FullName', width: 200, edittype: 'text', editable: true, editrules: { required: true }, editoptions: { size: 50, maxlength: 100 }, formoptions: { elmprefix: '(*)' } },
                    { label: 'Login', name: 'UserName', width: 120, edittype: 'text', editable: true, editrules: { required: true }, editoptions: { size: 30, maxlength: 50 }, formoptions: { elmprefix: '(*)' } },
                    { label: 'Password', name: 'Password', width: 100, edittype: 'password', editable: true, hidden: true, editrules: { required: true, edithidden: true }, editoptions: { size: 30, maxlength: 50 }, formoptions: { elmprefix: '(*)' } },
                    { label: 'E-mail', name: 'Email', width: 240, edittype: 'text', editable: true, editrules: { required: true, email: true }, editoptions: { size: 50, maxlength: 100 }, formoptions: { elmprefix: '(*)' } },
                    { label: 'Teléfono', name: 'PhoneNumber', width: 120, edittype: 'text', editable: true, editoptions: { size: 30, maxlength: 50 } },
                    { label: 'Ciudad', name: 'Hometown', width: 150, edittype: 'text', editable: true, editoptions: { size: 30, maxlength: 50 } },
                    { label: 'Fecha Registro', name: 'UsuarioCreadoEn', width: 120, formatter: "date", formatoptions: { srcformat: "ISO8601Long", newformat: "d/m/Y H:i" } }
                ],
                viewrecords: true,
                shrinkToFit: false,
                autowidth: true,
                multiselect: true,
                rowNum: 20,
                rowList: [10, 20, 30],
                gridview: true,
                pager: "#gridPager",
                sortname: "FullName",
                sortorder: "asc",
                beforeRequest: function () {
                    var $PANEL = $('#pnlGrid'),
                        $FOOTER = $('footer');

                    // 125 = otros altos, como paddings y la fila de paginación
                    $("#gridUsuario").jqGrid('setGridHeight', $FOOTER.offset().top - $PANEL.offset().top - 125);
                },
                rowattr: function (rd) {
                    if (!rd.UsuarioVigente) {
                        return { "class": "no-vigente" };
                    }
                }
            });

All works perfect but responsive behaviour.

At bottom toolbar, I have several actions created with navButtonAdd method.

When I test responsiveness, the action icons at bottom toolbar are replaced by a button with "Actions..." label. When clicked, all action items pop up. That is perfect, however, the paging does not behave the same, causing paging icons to appear over the "Actions..." button.

Is this a bug in JQGRID? is there a way to solve this?


问:
Python - BeautifulSoup, get tag within a tag
How would I got about getting a tag within a tag?

Out of the td tag here:

```<code><td scope="row"><a href="/Archives/edgar/data/1085621/000108562117000004/actuacorp12312016.htm">actuacorp12312016.htm</a></td>
</code>```

I want the value of the href tag within it, primarily the htm link:

```<code><a href="/Archives/edgar/data/1085621/000108562117000004/actuacorp12312016.htm">actuacorp12312016.htm</a>
</code>```

I have tags like these:

```<code><tr>
<td scope="row">1</td>
<td scope="row">10-K</td>
<td scope="row"><a href="/Archives/edgar/data/1085621/000108562117000004/actuacorp12312016.htm">actuacorp12312016.htm</a></td>
<td scope="row">10-K</td>
<td scope="row">2724989</td>
</tr>
<tr class="blueRow">
<td scope="row">2</td>
<td scope="row">EXHIBIT 21.1</td>
<td scope="row"><a href="/Archives/edgar/data/1085621/000108562117000004/exhibit211q42016.htm">exhibit211q42016.htm</a></td>
<td scope="row">EX-21.1</td>
<td scope="row">21455</td>
</tr>
<tr>
<td scope="row">3</td>
<td scope="row">EXHIBIT 23.1</td>
<td scope="row"><a href="/Archives/edgar/data/1085621/000108562117000004/exhibit231q42016.htm">exhibit231q42016.htm</a></td>
<td scope="row">EX-23.1</td>
<td scope="row">4354</td>
</tr>
</code>```

Code to see all the tags:

```<code>base_url = "https://www.sec.gov/Archives/edgar/data/1085621/000108562117000004/" \
               "0001085621-17-000004-index.htm"
    response = requests.get(base_url)
    base_data = response.content
    base_soup = BeautifulSoup(base_data, "html.parser")
</code>```

答:
You can use find_all to first get all td tags, and then search for anchors within those tags:

```<code>links = []
for tag in base_soup.find_all('td', {'scope' : 'row'}):
    for anchor in tag.find_all('a'):
        links.append(anchor['href'])

print(links)
</code>```

Output:

```<code>['/Archives/edgar/data/1085621/000108562117000004/actuacorp12312016.htm',
 '/Archives/edgar/data/1085621/000108562117000004/exhibit211q42016.htm',
...
 '/Archives/edgar/data/1085621/000108562117000004/acta-20161231_lab.xml',
 '/Archives/edgar/data/1085621/000108562117000004/acta-20161231_pre.xml']
</code>```

You can write a little filter to remove those non-htm links if you want:

```<code>filtered_links = list(filter(lambda x: x.endswith('.htm'), links))
</code>```

To get just the first link, here's a slightly different version that's suited to your use case.

```<code>link = None
for tag in base_soup.find_all('td', {'scope' : 'row'}):
    children = tag.findChildren()
    if len(children) > 0:
        try:
            link = children[0]['href']
            break
        except:
            continue

print(link)
</code>```

This prints out '/Archives/edgar/data/1085621/000108562117000004/acta-20161231_pre.xml'.

Body:
How would I got about getting a tag within a tag?

Out of the td tag here:

actuacorp12312016.htm

I want the value of the href tag within it, primarily the htm link:

actuacorp12312016.htm

I have tags like these:

1
10-K
actuacorp12312016.htm
10-K
2724989

2
EXHIBIT 21.1
exhibit211q42016.htm
EX-21.1
21455

3
EXHIBIT 23.1
exhibit231q42016.htm
EX-23.1
4354

Code to see all the tags:

base_url = "https://www.sec.gov/Archives/edgar/data/1085621/000108562117000004/" \
               "0001085621-17-000004-index.htm"
    response = requests.get(base_url)
    base_data = response.content
    base_soup = BeautifulSoup(base_data, "html.parser")

Body:
You can use find_all to first get all td tags, and then search for anchors within those tags:

links = []
for tag in base_soup.find_all('td', {'scope' : 'row'}):
    for anchor in tag.find_all('a'):
        links.append(anchor['href'])

print(links)

Output:

['/Archives/edgar/data/1085621/000108562117000004/actuacorp12312016.htm',
 '/Archives/edgar/data/1085621/000108562117000004/exhibit211q42016.htm',
...
 '/Archives/edgar/data/1085621/000108562117000004/acta-20161231_lab.xml',
 '/Archives/edgar/data/1085621/000108562117000004/acta-20161231_pre.xml']

You can write a little filter to remove those non-htm links if you want:

filtered_links = list(filter(lambda x: x.endswith('.htm'), links))

To get just the first link, here's a slightly different version that's suited to your use case.

link = None
for tag in base_soup.find_all('td', {'scope' : 'row'}):
    children = tag.findChildren()
    if len(children) > 0:
        try:
            link = children[0]['href']
            break
        except:
            continue

print(link)

This prints out '/Archives/edgar/data/1085621/000108562117000004/acta-20161231_pre.xml'.


问:
declarative_authorization and user context
Am planning on using declarative authorization in a Rails 3 app.
I have the following model relationships:

```<code>class Role < ActiveRecord::Base
  has_many :permissions, :dependent => :destroy
  has_many :users, :through => :permissions, :uniq => true
end

class Permission < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
  belongs_to :context
end

class User < ActiveRecord::Base
  has_many :permissions, :dependent => :destroy
  has_many :roles, :through => :permissions

  roles.map do |role|
      role.name.underscore.to_sym
  end
end

class Context < ActiveRecord::Base
  has_many :contexts, :dependent => :destroy

end
</code>```

The concept here is that I am going to segment various datasets into different contexts. However, a given user may have different roles for each context -- maybe an admin in one context and a basic user in another. I have implemented current_user and current_context for use in controllers and views.

I plan on using the if_attribute to reference the right permission on the right dataset.
However, the question is how do I make the def role_symbols only return the roles associated with the user in a particular context when I cannot/should not reference current_context in a model (where role_symbols is defined).

Any ideas?

答:
Was luck enough to find the answer here:

http://blog.drivingthevortex.nl/2010/01/24/using-declarative_authorization-with-subdomains/

Body:
Am planning on using declarative authorization in a Rails 3 app.
I have the following model relationships:

class Role < ActiveRecord::Base
  has_many :permissions, :dependent => :destroy
  has_many :users, :through => :permissions, :uniq => true
end

class Permission < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
  belongs_to :context
end

class User < ActiveRecord::Base
  has_many :permissions, :dependent => :destroy
  has_many :roles, :through => :permissions

  roles.map do |role|
      role.name.underscore.to_sym
  end
end

class Context < ActiveRecord::Base
  has_many :contexts, :dependent => :destroy

end

The concept here is that I am going to segment various datasets into different contexts. However, a given user may have different roles for each context -- maybe an admin in one context and a basic user in another. I have implemented current_user and current_context for use in controllers and views.

I plan on using the if_attribute to reference the right permission on the right dataset.
However, the question is how do I make the def role_symbols only return the roles associated with the user in a particular context when I cannot/should not reference current_context in a model (where role_symbols is defined).

Any ideas?


问:
Does information about rsyslog apply to syslog?
I'm trying to configure syslog to send events to a remote server running Logstash. I can only find information about using rsyslog with Logstash, rather than syslog with Logstash.

Will most of the information pertaining to rsyslog be applicable to my task using syslog?

答: Legacy syslog has many similarities to rsyslog, but other than simple functionality not much carries over.</p>


问:
Populate DBCOMBO in VB6 with recordset
I need to populate one dbcombo, i have write this

```<code>Private Sub cargamunicipios()

   Conexao_Banco

   Dim rs As New ADODB.Recordset

   SQL = "select código , nome from aux_municipios"

   rs.Open SQL, cn

   DBCombo4.RowSource = rs

End Sub
</code>```

the recorset works fine but have type mistmach , what is the right code to populate a dbcombo???
Thanks Alejnadro

答:
DBcombo controls (data bound) only works with ADO data controls, instead use DataCombo (data list) below a sample code..</p>

```<code>Private Sub cargamunicipios()
    Conexao_Banco
        Dim rs As New ADODB.Recordset
        SQL = "select código , nome from aux_municipios"
    rs.Open SQL, cn
    With DBCombo4
        .RowSource = rs
        .ListField = "código"
        .BoundColumn = "name"
    End With
End Sub
</code>```

Title: Populate DBCOMBO in VB6 with recordset

Body:
I need to populate one dbcombo, i have write this

Private Sub cargamunicipios()

   Conexao_Banco

   Dim rs As New ADODB.Recordset

   SQL = "select código , nome from aux_municipios"

   rs.Open SQL, cn

   DBCombo4.RowSource = rs

End Sub

the recorset works fine but have type mistmach , what is the right code to populate a dbcombo???
Thanks Alejnadro

Body:
DBcombo controls (data bound) only works with ADO data controls, instead use DataCombo (data list) below a sample code..

Private Sub cargamunicipios()
    Conexao_Banco
        Dim rs As New ADODB.Recordset
        SQL = "select código , nome from aux_municipios"
    rs.Open SQL, cn
    With DBCombo4
        .RowSource = rs
        .ListField = "código"
        .BoundColumn = "name"
    End With
End Sub


问:
PE: Adding code at the end of .txt section
As I understand in PE file Virtual Size shows how much space it allocates for section during loading and Raw Size shows how big the section is on disk.

I came across to this executable which did the following:

It subtracted the virtual size (offset 0x8) from the raw data size (offset 0x10) and made sure there was some space(for example 100 bytes). At offset 0x14 from the text section header it found the offset in the file for the section itself. It added to this the virtual size, finding right where the section ends in the file. it copied some shellcode(which at the end eventually jumped to the original entry point of an executable to make sure original executable ran) to the end of the text section of the binary.

Now I'm little confused here, if the Virtual Size shows the exact space which will be allocated for executable, would not adding code at the end of .txt section overwrite some other data of executable and make it crash? thanks.

答:
This is a great question and illustrates a very important point (or you might say quirk) about how the Windows loader calculates memory sizes.

The PE/COFF spec does indeed describe VirtualSize as "The total size of the section when loaded into memory".  This is technically true if you consider total to be the total amount of REAL data that comprises the section, but it is not the total amount of memory Windows allocates for the section.  You'll find VirtualSize is often LESS than the amount Windows allocates for the section in memory because VirtualSize must be rounded UP to the nearest memory alignment value (set in the PE image).

In other words, VirtualSize represents the unrounded size of the section while SizeOfRawData is the size of the data in the image file, but rounded up to the nearest file alignment padding value.  This is the reason VirtualSize is the better representation of the true "raw" size of the data, in memory or on disk.  The PE/COFF spec does not make this distinction.  Why one is rounded in the image file and not the other probably has its ancient roots in backwards compatibility.

This is precisely why your shellcode uses VirtualSize to find the "real" end of data even as it resides in the image file.  Not surprisingly, you can calculate SizeOfRawData by rounding VirtualSize up to the file alignment's value, at least in well formed PE files.

The shellcode simply used VirtualSize to find the end of the REAL code.  Between there and SizeOfRawData bytes, are just unused padding zeroes, making it a prime spot to add new code without affecting the size of the file or breaking addressing offsets within the PE file.

In summary, the Windows loader essentially takes the VirtualSize value and rounds it up to the memory alignment value to get the real size of the memory allocation (and even this may be rounded up to the nearest 4k-minimum memory page).  Then up to SizeOfRawData bytes are copied from the file to the beginning of the memory section.  If it is less than the size of the section in memory, the remainder is zero filled.


问:
clear text fields in all html text boxes when clicking on one html text box
I have a form in which I have three text fields, name,latitude and longitude.  These forms are already pre-filled however, I want to when I click on latitude and longitude all the pre-filled text values to be cleared.  How can I do this?</p>

答:
You simply gather references to all the input elements in an array and then iterate the array, clearing out the contents upon each iteration:

// Get a reference to the button
var btn = document.getElementById("clear");

// Set the button up for a click event handler
btn.addEventListener("click", function(){
  // Get all the input elements that are text fields and convert that list into an array
  // Loop through that array and clear the value of each text field
  Array.prototype.slice.call(document.querySelectorAll("input[type='text']")).forEach(function(element){
    element.value = "";
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" value="abc">
<input type="text" value="abc">
<input type="text" value="abc">
<input type="text" value="abc">
<input type="text" value="abc">
<button id="clear">Clear all text fields</button></code>```

Body:
You simply gather references to all the input elements in an array and then iterate the array, clearing out the contents upon each iteration:

// Get a reference to the button
var btn = document.getElementById("clear");

// Set the button up for a click event handler
btn.addEventListener("click", function(){
  // Get all the input elements that are text fields and convert that list into an array
  // Loop through that array and clear the value of each text field
  Array.prototype.slice.call(document.querySelectorAll("input[type='text']")).forEach(function(element){
    element.value = "";
  });
});

<input type="text" value="abc">
<input type="text" value="abc">
<input type="text" value="abc">
<input type="text" value="abc">
<input type="text" value="abc">
<button id="clear">Clear all text fields</button>


问:
Insert (push) multiple elements at multiple different positions at the same time
I like the append function in R:

```<code>L <- 1:4
append(L,5,3)
[1] 1 2 3 5 4
</code>```

I was wondering if there was a function that worked like append but allowed the insertion of multiple elements at multiple positions at the same time?

```<code>L <- 1:100
elements <- letters[1:5]
positions <- c(17,28,50,65,80)
</code>```

Something like:

```<code>append(L, elements, positions)
</code>```

答:
I think this is what you want: Add a series of elements in different locations within a vector

I don't think a function like append(L, elements, positions) exists, although it'd be cool.

Body:
I like the append function in R:

L <- 1:4
append(L,5,3)
[1] 1 2 3 5 4

I was wondering if there was a function that worked like append but allowed the insertion of multiple elements at multiple positions at the same time?

L <- 1:100
elements <- letters[1:5]
positions <- c(17,28,50,65,80)

Something like:

append(L, elements, positions)


问:
oracle sql: how do i sum different data points in a select statment?
i'm trying to return a sum which is the total of multiple rows of data that are returned. i'm trying to return data that shows an employee, account, and department. i want the sum of salary paid by those three data points. i also want a sum just by employee to show how their salary was distributed. an example is below. any help would be appreciated.

example

答:
You can achieve this with different groups in a windowing clause using the SUM analytic function.

```<code>SELECT employee
  , account
  , dept
  , SUM (salary) OVER (PARTITION BY employee) AS employee_salary
  , SUM (salary) OVER (PARTITION BY dept) AS dept_salary_paid
  , SUM (salary) OVER (PARTITION BY account) AS acct_salary_paid
FROM mytable
</code>```

I'm not sure if these groupings are exactly what you want (perhaps I misinterpreted your question) but it should give you the right idea. Windowing clauses give you more flexibility and allow you to group sums by different values, whereas a GROUP BY forces a single grouping per SELECT.

Edit, based on your most recent update:

You don't need a GROUP BY and a windowing clause. You can do two different OVER(PARTITION BY ....) clauses, so it would look like this:

```<code>select employee
, activity
, SUM (salary_amt) OVER (PARTITION BY employee, activity) AS "total salary by employee and activity"
, SUM (salary_amt) OVER (PARTITION BY employee) AS "total salary by employee"
from mytable where employee = 'xxx'
</code>```

Body:
You can achieve this with different groups in a windowing clause using the SUM analytic function.

SELECT employee
  , account
  , dept
  , SUM (salary) OVER (PARTITION BY employee) AS employee_salary
  , SUM (salary) OVER (PARTITION BY dept) AS dept_salary_paid
  , SUM (salary) OVER (PARTITION BY account) AS acct_salary_paid
FROM mytable

I'm not sure if these groupings are exactly what you want (perhaps I misinterpreted your question) but it should give you the right idea. Windowing clauses give you more flexibility and allow you to group sums by different values, whereas a GROUP BY forces a single grouping per SELECT.

Edit, based on your most recent update:

You don't need a GROUP BY and a windowing clause. You can do two different OVER(PARTITION BY ....) clauses, so it would look like this:

select employee
, activity
, SUM (salary_amt) OVER (PARTITION BY employee, activity) AS "total salary by employee and activity"
, SUM (salary_amt) OVER (PARTITION BY employee) AS "total salary by employee"
from mytable where employee = 'xxx'


问:
Modify str in db
I have a table, and in one colu,m I store comma separated strings, like:

book, table, lamp (New)

need to write query loop through all the strings  and remove

(New)

I think I can do it by first running a query to fetch results containing (New), then using PHP's REGEX, remove (New) and then update the the same row with new string. However this sounds a bit convoluted. Isn't there a way to do this with a single query?

答:
There is a replace string function in mysql: https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace

```<code>UPDATE <table> SET <column> = REPLACE(<column>,'(NEW)','')
</code>```

Try it with select first to see if the result is what you want (you may want to remove the trailing space if new is always preceded by it)

Title: Modify str in db

Body:
There is a replace string function in mysql: https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace

UPDATE <table> SET <column> = REPLACE(<column>,'(NEW)','')

Try it with select first to see if the result is what you want (you may want to remove the trailing space if new is always preceded by it)


问:
Cartesian Product of Sets where No Elements are Identical under Permutations in Python
I have some sets I would like to take the Cartesian product of, which is working well. However, I want to remove all elements of this new set which are identical under a permutation of the elements.

For example, take the following code:

```<code>import itertools as ittools
x = 2
y = 3
z = 5

flist = list(ittools.product([x,y,z],repeat=3))

for f in flist:
    print reduce(lambda a,b: a*b, f)
</code>```

This code find the Cartesian product of the set {2,3,5} and returns the product of all three components of each element in the resulting set. However, some numbers appear multiple times, i.e. 12 can be written as 2*2*3, 2*3*2, or 3*2*2. I would like to remove all but one instance of these duplicates.

I know that this fundamentally a combinatorics problem, but this seems like there is probably a nice solution in Python that doesn't involve doing an extra pass over the list like I did here to compute some identifier for each element of the Cartesian product.

答:
Use a dict to map each unique product to the most recently seen tuple.

```<code>d = {reduce(operator.mul, f): f for f in flist}
</code>```

If you would need to treat tuples that aren't permutations of each other as distinct elements, you'll need a more complicated key that incorporates a canonical representation of the tuple.

```<code>from operator import mul
d = {(tuple(sorted(f)), reduce(mul, f)): f for f in flist}
</code>```

Actually, once you do that, you don't need to map the tuple/product pair to a tuple; you can just maintain a set of pairs:

```<code>d = {(tuple(sorted(f)), reduce(mul, f)) for f in flist}
</code>```

In any case, retrieving just the tuples is as simple as

```<code>tuples = d.values()  # In the first two cases
tuples = {x for x,y in d} # In the third case
</code>```

Body:
I have some sets I would like to take the Cartesian product of, which is working well. However, I want to remove all elements of this new set which are identical under a permutation of the elements.

For example, take the following code:

import itertools as ittools
x = 2
y = 3
z = 5

flist = list(ittools.product([x,y,z],repeat=3))

for f in flist:
    print reduce(lambda a,b: a*b, f)

This code find the Cartesian product of the set {2,3,5} and returns the product of all three components of each element in the resulting set. However, some numbers appear multiple times, i.e. 12 can be written as 2*2*3, 2*3*2, or 3*2*2. I would like to remove all but one instance of these duplicates.

I know that this fundamentally a combinatorics problem, but this seems like there is probably a nice solution in Python that doesn't involve doing an extra pass over the list like I did here to compute some identifier for each element of the Cartesian product.

Body:
Use a dict to map each unique product to the most recently seen tuple.

d = {reduce(operator.mul, f): f for f in flist}

If you would need to treat tuples that aren't permutations of each other as distinct elements, you'll need a more complicated key that incorporates a canonical representation of the tuple.

from operator import mul
d = {(tuple(sorted(f)), reduce(mul, f)): f for f in flist}

Actually, once you do that, you don't need to map the tuple/product pair to a tuple; you can just maintain a set of pairs:

d = {(tuple(sorted(f)), reduce(mul, f)) for f in flist}

In any case, retrieving just the tuples is as simple as

tuples = d.values()  # In the first two cases
tuples = {x for x,y in d} # In the third case


问:
Set brand image on bootstrap navbar using link_to
Bootstrap uses this structure to set brand image:

```<code><nav class="navbar navbar-default">
  <div class="container-fluid">
   <div class="navbar-header">
     <a class="navbar-brand" href="#">
       <img alt="Brand" src="...">
     </a>
   </div>
  </div>
</nav>
</code>```

But im using a link_to tag and it actually works fine but with no image:

```<code><%= link_to raw('CIFCO'), cr_clientes_path, :class=>'navbar-brand'%>
</code>```

So, how do I turn that link to into the bootstrap structure to show brand image instead of text?

答:
You should use image_tag inside link_to to display image

```<code><%= link_to image_tag("your-image-name", alt: "Brand"), cr_clientes_path, :class=>'navbar-brand' %>
</code>```

Body:
Bootstrap uses this structure to set brand image:

But im using a link_to tag and it actually works fine but with no image:

<%= link_to raw('CIFCO'), cr_clientes_path, :class=>'navbar-brand'%>

So, how do I turn that link to into the bootstrap structure to show brand image instead of text?

Body:
You should use image_tag inside link_to to display image

<%= link_to image_tag("your-image-name", alt: "Brand"), cr_clientes_path, :class=>'navbar-brand' %>


问:
Plotting a 2d contour plot in python with sparse data
I have some output data from an ocean circulation model (MITgcm). It is an idealised channel (Cartesian) so the geometry is not confusing, luckily.

I'd like to plot some of the fields (velocity, temperature etc.) in the y-z plane. The simulation domain involves 30 vertical layers where each layer is an 800x400 y-x grid. I have each of the fields stored in numpy arrays with shape (30, 800, 400) going z,y,x respectively.

I can easily plot x-y plane slices for the 30 vertical levels. I can do this using matplotlib's contourf or imshow and changing the extent to the correct physical values in km.

The problem is that the vertical layers are unevenly spaced. I have the grid data for Z which tells me what physical depth (in metres) each of the layers corresponds to.

Z is: [-5.  -15.  -25.    -36.    -49.    -65.    -84.   -105.5  -130.5 -159.5  -192.5  -230. -273.   -322.5  -379.   -443.   -515.   -596. -688. -792. -909.5 -1042.5 -1192.5 -1362.  -1553.5 -1770.  -2015.
 -2285.  -2565.  -2845.]

I tried to get round this by creating an empty matrix with 2985 (as the full domain depth is 2985m) 'vertical' layers, and inputting the y-data at the corresponding positions for the 30 layers as given by Z above (here yz_zonal is a (30,800) matrix of data values):

```<code>yz_matrix = np.empty((2985, 800)) #empty matrix for yz-plane data, vertical extent is 2985 (m)

for i in range(len(Z)):
     yz_matrix[round(-Z[i])] = yz_zonal[i] #set matrix values to correct depths
</code>```

Then if I try to plot yz_matrix using matplotlib's imshow, by doing:

```<code>fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('y (km)')
ax.set_ylabel('z (m)')
yzplot = ax.imshow(yz_matrix, aspect='auto', interpolation='gaussian', cmap='inferno', extent=[0,2000,-2985,0])
plt.colorbar(yzplot)
</code>```

I just get this figure:BAD y-z plot of velocity data

There are 30 strips of data values at the correct physical z positions, but there's a whole load of zeros in between them. I only want to interpolate the data in between the 30 strips and ignore all of the other points.

It would be brilliant if anyone could sort this out for me. Thanks in advance!

Peter

答:
Take a look at this example from the matplotlib site, and especially the functions np.meshgrid and plt.contourf. Something like this with irregular z's will work:

```<code>z = [1,2,5,10]
x = [1,2,3,4,5,6,7,8]

zz, xx = np.meshgrid(z, x)

# create some data
values = np.random.randn(len(x), len(z))

plt.contourf(zz, xx, values)
plt.show()
</code>```

Body:
I have some output data from an ocean circulation model (MITgcm). It is an idealised channel (Cartesian) so the geometry is not confusing, luckily.

I'd like to plot some of the fields (velocity, temperature etc.) in the y-z plane. The simulation domain involves 30 vertical layers where each layer is an 800x400 y-x grid. I have each of the fields stored in numpy arrays with shape (30, 800, 400) going z,y,x respectively.

I can easily plot x-y plane slices for the 30 vertical levels. I can do this using matplotlib's contourf or imshow and changing the extent to the correct physical values in km.

The problem is that the vertical layers are unevenly spaced. I have the grid data for Z which tells me what physical depth (in metres) each of the layers corresponds to.

Z is: [-5.  -15.  -25.    -36.    -49.    -65.    -84.   -105.5  -130.5 -159.5  -192.5  -230. -273.   -322.5  -379.   -443.   -515.   -596. -688. -792. -909.5 -1042.5 -1192.5 -1362.  -1553.5 -1770.  -2015.
 -2285.  -2565.  -2845.]

I tried to get round this by creating an empty matrix with 2985 (as the full domain depth is 2985m) 'vertical' layers, and inputting the y-data at the corresponding positions for the 30 layers as given by Z above (here yz_zonal is a (30,800) matrix of data values):

yz_matrix = np.empty((2985, 800)) #empty matrix for yz-plane data, vertical extent is 2985 (m)

for i in range(len(Z)):
     yz_matrix[round(-Z[i])] = yz_zonal[i] #set matrix values to correct depths

Then if I try to plot yz_matrix using matplotlib's imshow, by doing:

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('y (km)')
ax.set_ylabel('z (m)')
yzplot = ax.imshow(yz_matrix, aspect='auto', interpolation='gaussian', cmap='inferno', extent=[0,2000,-2985,0])
plt.colorbar(yzplot)

I just get this figure:BAD y-z plot of velocity data

There are 30 strips of data values at the correct physical z positions, but there's a whole load of zeros in between them. I only want to interpolate the data in between the 30 strips and ignore all of the other points.

It would be brilliant if anyone could sort this out for me. Thanks in advance!

Peter

Body:
Take a look at this example from the matplotlib site, and especially the functions np.meshgrid and plt.contourf. Something like this with irregular z's will work:

z = [1,2,5,10]
x = [1,2,3,4,5,6,7,8]

zz, xx = np.meshgrid(z, x)

# create some data
values = np.random.randn(len(x), len(z))

plt.contourf(zz, xx, values)
plt.show()


问:
How can I improve this actions in API controller?

Overview

I am designing one api that will be integration with another system, however I stumbled upon one code which I know it can be improved but I don't know how to do it properly.

Code

```<code>    [HttpPost]
    [Route("Reserve")]
    public IHttpActionResult Reserve([FromUri]ReserveData reserveData, [FromBody]BetsData bet)
    {
        var result = new ReserveResponse();
        // Question 1.
        if (reserveData == null || !IsDataForReserveValid(reserveData))
        {
            // Question 2.
            return Ok(_responseStringBuilder.BuildWrongRequestResponse().Create());
        }
        // Question 3.
        if (!_customerService.CheckIfCustomerExists(reserveData.cust_id))
        {
            return Ok(_responseStringBuilder.BuildCustomerNotFoundResponse().Create());
        }
        if (_customerService.IsCustomerRestricted(reserveData.cust_id))
        {
            return Ok(_responseStringBuilder.BuildRestrictedCustomerResponse().Create());
        }
        if (!_reserveService.ReserveAmount(reserveData.cust_id, reserveData.amount))
        {
            return Ok(_responseStringBuilder.BuildInsufficientFundsResponse().Create());
        }

        if (bet != null)
        {

        }

        _reserveService.InsertReserve(reserveData);
        return Ok(_responseStringBuilder.BuildNoErrorsResponse().Create());
    }
</code>```

Requirements

This is simple action that should return Ok with string in its response content.

Questions

Is there any better what of checking for valid input? I've created
hierarchy of methods validating input of each action in this
controller(because most of the input for different actions is actually repeating) as
private methods in the controller.

I've created string builder pattern and I build each time my request with needed properties. Is this the best way?

There is some business logic which I've put in the controller, but I am not sure if it should be in the service layer or not Should I leave it like that or invoke single method from a service which does all the logic by itself there and simply returns result to me if there are errors or not?

```<code>Example response would be:
...(some data)
error_code=NoErrors\r\n
error_message=There were no errors\r\n
</code>```

答:
Here are my 2 cents:

Is there any better what of checking for valid input?

If possible, put the validation attributes on your models for basic validation. See this as an example.

For more business-oriented validation, I think it should happen inside a method which encapsulates an action, so your checks against customer restriction and other stuff would go there. The method could throw an exception with a meaningful message if something is wrong and then you could catch the exception, take its message and construct a response using it.

I've created string builder pattern and I build each time my request with needed properties. Is this the best way?

As you've stated you need a string as a response. Is there any particular format, though? If yes, I'd advise to leverage custom formatters to put the formatting logic in one place.

Should I leave it like that or invoke single method from a service which does all the logic by itself there and simply returns result to me if there are errors or not?

Typical service layer should care about business validation and business logic. That is, format of the request and primitive validation can be put outside of this method but the method itself should validate passed parameters anyway and can't rely on caller providing them correctly. However, I should note that such questions are extremely opinionated and depend on particular use case. There are a lot of possible approaches and there isn't reason for a controller to be a proxy just as there is no reason for a controller to be bloated.

Also, this should probably go to https://codereview.stackexchange.com/.

Body:
Overview

I am designing one api that will be integration with another system, however I stumbled upon one code which I know it can be improved but I don't know how to do it properly.

Code

    [HttpPost]
    [Route("Reserve")]
    public IHttpActionResult Reserve([FromUri]ReserveData reserveData, [FromBody]BetsData bet)
    {
        var result = new ReserveResponse();
        // Question 1.
        if (reserveData == null || !IsDataForReserveValid(reserveData))
        {
            // Question 2.
            return Ok(_responseStringBuilder.BuildWrongRequestResponse().Create());
        }
        // Question 3.
        if (!_customerService.CheckIfCustomerExists(reserveData.cust_id))
        {
            return Ok(_responseStringBuilder.BuildCustomerNotFoundResponse().Create());
        }
        if (_customerService.IsCustomerRestricted(reserveData.cust_id))
        {
            return Ok(_responseStringBuilder.BuildRestrictedCustomerResponse().Create());
        }
        if (!_reserveService.ReserveAmount(reserveData.cust_id, reserveData.amount))
        {
            return Ok(_responseStringBuilder.BuildInsufficientFundsResponse().Create());
        }

        if (bet != null)
        {

        }

        _reserveService.InsertReserve(reserveData);
        return Ok(_responseStringBuilder.BuildNoErrorsResponse().Create());
    }

Requirements

This is simple action that should return Ok with string in its response content.

Questions

Is there any better what of checking for valid input? I've created
hierarchy of methods validating input of each action in this
controller(because most of the input for different actions is actually repeating) as
private methods in the controller.

I've created string builder pattern and I build each time my request with needed properties. Is this the best way?

There is some business logic which I've put in the controller, but I am not sure if it should be in the service layer or not Should I leave it like that or invoke single method from a service which does all the logic by itself there and simply returns result to me if there are errors or not?

Example response would be:
...(some data)
error_code=NoErrors\r\n
error_message=There were no errors\r\n


问:
Print msg to the console from GUI app - C#
Hi
I want to print some messages when I'm running C# GUI app on Visual Studio. It's like debugging. So I tried it, but not worked. console.writeline() didn't work or It may work, but I couldn't see the messages. Anyone knows about this? give me a solution if you know.
Thank you.</p>

答:
Console.WriteLine("Application Started!!");

that will also write into output window.


问:
Generating all permutations of a given string
What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer string such as abcdefgh? Is there any Java implementation example?

答:
Simple python solution using recursion.</p>

```<code>def get_permutations(string):

    # base case
    if len(string) <= 1:
        return set([string])

    all_chars_except_last = string[:-1]
    last_char = string[-1]

    # recursive call: get all possible permutations for all chars except last
    permutations_of_all_chars_except_last = get_permutations(all_chars_except_last)

    # put the last char in all possible positions for each of the above permutations
    permutations = set()
    for permutation_of_all_chars_except_last in permutations_of_all_chars_except_last:
        for position in range(len(all_chars_except_last) + 1):
            permutation = permutation_of_all_chars_except_last[:position] + last_char + permutation_of_all_chars_except_last[position:]
            permutations.add(permutation)

    return permutations
</code>```

Body:
Simple python solution using recursion.

def get_permutations(string):

    # base case
    if len(string) <= 1:
        return set([string])

    all_chars_except_last = string[:-1]
    last_char = string[-1]

    # recursive call: get all possible permutations for all chars except last
    permutations_of_all_chars_except_last = get_permutations(all_chars_except_last)

    # put the last char in all possible positions for each of the above permutations
    permutations = set()
    for permutation_of_all_chars_except_last in permutations_of_all_chars_except_last:
        for position in range(len(all_chars_except_last) + 1):
            permutation = permutation_of_all_chars_except_last[:position] + last_char + permutation_of_all_chars_except_last[position:]
            permutations.add(permutation)

    return permutations


问:
Send a json with a multiline string instead of \n
I have a string with \n as a join result:

```<code>my_var = ['name','phone','age'].join("\n")
</code>```

I will send this string in the body of a post as a Json:

```<code>def body
  { "str": my_var }
end
</code>```

I want to send the var in multiple lines instead of sending the \n like this:

```<code>"name\nphone\nage"
</code>```

EDIT:
I am sending this string joined with \n to another dev team as a json in the body of my post request to their uri. But they don't want to receive a string with \n and replace or translate there. They want to recieve in multiple lines.

答:
They are receiving multiple lines, depending on their OS: https://en.wikipedia.org/wiki/Newline

```<code>2.1.10 :001 > my_var = ['name','phone','age'].join("\n")
 => "name\nphone\nage"
2.1.10 :002 > puts my_var
name
phone
age
 => nil
2.1.10 :003 > my_var.to_json
 => "\"name\\nphone\\nage\""
2.1.10 :004 > puts my_var.to_json
"name\nphone\nage"
 => nil
2.1.10 :005 >
</code>```

The text you're sending them contains instructions on where a line break is (i.e. the \n character).  The graphical display of it is up to their end.

Body:
I have a string with \n as a join result:

my_var = ['name','phone','age'].join("\n")

I will send this string in the body of a post as a Json:

def body
  { "str": my_var }
end

I want to send the var in multiple lines instead of sending the \n like this:

"name\nphone\nage"

EDIT:
I am sending this string joined with \n to another dev team as a json in the body of my post request to their uri. But they don't want to receive a string with \n and replace or translate there. They want to recieve in multiple lines.

Body:
They are receiving multiple lines, depending on their OS: https://en.wikipedia.org/wiki/Newline

2.1.10 :001 > my_var = ['name','phone','age'].join("\n")
 => "name\nphone\nage"
2.1.10 :002 > puts my_var
name
phone
age
 => nil
2.1.10 :003 > my_var.to_json
 => "\"name\\nphone\\nage\""
2.1.10 :004 > puts my_var.to_json
"name\nphone\nage"
 => nil
2.1.10 :005 >

The text you're sending them contains instructions on where a line break is (i.e. the \n character).  The graphical display of it is up to their end.


问:
event propagation in angular2+
I know this question might sound familiar and repetitive and already answered plenty of times. Please bear with me.  I'm posting only because I could not resolve my issue despite trying the solutions expressed in other questions.

I have a component <od-resource-table [..] [..]></od-resource-table> rendered 2 times in the page. It's basically a table and comes with controls to show/hide columns. The problem I'm facing is that when I tried to hide a column in second table it's affecting the first table and not the table I intended. If I remove the first table, then no problems. Please advise. What am I missing Thanks in advance.

Here's the code that emits

```<code>  onChange(event: MouseEvent, field: string) {
        this.onToggleColumnVisibility.next(field)
        event.stopPropagation();
    }
</code>```

Here's the gif showcasing the behavior

http://g.recordit.co/AoKbazXdr2.gif

search control component contains column picker controls

```<code>@Component({
    selector: 'od-search-control',
    templateUrl: './search-control.component.html',
    styleUrls: ['./search-control.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    encapsulation: ViewEncapsulation.None
})
export class SearchControlComponent {
    @Input() searchText: string = '';
    @Input() searchPlaceholder: string = 'Search';
    @Input() downloadUrl: any = '';
    @Input() columnPickerDefs: Array<ISearchControl.ColumnPickerDef> = [];

    @Output() onRefresh = new EventEmitter<any>();
    @Output() onToggleColumnVisibility = new EventEmitter<any>();
    @Output() onTextChange = new EventEmitter<any>();

    constructor() { }

    onChange(event: MouseEvent, field: string) {
        event.stopPropagation();
        this.onToggleColumnVisibility.next(field)
    }
}
</code>```

resource table component

```<code><div class="od-search-controls-bar">
      <div class="header">
        <h3>
          <span class="page-title">{{title}}</span>
          <span class="estimate">{{(estimate$ | async) | lpad : 2 : '0'}}</span>
        </h3>
        <div class="search-control-bar-wrapper">
            <od-search-control
            ...
            ...
            ...
            (onToggleColumnVisibility)="onToggleColumnVisibility($event)"

            ></od-search-control>
        </div>
      </div>
    </div>
    <od-data-table
      #resTable
      [columnDefs]="columnDefs"
      [rowData]="rowData$ | async"
      [estimates]="estimate$ | async"
      [currentPage]="currentPage$ | async"
      [itemsPerPage]="itemsPerPage$ | async"
      (onPageChange)="onPageChange($event)"
      (sortModel)="onSort($event)"
    ></od-data-table>
@Component({
  selector: "od-resource-table",
  templateUrl: "./resource-table.component.html",
  styleUrls: ["./resource-table.component.scss"],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ResourceTableComponent implements OnInit, OnDestroy, OnChanges {
  @Input() category: string;
  ...
  ...
    onToggleColumnVisibility(columnField: string) {
    let columnIndex = this.columnDefs.findIndex(col => col.field === columnField);
    if (columnIndex > -1) {
      this.columnDefs[columnIndex].hide = !this.columnDefs[columnIndex].hide;
      this.columnDefs = [...this.columnDefs];
    }
  }

}
</code>```

Page containing 2 tables

```<code>@Component({

  selector: 'od-resource-assignment-view',
  template: `
   <div class="resource-navigation-panel">
      <label class="active"
          routerLink="/console-settings/resource-groups/"
      >Resource Groups</label>
      <label class="text-ellipsis"><span class="active">/</span>{{resourceGroupName}}</label>
    </div>
    <div class="assignment-resource-wrapper">
      <od-resource-table #assignedResourcesTable
        [resources]="(resourceGroupType$ | async)"
        [resourceGroupId]="resourceGroupId"
        [enableNodeSelection]="true"
        title="Assigned Resources"
        category="resource group">
      </od-resource-table>
      <div class="assign-button-wrapper">
        <button type="button" class="btn btn-secondary" (click)="unassignResources()">
          DEASSIGN
        </button>
      </div>
    </div>
    <div>
      <od-resource-table #enterpriseResourcesTable
        [resources]="(resourceGroupType$ | async)"
        [enableNodeSelection]="true"
        [exclude]="(excludeResources$ | async)"
        title="Total Resources"
        category="enterprise">
      </od-resource-table>
      <div class="assign-button-wrapper">
        <button type="button" class="btn btn-secondary" (click)="assignResources()">
          ASSIGN
        </button>
      </div>
    </div>
  `,
  styleUrls: ['./resource-assignment-view.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None
})
export class ResourcesAssignmentViewComponent implements OnInit, OnDestroy {
  @Input() resourceGroupId: string;
  @Input() resourceGroupName: string;
  @ViewChild('assignedResourcesTable') assignedResourcesTable: ResourceTableComponent
  @ViewChild('enterpriseResourcesTable') enterpriseResourcesTable: ResourceTableComponent
  resourceGroupType$: Observable<string>
  excludeResources$: Observable<string[]>
  resourceGroup: IResourceGroups.ResourceGroupItem
  _subs: Subscription[] = new Array<Subscription>()

  constructor(private _store: Store<IResourceGroups.ResourceGroupsState>) { }

  ngOnInit() {}
   ...
...
...

}
</code>```

答:
That is because both of the tables are using the same instance of onChange and when you perform action, the first table receives the event first and then you execute event.stopPropagation();
 within the listener.

Solution:
Try to differentiate the tables in the listener (onChange) or use the separate instance of the listener.

Title: event propagation in angular2+

Body:
I know this question might sound familiar and repetitive and already answered plenty of times. Please bear with me.  I'm posting only because I could not resolve my issue despite trying the solutions expressed in other questions.

I have a component <od-resource-table [..] [..]></od-resource-table> rendered 2 times in the page. It's basically a table and comes with controls to show/hide columns. The problem I'm facing is that when I tried to hide a column in second table it's affecting the first table and not the table I intended. If I remove the first table, then no problems. Please advise. What am I missing Thanks in advance.

Here's the code that emits

  onChange(event: MouseEvent, field: string) {
        this.onToggleColumnVisibility.next(field)
        event.stopPropagation();
    }

Here's the gif showcasing the behavior

http://g.recordit.co/AoKbazXdr2.gif

search control component contains column picker controls

@Component({
    selector: 'od-search-control',
    templateUrl: './search-control.component.html',
    styleUrls: ['./search-control.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    encapsulation: ViewEncapsulation.None
})
export class SearchControlComponent {
    @Input() searchText: string = '';
    @Input() searchPlaceholder: string = 'Search';
    @Input() downloadUrl: any = '';
    @Input() columnPickerDefs: Array<ISearchControl.ColumnPickerDef> = [];

    @Output() onRefresh = new EventEmitter<any>();
    @Output() onToggleColumnVisibility = new EventEmitter<any>();
    @Output() onTextChange = new EventEmitter<any>();

    constructor() { }

    onChange(event: MouseEvent, field: string) {
        event.stopPropagation();
        this.onToggleColumnVisibility.next(field)
    }
}

resource table component

          {{title}}
          {{(estimate$ | async) | lpad : 2 : '0'}}

            <od-search-control
            ...
            ...
            ...
            (onToggleColumnVisibility)="onToggleColumnVisibility($event)"

            ></od-search-control>

    <od-data-table
      #resTable
      [columnDefs]="columnDefs"
      [rowData]="rowData$ | async"
      [estimates]="estimate$ | async"
      [currentPage]="currentPage$ | async"
      [itemsPerPage]="itemsPerPage$ | async"
      (onPageChange)="onPageChange($event)"
      (sortModel)="onSort($event)"
    ></od-data-table>
@Component({
  selector: "od-resource-table",
  templateUrl: "./resource-table.component.html",
  styleUrls: ["./resource-table.component.scss"],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ResourceTableComponent implements OnInit, OnDestroy, OnChanges {
  @Input() category: string;
  ...
  ...
    onToggleColumnVisibility(columnField: string) {
    let columnIndex = this.columnDefs.findIndex(col => col.field === columnField);
    if (columnIndex > -1) {
      this.columnDefs[columnIndex].hide = !this.columnDefs[columnIndex].hide;
      this.columnDefs = [...this.columnDefs];
    }
  }

}

Page containing 2 tables

@Component({

  selector: 'od-resource-assignment-view',
  template: `

      Resource Groups
      /{{resourceGroupName}}

      <od-resource-table #assignedResourcesTable
        [resources]="(resourceGroupType$ | async)"
        [resourceGroupId]="resourceGroupId"
        [enableNodeSelection]="true"
        title="Assigned Resources"
        category="resource group">
      </od-resource-table>

        <button type="button" class="btn btn-secondary" (click)="unassignResources()">
          DEASSIGN
        </button>

      <od-resource-table #enterpriseResourcesTable
        [resources]="(resourceGroupType$ | async)"
        [enableNodeSelection]="true"
        [exclude]="(excludeResources$ | async)"
        title="Total Resources"
        category="enterprise">
      </od-resource-table>

        <button type="button" class="btn btn-secondary" (click)="assignResources()">
          ASSIGN
        </button>

  `,
  styleUrls: ['./resource-assignment-view.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None
})
export class ResourcesAssignmentViewComponent implements OnInit, OnDestroy {
  @Input() resourceGroupId: string;
  @Input() resourceGroupName: string;
  @ViewChild('assignedResourcesTable') assignedResourcesTable: ResourceTableComponent
  @ViewChild('enterpriseResourcesTable') enterpriseResourcesTable: ResourceTableComponent
  resourceGroupType$: Observable<string>
  excludeResources$: Observable<string[]>
  resourceGroup: IResourceGroups.ResourceGroupItem
  _subs: Subscription[] = new Array<Subscription>()

  constructor(private _store: Store<IResourceGroups.ResourceGroupsState>) { }

  ngOnInit() {}
   ...
...
...

}


问:
"Partition is below target replica or instance count" error after deploying service fabric application to public service fabric cluster
I have created a service fabric stateless reliable service, in which i used OWIN to host a web API. When I deployed the application to the Local cluster, it worked fine and i could call the API.

When i deployed the application to the public cluster, The deployment completed successfully but when i inspected the cluster using Service fabric explorer,

the the replicas seemed to be in "In Build" status for sometime,
then it moved to "Warning" State and finally the entire tree in the fabric explorer went red and there are no more replicas present under the partition.
And showed the health status as Error.
Showing the error "Partition is below target replica or instance count".

Also I used the allowed port for creating the OWIN web server.

This doesn't happen when i deploy the application in local cluster.
Service Fabric Explorer Screenshot for public cluster ,
Service Fabric Explorer Screenshot for Local Cluster

答:
I came across this issue and it was a config error.

The error in service Fabric explorer on port 19080 said:

```<code>Error event: SourceId='System.FM', Property='State'.
</code>```

Partition is below target replica or instance count.
fabric:/MyApp/MyService 3 2 [partitionid]
  N/P RD _Node_0 Up [a long numeric]
  (Showing 1 out of 1 replicas. Total available replicas: 1.)

In my ApplicationManifest.xml I had :

```<code>  <Service Name="MyService">
  <StatefulService ServiceTypeName="MyServiceType" TargetReplicaSetSize=**"3"** MinReplicaSetSize=**"2"**>
    <SingletonPartition />
  </StatefulService>
</Service>
</code>```

Reducing MinReplicaSetSize to 1 and TargetReplicaSetSize to 1 and republishing solved the problem on my end.

Classic Eye-Dee-Ten-Tee (ID10T) config issue :-D

Body:
I came across this issue and it was a config error.

The error in service Fabric explorer on port 19080 said:

Error event: SourceId='System.FM', Property='State'.

Partition is below target replica or instance count.
fabric:/MyApp/MyService 3 2 [partitionid]
  N/P RD _Node_0 Up [a long numeric]
  (Showing 1 out of 1 replicas. Total available replicas: 1.)

In my ApplicationManifest.xml I had :

  <Service Name="MyService">
  <StatefulService ServiceTypeName="MyServiceType" TargetReplicaSetSize=**"3"** MinReplicaSetSize=**"2"**>
    <SingletonPartition />
  </StatefulService>
</Service>

Reducing MinReplicaSetSize to 1 and TargetReplicaSetSize to 1 and republishing solved the problem on my end.

Classic Eye-Dee-Ten-Tee (ID10T) config issue :-D


问:
Sort three numbers in array from least to greatest
I have to create a function that takes 3 numbers. The function should return an array containing the numbers from least to greatest. So far I have this.I know it isn't correct but it's a start.I'm not using native functions as well. Can anyone give me some tips? Appreciate any help.</p>

```<code>   function leastToGreatest (num) {
        var array = [];
        var num1 = 0;
        var num2 = 0;
        var num3 = 0;
        for (var i = 0; i < num.length; i++) {
           if(num[i] < num[i] && num[i] < num[i]) {
                  num[i] = num1;
                  array.push(num1);
           }
           else if(num[i] > num[i] && num[i] < num[i]) {
             num[i] = num2;
             array.push(num2);
           }
           else if(num[i] > num[i] && num[i] > num[i])
             num[i] = num3;
             array.push(num3);
           }
           return array;
     }
     leastToGreatest(2,1,3);
</code>```

答: Your code as it is now currently does not work because you are comparing a number with itself, so it will always be equal (causing your sorting to do nothing). To get a working sort you could fix this or use array.prototype.sort.</p>

Body:
I have to create a function that takes 3 numbers. The function should return an array containing the numbers from least to greatest. So far I have this.I know it isn't correct but it's a start.I'm not using native functions as well. Can anyone give me some tips? Appreciate any help.

   function leastToGreatest (num) {
        var array = [];
        var num1 = 0;
        var num2 = 0;
        var num3 = 0;
        for (var i = 0; i < num.length; i++) {
           if(num[i] < num[i] && num[i] < num[i]) {
                  num[i] = num1;
                  array.push(num1);
           }
           else if(num[i] > num[i] && num[i] < num[i]) {
             num[i] = num2;
             array.push(num2);
           }
           else if(num[i] > num[i] && num[i] > num[i])
             num[i] = num3;
             array.push(num3);
           }
           return array;
     }
     leastToGreatest(2,1,3);


问:
How can I merge duplicate objects with Linq while concatenating a property?
I have an object:

```<code>private class User
    {
        public string fullname { get; set; }
        public string manager { get; set; }
        public string businessunit { get; set; }
        public string employeeid { get; set; }
        public string mainphone { get; set; }
        public string fax { get; set; }
        public string mobile { get; set; }
        public string email { get; set; }
        public string street3 { get; set; }
        public string street2 { get; set; }
        public string street1 { get; set; }
        public string city { get; set; }
        public string stateorprovince { get; set; }
        public string ziporpostalcode { get; set; }
        public string department { get; set; }
        public string countryorregion { get; set; }
        public string salesarea { get; set; }
        public string title { get; set; }
        public string username { get; set; }
        public string companyname { get; set; }
        public string securityroles { get; set; }
        public User()
        {

        }
    }
</code>```

I also have a list of that object:

```<code>List<User> users = new List<User>();
</code>```

What I'd like to do is merge all Users in the list with the same fullname while concatenating all of their different securityroles into the same securityroles property.

I was thinking something along the lines of this would work:

```<code>users = (from user in users
                 group user by user.fullname
                 /*not sure what to put here*/).ToList();
</code>```

答:
I would write a function that merges a collection of Users into one and call that from your query:

```<code>private User Merge(IEnumerable<User> users)
{
    User user = new User();

    if(!users.Any()) return user; // or null, whatever you think is appropriate

    user.fullname = users.First().fullname;
    user.securityroles = string.Join(", ", users.Select(u => u.securityroles));
    // similar rules/queries for other properties.
}
</code>```

Then just call it from the main query:

```<code>users = (from user in users
         group user by user.fullname into g
         select Merge(g)
        ).ToList();
</code>```

If you don't like having multiple queries in the Merge function, then re-write it as a foreach loop, or use whatever construct you see fit.

The point is to get something that works and defines your rules for "merge" outside of your Linq query, then make it better.

Body:
I have an object:

private class User
    {
        public string fullname { get; set; }
        public string manager { get; set; }
        public string businessunit { get; set; }
        public string employeeid { get; set; }
        public string mainphone { get; set; }
        public string fax { get; set; }
        public string mobile { get; set; }
        public string email { get; set; }
        public string street3 { get; set; }
        public string street2 { get; set; }
        public string street1 { get; set; }
        public string city { get; set; }
        public string stateorprovince { get; set; }
        public string ziporpostalcode { get; set; }
        public string department { get; set; }
        public string countryorregion { get; set; }
        public string salesarea { get; set; }
        public string title { get; set; }
        public string username { get; set; }
        public string companyname { get; set; }
        public string securityroles { get; set; }
        public User()
        {

        }
    }

I also have a list of that object:

List<User> users = new List<User>();

What I'd like to do is merge all Users in the list with the same fullname while concatenating all of their different securityroles into the same securityroles property.

I was thinking something along the lines of this would work:

users = (from user in users
                 group user by user.fullname
                 /*not sure what to put here*/).ToList();

Body:
I would write a function that merges a collection of Users into one and call that from your query:

private User Merge(IEnumerable<User> users)
{
    User user = new User();

    if(!users.Any()) return user; // or null, whatever you think is appropriate

    user.fullname = users.First().fullname;
    user.securityroles = string.Join(", ", users.Select(u => u.securityroles));
    // similar rules/queries for other properties.
}

Then just call it from the main query:

users = (from user in users
         group user by user.fullname into g
         select Merge(g)
        ).ToList();

If you don't like having multiple queries in the Merge function, then re-write it as a foreach loop, or use whatever construct you see fit.

The point is to get something that works and defines your rules for "merge" outside of your Linq query, then make it better.