问:
Java-Swing: A problem using layout managers!
I'm working on a JDialog (by hand, no GUI builders) and I'm having a problem doing the layout.

I have this:

My problem is that I don't know what how to tell that JList (within a JScrollPane) to have a Maximum width, I used the setSize, setMaximumSize and nothing works! I need that JList's width to be the half of the picture's size.

Explain the layouts:

The "Gene Information" is a GridLayout 2x4, it's contained by a JPanel with BoxLayout, the +/- JButtons is a BoxLayout also, all what I said before is within a BoxLayout.
Now, the "Genes" JPanel is a GridBagLayout.

What can I do?

Thanks in advance!

PD: The other borders are just for seeign the boundaries of the components.

    Source Code:

```<code>scpGenesList.setViewportView(lstGenesList);

pnlGeneInfo.setLayout(new GridLayout(4, 2, 10, 10));
pnlGeneInfo.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Gene Information"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
lblGeneSymbol.setText("Symbol:");
lblGeneSymbol.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneChromosome.setText("Chromosome:");
lblGeneChromosome.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStartPosition.setText("Start Position:");
lblGeneStartPosition.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStopPosition.setText("Stop Position:");
lblGeneStopPosition.setHorizontalAlignment(SwingConstants.RIGHT);
pnlGeneInfo.add(lblGeneSymbol);
pnlGeneInfo.add(lblGeneSymbolValue);
pnlGeneInfo.add(lblGeneChromosome);
pnlGeneInfo.add(lblGeneChromosomeValue);
pnlGeneInfo.add(lblGeneStartPosition);
pnlGeneInfo.add(lblGeneStartPositionValue);
pnlGeneInfo.add(lblGeneStopPosition);
pnlGeneInfo.add(lblGeneStopPositionValue);

pnlGWASAddRemoveButtons.setLayout(new BoxLayout(pnlGWASAddRemoveButtons, BoxLayout.X_AXIS));
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());
pnlGWASAddRemoveButtons.add(cmdGenesAdd);
pnlGWASAddRemoveButtons.add(Box.createHorizontalStrut(10));
pnlGWASAddRemoveButtons.add(cmdGenesRemove);
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());

pnlGeneInfoButtons.setLayout(new BoxLayout(pnlGeneInfoButtons, BoxLayout.Y_AXIS));
pnlGeneInfoButtons.add(pnlGeneInfo);
pnlGeneInfoButtons.add(Box.createVerticalStrut(10));
pnlGeneInfoButtons.add(pnlGWASAddRemoveButtons);

pnlGenesPanel.setLayout(new GridBagLayout());
pnlGenesPanel.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Genes"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));

GridBagConstraints ctrGenes = new GridBagConstraints();
ctrGenes.fill = GridBagConstraints.BOTH;
ctrGenes.gridx = 0;
ctrGenes.gridy = 0;
ctrGenes.gridwidth = 1;
ctrGenes.gridheight = 1;
ctrGenes.weighty = 1.0;
ctrGenes.weightx = 1.0;
ctrGenes.insets = new Insets(0, 0, 0, 10);
pnlGenesPanel.add(scpGenesList, ctrGenes);

GridBagConstraints ctrGenesInfoButton = new GridBagConstraints();
ctrGenesInfoButton.fill = GridBagConstraints.BOTH;
ctrGenesInfoButton.gridx = 1;
ctrGenesInfoButton.gridy = 0;
ctrGenesInfoButton.gridwidth = 1;
ctrGenesInfoButton.gridheight = 1;
ctrGenesInfoButton.weighty = 1.0;
ctrGenesInfoButton.weightx = 1.0;
pnlGenesPanel.add(pnlGeneInfoButtons, ctrGenesInfoButton);

contentPane.add(pnlGenesPanel);

pack();
</code>```

答:
Without seeing all the code here it may be impossible to tell you what is wrong. One thing I would suggest if you have time is to take a look at MigLayout. You can use it with Swing & SWT and once you learn it is a pretty powerful layout manager IMHO.

Hope this helps, good luck.

Body:
I'm working on a JDialog (by hand, no GUI builders) and I'm having a problem doing the layout.

I have this:

My problem is that I don't know what how to tell that JList (within a JScrollPane) to have a Maximum width, I used the setSize, setMaximumSize and nothing works! I need that JList's width to be the half of the picture's size.

Explain the layouts:

The "Gene Information" is a GridLayout 2x4, it's contained by a JPanel with BoxLayout, the +/- JButtons is a BoxLayout also, all what I said before is within a BoxLayout.
Now, the "Genes" JPanel is a GridBagLayout.

What can I do?

Thanks in advance!

PD: The other borders are just for seeign the boundaries of the components.

    Source Code:

scpGenesList.setViewportView(lstGenesList);

pnlGeneInfo.setLayout(new GridLayout(4, 2, 10, 10));
pnlGeneInfo.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Gene Information"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
lblGeneSymbol.setText("Symbol:");
lblGeneSymbol.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneChromosome.setText("Chromosome:");
lblGeneChromosome.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStartPosition.setText("Start Position:");
lblGeneStartPosition.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStopPosition.setText("Stop Position:");
lblGeneStopPosition.setHorizontalAlignment(SwingConstants.RIGHT);
pnlGeneInfo.add(lblGeneSymbol);
pnlGeneInfo.add(lblGeneSymbolValue);
pnlGeneInfo.add(lblGeneChromosome);
pnlGeneInfo.add(lblGeneChromosomeValue);
pnlGeneInfo.add(lblGeneStartPosition);
pnlGeneInfo.add(lblGeneStartPositionValue);
pnlGeneInfo.add(lblGeneStopPosition);
pnlGeneInfo.add(lblGeneStopPositionValue);

pnlGWASAddRemoveButtons.setLayout(new BoxLayout(pnlGWASAddRemoveButtons, BoxLayout.X_AXIS));
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());
pnlGWASAddRemoveButtons.add(cmdGenesAdd);
pnlGWASAddRemoveButtons.add(Box.createHorizontalStrut(10));
pnlGWASAddRemoveButtons.add(cmdGenesRemove);
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());

pnlGeneInfoButtons.setLayout(new BoxLayout(pnlGeneInfoButtons, BoxLayout.Y_AXIS));
pnlGeneInfoButtons.add(pnlGeneInfo);
pnlGeneInfoButtons.add(Box.createVerticalStrut(10));
pnlGeneInfoButtons.add(pnlGWASAddRemoveButtons);

pnlGenesPanel.setLayout(new GridBagLayout());
pnlGenesPanel.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Genes"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));

GridBagConstraints ctrGenes = new GridBagConstraints();
ctrGenes.fill = GridBagConstraints.BOTH;
ctrGenes.gridx = 0;
ctrGenes.gridy = 0;
ctrGenes.gridwidth = 1;
ctrGenes.gridheight = 1;
ctrGenes.weighty = 1.0;
ctrGenes.weightx = 1.0;
ctrGenes.insets = new Insets(0, 0, 0, 10);
pnlGenesPanel.add(scpGenesList, ctrGenes);

GridBagConstraints ctrGenesInfoButton = new GridBagConstraints();
ctrGenesInfoButton.fill = GridBagConstraints.BOTH;
ctrGenesInfoButton.gridx = 1;
ctrGenesInfoButton.gridy = 0;
ctrGenesInfoButton.gridwidth = 1;
ctrGenesInfoButton.gridheight = 1;
ctrGenesInfoButton.weighty = 1.0;
ctrGenesInfoButton.weightx = 1.0;
pnlGenesPanel.add(pnlGeneInfoButtons, ctrGenesInfoButton);

contentPane.add(pnlGenesPanel);

pack();


来源: stackexchange

问:
Calling SKPaymentQueue restoreCompletedTransactions, no response
The use case here is that the user has never purchased my in-app purchase but taps the Restore button. I want to let the user know that the restore has failed because there is nothing to restore.

The problem is that I'm not getting any event. So I don't know that anything has happened.

When my user taps the Restore button in my interface, I call

```<code>SKPaymentQueue.default().restoreCompletedTransactions
</code>```

However, after that nothing is happening. I expect my SKPaymentTransactionObserver paymentQueue(_:updatedTransactions:) to be called, but it isn't.

I tried implementing paymentQueue(_:restoreCompletedTransactionsFailedWithError:), but it isn't being called either.

答:
You're so close! You need to implement this SKPaymentTransactionObserver method:

```<code>func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
    // ...
}
</code>```

That method is called after restoreCompletedTransactions, if the device was able to communicate with the App Store — regardless of whether the restore succeeded because the user did indeed have purchases to restore, or failed because the user had no purchases to restore.

Unfortunately, you don't get any information here about what just happened. I regard that as a flaw in the StoreKit architecture.

However, if the restore succeeded, we will have passed through paymentQueue(_:updatedTransactions:) with a transactionState of .restored. So presumably you are setting some sort of UserDefaults Bool (or similar) to indicate that the user has made this purchase.

Well, that happens or doesn't happen before paymentQueueRestoreCompletedTransactionsFinished is called. So in paymentQueueRestoreCompletedTransactionsFinished you can look to see whether that UserDefaults Bool is set, and if it isn't, you can guess that the user probably never made any purchase in the first place, and respond accordingly.

It's guesswork, but it's better than nothing.

ContentLicense: CC BY-SA 3.0

Body:
The use case here is that the user has never purchased my in-app purchase but taps the Restore button. I want to let the user know that the restore has failed because there is nothing to restore.

The problem is that I'm not getting any event. So I don't know that anything has happened.

When my user taps the Restore button in my interface, I call

SKPaymentQueue.default().restoreCompletedTransactions

However, after that nothing is happening. I expect my SKPaymentTransactionObserver paymentQueue(_:updatedTransactions:) to be called, but it isn't.

I tried implementing paymentQueue(_:restoreCompletedTransactionsFailedWithError:), but it isn't being called either.

Body:
You're so close! You need to implement this SKPaymentTransactionObserver method:

func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
    // ...
}

That method is called after restoreCompletedTransactions, if the device was able to communicate with the App Store — regardless of whether the restore succeeded because the user did indeed have purchases to restore, or failed because the user had no purchases to restore.

Unfortunately, you don't get any information here about what just happened. I regard that as a flaw in the StoreKit architecture.

However, if the restore succeeded, we will have passed through paymentQueue(_:updatedTransactions:) with a transactionState of .restored. So presumably you are setting some sort of UserDefaults Bool (or similar) to indicate that the user has made this purchase.

Well, that happens or doesn't happen before paymentQueueRestoreCompletedTransactionsFinished is called. So in paymentQueueRestoreCompletedTransactionsFinished you can look to see whether that UserDefaults Bool is set, and if it isn't, you can guess that the user probably never made any purchase in the first place, and respond accordingly.

It's guesswork, but it's better than nothing.


问:
Swift 4 Mac OS TableView Col failing to get binding value from Core Data NSManagedObject
Condition: I have an NSArrayController in an NSViewController properly bound to a Core Data entity. I have added buttons to add and delete rows (see pic) that are properly connected to the array controller. But, when I add a row, instead of getting the bound variable as the table cell contents, I get the title of the cell.

Information: In the image provided below you see a view controller with a table view and a text field. The text field value is bound to the Array Controller.selection.myvariable, and it properly shows the value of myvariable. The table view column is bound to Array Controller.arrangedObjects.myvalue, but it shows the cell.title ("New Table Cell") rather than myvalue.

Question: What have I missed to get the proper value into the cell. I have not implemented Table View Delegate or Data Source methods. My understanding is that the Cocoa Binding eliminates the needs for such "glue". Why does the textfield work but not the table column? Thanks for helping if you are able.

答: In Xcode 9.1 you can't bind the tableview column to the attribute, you just bind it to Controller Ket to arrangedObjects and leave the Model Key Path blank. Then bind the text field cell of the column to the Model Key path objectValue.yourvar.</p>


问:
WSO2 Governance Registry - Solr index problems
We're having some problems about the assets in Publisher/Store in WSO2 using MySQL. We load our database of assets into WSO2 but not all of the assets show up in the store or publisher when queried. This also occuries when we try to get the assets using API.

But the missing assets can be found by:

Calling the database directly

looking them up in carbon

using the store or publisher url with the asset id

the governance rest api through id only

Using WSO2 database default (H2), this issue didn't happened.

After some research about this issue, we have found some solutions like "deleting solr and update registry.xml" to reindex all the assets that are missing but without success.

This question represents a lot of our issues with missing assets.

WSO2 Governance Not Finding All Assets in JDBC Database

If someone went through this, any help would be appreciated.

答:
If you are using WSO2 API Manager 2.1.0, you can use skipCache property as mentioned in 1. This will directly fetch data from the database.

1 - https://docs.wso2.com/display/AM210/Distributed+Deployment+of+API+Manager


问:
Understanding the string pushed onto a stack in a NPDA
I'm learning about NPDA, and to be frank, I'm trying to understand what I'm looking at in this problem:

What exactly determined "aaz" or "aaa" being pushed onto the stack? Does it matter, as long as these are getting popped when a b is read?

答: "aaz" and "aaa" are distinguished since one replaces "z" and the other replaces "a" on top of the stack. Each has the effect of leaving the topmost stack symbol alone and pushing two more a's on top. The NPDA works by pushing two a's on the stack for every a seen, then popping off a single a for every b seen. If the stack ends up empty, you must have seen exactly twice as many b's as a's.</p>


问:
.on(click - make new image appear while incrementing score - jQuery
Here's my  jfiddle. It doesn't look right when I run it. When I click Start in Firefox, the Timer starts to go down and the Mole appears. A new one appears every time I click start, just not when I click the Mole, and the Score isn't changing

I hope this isn't too broad, I don't know how to separate the question.

Whack-a-Mole Game for javascript/jquery class. I have to keep it so that the Mole appears when the Start Button is clicked and a new Mole appears every time you click on a Mole. The Score goes up one with every click.

The instructions say to use the .on() and to put it in the .ready() function. I'm supposed  to call my incrementing function in the process.

```<code>     $(document).ready(function(){
        $("#start_button").click(function(){
            start();
            run();
        }); //end start button
        $("<img src='img/mole.png' />").on("click", function(){
            incScore();
            addMole();
        }); //end.on
    }); //end.ready
    function start(){
        $("#timer").show();
        addMole()
    }; //end start
</code>```

答:
As long as addMole and incScore work I think you are pretty close.  Your img selector looks like it isn't quite right, ideally you should add a class to the mole image ("mole-img" for example) so you can make a selector like this $('.mole-img').on('click', ...)

If you want to call multiple functions you can supply an anonymous function to the click handler, that will get executed every time the mole is clicked. (just like the #start_button handler has)

I don't think you want to put the handler for the mole clicks inside of the #start_button handler, so I moved that outside.

The start function can also be inside of $(document).ready, you can define as many functions inside of that as you want.  Might want to put all your code inside.

If we put those things together it'll look like this

```<code>$(document).ready(function(){
  $("#start_button").click(function(){
    start();
    run();
  });

  $('.mole-img').on('click', function(){
    addMole();
    incScore();
  });

  function start() {
    $("#timer").show();
    addMole();
  }
});
</code>```

If you don't want to add a class to your img, $("img[src='img/mole.png']").on... might also work, but that seems more prone to break later.

Notes from fiddle:

Changed moleImg from an id to a class.  Not sure if you can have multiple moles active at the same time, ids should be unique so to be safe I am using class.

setTimeout takes a function not a string, you don't need parentheses after the function. setTimeout("run()", 1000); --> setTimeout(run, 1000);

Click handlers need to be written a little differnetly when they are supposed to trigger on things that will be added later on.  When the mole click handler is declared there are no moles on the screen.

Here is the way to write the handler to make it listen for elements that will be added later:

$("container to look in").on("click", "element selector", function(){

Apply that to the #gamespace and moleImg selector we get this:

$("#gamespace").on("click", '.moleImg', function() {

That should get you moving along, you might want to add $("gamespace").empty() to your addMole function so they don't keep piling up.

To get them to display randomly look into css position: absolute, left, top properties along with Math.random

Body:
Here's my  jfiddle. It doesn't look right when I run it. When I click Start in Firefox, the Timer starts to go down and the Mole appears. A new one appears every time I click start, just not when I click the Mole, and the Score isn't changing

I hope this isn't too broad, I don't know how to separate the question.

Whack-a-Mole Game for javascript/jquery class. I have to keep it so that the Mole appears when the Start Button is clicked and a new Mole appears every time you click on a Mole. The Score goes up one with every click.

The instructions say to use the .on() and to put it in the .ready() function. I'm supposed  to call my incrementing function in the process.

     $(document).ready(function(){
        $("#start_button").click(function(){
            start();
            run();
        }); //end start button
        $("").on("click", function(){
            incScore();
            addMole();
        }); //end.on
    }); //end.ready
    function start(){
        $("#timer").show();
        addMole()
    }; //end start

Body:
As long as addMole and incScore work I think you are pretty close.  Your img selector looks like it isn't quite right, ideally you should add a class to the mole image ("mole-img" for example) so you can make a selector like this $('.mole-img').on('click', ...)

If you want to call multiple functions you can supply an anonymous function to the click handler, that will get executed every time the mole is clicked. (just like the #start_button handler has)

I don't think you want to put the handler for the mole clicks inside of the #start_button handler, so I moved that outside.

The start function can also be inside of $(document).ready, you can define as many functions inside of that as you want.  Might want to put all your code inside.

If we put those things together it'll look like this

$(document).ready(function(){
  $("#start_button").click(function(){
    start();
    run();
  });

  $('.mole-img').on('click', function(){
    addMole();
    incScore();
  });

  function start() {
    $("#timer").show();
    addMole();
  }
});

If you don't want to add a class to your img, $("img[src='img/mole.png']").on... might also work, but that seems more prone to break later.

Notes from fiddle:

Changed moleImg from an id to a class.  Not sure if you can have multiple moles active at the same time, ids should be unique so to be safe I am using class.

setTimeout takes a function not a string, you don't need parentheses after the function. setTimeout("run()", 1000); --> setTimeout(run, 1000);

Click handlers need to be written a little differnetly when they are supposed to trigger on things that will be added later on.  When the mole click handler is declared there are no moles on the screen.

Here is the way to write the handler to make it listen for elements that will be added later:

$("container to look in").on("click", "element selector", function(){

Apply that to the #gamespace and moleImg selector we get this:

$("#gamespace").on("click", '.moleImg', function() {

That should get you moving along, you might want to add $("gamespace").empty() to your addMole function so they don't keep piling up.

To get them to display randomly look into css position: absolute, left, top properties along with Math.random


问:
using like condition in Subsonic 2.2
I need some help in using "like" condition in Subsonic 2.2

Following is my query

```<code>DAL.DB.Select()
    .From("tblName")
    .Where("NewFirstName")
    .Like(strFirstName)
    .Or("PrevFirstName")
    .Like(strFirstName)
    .ExecuteDataSet();
</code>```

the result returned by above query contains records those have firstname euqal to strFirstName not like strFirstName

example: there are two records which has NewFirstName as 'joe' and 'joe J' so above query just returns record that has 'joe' as NewFirstName .

答:
You seem to be misunderstanding how the LIKE operator works.

Perhaps you should peruse the documentation.

ContentLicense: CC BY-SA 2.5

Title: using like condition in Subsonic 2.2

Body:
I need some help in using "like" condition in Subsonic 2.2

Following is my query

DAL.DB.Select()
    .From("tblName")
    .Where("NewFirstName")
    .Like(strFirstName)
    .Or("PrevFirstName")
    .Like(strFirstName)
    .ExecuteDataSet();

the result returned by above query contains records those have firstname euqal to strFirstName not like strFirstName

example: there are two records which has NewFirstName as 'joe' and 'joe J' so above query just returns record that has 'joe' as NewFirstName .


问:
Am I abusing toString()?
Javadoc for Object.toString() says:

Returns a string representation of the object. In general, the
  toString method returns a string that "textually represents" this
  object. The result should be a concise but informative representation
  that is easy for a person to read. It is recommended that all
  subclasses override this method.  The toString method for class Object
  returns a string consisting of the name of the class of which the
  object is an instance, the at-sign character '@', and the unsigned
  hexadecimal representation of the hash code of the object. In other
  words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Therefore, I am questioning myself if I'm abusing this when I am overriding toString() of a class Foo just so that a ComboBox control (doesn't matter it's JavaFX or Swing control) can render a list of Foo correctly without me doing anything explicit in the ComboBox.

```<code>class Foo {
    private String name;
    public final String getName() { return name; }
    public final void setName(String n) { name = n; }

    @Override
    public String toString() {
        return name;
    }
}

List<Foo> foos = getFoos(); // Get list of Foos from somewhere
ComboBox comboBox = ....; // Some ComboBox control
comboBox.addItems(foos); // Add the list to the ComboBox
</code>```

The default implementation of toString() that most IDE generates are JSON representation of the class. I am suspecting this allows easy serialization/deserialization of class objects. Although I do not need to serialize or deserialize through this method, but I am definitely breaking this possibility by overriding like this.

Edit

I've read the comments of many people, as well as the answer given by VGR. I can see that the general consensus is that there is no hard and fast rule on this. I see that it is generally agreed that toString() is better left for debugging purposes.

The biggest reason why I am doing this "hack" is because I have ComboBox in quite a number of different places. Of course the indisputably correct and clean way is to use a "renderer" to do this job, but it is causing a significant amount of code duplication.

I will mull over this for a few days before I decide which is the best way to do it. Thanks a lot for the bunch of comments and answer.

答:
For Swing, you definitely need to override the toString method of some class.  That’s how Swing model objects work.  (Do not use cell renderers to convert a value to String;  that will break accessibility, keyboard navigation, and built-in sorting of JTables.)

Usually you’d want to separate your display logic from your data, such as by creating a wrapper class, but since you are just returning the raw value of a property (as opposed to formatting it or concatenating it with other information), what you’re doing is fine.

JavaFX is another matter:  Controls use cell factory callback objects to determine what text appears in a cell, so a data class probably should not override toString with a display value in a JavaFX application.

I’m not familiar with IDEs’ auto-generated toString methods, but converting an object to JSON in a toString method is a horrible idea in my opinion.  Swing model objects should have a toString method that returns a human-readable form of the object;  most other classes should return a one-line string with a summary of the object’s state (which does not have to be every property in the object), like getClass().getName() + "[" + getName() + "]".

In summary, you are not abusing toString.  For Swing, you’re doing the right thing.  For JavaFX, it’s better to return a string useful for debugging.

Title: Am I abusing toString()?

Body:
Javadoc for Object.toString() says:

Returns a string representation of the object. In general, the
  toString method returns a string that "textually represents" this
  object. The result should be a concise but informative representation
  that is easy for a person to read. It is recommended that all
  subclasses override this method.  The toString method for class Object
  returns a string consisting of the name of the class of which the
  object is an instance, the at-sign character '@', and the unsigned
  hexadecimal representation of the hash code of the object. In other
  words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Therefore, I am questioning myself if I'm abusing this when I am overriding toString() of a class Foo just so that a ComboBox control (doesn't matter it's JavaFX or Swing control) can render a list of Foo correctly without me doing anything explicit in the ComboBox.

class Foo {
    private String name;
    public final String getName() { return name; }
    public final void setName(String n) { name = n; }

    @Override
    public String toString() {
        return name;
    }
}

List<Foo> foos = getFoos(); // Get list of Foos from somewhere
ComboBox comboBox = ....; // Some ComboBox control
comboBox.addItems(foos); // Add the list to the ComboBox

The default implementation of toString() that most IDE generates are JSON representation of the class. I am suspecting this allows easy serialization/deserialization of class objects. Although I do not need to serialize or deserialize through this method, but I am definitely breaking this possibility by overriding like this.

Edit

I've read the comments of many people, as well as the answer given by VGR. I can see that the general consensus is that there is no hard and fast rule on this. I see that it is generally agreed that toString() is better left for debugging purposes.

The biggest reason why I am doing this "hack" is because I have ComboBox in quite a number of different places. Of course the indisputably correct and clean way is to use a "renderer" to do this job, but it is causing a significant amount of code duplication.

I will mull over this for a few days before I decide which is the best way to do it. Thanks a lot for the bunch of comments and answer.


问:
Artifactory user privileges
Is there a way to check if a user has deploy permissions via the Artifactory REST API?

I am sending requests to the Artifactory server using cURL.

答:
Yes, use the /api/storage/{repo-key}/{item}?permissions API. See the docs at https://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-EffectiveItemPermissions

The docs explain the meaning of the permission chars.

```<code>GET /api/storage/libs-release-local/org/acme?permissions
{
"uri": "http://localhost:8081/artifactory/api/storage/libs-release-local/org/acme"
"principals": {
        "users" : {
          "bob": ["r","w","m"],
          "alice" : ["d","w","n", "r"]
        },
        "groups" : {
          "dev-leads" : ["m","r","n"],
          "readers" : ["r"]
        }
    }
}
</code>```

Title: Artifactory user privileges

Body:
Yes, use the /api/storage/{repo-key}/{item}?permissions API. See the docs at https://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-EffectiveItemPermissions

The docs explain the meaning of the permission chars.

GET /api/storage/libs-release-local/org/acme?permissions
{
"uri": "http://localhost:8081/artifactory/api/storage/libs-release-local/org/acme"
"principals": {
        "users" : {
          "bob": ["r","w","m"],
          "alice" : ["d","w","n", "r"]
        },
        "groups" : {
          "dev-leads" : ["m","r","n"],
          "readers" : ["r"]
        }
    }
}


问:
using fig,axes in a loop matplotlib
I have a question about using fig, axes function in a loop in matplotlib.
I am trying to create a few plots with multiple subplots (the number of subplots isn not fixed) in a loop as follows:

```<code>def start_plot(self):
    if self.running:
        run_fig, run_ax = plt.subplots(*self.matrix)
    if self.histogram:
        hist_fig, hist_ax = plt.subplots(*self.matrix)

def create_signal_plots(self, iwindow, window_name):
    if self.running:
        run_ax[iwindow+1].plot(running_perf, label=window_name) # throws error run_ax not recognized
    if self.histogram:
        hist_ax[iwindow+1].hist(timeseries, label=window_name)

plot = plot_class(run =1, hist =1, matrix = get_matrix(*args)) # e.g. matrix = (3,2)

for istrat, strat in enumerate(strats):
    plot.start_plot()
    for iwindow, window in enumerate(windows):
        plot.create_plots(iwindow, window)
</code>```

Is there a way to make this work without having to return axes in function and pass it around? If I use plt.figure instead of fix,axes, then i can simply update any figure using plt.figure(fig_no).

答:
You can store run_fig and run_ax in your object as instance attributes and then access them from any other method of that object. This would be done using  self.

Use self.run_fig, etc. in start_plot and create_signal_plots as in:

```<code>def start_plot(self):
    if self.running:
        self.run_fig, self.run_ax = plt.subplots(*self.matrix)
    if self.histogram:
        self.hist_fig, self.hist_ax = plt.subplots(*self.matrix)

def create_signal_plots(self, iwindow, window_name):
    if self.running:
        self.run_ax[iwindow+1].plot(running_perf, label=window_name) # throws error run_ax not recognized
    if self.histogram:
        self.hist_ax[iwindow+1].hist(timeseries, label=window_name)
</code>```

Title: using fig,axes in a loop matplotlib

Body:
I have a question about using fig, axes function in a loop in matplotlib.
I am trying to create a few plots with multiple subplots (the number of subplots isn not fixed) in a loop as follows:

def start_plot(self):
    if self.running:
        run_fig, run_ax = plt.subplots(*self.matrix)
    if self.histogram:
        hist_fig, hist_ax = plt.subplots(*self.matrix)

def create_signal_plots(self, iwindow, window_name):
    if self.running:
        run_ax[iwindow+1].plot(running_perf, label=window_name) # throws error run_ax not recognized
    if self.histogram:
        hist_ax[iwindow+1].hist(timeseries, label=window_name)

plot = plot_class(run =1, hist =1, matrix = get_matrix(*args)) # e.g. matrix = (3,2)

for istrat, strat in enumerate(strats):
    plot.start_plot()
    for iwindow, window in enumerate(windows):
        plot.create_plots(iwindow, window)

Is there a way to make this work without having to return axes in function and pass it around? If I use plt.figure instead of fix,axes, then i can simply update any figure using plt.figure(fig_no).

Body:
You can store run_fig and run_ax in your object as instance attributes and then access them from any other method of that object. This would be done using  self.

Use self.run_fig, etc. in start_plot and create_signal_plots as in:

def start_plot(self):
    if self.running:
        self.run_fig, self.run_ax = plt.subplots(*self.matrix)
    if self.histogram:
        self.hist_fig, self.hist_ax = plt.subplots(*self.matrix)

def create_signal_plots(self, iwindow, window_name):
    if self.running:
        self.run_ax[iwindow+1].plot(running_perf, label=window_name) # throws error run_ax not recognized
    if self.histogram:
        self.hist_ax[iwindow+1].hist(timeseries, label=window_name)


问:
Windows 10 poor performance compared to Windows 7 (page fault handling is not scalable, severe lock contention when no of threads > 16)
We set up two identical HP Z840 Workstations with the following specs

2 x Xeon E5-2690 v4 @ 2.60GHz (Turbo Boost ON, HT OFF, total 28 logical CPUs)

32GB DDR4 2400 Memory, Quad-channel

and installed Windows 7 SP1 (x64) and Windows 10 Creators Update (x64) on each.

Then we ran a small memory benchmark (code below, built with VS2015 Update 3, 64-bit architecture) which performs memory allocation-fill-free simultaneously from multiple threads.

#include <Windows.h>
#include <vector>
#include <ppl.h>

unsigned __int64 ZQueryPerformanceCounter()
{
    unsigned __int64 c;
    ::QueryPerformanceCounter((LARGE_INTEGER *)&c);
    return c;
}

unsigned __int64 ZQueryPerformanceFrequency()
{
    unsigned __int64 c;
    ::QueryPerformanceFrequency((LARGE_INTEGER *)&c);
    return c;
}

class CZPerfCounter {
public:
    CZPerfCounter() : m_st(ZQueryPerformanceCounter()) {};
    void reset() { m_st = ZQueryPerformanceCounter(); };
    unsigned __int64 elapsedCount() { return ZQueryPerformanceCounter() - m_st; };
    unsigned long elapsedMS() { return (unsigned long)(elapsedCount() * 1000 / m_freq); };
    unsigned long elapsedMicroSec() { return (unsigned long)(elapsedCount() * 1000 * 1000 / m_freq); };
    static unsigned __int64 frequency() { return m_freq; };
private:
    unsigned __int64 m_st;
    static unsigned __int64 m_freq;
};

unsigned __int64 CZPerfCounter::m_freq = ZQueryPerformanceFrequency();

int main(int argc, char ** argv)
{
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    int ncpu = sysinfo.dwNumberOfProcessors;

    if (argc == 2) {
        ncpu = atoi(argv[1]);
    }

    {
        printf("No of threads %d\n", ncpu);

        try {
            concurrency::Scheduler::ResetDefaultSchedulerPolicy();
            int min_threads = 1;
            int max_threads = ncpu;
            concurrency::SchedulerPolicy policy
            (2 // two entries of policy settings
                , concurrency::MinConcurrency, min_threads
                , concurrency::MaxConcurrency, max_threads
            );
            concurrency::Scheduler::SetDefaultSchedulerPolicy(policy);
        }
        catch (concurrency::default_scheduler_exists &) {
            printf("Cannot set concurrency runtime scheduler policy (Default scheduler already exists).\n");
        }

        static int cnt = 100;
        static int num_fills = 1;
        CZPerfCounter pcTotal;

        // malloc/free
        printf("malloc/free\n");
        {
            CZPerfCounter pc;
            for (int i = 1 * 1024 * 1024; i <= 8 * 1024 * 1024; i *= 2) {
                concurrency::parallel_for(0, 50, [i](size_t x) {
                    std::vector<void *> ptrs;
                    ptrs.reserve(cnt);
                    for (int n = 0; n < cnt; n++) {
                        auto p = malloc(i);
                        ptrs.emplace_back(p);
                    }
                    for (int x = 0; x < num_fills; x++) {
                        for (auto p : ptrs) {
                            memset(p, num_fills, i);
                        }
                    }
                    for (auto p : ptrs) {
                        free(p);
                    }
                });
                printf("size %4d MB,  elapsed %8.2f s, \n", i / (1024 * 1024), pc.elapsedMS() / 1000.0);
                pc.reset();
            }
        }
        printf("\n");
        printf("Total %6.2f s\n", pcTotal.elapsedMS() / 1000.0);
    }

    return 0;
}
```

Surprisingly, the result is very bad in Windows 10 CU compared to Windows 7. I plotted the result below for 1MB chunk size and 8MB chunk size, varying the number of threads from 2,4,.., up to 28. While Windows 7 gave slightly worse performance when we increased the number of threads, Windows 10 gave much worse scalability.

We have tried to make sure all Windows update is applied, update drivers, tweak BIOS settings, without success. We also ran the same benchmark on several other hardware platforms, and all gave similar curve for Windows 10. So it seems to be a problem of Windows 10.

Does anyone have similar experience, or maybe know-how about this (maybe we missed something ?). This behavior has made our multithreaded application got significant performance hit.

*** EDITED

Using https://github.com/google/UIforETW (thanks to Bruce Dawson) to analyze the benchmark, we found that most of the time is spent inside kernels KiPageFault. Digging further down the call tree, all leads to ExpWaitForSpinLockExclusiveAndAcquire. Seems that the lock contention is causing this issue.

*** EDITED

Collected Server 2012 R2 data on the same hardware. Server 2012 R2 is also worse than Win7, but still a lot better than Win10 CU.

*** EDITED

It happens in Server 2016 as well. I added the tag windows-server-2016.

*** EDITED

Using info from @Ext3h, I modified the benchmark to use VirtualAlloc and VirtualLock. I can confirmed significant improvement compared to when VirtualLock is not used. Overall Win10 is still 30% to 40% slower than Win7 when both using VirtualAlloc and VirtualLock.

答:
Microsoft seems to have fixed this issue with Windows 10 Fall Creators Update and Windows 10 Pro for Workstation.

Here is the updated graph.

Win 10 FCU and WKS has lower overhead than Win 7. In exchange, the VirtualLock seems to have higher overhead.

Body:
We set up two identical HP Z840 Workstations with the following specs

2 x Xeon E5-2690 v4 @ 2.60GHz (Turbo Boost ON, HT OFF, total 28 logical CPUs)

32GB DDR4 2400 Memory, Quad-channel

and installed Windows 7 SP1 (x64) and Windows 10 Creators Update (x64) on each.

Then we ran a small memory benchmark (code below, built with VS2015 Update 3, 64-bit architecture) which performs memory allocation-fill-free simultaneously from multiple threads.

#include <Windows.h>
#include <vector>
#include <ppl.h>

unsigned __int64 ZQueryPerformanceCounter()
{
    unsigned __int64 c;
    ::QueryPerformanceCounter((LARGE_INTEGER *)&c);
    return c;
}

unsigned __int64 ZQueryPerformanceFrequency()
{
    unsigned __int64 c;
    ::QueryPerformanceFrequency((LARGE_INTEGER *)&c);
    return c;
}

class CZPerfCounter {
public:
    CZPerfCounter() : m_st(ZQueryPerformanceCounter()) {};
    void reset() { m_st = ZQueryPerformanceCounter(); };
    unsigned __int64 elapsedCount() { return ZQueryPerformanceCounter() - m_st; };
    unsigned long elapsedMS() { return (unsigned long)(elapsedCount() * 1000 / m_freq); };
    unsigned long elapsedMicroSec() { return (unsigned long)(elapsedCount() * 1000 * 1000 / m_freq); };
    static unsigned __int64 frequency() { return m_freq; };
private:
    unsigned __int64 m_st;
    static unsigned __int64 m_freq;
};

unsigned __int64 CZPerfCounter::m_freq = ZQueryPerformanceFrequency();

int main(int argc, char ** argv)
{
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    int ncpu = sysinfo.dwNumberOfProcessors;

    if (argc == 2) {
        ncpu = atoi(argv[1]);
    }

    {
        printf("No of threads %d\n", ncpu);

        try {
            concurrency::Scheduler::ResetDefaultSchedulerPolicy();
            int min_threads = 1;
            int max_threads = ncpu;
            concurrency::SchedulerPolicy policy
            (2 // two entries of policy settings
                , concurrency::MinConcurrency, min_threads
                , concurrency::MaxConcurrency, max_threads
            );
            concurrency::Scheduler::SetDefaultSchedulerPolicy(policy);
        }
        catch (concurrency::default_scheduler_exists &) {
            printf("Cannot set concurrency runtime scheduler policy (Default scheduler already exists).\n");
        }

        static int cnt = 100;
        static int num_fills = 1;
        CZPerfCounter pcTotal;

        // malloc/free
        printf("malloc/free\n");
        {
            CZPerfCounter pc;
            for (int i = 1 * 1024 * 1024; i <= 8 * 1024 * 1024; i *= 2) {
                concurrency::parallel_for(0, 50, [i](size_t x) {
                    std::vector<void *> ptrs;
                    ptrs.reserve(cnt);
                    for (int n = 0; n < cnt; n++) {
                        auto p = malloc(i);
                        ptrs.emplace_back(p);
                    }
                    for (int x = 0; x < num_fills; x++) {
                        for (auto p : ptrs) {
                            memset(p, num_fills, i);
                        }
                    }
                    for (auto p : ptrs) {
                        free(p);
                    }
                });
                printf("size %4d MB,  elapsed %8.2f s, \n", i / (1024 * 1024), pc.elapsedMS() / 1000.0);
                pc.reset();
            }
        }
        printf("\n");
        printf("Total %6.2f s\n", pcTotal.elapsedMS() / 1000.0);
    }

    return 0;
}

Surprisingly, the result is very bad in Windows 10 CU compared to Windows 7. I plotted the result below for 1MB chunk size and 8MB chunk size, varying the number of threads from 2,4,.., up to 28. While Windows 7 gave slightly worse performance when we increased the number of threads, Windows 10 gave much worse scalability.

We have tried to make sure all Windows update is applied, update drivers, tweak BIOS settings, without success. We also ran the same benchmark on several other hardware platforms, and all gave similar curve for Windows 10. So it seems to be a problem of Windows 10.

Does anyone have similar experience, or maybe know-how about this (maybe we missed something ?). This behavior has made our multithreaded application got significant performance hit.

*** EDITED

Using https://github.com/google/UIforETW (thanks to Bruce Dawson) to analyze the benchmark, we found that most of the time is spent inside kernels KiPageFault. Digging further down the call tree, all leads to ExpWaitForSpinLockExclusiveAndAcquire. Seems that the lock contention is causing this issue.

*** EDITED

Collected Server 2012 R2 data on the same hardware. Server 2012 R2 is also worse than Win7, but still a lot better than Win10 CU.

*** EDITED

It happens in Server 2016 as well. I added the tag windows-server-2016.

*** EDITED

Using info from @Ext3h, I modified the benchmark to use VirtualAlloc and VirtualLock. I can confirmed significant improvement compared to when VirtualLock is not used. Overall Win10 is still 30% to 40% slower than Win7 when both using VirtualAlloc and VirtualLock.


问:
PHP session variable not being stored all of the time
I'm trying to implement a post-redirect-get interface using PHP for a UWP app. Shown below is my actual PHP interface. If I access this PHP script via a web browser (Chrome), then a hashed variable is created and stored in $_SESSION. I can verify that this is working via another script that I wrote that prints out all stored session variables.

If I try to access this same script through my UWP app, then a hashed variable is not stored in $_SESSION. Thinking that I somehow botched my UWP code, I wiresharked the network transmissions, and I can see that a hashed variable is being returned in the 303 redirect, but that same variable is not being stored in $_SESSION. This script seems to only not store the variable when accessed via my UWP app. Why would that be?

```<code><?php
   include_once '/var/www/errLogger.php';
   include_once '/var/www/hasher.php';
   include_once '/var/www/jsonConverter.php';

   //Get JSON data
   try
   {
      $jsonArray = jsonToArray($_SERVER);
   } catch (Exception $ex)
   {
      echo logger((string)($ex->getLine()), $ex->getFile(), $ex->getMessage());
   }

   //Save JSON to session
   session_start();
   $hash_id = createRedirectHash();
   $_SESSION[$hash_id] = $jsonArray;

   //Generate URL for this post request
   $hashURL = "http://$_SERVER[HTTP_HOST]/php/redirectTest.php?hash=$hash_id";

   //Reply with 303 redirect - 303 is used so GET request can pull requested data
   header("HTTP/1.1 303 See Other");
   header("Location: {$hashURL}");
?>
</code>```

Below is some sample output from my script that prints the stored session variables....

```<code>Array (
     [92ed11ad76704bf1e4fafcc8b4393d36f7f42dcdf0c1b28acd8c66bbdc545cd9] => test
     [f4bdc2c305922e66790fae080587f54a169140f506734061ed4c23c285efa751] => test
     [48d4979004aba405020ee5148dab8823ce450b4cb741953df598061178504398] => )
</code>```

UPDATE: After further investigation, I've come to realize that a session is only saved when Chrome on a certain computer is used to access the php script. Accessing the script via Firefox or through Chrome on a different computer results in a session variable not being saved. I have even tried adding session_write_close(); to my script and have not yet seen any difference in behavior...

答:
Check the php.ini file.

; where MODE is the octal representation of the mode. Note that this
; does not overwrite the process's umask.
; http://php.net/session.save-path

session.save_path = "/tmp"

Body:
I'm trying to implement a post-redirect-get interface using PHP for a UWP app. Shown below is my actual PHP interface. If I access this PHP script via a web browser (Chrome), then a hashed variable is created and stored in $_SESSION. I can verify that this is working via another script that I wrote that prints out all stored session variables.

If I try to access this same script through my UWP app, then a hashed variable is not stored in $_SESSION. Thinking that I somehow botched my UWP code, I wiresharked the network transmissions, and I can see that a hashed variable is being returned in the 303 redirect, but that same variable is not being stored in $_SESSION. This script seems to only not store the variable when accessed via my UWP app. Why would that be?

<?php
   include_once '/var/www/errLogger.php';
   include_once '/var/www/hasher.php';
   include_once '/var/www/jsonConverter.php';

   //Get JSON data
   try
   {
      $jsonArray = jsonToArray($_SERVER);
   } catch (Exception $ex)
   {
      echo logger((string)($ex->getLine()), $ex->getFile(), $ex->getMessage());
   }

   //Save JSON to session
   session_start();
   $hash_id = createRedirectHash();
   $_SESSION[$hash_id] = $jsonArray;

   //Generate URL for this post request
   $hashURL = "http://$_SERVER[HTTP_HOST]/php/redirectTest.php?hash=$hash_id";

   //Reply with 303 redirect - 303 is used so GET request can pull requested data
   header("HTTP/1.1 303 See Other");
   header("Location: {$hashURL}");
?>

Below is some sample output from my script that prints the stored session variables....

Array (
     [92ed11ad76704bf1e4fafcc8b4393d36f7f42dcdf0c1b28acd8c66bbdc545cd9] => test
     [f4bdc2c305922e66790fae080587f54a169140f506734061ed4c23c285efa751] => test
     [48d4979004aba405020ee5148dab8823ce450b4cb741953df598061178504398] => )

UPDATE: After further investigation, I've come to realize that a session is only saved when Chrome on a certain computer is used to access the php script. Accessing the script via Firefox or through Chrome on a different computer results in a session variable not being saved. I have even tried adding session_write_close(); to my script and have not yet seen any difference in behavior...


问:
MSBuild 2008 stops on first error while building a solution
We recently upgraded from MSBuild 2005 to 2008. Since then MSBuild stops on the first error when building a solution. This wasn't the case in 2005.
Is there a way to get the old behavior?

EDIT: We call MSBuild form the command line:

```<code>MSBuild.exe xyz.sln /p:Platform=Win32 /p:Configuration=Debug
</code>```

答:
```<code><MSBuild Projects="@(Solution)" ContinueOnError="false" StopOnFirstFailure="true"></MSBuild>
</code>```

You have to change this on the script

OwnerDisplayName: rstevens

Body:
We recently upgraded from MSBuild 2005 to 2008. Since then MSBuild stops on the first error when building a solution. This wasn't the case in 2005.
Is there a way to get the old behavior?

EDIT: We call MSBuild form the command line:

MSBuild.exe xyz.sln /p:Platform=Win32 /p:Configuration=Debug

LastEditorDisplayName: moocha

Body:
<MSBuild Projects="@(Solution)" ContinueOnError="false" StopOnFirstFailure="true"></MSBuild>

You have to change this on the script

OwnerDisplayName: Mariano


问:
ASP.NET (C#) event to happen before printing
I have a web form in ASP.Net with C# code behind. It's a simple thing, and I'm pretty new so I'm kind of stuck.

In the source code of the web form I have a button called "print" that looks like this:

```<code><asp:Button ID="btnPrint" runat="server" onclientclick="window.print();" Text="Print" />
</code>```

No problem. In the code behind I have this:

```<code> protected void btnPrint_Click(object sender, EventArgs e)
{
    //get current Date/Time
    string dateTime = DateTime.Now.ToLongDateString() + ", at " + DateTime.Now.ToShortTimeString();

    //set it to labelDate
    lblDate.Text = "Requested on " + dateTime;

}
</code>```

So the problem is that when I hit the print button, the form prints before the code executes and stamps the label (lblDate.Text).

Soooo... my noob question is how to get that date/time stamp to process before the form prints?

Thanks for your advice.

Mark

答: My first instinct would be to ditch the server side event, and populate the time stamp with javascript before the print call.</p>

Body:
I have a web form in ASP.Net with C# code behind. It's a simple thing, and I'm pretty new so I'm kind of stuck.

In the source code of the web form I have a button called "print" that looks like this:

<asp:Button ID="btnPrint" runat="server" onclientclick="window.print();" Text="Print" />

No problem. In the code behind I have this:

 protected void btnPrint_Click(object sender, EventArgs e)
{
    //get current Date/Time
    string dateTime = DateTime.Now.ToLongDateString() + ", at " + DateTime.Now.ToShortTimeString();

    //set it to labelDate
    lblDate.Text = "Requested on " + dateTime;

}

So the problem is that when I hit the print button, the form prints before the code executes and stamps the label (lblDate.Text).

Soooo... my noob question is how to get that date/time stamp to process before the form prints?

Thanks for your advice.

Mark


问:
Non Clustered Columnstore Indexes and Primary/Foreign keys
Documentation says that we can't create nonclustered columnstore indexes in primary key or foreign key columns

https://learn.microsoft.com/en-us/sql/t-sql/statements/create-columnstore-index-transact-sql

"
A table with a nonclustered columnstore index can have unique constraints, primary key constraints, or foreign key constraints, but the constraints cannot be included in the nonclustered columnstore index.
"

but on my tests, It is working:

```<code>CREATE TABLE SimpleTable(
ProductKey [int] primary key,
OrderDateKey [int] NOT NULL,
DueDateKey [int] NOT NULL,
ShipDateKey [int] NOT NULL)

GO

insert into SimpleTable values (1,2,3,4)

CREATE nonclustered COLUMNSTORE INDEX IXTEST ON SimpleTable(ProductKey)
</code>```

What am I missing here? Is documentation correct?

Here is my SQL Server version

Microsoft SQL Server 2016 (SP1-CU4) (KB4024305) - 13.0.4446.0 (X64)   Jul 16 2017 18:08:49   Copyright (c) Microsoft Corporation  Developer Edition

Regards

答: I'm not sure on the significance of the statement, as the constraints will still exist on the table, but I imagine, purely based on the language, that what is being said is that the constraints cannot be included, but the columns can.

Body:
Documentation says that we can't create nonclustered columnstore indexes in primary key or foreign key columns

https://learn.microsoft.com/en-us/sql/t-sql/statements/create-columnstore-index-transact-sql

"
A table with a nonclustered columnstore index can have unique constraints, primary key constraints, or foreign key constraints, but the constraints cannot be included in the nonclustered columnstore index.
"

but on my tests, It is working:

CREATE TABLE SimpleTable(
ProductKey [int] primary key,
OrderDateKey [int] NOT NULL,
DueDateKey [int] NOT NULL,
ShipDateKey [int] NOT NULL)

GO

insert into SimpleTable values (1,2,3,4)

CREATE nonclustered COLUMNSTORE INDEX IXTEST ON SimpleTable(ProductKey)

What am I missing here? Is documentation correct?

Here is my SQL Server version

Microsoft SQL Server 2016 (SP1-CU4) (KB4024305) - 13.0.4446.0 (X64)   Jul 16 2017 18:08:49   Copyright (c) Microsoft Corporation  Developer Edition

Regards


问:
Go - How do I mock a dependency that takes a callback?
Suppose I have a dependency that looks like this:

```<code>type Dependency interface {
    Retrieve(transform func(row *Row) string) []string
}
</code>```

And I'm using it in code that I'd like to unit test

```<code>// ...
result := dep.Retrieve(func(row *Row) string {
    // ... do stuff
})
// ...
</code>```

This is a contrived example, but consider it for something like gcloud pubsub, which has a Receive method that calls a user-defined function for each message it pulls.

If I use mockgen to get a mock of Dependency, how do I tell the mock how to behave? I'd want it to call its input function some number of times with some sets of input.

答:
Here is some code while trying to understand what you wanted to achieve.
I don't use mockgen, but manually, you can do what you want. I totally changed the behavior between the original and the mocked call. Does it answer your questions?

```<code>package main

import (
    "fmt"
)

var str = [...]string{
    "world",
    "night",
}

type Dependency interface {
    Get(val string) string
}

type dependency struct {
    i int
}

func (d *dependency) Get(fn func(int) string) string {
    d.i++
    d.i = d.i % len(str)

    return "hello " + fn(d.i)
}

func main() {
    d := dependency{}
    myfn := func(idx int) string { return str[idx] }
    fmt.Println(d.Get(myfn))
    fmt.Println(d.Get(myfn))
    fmt.Println(d.Get(myfn))

    m := mock{}
    fmt.Println(m.Get(myfn))
}

type mock struct {
}

func (m *mock) Get(fn func(int) string) string {
    i := 0
    j := (i + 1) % len(str)
    k := (j + 1) % len(str)

    return "mocked " + fn(i) + fn(j) + fn(k)
}
</code>```

The play link:
https://play.golang.org/p/bb7WrmlIEN

Body:
Suppose I have a dependency that looks like this:

type Dependency interface {
    Retrieve(transform func(row *Row) string) []string
}

And I'm using it in code that I'd like to unit test

// ...
result := dep.Retrieve(func(row *Row) string {
    // ... do stuff
})
// ...

This is a contrived example, but consider it for something like gcloud pubsub, which has a Receive method that calls a user-defined function for each message it pulls.

If I use mockgen to get a mock of Dependency, how do I tell the mock how to behave? I'd want it to call its input function some number of times with some sets of input.

Body:
Here is some code while trying to understand what you wanted to achieve.
I don't use mockgen, but manually, you can do what you want. I totally changed the behavior between the original and the mocked call. Does it answer your questions?

package main

import (
    "fmt"
)

var str = [...]string{
    "world",
    "night",
}

type Dependency interface {
    Get(val string) string
}

type dependency struct {
    i int
}

func (d *dependency) Get(fn func(int) string) string {
    d.i++
    d.i = d.i % len(str)

    return "hello " + fn(d.i)
}

func main() {
    d := dependency{}
    myfn := func(idx int) string { return str[idx] }
    fmt.Println(d.Get(myfn))
    fmt.Println(d.Get(myfn))
    fmt.Println(d.Get(myfn))

    m := mock{}
    fmt.Println(m.Get(myfn))
}

type mock struct {
}

func (m *mock) Get(fn func(int) string) string {
    i := 0
    j := (i + 1) % len(str)
    k := (j + 1) % len(str)

    return "mocked " + fn(i) + fn(j) + fn(k)
}

The play link:
https://play.golang.org/p/bb7WrmlIEN


Title: add_trace in Plotly in a loop

Body:
I want to plot multiple traces in a loop without overwriting all previous traces.

In this post from 2015, a solution to adding traces within a loop is presented, by setting evaluate = TRUE in the plot_ly or add_trace functions. However, as of 2017 in the newer version of plot_ly, evaluate isn't an attribute.

'scatter3d' objects don't have these attributes: 'evaluate'

This question, and this question also fail to answer the problem. This post acknowledges that evaluate = TRUE isn't doesn't work with new plotly, but doesn't give a solution. What is the new solution to this problem?

My data for copy/paste:

structure(list(x_1 = c(74.651438, 75.31493, 76.736865, 77.858125,
79.347856, 80.302483), y_1 = c(249.063605, 247.149121, 245.461889,
243.811041, 242.382685, 240.300034), z_1 = c(4.373868, 3.653744,
4.101455, 4.134471, 4.225507, 4.890157), x_2 = c(85.468712, 86.637469,
87.993127, 87.907308, 88.748766, 89.680155), y_2 = c(249.063405,
247.145423, 245.46148, 244.949469, 244.005001, 242.917665), z_2 = c(4.56633,
4.059976, 3.842906, 4.019021, 4.316799, 4.378894), x_3 = c(101.720648,
101.70598, 102.022836, 102.166059, 102.242424, 102.317043), y_3 = c(249.660075,
249.562464, 249.771452, 249.619983, 249.39349, 249.444531), z_3 = c(3.080686,
3.003508, 2.774651, 2.291644, 2.239727, 1.932501)), .Names = c("x_1",
"y_1", "z_1", "x_2", "y_2", "z_2", "x_3", "y_3", "z_3"), row.names = c(NA,
6L), class = "data.frame")

My code:

library(plotly)
p <- plot_ly(temp, type = 'scatter3d', mode = 'lines', width = 1)
for(i in 1:3){
  x = paste0("x_",i)
  y = paste0("y_",i)
  z = paste0("z_",i)
  p <- add_trace(p, x = ~get(x), y = ~get(y), z = ~get(z))
}

p

Body:
You could start with an empty Plotly object and then add the traces sequentially.

library(plotly)

temp <- structure(list(x_1 = c(74.651438, 75.31493, 76.736865, 77.858125,
                       79.347856, 80.302483), y_1 = c(249.063605, 247.149121, 245.461889,
                                                      243.811041, 242.382685, 240.300034), z_1 = c(4.373868, 3.653744,
                                                                                4.101455, 4.134471, 4.225507, 4.890157), x_2 = c(85.468712, 86.637469,
                                                                                87.993127, 87.907308, 88.748766, 89.680155), y_2 = c(249.063405,
                                                                                247.145423, 245.46148, 244.949469, 244.005001, 242.917665), z_2 = c(4.56633,
                                                                                4.059976, 3.842906, 4.019021, 4.316799, 4.378894), x_3 = c(101.720648,
                                                                                101.70598, 102.022836, 102.166059, 102.242424, 102.317043), y_3 = c(249.660075,
                                                                                249.562464, 249.771452, 249.619983, 249.39349, 249.444531), z_3 = c(3.080686,
                                                                                3.003508, 2.774651, 2.291644, 2.239727, 1.932501)), .Names = c("x_1",
                                                                                "y_1", "z_1", "x_2", "y_2", "z_2", "x_3", "y_3", "z_3"), row.names = c(NA,
                                                                                6L), class = "data.frame")

p <- plot_ly()
for(i in 1:3){
  x = paste0("x_",i)
  y = paste0("y_",i)
  z = paste0("z_",i)
  p <- add_trace(p,
                 x = temp[[x]],
                 y = temp[[y]],
                 z = temp[[z]],
                 type = 'scatter3d',
                 mode = 'lines',
                 line = list(width = 1))
}

p