问:
Need to detect whether jQuery is triggered in normal or multiselect combobox
I have some jQuery code that allows me to select multiple entries in a multiselect combobox without the need to press the Ctrl key.

This works, but interferes with a normal select box, which can now not be changed with the mouse.

The original jQuery code is:

```<code>(function ($) {
$(document).ready(function () {
    $("option").mousedown(function(e) {
      this.selected = ! this.selected;
      e.preventDefault();
      return false;
    });
});
})(jQuery);
</code>```

Of course, the $("option") selector applies to the normal select box as well, which is why it fails.

I tried to detect whether the event is triggered by a select box with the "multiple" attribute, but couldn't figure out how. The following doesn't work for various reasons, one of them being that the event is triggered by the option, not the select:

```<code>(function ($) {
$(document).ready(function () {
    $("option").mousedown(function(e) {
        if($(this).attr('multiple','multiple')) {
          this.selected = ! this.selected;
          e.preventDefault();
          return false;
        }
        else {
          return true;
        }
    });
});
})(jQuery);
</code>```

Any ideas of how this could be done?

Ah, I don't want to include the ID of the multiselect, because the same code is also used by another multiselect in my real-world case.

Here is a fiddle:
https://jsfiddle.net/mheumann/3zn76mex/

答:
Give all the multiselect elements to which you want to apply this behavior a new CSS class -- perhaps custom-multiselect.

Then you can use a compound selector like .custom-multiselect option in the code you have...

```<code>(function ($) {
  $(document).ready(function () {
    $(".custom-multiselect option").mousedown(function(e) {
      this.selected = ! this.selected;
      e.preventDefault();
      return false;
    });
  });
})(jQuery);
</code>```

Body:
I have some jQuery code that allows me to select multiple entries in a multiselect combobox without the need to press the Ctrl key.

This works, but interferes with a normal select box, which can now not be changed with the mouse.

The original jQuery code is:

(function ($) {
$(document).ready(function () {
    $("option").mousedown(function(e) {
      this.selected = ! this.selected;
      e.preventDefault();
      return false;
    });
});
})(jQuery);

Of course, the $("option") selector applies to the normal select box as well, which is why it fails.

I tried to detect whether the event is triggered by a select box with the "multiple" attribute, but couldn't figure out how. The following doesn't work for various reasons, one of them being that the event is triggered by the option, not the select:

(function ($) {
$(document).ready(function () {
    $("option").mousedown(function(e) {
        if($(this).attr('multiple','multiple')) {
          this.selected = ! this.selected;
          e.preventDefault();
          return false;
        }
        else {
          return true;
        }
    });
});
})(jQuery);

Any ideas of how this could be done?

Ah, I don't want to include the ID of the multiselect, because the same code is also used by another multiselect in my real-world case.

Here is a fiddle:
https://jsfiddle.net/mheumann/3zn76mex/

Body:
Give all the multiselect elements to which you want to apply this behavior a new CSS class -- perhaps custom-multiselect.

Then you can use a compound selector like .custom-multiselect option in the code you have...

(function ($) {
  $(document).ready(function () {
    $(".custom-multiselect option").mousedown(function(e) {
      this.selected = ! this.selected;
      e.preventDefault();
      return false;
    });
  });
})(jQuery);


来源: stackexchange

问:
When is pointer to array useful?
I can declare:

int (*ap)[N];

So ap is pointer to int array of size N. Why is this ever useful? If I pass it to function, what useful thing it can do with it that it could not do with just a normal pointer to the array's contents?

C FAQ say:

2.12: How do I declare a pointer to an array?

Usually, you don't want to.

答:
Following code is a part of my article  : Pointers and Arrays in C C++

You can check it out @ http://pointersandarrays.blogspot.com/

Pointers and 2D Arrays

Following code snippet illustrates how  to declare and access a 2D array. Underneath 2D Array lies a single dimensional array. You will get be sure of this after playing with the following piece of code.

Code Snippet #4

```<code>
 #include<iostream&rt;
    using namespace std;

    int main()
    {
     cout<< "Understanding Pointers and 2 D Arrays"<<endl;
     cout<< "----------------------\n"<<endl;

    //Declaration of a 2D Array.
    int tab[3][5];
    //Total space required : 3*5 * sizeof(int) = 15 * sizeof(int)
    //Funda : Since the amount of required space is known by compiler, contiguous 15 memory cells are allocated here.
    //Hence the case is similar to a 1 D Array of size 15. Lets try this out!

    //Array initialization using array name
    for(int i=0; i<3;i++)
     for(int j=0; j<5;j++)
       tab[i][j]=i+2*j;

    //Print array using array name
    cout << "\nPrint array using array name ..."<<endl;
    for(int i=0; i<3;i++)
     {
      for(int j=0; j<5;j++)
       printf("%2d ",tab[i][j] );
      printf("\n");
     }

    //Print array using a pointer. Proof of 1 D array being allocated
    cout << "\nPrint array using a pointer. Proof of 1 D array being allocated ..." << endl;
    int *tptr;
    tptr = &tab[0][0]; // pointer tptr points at first element of the array.

    for(int i=0; i<15;i++)
     printf("%d ",*(tptr+i) );
    tptr = &tab[0][0];
    cout << "\nNotice that array is printed row by row in a linear fashion."<<endl;
     return 0;
    }

</code>```

Output #4:

```<code>Understanding Pointers and 2D Arrays

Print array using array name ...
 0  2  4  6  8
 1  3  5  7  9
 2  4  6  8 10

Print array using a pointer. Proof of 1 D array being allocated ...
0 2 4 6 8 1 3 5 7 9 2 4 6 8 10
Notice that array is printed row by row in a linear fashion.
</code>```

ContentLicense: CC BY-SA 2.5

Title: When is pointer to array useful?

Body:
Following code is a part of my article  : Pointers and Arrays in C C++

You can check it out @ http://pointersandarrays.blogspot.com/

Pointers and 2D Arrays

Following code snippet illustrates how  to declare and access a 2D array. Underneath 2D Array lies a single dimensional array. You will get be sure of this after playing with the following piece of code.

Code Snippet #4

 #include<iostream&rt;
    using namespace std;

    int main()
    {
     cout<< "Understanding Pointers and 2 D Arrays"<<endl;
     cout<< "----------------------\n"<<endl;

    //Declaration of a 2D Array.
    int tab[3][5];
    //Total space required : 3*5 * sizeof(int) = 15 * sizeof(int)
    //Funda : Since the amount of required space is known by compiler, contiguous 15 memory cells are allocated here.
    //Hence the case is similar to a 1 D Array of size 15. Lets try this out!

    //Array initialization using array name
    for(int i=0; i<3;i++)
     for(int j=0; j<5;j++)
       tab[i][j]=i+2*j;

    //Print array using array name
    cout << "\nPrint array using array name ..."<<endl;
    for(int i=0; i<3;i++)
     {
      for(int j=0; j<5;j++)
       printf("%2d ",tab[i][j] );
      printf("\n");
     }

    //Print array using a pointer. Proof of 1 D array being allocated
    cout << "\nPrint array using a pointer. Proof of 1 D array being allocated ..." << endl;
    int *tptr;
    tptr = &tab[0][0]; // pointer tptr points at first element of the array.

    for(int i=0; i<15;i++)
     printf("%d ",*(tptr+i) );
    tptr = &tab[0][0];
    cout << "\nNotice that array is printed row by row in a linear fashion."<<endl;
     return 0;
    }

Output #4:

Understanding Pointers and 2D Arrays

Print array using array name ...
 0  2  4  6  8
 1  3  5  7  9
 2  4  6  8 10

Print array using a pointer. Proof of 1 D array being allocated ...
0 2 4 6 8 1 3 5 7 9 2 4 6 8 10
Notice that array is printed row by row in a linear fashion.


问:
Quasar NPE when passing a Kotlin Lambda to a Corda Flow
When passing a lambda to the CollectSignaturesFlow Quasar crashes silently and is unable to continue processing. The issue is with others.map { initiateFlow(it as Party) }.toSet(). Moving this outside and establishing the set as a local variable resolves the issue.

Is there a set of known issues around what can and cannot be serialized with Quasar?

```<code>@InitiatingFlow
@StartableByRPC
class IOUIssueFlow(val state: IOUState) : FlowLogic<SignedTransaction>() {
   @Suspendable
   override fun call(): SignedTransaction {
       val txCommand = Command(
               IOUContract.Commands.Issue(),
               state.participants.map { it.owningKey })
       val builder = TransactionBuilder(serviceHub.networkMapCache.notaryIdentities.first())
               .withItems(
                       StateAndContract(
                               state,
                               IOUContract.IOU_CONTRACT_ID),
                       txCommand)
       builder.verify(serviceHub)
       val others = state.participants - ourIdentity
       return subFlow(
               FinalityFlow(
                       subFlow(
                               CollectSignaturesFlow(
                                       serviceHub.signInitialTransaction(builder),
                                       others.map { initiateFlow(it as Party) }.toSet()))))
   }
}
</code>```

The code will run indefinitely without end and produces this warning:

```<code>[WARN ] 16:38:13,655 [Mock network] (FlowStateMachineImpl.kt:127) flow.[49f2ebbd-be62-462d-af87-24f5ae40c7d6].run - Terminated by unexpected exception
java.lang.NullPointerException: null
    at net.corda.node.services.statemachine.FlowStateMachineImpl.suspend(FlowStateMachineImpl.kt:468) ~[corda-node-1.0.0.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.sendInternal(FlowStateMachineImpl.kt:332) ~[corda-node-1.0.0.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.initiateSession(FlowStateMachineImpl.kt:396) ~[corda-node-1.0.0.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.sendAndReceive(FlowStateMachineImpl.kt:200) ~[corda-node-1.0.0.jar:?]
    at net.corda.core.internal.FlowStateMachine$DefaultImpls.sendAndReceive$default(FlowStateMachine.kt:27) ~[corda-core-1.0.0.jar:?]
    at net.corda.node.services.statemachine.FlowSessionImpl.sendAndReceive(FlowSessionImpl.kt:25) ~[corda-node-1.0.0.jar:?]
    at net.corda.core.flows.DataVendingFlow.sendPayloadAndReceiveDataRequest(SendTransactionFlow.kt:70) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.DataVendingFlow.call(SendTransactionFlow.kt:48) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.DataVendingFlow.call(SendTransactionFlow.kt:31) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.FlowLogic.subFlow(FlowLogic.kt:212) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.CollectSignatureFlow.call(CollectSignaturesFlow.kt:140) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.CollectSignatureFlow.call(CollectSignaturesFlow.kt:134) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.FlowLogic.subFlow(FlowLogic.kt:212) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.CollectSignaturesFlow.call(CollectSignaturesFlow.kt:113) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.CollectSignaturesFlow.call(CollectSignaturesFlow.kt:64) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.FlowLogic.subFlow(FlowLogic.kt:212) ~[corda-core-1.0.0.jar:?]
    at net.corda.training.flow.IOUIssueFlow.call(IOUIssueFlow.kt:39) ~[classes/:?]
    at net.corda.training.flow.IOUIssueFlow.call(IOUIssueFlow.kt:22) ~[classes/:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:112) [corda-node-1.0.0.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:40) [corda-node-1.0.0.jar:?]
    at co.paralleluniverse.fibers.Fiber.run1(Fiber.java:1092) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at co.paralleluniverse.fibers.Fiber.exec(Fiber.java:788) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at co.paralleluniverse.fibers.RunnableFiberTask.doExec(RunnableFiberTask.java:100) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at co.paralleluniverse.fibers.RunnableFiberTask.run(RunnableFiberTask.java:91) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_151]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_151]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [?:1.8.0_151]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [?:1.8.0_151]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_151]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_151]
    at net.corda.node.utilities.AffinityExecutor$ServiceAffinityExecutor$1$thread$1.run(AffinityExecutor.kt:69) [corda-node-1.0.0.jar:?]
[WARN ] 16:38:13,670 [Mock network] (StateMachineManager.kt:93) flow.[49f2ebbd-be62-462d-af87-24f5ae40c7d6].uncaughtException - Caught exception from flow
java.lang.IllegalStateException: No transaction in context
</code>```

.

答:
The issue is that the lambda captures a reference to the entire stack. If you try to suspend the flow at this point, it will attempt to serialise the entire stack via the lambda, and the suspension of the flow will fail.

The solution is to create a local variable, or to use the lambda inside a function. The lambda will then be discarded from the stack when the function returns, so there will be no issue at suspension time.

ContentLicense: CC BY-SA 3.0

Body:
When passing a lambda to the CollectSignaturesFlow Quasar crashes silently and is unable to continue processing. The issue is with others.map { initiateFlow(it as Party) }.toSet(). Moving this outside and establishing the set as a local variable resolves the issue.

Is there a set of known issues around what can and cannot be serialized with Quasar?

@InitiatingFlow
@StartableByRPC
class IOUIssueFlow(val state: IOUState) : FlowLogic<SignedTransaction>() {
   @Suspendable
   override fun call(): SignedTransaction {
       val txCommand = Command(
               IOUContract.Commands.Issue(),
               state.participants.map { it.owningKey })
       val builder = TransactionBuilder(serviceHub.networkMapCache.notaryIdentities.first())
               .withItems(
                       StateAndContract(
                               state,
                               IOUContract.IOU_CONTRACT_ID),
                       txCommand)
       builder.verify(serviceHub)
       val others = state.participants - ourIdentity
       return subFlow(
               FinalityFlow(
                       subFlow(
                               CollectSignaturesFlow(
                                       serviceHub.signInitialTransaction(builder),
                                       others.map { initiateFlow(it as Party) }.toSet()))))
   }
}

The code will run indefinitely without end and produces this warning:

[WARN ] 16:38:13,655 [Mock network] (FlowStateMachineImpl.kt:127) flow.[49f2ebbd-be62-462d-af87-24f5ae40c7d6].run - Terminated by unexpected exception
java.lang.NullPointerException: null
    at net.corda.node.services.statemachine.FlowStateMachineImpl.suspend(FlowStateMachineImpl.kt:468) ~[corda-node-1.0.0.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.sendInternal(FlowStateMachineImpl.kt:332) ~[corda-node-1.0.0.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.initiateSession(FlowStateMachineImpl.kt:396) ~[corda-node-1.0.0.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.sendAndReceive(FlowStateMachineImpl.kt:200) ~[corda-node-1.0.0.jar:?]
    at net.corda.core.internal.FlowStateMachine$DefaultImpls.sendAndReceive$default(FlowStateMachine.kt:27) ~[corda-core-1.0.0.jar:?]
    at net.corda.node.services.statemachine.FlowSessionImpl.sendAndReceive(FlowSessionImpl.kt:25) ~[corda-node-1.0.0.jar:?]
    at net.corda.core.flows.DataVendingFlow.sendPayloadAndReceiveDataRequest(SendTransactionFlow.kt:70) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.DataVendingFlow.call(SendTransactionFlow.kt:48) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.DataVendingFlow.call(SendTransactionFlow.kt:31) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.FlowLogic.subFlow(FlowLogic.kt:212) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.CollectSignatureFlow.call(CollectSignaturesFlow.kt:140) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.CollectSignatureFlow.call(CollectSignaturesFlow.kt:134) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.FlowLogic.subFlow(FlowLogic.kt:212) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.CollectSignaturesFlow.call(CollectSignaturesFlow.kt:113) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.CollectSignaturesFlow.call(CollectSignaturesFlow.kt:64) ~[corda-core-1.0.0.jar:?]
    at net.corda.core.flows.FlowLogic.subFlow(FlowLogic.kt:212) ~[corda-core-1.0.0.jar:?]
    at net.corda.training.flow.IOUIssueFlow.call(IOUIssueFlow.kt:39) ~[classes/:?]
    at net.corda.training.flow.IOUIssueFlow.call(IOUIssueFlow.kt:22) ~[classes/:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:112) [corda-node-1.0.0.jar:?]
    at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:40) [corda-node-1.0.0.jar:?]
    at co.paralleluniverse.fibers.Fiber.run1(Fiber.java:1092) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at co.paralleluniverse.fibers.Fiber.exec(Fiber.java:788) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at co.paralleluniverse.fibers.RunnableFiberTask.doExec(RunnableFiberTask.java:100) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at co.paralleluniverse.fibers.RunnableFiberTask.run(RunnableFiberTask.java:91) [quasar-core-0.7.9-jdk8.jar:0.7.9]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_151]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_151]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [?:1.8.0_151]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [?:1.8.0_151]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_151]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_151]
    at net.corda.node.utilities.AffinityExecutor$ServiceAffinityExecutor$1$thread$1.run(AffinityExecutor.kt:69) [corda-node-1.0.0.jar:?]
[WARN ] 16:38:13,670 [Mock network] (StateMachineManager.kt:93) flow.[49f2ebbd-be62-462d-af87-24f5ae40c7d6].uncaughtException - Caught exception from flow
java.lang.IllegalStateException: No transaction in context

.


问:
Reshaping a broadcasted expression
I would like to make the following broadcasted expression work:

```<code>J = rand(4,4)
fx1 = rand(2,2)
fx2 = rand(2,2)
@. J[:,1] = fx1 + fx2
</code>```

I really want some kind of:

```<code>@. J[:,1] = vec(fx1 + fx2)
</code>```

where this vec is saying it should reshape to be 4x1, but I don't want to have to make this allocating. How could this be generically handled (i.e. no indexing on the fx)?

答:
Another possibility, is instead of vec-ing the fx1 and fx2 to reshape the slice of J:

```<code>Jcol = reshape(view(J,:,1),(2,2))
@. Jcol = fx1 + fx2
</code>```

Not sure about efficiency, but it may give a clearer perspective depending on the surrounding algorithm. The LLVM code seems short enough and the assignment statement is clear.

Title: Reshaping a broadcasted expression

Body:
I would like to make the following broadcasted expression work:

J = rand(4,4)
fx1 = rand(2,2)
fx2 = rand(2,2)
@. J[:,1] = fx1 + fx2

I really want some kind of:

@. J[:,1] = vec(fx1 + fx2)

where this vec is saying it should reshape to be 4x1, but I don't want to have to make this allocating. How could this be generically handled (i.e. no indexing on the fx)?

Body:
Another possibility, is instead of vec-ing the fx1 and fx2 to reshape the slice of J:

Jcol = reshape(view(J,:,1),(2,2))
@. Jcol = fx1 + fx2

Not sure about efficiency, but it may give a clearer perspective depending on the surrounding algorithm. The LLVM code seems short enough and the assignment statement is clear.


问:
Selecting an html element that is loaded after documents loads, using selenium find element by xpath to select the element
How my web application works:

My web application loads a div with radio button input elements after conditions in the form above are changed. The form above will allow the manager to select a date and time. The div below will load with all the employees available at that date and time. I give this div the id "EmployeeListBox". Everytime conditions change in the form above the EmployeeListBox gets radio buttons injected using jquery's append method.

Okay so that's the idea of how my web application works. What I am trying to do is click the first radio button in the div EmployeeListBox after the form gets changed, using selenium web driver for Firefox in java. This is the line that I need to fix:

```<code>`driver.findElement(By.xpath("//[@id="EmployeeCell"]/span[2]/input")).click();`
</code>```

When I run this xpath I recive this error:
    Exception processing script - Element not found in the cache - perhaps the page has changed since it was looked up.
 I guess the xpaths I have tried do not work because the elements are dynamically loaded.

Here is the JS code that loads the EmployeeListBox.

```<code>AvialableStaff = JSON.parse( data );
var MSG = "";
$('#EmployeeListBox').empty();
/*for each employee in AvialableStaff load the #CreateShiftLifeOfEmployees Select option*/
var eico = 0;
for (   var Staff in AvialableStaff )
{
    var ID = AvialableStaff[Staff]["employeeID"];
    var name = AvialableStaff[Staff]["Firstname"]+" "+ AvialableStaff[Staff]["Lastname"];
    MSG += "<div id = \"EmployeeCell\">";
    MSG += "<span class = \"MakeLeft\" id = \"EI"+eico+"\" > "+name+" </span>";
    MSG += "<span class = \"MakeRight\"><input type = \"radio\" name=\"ChooseStaff\" value = \""+ID+"\" class = \"CSTAFFradioButtons\" />    </span>";
    MSG += "</div>";
    eico++;
}
$('#EmployeeListBox').append( MSG );
</code>```

Here is my EmployeeListBox without the employee cells:

```<code>        <p>Select an available employee</p>
        <div id = "CSEmployeeList" >
            <div id = "StaffAvaileP"> <h3> Staff Available</h3> </div>
            <div id = "EmployeeListBox">
                <!-- Radio Buttons go here -->

            </div>
        </div>
</code>```

This is what the employee box looks like after the form has been changed and employee radio buttons have been inserted:

```<code><div id="EmployeeListBox">

    <div id="EmployeeCell">
        <span class="MakeLeft" id="EI0"> Person One </span>
        <span class="MakeRight">
            <input type="radio" name="ChooseStaff" value="9" class="CSTAFFradioButtons">
        </span>
    </div>

    <div id="EmployeeCell">
        <span class="MakeLeft" id="EI1"> Person Two </span>
        <span class="MakeRight">
            <input type="radio" name="ChooseStaff" value="10" class="CSTAFFradioButtons">
        </span>
    </div>

    <div id="EmployeeCell">
        <span class="MakeLeft" id="EI2"> Person Three </span>
        <span class="MakeRight">
            <input type="radio" name="ChooseStaff" value="11" class="CSTAFFradioButtons">
        </span>
    </div>

</div><!--End of EmployeeListBox -->
</code>```

Here is my java method which runs the test:

```<code>/** Method testCreateShifts
 *      purpose: Loads shifts with realistic shift data like the
 *               real life Saturday schedule.
 */
public static void testCreateShifts()
{
    driver.get(theurl);
    String createshiftPage = "https://***/index.php?/CreateAShift";
    driver.get(createshiftPage);
    new Select(driver.findElement(By.id("Day"))).selectByVisibleText("11");
    new Select(driver.findElement(By.id("StartTime"))).selectByVisibleText("8:30am");
    new Select(driver.findElement(By.id("EndTime"))).selectByVisibleText("2:00pm");
    driver.findElement(By.id("Instructor")).click();

    /*TODO: Currently trying to click on first employee in employee list box*/
    driver.findElement(By.xpath("//*[@id=\"EmployeeCell\"]/span[2]/input")).click();

    driver.findElement(By.id("CreateShiftSubmit")).click();
}/*End of Method testCreateShifts*/
</code>```

So using selenium in java how do I click first radio button that is in the list after the EmployeeListBox gets reloaded by jquery?

答:
I found out what was wrong. I needed to give my webapplication time to load.
I told my java test to wait 1 second with this line.</p>

```<code>try {Thread.sleep(2000);}catch (InterruptedException ex) {  }
</code>```

Body:
How my web application works:

My web application loads a div with radio button input elements after conditions in the form above are changed. The form above will allow the manager to select a date and time. The div below will load with all the employees available at that date and time. I give this div the id "EmployeeListBox". Everytime conditions change in the form above the EmployeeListBox gets radio buttons injected using jquery's append method.

Okay so that's the idea of how my web application works. What I am trying to do is click the first radio button in the div EmployeeListBox after the form gets changed, using selenium web driver for Firefox in java. This is the line that I need to fix:

`driver.findElement(By.xpath("//[@id="EmployeeCell"]/span[2]/input")).click();`

When I run this xpath I recive this error:
    Exception processing script - Element not found in the cache - perhaps the page has changed since it was looked up.
 I guess the xpaths I have tried do not work because the elements are dynamically loaded.

Here is the JS code that loads the EmployeeListBox.

AvialableStaff = JSON.parse( data );
var MSG = "";
$('#EmployeeListBox').empty();
/*for each employee in AvialableStaff load the #CreateShiftLifeOfEmployees Select option*/
var eico = 0;
for (   var Staff in AvialableStaff )
{
    var ID = AvialableStaff[Staff]["employeeID"];
    var name = AvialableStaff[Staff]["Firstname"]+" "+ AvialableStaff[Staff]["Lastname"];
    MSG += "
";
    MSG += " "+name+" ";
    MSG += "<input type = \"radio\" name=\"ChooseStaff\" value = \""+ID+"\" class = \"CSTAFFradioButtons\" />    ";
    MSG += "
";
    eico++;
}
$('#EmployeeListBox').append( MSG );

Here is my EmployeeListBox without the employee cells:

Select an available employee

 Staff Available

This is what the employee box looks like after the form has been changed and employee radio buttons have been inserted:

         Person One

            <input type="radio" name="ChooseStaff" value="9" class="CSTAFFradioButtons">

         Person Two

            <input type="radio" name="ChooseStaff" value="10" class="CSTAFFradioButtons">

         Person Three

            <input type="radio" name="ChooseStaff" value="11" class="CSTAFFradioButtons">

Here is my java method which runs the test:

/** Method testCreateShifts
 *      purpose: Loads shifts with realistic shift data like the
 *               real life Saturday schedule.
 */
public static void testCreateShifts()
{
    driver.get(theurl);
    String createshiftPage = "https://***/index.php?/CreateAShift";
    driver.get(createshiftPage);
    new Select(driver.findElement(By.id("Day"))).selectByVisibleText("11");
    new Select(driver.findElement(By.id("StartTime"))).selectByVisibleText("8:30am");
    new Select(driver.findElement(By.id("EndTime"))).selectByVisibleText("2:00pm");
    driver.findElement(By.id("Instructor")).click();

    /*TODO: Currently trying to click on first employee in employee list box*/
    driver.findElement(By.xpath("//*[@id=\"EmployeeCell\"]/span[2]/input")).click();

    driver.findElement(By.id("CreateShiftSubmit")).click();
}/*End of Method testCreateShifts*/

So using selenium in java how do I click first radio button that is in the list after the EmployeeListBox gets reloaded by jquery?

Body:
I found out what was wrong. I needed to give my webapplication time to load.
I told my java test to wait 1 second with this line.

try {Thread.sleep(2000);}catch (InterruptedException ex) {  }


问:
force horizontal scrollbar on JScrollPane in grid bag layout
I have a swing JPanel using a GridBagLayout with a JLabel (image) and a JList inside a JScrollPane each taking 50% of the width.

This works well, except when I add a really long string to the JList.
Then instead of scrolling horizontally, the JScrollPane takes all of the area of the JPanel leaving a tiny image in the JLabel.

Odd thing is if I resize the window to smaller than the width of the long string, then it starts using the horizontal scroll and goes back to 50%/50% width.

How can I force the JList to always use the scroll and only take 50% of the width?

(must use GridBagLayout)

hacks welcome,

答:
I ended up fixing this by setting a very small preferedSize on the scrollpane.
This seems to make it use the scroll bar for some reason and remain at 50% of the width.</p>

```<code>JScrollPane scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(40, 40));
JList list = new JList();
scroll.setViewportView(list);
parent.add(scroll, new GridBagConstraints(x,y,1,1, xWeight,yWeight, GridBagConstraints.CENTER,GridBagConstraints.BOTH, insets, 0,0));
</code>```

Body:
I ended up fixing this by setting a very small preferedSize on the scrollpane.
This seems to make it use the scroll bar for some reason and remain at 50% of the width.

JScrollPane scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(40, 40));
JList list = new JList();
scroll.setViewportView(list);
parent.add(scroll, new GridBagConstraints(x,y,1,1, xWeight,yWeight, GridBagConstraints.CENTER,GridBagConstraints.BOTH, insets, 0,0));


问:
Using mySQL Server (Xampp) and SQL Server on the same machine
I have been using Xampp to test my website stuff and everything was working perfectly until I decided to install Microsoft SQL SERVER 2017 to do some data science stuff (school stuff).

Now I can still start Apache but I cant start MySQL. Here is the log :

```<code>2015-11-10 15:26:56 10fc InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
2015-11-10 15:26:56 4348 [Note] InnoDB: Using mutexes to ref count buffer pool pages
2015-11-10 15:26:56 4348 [Note] InnoDB: The InnoDB memory heap is disabled
2015-11-10 15:26:56 4348 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2015-11-10 15:26:56 4348 [Note] InnoDB: Memory barrier is not used
2015-11-10 15:26:56 4348 [Note] InnoDB: Compressed tables use zlib 1.2.3
2015-11-10 15:26:56 4348 [Note] InnoDB: Not using CPU crc32 instructions
2015-11-10 15:26:56 4348 [Note] InnoDB: Initializing buffer pool, size = 16.0M
2015-11-10 15:26:56 4348 [Note] InnoDB: Completed initialization of buffer pool
2015-11-10 15:26:56 4348 [Note] InnoDB: Highest supported file format is Barracuda.
2015-11-10 15:26:57 4348 [Note] InnoDB: 128 rollback segment(s) are active.
2015-11-10 15:26:57 4348 [Note] InnoDB: Waiting for purge to start
2015-11-10 15:26:57 4348 [Note] InnoDB:  Percona XtraDB (http://www.percona.com) 5.6.26-74.0 started; log sequence number 1835027
2015-11-10 15:26:57 6140 [Note] InnoDB: Dumping buffer pool(s) not yet started
2015-11-10 15:26:57 4348 [Note] Plugin 'FEEDBACK' is disabled.
2015-11-10 15:26:57 4348 [Note] Server socket created on IP: '::'.
2015-11-10 15:26:57 4348 [Note] Event Scheduler: Loaded 0 events
2015-11-10 15:26:57 4348 [Note] C:\xampp\mysql\bin\mysqld.exe: ready for connections.
Version: '10.1.8-MariaDB'  socket: ''  port: 3306  mariadb.org binary distribution
2015-11-10 15:27:11 5152 [Note] C:\xampp\mysql\bin\mysqld.exe: Normal shutdown

2015-11-10 15:27:11 5152 [Note] Event Scheduler: Purging the queue. 0 events
2015-11-10 15:27:11 5732 [Note] InnoDB: FTS optimize thread exiting.
2015-11-10 15:27:11 5152 [Note] InnoDB: Starting shutdown...
2015-11-10 15:27:13 5152 [Note] InnoDB: Shutdown completed; log sequence number 1835037
2015-11-10 15:27:13 5152 [Note] C:\xampp\mysql\bin\mysqld.exe: Shutdown complete

2017-11-17 13:40:05 33f8 InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
2017-11-17 13:40:05 13304 [Note] InnoDB: innodb_empty_free_list_algorithm has been changed to legacy because of small buffer pool size. In order to use backoff, increase buffer pool at least up to 20MB.

2017-11-17 13:40:05 13304 [Note] InnoDB: Using mutexes to ref count buffer pool pages
2017-11-17 13:40:05 13304 [Note] InnoDB: The InnoDB memory heap is disabled
2017-11-17 13:40:05 13304 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2017-11-17 13:40:05 13304 [Note] InnoDB: _mm_lfence() and _mm_sfence() are used for memory barrier
2017-11-17 13:40:05 13304 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-11-17 13:40:05 13304 [Note] InnoDB: Using generic crc32 instructions
2017-11-17 13:40:05 13304 [Note] InnoDB: Initializing buffer pool, size = 16.0M
2017-11-17 13:40:05 13304 [Note] InnoDB: Completed initialization of buffer pool
2017-11-17 13:40:05 13304 [Note] InnoDB: Highest supported file format is Barracuda.
2017-11-17 13:40:06 13304 [Note] InnoDB: 128 rollback segment(s) are active.
2017-11-17 13:40:06 13304 [Note] InnoDB: Waiting for purge to start
2017-11-17 13:40:06 13304 [Note] InnoDB:  Percona XtraDB (http://www.percona.com) 5.6.36-82.2 started; log sequence number 1835037
2017-11-17 13:40:06 13284 [Note] InnoDB: Dumping buffer pool(s) not yet started
2017-11-17 13:40:06 13304 [Note] Plugin 'FEEDBACK' is disabled.
2017-11-17 13:40:06 13304 [Note] Server socket created on IP: '::'.
2017-11-17 13:40:06 13304 [ERROR] Can't start server: Bind on TCP/IP port. Got error: 10048: Only one usage of each socket address (protocol/network address/port) is normally permitted.

2017-11-17 13:40:06 13304 [ERROR] Do you already have another mysqld server running on port: 3306 ?
2017-11-17 13:40:06 13304 [ERROR] Aborting
</code>```

I tried shutting down the SQL Server using SQL Server Management but I still can't connect MySQL.

答:
As in the log, when you installed the SQL Server it "reserverd" the same port that your MySQL was using

```<code>2017-11-17 13:40:06 13304 [ERROR] Do you already have another mysqld server running on port: 3306 ?
</code>```

You can change the MySql port in the my.ini file, which can be acessed by the Xampp Control Panel, under "config".

Or, you can change de SQL Server Port, following this tutorial: https://www.syskit.com/blog/change-sql-server-port/

Body:
I have been using Xampp to test my website stuff and everything was working perfectly until I decided to install Microsoft SQL SERVER 2017 to do some data science stuff (school stuff).

Now I can still start Apache but I cant start MySQL. Here is the log :

2015-11-10 15:26:56 10fc InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
2015-11-10 15:26:56 4348 [Note] InnoDB: Using mutexes to ref count buffer pool pages
2015-11-10 15:26:56 4348 [Note] InnoDB: The InnoDB memory heap is disabled
2015-11-10 15:26:56 4348 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2015-11-10 15:26:56 4348 [Note] InnoDB: Memory barrier is not used
2015-11-10 15:26:56 4348 [Note] InnoDB: Compressed tables use zlib 1.2.3
2015-11-10 15:26:56 4348 [Note] InnoDB: Not using CPU crc32 instructions
2015-11-10 15:26:56 4348 [Note] InnoDB: Initializing buffer pool, size = 16.0M
2015-11-10 15:26:56 4348 [Note] InnoDB: Completed initialization of buffer pool
2015-11-10 15:26:56 4348 [Note] InnoDB: Highest supported file format is Barracuda.
2015-11-10 15:26:57 4348 [Note] InnoDB: 128 rollback segment(s) are active.
2015-11-10 15:26:57 4348 [Note] InnoDB: Waiting for purge to start
2015-11-10 15:26:57 4348 [Note] InnoDB:  Percona XtraDB (http://www.percona.com) 5.6.26-74.0 started; log sequence number 1835027
2015-11-10 15:26:57 6140 [Note] InnoDB: Dumping buffer pool(s) not yet started
2015-11-10 15:26:57 4348 [Note] Plugin 'FEEDBACK' is disabled.
2015-11-10 15:26:57 4348 [Note] Server socket created on IP: '::'.
2015-11-10 15:26:57 4348 [Note] Event Scheduler: Loaded 0 events
2015-11-10 15:26:57 4348 [Note] C:\xampp\mysql\bin\mysqld.exe: ready for connections.
Version: '10.1.8-MariaDB'  socket: ''  port: 3306  mariadb.org binary distribution
2015-11-10 15:27:11 5152 [Note] C:\xampp\mysql\bin\mysqld.exe: Normal shutdown

2015-11-10 15:27:11 5152 [Note] Event Scheduler: Purging the queue. 0 events
2015-11-10 15:27:11 5732 [Note] InnoDB: FTS optimize thread exiting.
2015-11-10 15:27:11 5152 [Note] InnoDB: Starting shutdown...
2015-11-10 15:27:13 5152 [Note] InnoDB: Shutdown completed; log sequence number 1835037
2015-11-10 15:27:13 5152 [Note] C:\xampp\mysql\bin\mysqld.exe: Shutdown complete

2017-11-17 13:40:05 33f8 InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
2017-11-17 13:40:05 13304 [Note] InnoDB: innodb_empty_free_list_algorithm has been changed to legacy because of small buffer pool size. In order to use backoff, increase buffer pool at least up to 20MB.

2017-11-17 13:40:05 13304 [Note] InnoDB: Using mutexes to ref count buffer pool pages
2017-11-17 13:40:05 13304 [Note] InnoDB: The InnoDB memory heap is disabled
2017-11-17 13:40:05 13304 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2017-11-17 13:40:05 13304 [Note] InnoDB: _mm_lfence() and _mm_sfence() are used for memory barrier
2017-11-17 13:40:05 13304 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-11-17 13:40:05 13304 [Note] InnoDB: Using generic crc32 instructions
2017-11-17 13:40:05 13304 [Note] InnoDB: Initializing buffer pool, size = 16.0M
2017-11-17 13:40:05 13304 [Note] InnoDB: Completed initialization of buffer pool
2017-11-17 13:40:05 13304 [Note] InnoDB: Highest supported file format is Barracuda.
2017-11-17 13:40:06 13304 [Note] InnoDB: 128 rollback segment(s) are active.
2017-11-17 13:40:06 13304 [Note] InnoDB: Waiting for purge to start
2017-11-17 13:40:06 13304 [Note] InnoDB:  Percona XtraDB (http://www.percona.com) 5.6.36-82.2 started; log sequence number 1835037
2017-11-17 13:40:06 13284 [Note] InnoDB: Dumping buffer pool(s) not yet started
2017-11-17 13:40:06 13304 [Note] Plugin 'FEEDBACK' is disabled.
2017-11-17 13:40:06 13304 [Note] Server socket created on IP: '::'.
2017-11-17 13:40:06 13304 [ERROR] Can't start server: Bind on TCP/IP port. Got error: 10048: Only one usage of each socket address (protocol/network address/port) is normally permitted.

2017-11-17 13:40:06 13304 [ERROR] Do you already have another mysqld server running on port: 3306 ?
2017-11-17 13:40:06 13304 [ERROR] Aborting

I tried shutting down the SQL Server using SQL Server Management but I still can't connect MySQL.

Body:
As in the log, when you installed the SQL Server it "reserverd" the same port that your MySQL was using

2017-11-17 13:40:06 13304 [ERROR] Do you already have another mysqld server running on port: 3306 ?

You can change the MySql port in the my.ini file, which can be acessed by the Xampp Control Panel, under "config".

Or, you can change de SQL Server Port, following this tutorial: https://www.syskit.com/blog/change-sql-server-port/


问:
In javascript, when creating properties, which is the right way or better syntax?
properties(keys) can be accessed and set using the dot notation as well as the square brackets. any advice when to use dot prototype syntax</p>

```<code>var myObj = {};
myObj.myProp1 = 'value1'; //works, an expando property
myObj[myProp2] = 'value2'; // FAILS, myProp2 is undefined
myObj["myProp2"] = 'value2'; // works, an expando property
myObj[2010]= 'value'; //note the key is number, still works, an expando property??
myObj.2010 = 'value'; // FAILS. to use dot notation, key must be a string

myObj.prototype.myProp3 = 'value3' // whats the advantage?
</code>```

答:
basically , there is no difference between accessing an object's property via the "." syntax or through the key.

```var obj = new function(){this.x = "value";}
alert(obj.x === obj['x']); //it will output true
```

There are times when you can't use the "." , because the name of the property you're trying to access is not a valid variable name (as you pointed with your numeric key) :

```var obj = new function(){this['my-value'] = "my value";}
alert(obj['my-value']); // it will output "my value"
alert(obj.my-value); // it will trigger an exception , because the javascript
//interpretor interprets "obj.my-value" as the
//property "my" of obj minus the variable "value"
```

The big difference is the way the browser handles your syntax . As you can see here , a friend of mine did some testing and it seems that Chrome and IE work a lot faster with the dot syntax while Firefox and Safari are more "keen on" the key syntax.

In conclusion, you can use almost every time either one of them , although there are situations where the "." comes a bit "unprepared".

About the prototype syntax, well, when you define an object you can attach members to every instance , but you can also attach members to the prototype of the object, meaning that whenever a new object of your defined type is created, it will automatically inherit that member from it's prototype. I think it's better understood with an example:

```
function Point(x,y){this.x = x;this.y = y;}
Point.prototype.toString = function(){
  return "I am a point with my x coord at "+this.x+" and my y coord at "+this.y;
}

function Point2(x,y){
  this.x = x;
  this.y = y;
  this.toString = function(){
    return "I'm a point too.I'm at x:"+this.x+", y:"+this.y;
  };
}
```

When you create a new Point2, it's toString method an instance method and the javascript interpretor allocates memory for this method.

When you create a 'new Point', it's toString method will be chained on it's prototype property. That means that no memory is allocated for that method.

```
var p = [], p2 = [];
for(var i = 0; i < 100000000; i++)
   {
     p.push(new Point(0,0));
     p2.push(new Point2(0,0));
   }
```

If you test this, you'll see that both of the objects are working perfect, but your Point2 objects will take a bit more memory out of your system. Why is that?

The thing is that when you call a new Point()'s toString() method, the object realizes that it doesn't have a member called "toString" and it starts to search for it up it's prototype chain and returns the 'toString' member found in the object's declaration.

In the above example, all of the p's items will point their toString method to the one mentioned in the prototype, while all of p2's items will point to their each copy of the method.

In addition, if you later want to modify the toString method, it will be very easy to modify it for all the Point instances :

Point.prototype.toString = function(){return "I'm a smarter point";};
After that, every instance of new Point will return "I'm a smarter point" when you call it's toString method.

If you try to modify it for the Point2 instances, it's a bit harder. You will find out that  Point2.toString = function(){return "I'm a dumber point";}  will not work as expected, you will have to manually change the method for each instance :

```
for(var i in p2)
  p2[i].toString = function(){return "I'm a dumber point";};
```

I'll let you decide on which method is better :P

Body:
properties(keys) can be accessed and set using the dot notation as well as the square brackets. any advice when to use dot prototype syntax

var myObj = {};
myObj.myProp1 = 'value1'; //works, an expando property
myObj[myProp2] = 'value2'; // FAILS, myProp2 is undefined
myObj["myProp2"] = 'value2'; // works, an expando property
myObj[2010]= 'value'; //note the key is number, still works, an expando property??
myObj.2010 = 'value'; // FAILS. to use dot notation, key must be a string

myObj.prototype.myProp3 = 'value3' // whats the advantage?

Body:
basically , there is no difference between accessing an object's property via the "." syntax or through the key.

var obj = new function(){this.x = "value";}
alert(obj.x === obj['x']); //it will output true

There are times when you can't use the "." , because the name of the property you're trying to access is not a valid variable name (as you pointed with your numeric key) :

var obj = new function(){this['my-value'] = "my value";}
alert(obj['my-value']); // it will output "my value"
alert(obj.my-value); // it will trigger an exception , because the javascript
//interpretor interprets "obj.my-value" as the
//property "my" of obj minus the variable "value"

The big difference is the way the browser handles your syntax . As you can see here , a friend of mine did some testing and it seems that Chrome and IE work a lot faster with the dot syntax while Firefox and Safari are more "keen on" the key syntax.

In conclusion, you can use almost every time either one of them , although there are situations where the "." comes a bit "unprepared".

About the prototype syntax, well, when you define an object you can attach members to every instance , but you can also attach members to the prototype of the object, meaning that whenever a new object of your defined type is created, it will automatically inherit that member from it's prototype. I think it's better understood with an example:

function Point(x,y){this.x = x;this.y = y;}
Point.prototype.toString = function(){
  return "I am a point with my x coord at "+this.x+" and my y coord at "+this.y;
}

function Point2(x,y){
  this.x = x;
  this.y = y;
  this.toString = function(){
    return "I'm a point too.I'm at x:"+this.x+", y:"+this.y;
  };
}

When you create a new Point2, it's toString method an instance method and the javascript interpretor allocates memory for this method.

When you create a 'new Point', it's toString method will be chained on it's prototype property. That means that no memory is allocated for that method.

var p = [], p2 = [];
for(var i = 0; i < 100000000; i++)
   {
     p.push(new Point(0,0));
     p2.push(new Point2(0,0));
   }

If you test this, you'll see that both of the objects are working perfect, but your Point2 objects will take a bit more memory out of your system. Why is that?

The thing is that when you call a new Point()'s toString() method, the object realizes that it doesn't have a member called "toString" and it starts to search for it up it's prototype chain and returns the 'toString' member found in the object's declaration.

In the above example, all of the p's items will point their toString method to the one mentioned in the prototype, while all of p2's items will point to their each copy of the method.

In addition, if you later want to modify the toString method, it will be very easy to modify it for all the Point instances :

Point.prototype.toString = function(){return "I'm a smarter point";};
After that, every instance of new Point will return "I'm a smarter point" when you call it's toString method.

If you try to modify it for the Point2 instances, it's a bit harder. You will find out that  Point2.toString = function(){return "I'm a dumber point";}  will not work as expected, you will have to manually change the method for each instance :

for(var i in p2)
  p2[i].toString = function(){return "I'm a dumber point";};

I'll let you decide on which method is better :P


问:
Update row, delete the same row if update fails
I have a table that aggregate items and their categories. An item can have multiple categories. Here is the simplified schema and example data:

Table name: xref, (itemID, catID) defined as primary key

```<code>itemID | catID
-------+-------
4059   | 159
4059   | 219
</code>```

I also have a category merge function. When doing this, I also move products that linked in source category to the destination (merged) category . For moving items from category 159 to 219, I use a SQL like this:

```<code>UPDATE `xref` SET `catID` = 219 WHERE `catID` = 159
</code>```

But the update fails because there is already a 4059-219 (PK constraint).

The desired result is

```<code>itemID | catID
-------+-------
4059   | 219
</code>```

I can't use stored procedures or functions on the database but can implement the required steps in my application.

Is there a way to delete row when an UPDATE query fails?

How can I write a query that "predicts" rows for to-be-failed UPDATE query? Something like "return itemID's that having catID's 219 AND 159 at the same time". Is SELECT * FROM xref WHERE catID IN (159, 219) GROUP BY itemID HAVING COUNT(*) >= 2 is a correct approach?

答:
Try following query:

```<code>UPDATE `xref`
SET `catID` = 219
WHERE `catID` = 159
and `itemID` not in (select 'itemID'
                     from (select *from 'xref') x
                     where 'catID' = 219)
;
</code>```

Hope it helps!

Body:
I have a table that aggregate items and their categories. An item can have multiple categories. Here is the simplified schema and example data:

Table name: xref, (itemID, catID) defined as primary key

itemID | catID
-------+-------
4059   | 159
4059   | 219

I also have a category merge function. When doing this, I also move products that linked in source category to the destination (merged) category . For moving items from category 159 to 219, I use a SQL like this:

UPDATE `xref` SET `catID` = 219 WHERE `catID` = 159

But the update fails because there is already a 4059-219 (PK constraint).

The desired result is

itemID | catID
-------+-------
4059   | 219

I can't use stored procedures or functions on the database but can implement the required steps in my application.

Is there a way to delete row when an UPDATE query fails?

How can I write a query that "predicts" rows for to-be-failed UPDATE query? Something like "return itemID's that having catID's 219 AND 159 at the same time". Is SELECT * FROM xref WHERE catID IN (159, 219) GROUP BY itemID HAVING COUNT(*) >= 2 is a correct approach?

Body:
Try following query:

UPDATE `xref`
SET `catID` = 219
WHERE `catID` = 159
and `itemID` not in (select 'itemID'
                     from (select *from 'xref') x
                     where 'catID' = 219)
;

Hope it helps!


问:
Firebase Authentication: auth/auth-domain-config-required
I'm getting auth-domain-config-required errors when using firebase.auth().signInWithPopup(provider).

I've tried with Google and Facebook. I've tested on my hosted site, and it works fine. You can test it live: Quiver Chat Demo

I suspect there's a problem with localhost:3333... does it not like my port? I can't add a port to the Authorized domains list, and adding it to my authDomain: config doesn't help either.

Here's my auth code, but as you can see from the screenshots below, I tried a bunch of different authDomain values.

```<code>  <script src="https://quiver-four.firebaseapp.com/__/firebase/4.6.2/firebase-app.js"></script>
  <script src="https://quiver-four.firebaseapp.com/__/firebase/4.6.2/firebase-auth.js"></script>
  <script>
    // Initialize Firebase
    var config = {
      apiKey: "AIzaSyCzNxnQ6WCJKejq6SBd7NqhVskxEOmDq_Y",
      authDomain: "quiver-four.firebaseapp.com",
      databaseURL: "https://quiver-four.firebaseio.com",
      projectId: "quiver-four",
      storageBucket: "quiver-four.appspot.com",
      messagingSenderId: "1082528354495"
    };
    firebase.initializeApp(config);
  </script>
</code>```

Attempting localhost:3333

Attempting localhost

Attempting quiver-four.firebaseapp.com

The domains are added

答:
You must not be providing the correct authDomain in your Firebase app initialization configuration.
You can get that web snippet from the Firebase Console. The authDomain has the form projectName.firebaseapp.com.

Body:
I'm getting auth-domain-config-required errors when using firebase.auth().signInWithPopup(provider).

I've tried with Google and Facebook. I've tested on my hosted site, and it works fine. You can test it live: Quiver Chat Demo

I suspect there's a problem with localhost:3333... does it not like my port? I can't add a port to the Authorized domains list, and adding it to my authDomain: config doesn't help either.

Here's my auth code, but as you can see from the screenshots below, I tried a bunch of different authDomain values.

Attempting localhost:3333

Attempting localhost

Attempting quiver-four.firebaseapp.com

The domains are added


问:
(C#) DataGridView: How to get Selected Count with cells AND rows?
So I have this DataGridView

And This code:

```<code>if(dataGridView1.SelectedRows.Count > 1)
        {
            MessageBox.Show("Error: More than one value selected");
            return false;
        }
</code>```

It counts correctly to 2 if I have 2 completly selected rows.
But I want to check if any cells from 2 different rows or more are selected.

In other words:
in my picture my current selection is returning 1 at the moment but i want it to return 2.

Thank you.

Edit after fix: Working code:

```<code>if(dataGridView1.SelectedCells.Cast<DataGridViewCell>().Select(c => c.RowIndex).Distinct().Count() > 1)
        {
            MessageBox.Show("Error: More than one value selected");
            return false;
        }
</code>```

答:
To get the number of rows with selected cells :

```<code>int count = dataGridView1.SelectedCells.Cast<DataGridViewCell>()
                                       .Select(c => c.RowIndex).Distinct().Count();
</code>```

To check if more than one row is selected:

```<code>var selectedCells = dataGridView1.SelectedCells;
bool check = selectedCells.Count > 0
         && selectedCells.Cast<DataGridViewCell>().Any(c => c.RowIndex != selectedCells[0].RowIndex);
</code>```

Body:
So I have this DataGridView

And This code:

if(dataGridView1.SelectedRows.Count > 1)
        {
            MessageBox.Show("Error: More than one value selected");
            return false;
        }

It counts correctly to 2 if I have 2 completly selected rows.
But I want to check if any cells from 2 different rows or more are selected.

In other words:
in my picture my current selection is returning 1 at the moment but i want it to return 2.

Thank you.

Edit after fix: Working code:

if(dataGridView1.SelectedCells.Cast<DataGridViewCell>().Select(c => c.RowIndex).Distinct().Count() > 1)
        {
            MessageBox.Show("Error: More than one value selected");
            return false;
        }

Body:
To get the number of rows with selected cells :

int count = dataGridView1.SelectedCells.Cast<DataGridViewCell>()
                                       .Select(c => c.RowIndex).Distinct().Count();

To check if more than one row is selected:

var selectedCells = dataGridView1.SelectedCells;
bool check = selectedCells.Count > 0
         && selectedCells.Cast<DataGridViewCell>().Any(c => c.RowIndex != selectedCells[0].RowIndex);

ContentLicense: CC BY-SA 4.0


问:
C# Linq adding to dictionary with list as value
I have a dictionary like this:

```<code>Dictionary<string, List<myobject>>
</code>```

As I am getting new items, I'm doing logic like this:

```<code>mydictionary[key].add(mynewobject);
</code>```

now, I'm trying to do the same with LINQ, but I'm stuck on the last line:
(please ignore the bit of irrelevant logic in the code):

```<code>var Test =
    (from F in Directory.EnumerateFiles(SOURCE_FOLDER, SOURCE_EXTENSIONS, SearchOption.AllDirectories)
    let Key = ParenthesisGroupRegex.Replace(F.ToLower(), string.Empty).Trim()
    let Descriptions =
        (from Match Match in ParenthesisGroupRegex.Matches(F.ToLower())
        let CleanedMatches = ParenthesisRegex.Replace(Match.Name, string.Empty)
        let MatchesList = CleanedMatches.Split(',')
        select new Description { Filename = F, Tag = MatchesList.ToList() })
    group Descriptions by Key into DescriptionList
    select new KeyValuePair<string, IEnumerable<string>>(Key, DescriptionList))
</code>```

If we look at the last two lines:
I'm trying to get my List (List

and on the last linne, I'm attempting to build dictionary entries, but this will not compile as it looks like neither Key, nor DescriptionList, are accessible at that stage.

(btw, I'm currently learning the LINQ syntax, so readability and maintainability are not the focus right now)

What did I miss?

答:
You could call the ToDictionary at the end of the query you have defined:

```<code>var Test =
(from F in Directory.EnumerateFiles(SOURCE_FOLDER, SOURCE_EXTENSIONS, SearchOption.AllDirectories)
let Key = ParenthesisGroupRegex.Replace(F.ToLower(), string.Empty).Trim()
let Descriptions =
    (from Match Match in ParenthesisGroupRegex.Matches(F.ToLower())
    let CleanedMatches = ParenthesisRegex.Replace(Match.Name, string.Empty)
    let MatchesList = CleanedMatches.Split(',')
    select new Description { Filename = F, Tag = MatchesList.ToList() })
group Descriptions by Key)
.ToDictionary(x=>x.Key,x=>x.ToList());
</code>```

Essentially GroupBy as it stated here:

Groups the elements of a sequence according to a specified key
  selector function and projects the elements for each group by using a
  specified function.

and it's signature is the following:

```<code>public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    Func<TSource, TElement> elementSelector
)
</code>```

Note that the return type of GroupBy is this

```<code>IEnumerable<IGrouping<TKey, TElement>>
</code>```

The above type essentially declares a sequence of keys and collections of objects that are associated with these keys (More formally it declares a sequence of objects of type IGrouping<TKey, TElement>, where IGrouping represents a collection of objects that have a common key.). That you want is a dicitonary with the keys in this sequence and values the corresponding collection of objects. This can be achieved as above by calling the ToDictionary method.

Body:
I have a dictionary like this:

Dictionary<string, List<myobject>>

As I am getting new items, I'm doing logic like this:

mydictionary[key].add(mynewobject);

now, I'm trying to do the same with LINQ, but I'm stuck on the last line:
(please ignore the bit of irrelevant logic in the code):

var Test =
    (from F in Directory.EnumerateFiles(SOURCE_FOLDER, SOURCE_EXTENSIONS, SearchOption.AllDirectories)
    let Key = ParenthesisGroupRegex.Replace(F.ToLower(), string.Empty).Trim()
    let Descriptions =
        (from Match Match in ParenthesisGroupRegex.Matches(F.ToLower())
        let CleanedMatches = ParenthesisRegex.Replace(Match.Name, string.Empty)
        let MatchesList = CleanedMatches.Split(',')
        select new Description { Filename = F, Tag = MatchesList.ToList() })
    group Descriptions by Key into DescriptionList
    select new KeyValuePair<string, IEnumerable<string>>(Key, DescriptionList))

If we look at the last two lines:
I'm trying to get my List (List

and on the last linne, I'm attempting to build dictionary entries, but this will not compile as it looks like neither Key, nor DescriptionList, are accessible at that stage.

(btw, I'm currently learning the LINQ syntax, so readability and maintainability are not the focus right now)

What did I miss?

Body:
You could call the ToDictionary at the end of the query you have defined:

var Test =
(from F in Directory.EnumerateFiles(SOURCE_FOLDER, SOURCE_EXTENSIONS, SearchOption.AllDirectories)
let Key = ParenthesisGroupRegex.Replace(F.ToLower(), string.Empty).Trim()
let Descriptions =
    (from Match Match in ParenthesisGroupRegex.Matches(F.ToLower())
    let CleanedMatches = ParenthesisRegex.Replace(Match.Name, string.Empty)
    let MatchesList = CleanedMatches.Split(',')
    select new Description { Filename = F, Tag = MatchesList.ToList() })
group Descriptions by Key)
.ToDictionary(x=>x.Key,x=>x.ToList());

Essentially GroupBy as it stated here:

Groups the elements of a sequence according to a specified key
  selector function and projects the elements for each group by using a
  specified function.

and it's signature is the following:

public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    Func<TSource, TElement> elementSelector
)

Note that the return type of GroupBy is this

IEnumerable<IGrouping<TKey, TElement>>

The above type essentially declares a sequence of keys and collections of objects that are associated with these keys (More formally it declares a sequence of objects of type IGrouping<TKey, TElement>, where IGrouping represents a collection of objects that have a common key.). That you want is a dicitonary with the keys in this sequence and values the corresponding collection of objects. This can be achieved as above by calling the ToDictionary method.


问:
How to print a PDF with C#
I´ve trying to solve this problem for nearly 2 days. There are a lot of more or fewer good solutions on the net, but not a single one fits my task perfectly.

Task:

Print a PDF programmatically

Do it with a fixed printer

Don´t let the user do more than one Button_Click

Do it silent - the more, the better

Do it client side

First Solutions:

Do it with a Forms.WebBrowser

If we have Adobe Reader installed, there is a plugin to show PDF´s in the webbrowser. With this solution we have a nice preview and with webbrowserControlName.Print() we can trigger the control to print its content.

Problem - we still have a PrintDialog.

Start the AcroRd32.exe with start arguments

The following CMD command let us use Adobe Reader to print our PDF.

InsertPathTo..\AcroRd32.exe /t "C:\sample.pdf" "\printerNetwork\printerName"

Problems - we need the absolute path to AcroRd32.exe | there is an Adobe Reader Window opening and it has to be opened until the print task is ready.

Use windows presets

```<code>Process process = new Process();

process.StartInfo.FileName = pathToPdf;
process.StartInfo.Verb = "printto";
process.StartInfo.Arguments = "\"" + printerName + "\"";
process.Start();

process.WaitForInputIdle();
process.Kill();
</code>```

Problem - there is still an Adobe Reader window popping up, but after the printing is done it closes itself usually.

Solution - convince the client to use Foxit Reader (don´t use last two lines of code).

Convert PDF pages to Drawing.Image

I´ve no idea how to do it with code, but when I get this to work the rest is just a piece of cake. Printing.PrintDocument can fulfill all demands.

Anyone an idea to get some Drawing.Image´s out of those PDF´s or another approach how to do it?

Best Regards,
Max

答:
I tried many things and the one that worked best for me was launching a SumatraPDF from the command line:

```<code>// Launch SumatraPDF Reader to print
String arguments = "-print-to-default -silent \"" + fileName + "\"";
System.Diagnostics.Process.Start("SumatraPDF.exe", arguments);
</code>```

There are so many advantages to this:

SumatraPDF is much much faster than Adobe Acrobat Reader.

The UI doesn't load.  It just prints.

You can use SumatraPDF as a standalone application so you can include it with your application so you can use your own pa.  Note that I did not read the license agreement; you should probably check it out yourself.

Title: How to print a PDF with C#

Body:
I´ve trying to solve this problem for nearly 2 days. There are a lot of more or fewer good solutions on the net, but not a single one fits my task perfectly.

Task:

Print a PDF programmatically

Do it with a fixed printer

Don´t let the user do more than one Button_Click

Do it silent - the more, the better

Do it client side

First Solutions:

Do it with a Forms.WebBrowser

If we have Adobe Reader installed, there is a plugin to show PDF´s in the webbrowser. With this solution we have a nice preview and with webbrowserControlName.Print() we can trigger the control to print its content.

Problem - we still have a PrintDialog.

Start the AcroRd32.exe with start arguments

The following CMD command let us use Adobe Reader to print our PDF.

InsertPathTo..\AcroRd32.exe /t "C:\sample.pdf" "\printerNetwork\printerName"

Problems - we need the absolute path to AcroRd32.exe | there is an Adobe Reader Window opening and it has to be opened until the print task is ready.

Use windows presets

Process process = new Process();

process.StartInfo.FileName = pathToPdf;
process.StartInfo.Verb = "printto";
process.StartInfo.Arguments = "\"" + printerName + "\"";
process.Start();

process.WaitForInputIdle();
process.Kill();

Problem - there is still an Adobe Reader window popping up, but after the printing is done it closes itself usually.

Solution - convince the client to use Foxit Reader (don´t use last two lines of code).

Convert PDF pages to Drawing.Image

I´ve no idea how to do it with code, but when I get this to work the rest is just a piece of cake. Printing.PrintDocument can fulfill all demands.

Anyone an idea to get some Drawing.Image´s out of those PDF´s or another approach how to do it?

Best Regards,
Max

Body:
I tried many things and the one that worked best for me was launching a SumatraPDF from the command line:

// Launch SumatraPDF Reader to print
String arguments = "-print-to-default -silent \"" + fileName + "\"";
System.Diagnostics.Process.Start("SumatraPDF.exe", arguments);

There are so many advantages to this:

SumatraPDF is much much faster than Adobe Acrobat Reader.

The UI doesn't load.  It just prints.

You can use SumatraPDF as a standalone application so you can include it with your application so you can use your own pa.  Note that I did not read the license agreement; you should probably check it out yourself.


问:
When iterating through a HashMap with Integer keys, will it always return keys in ascending order?
I have a HashMap defined as such:

public Map<Integer, String> staticBlockPositions = new HashMap<Integer, String>();

I am iterating over the map by getting each key, like this:

```<code>for (Integer key : blockPositions.keySet()) {
    System.out.println(key);
}
</code>```

My question is, can I rely on the value of key to always be in ascending order. So if my HashMap looks something like this:

```<code>{
    4: "abc123",
    1: "def456",
    11: "qwe789",
    10: "iop019"
}
</code>```

(I know this is JSON format, this is just so you get an idea of the data set).

Will my loop always output

```<code>1
4
10
11
</code>```

regardless of the order of my data?

Important to note, the order in which the keys are add is completely random, and I cannot control what key is added when.

This is for a Tetris style game, so getting the keys in ascending order is a must.

答:
No,

To maintain sorted order, use TreeMap.

To maintain insertion order, use LinkedHashMap.

Body:
I have a HashMap defined as such:

public Map<Integer, String> staticBlockPositions = new HashMap<Integer, String>();

I am iterating over the map by getting each key, like this:

for (Integer key : blockPositions.keySet()) {
    System.out.println(key);
}

My question is, can I rely on the value of key to always be in ascending order. So if my HashMap looks something like this:

{
    4: "abc123",
    1: "def456",
    11: "qwe789",
    10: "iop019"
}

(I know this is JSON format, this is just so you get an idea of the data set).

Will my loop always output

1
4
10
11

regardless of the order of my data?

Important to note, the order in which the keys are add is completely random, and I cannot control what key is added when.

This is for a Tetris style game, so getting the keys in ascending order is a must.


问:
Trouble writing a query for two tables using these tables (below)
MySQL

I am trying to fetch value's from a table Province that has a foreign key of country table.

```<code>SELECT *
  FROM province
  JOIN country
    ON country.Country_Id = province.Province_Id
</code>```

country table

province table

What I am trying to do: I want all the entries to shown in one single table on my PHP web page.

Error is : warning page

答:
first you have to specify the current column in join statement you mentioned that country_id is the foreign key in province table then you have to have:

```<code>SELECT province.*, country.name
  FROM province
  INNER JOIN country
    ON country.Country_Id = province.country_Id
</code>```

and since in the result set both country and province has country_id, using one of them would be sufficient

Body:
MySQL

I am trying to fetch value's from a table Province that has a foreign key of country table.

SELECT *
  FROM province
  JOIN country
    ON country.Country_Id = province.Province_Id

country table

province table

What I am trying to do: I want all the entries to shown in one single table on my PHP web page.

Error is : warning page

Body:
first you have to specify the current column in join statement you mentioned that country_id is the foreign key in province table then you have to have:

SELECT province.*, country.name
  FROM province
  INNER JOIN country
    ON country.Country_Id = province.country_Id

and since in the result set both country and province has country_id, using one of them would be sufficient


问:
Cannot use identity column key generation with the strategy TABLE_PER_CLASS in JPA?
This question is in context with the problem mentioned in this thread.
I'm also facing the same problem while using JPA on MySQL. I could resolve it only when I changed the generation strategy to TABLE.

But the question is, what was the reason behind this problem and why changing the strategy to TABLE is the solution (this remains unanswered in the thread) ?

答: The accepted answer (although old) is not quite correct. Using GenerationType.IDENTITY does not imply that table generation is used by the DB. The javadoc for GenerationType.IDENTITY says: "Indicates that the persistence provider must assign primary keys for the entity using a database identity column.".</p>


问:
Pointer in c++ struct name
I ran into this bit of code for a c++ linked list implementation.

```<code>struct node
{
    int info;
    struct node *next;
}*start;
</code>```

What does this mean to have *start rather than just start??

What happens when it is later used like this? What does s mean it is not referenced anywhere else in the function?

```<code>struct node *temp, *s;
temp = new(struct node);
</code>```

答:
Fragment

```<code>struct node
{
    int info;
    struct node *next;
}*start;
</code>```

is equivalent to

```<code>struct node
{
    int info;
    struct node *next;
};
struct node *start;
</code>```

So in your first fragment, you define a structure named node and a variable named start of type struct node * within one statement. That's all.

Note that in C++ (unlike in C), you could also write

```<code>struct node
{
    int info;
    node *next;
};
node *start;
</code>```

i.e. you can omit the struct-keyword when defining variables of type struct node.

Title: Pointer in c++ struct name

Body:
I ran into this bit of code for a c++ linked list implementation.

struct node
{
    int info;
    struct node *next;
}*start;

What does this mean to have *start rather than just start??

What happens when it is later used like this? What does s mean it is not referenced anywhere else in the function?

struct node *temp, *s;
temp = new(struct node);

Body:
Fragment

struct node
{
    int info;
    struct node *next;
}*start;

is equivalent to

struct node
{
    int info;
    struct node *next;
};
struct node *start;

So in your first fragment, you define a structure named node and a variable named start of type struct node * within one statement. That's all.

Note that in C++ (unlike in C), you could also write

struct node
{
    int info;
    node *next;
};
node *start;

i.e. you can omit the struct-keyword when defining variables of type struct node.


问:
Magento 2 slider extension
I have downloaded free image slider(MagebannerSlider). I want to use it but without upgrading the setup. When I run the command:

```<code>php bin/magento setup:upgrade
</code>```

it appears in the Content section of backend, if I just put the bannerSlider in the app->code->bannerSlider it is not working.

Could anyone help me?

答:
type commands:

```<code>php bin/magento module:enable Magestore_Bannerslider

php bin/magento setup:upgrade

php bin/magento setup:static-content:deploy
</code>```

First is to enable the module/plugin.
Second to upgrade setup. (db)
Last to get static files deployed.

Maybe clear cache too.

```<code>php bin/magento cache:clean
php bin/magento cache:flush
</code>```

Title: Magento 2 slider extension

Body:
I have downloaded free image slider(MagebannerSlider). I want to use it but without upgrading the setup. When I run the command:

php bin/magento setup:upgrade

it appears in the Content section of backend, if I just put the bannerSlider in the app->code->bannerSlider it is not working.

Could anyone help me?

Body:
type commands:

php bin/magento module:enable Magestore_Bannerslider

php bin/magento setup:upgrade

php bin/magento setup:static-content:deploy

First is to enable the module/plugin.
Second to upgrade setup. (db)
Last to get static files deployed.

Maybe clear cache too.

php bin/magento cache:clean
php bin/magento cache:flush


问:
Spring ControllerAdvice not being called on exceptions
Though I defined ControllerAdvice to handle exceptions, I dont see that being invoked.
Here is my code, could you please advice

```<code>    public class RestError {
        private String code;
        private String message;

    public RestError(String code, String message) {
        this.code = code;
        this.message = message;
    }

    public String getCode() { return code; }

    public String getMessage() { return message; }
}
</code>```

```<code>public class RestException extends RuntimeException {

   private String errorCode;
   private String errorMessage;

    public RestException(String errorCode, String errorMessage) {
        super(errorMessage);
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }
}
</code>```

ControllerAdvice

```<code>@Controller
public class RestController {

    private static final Logger LOG = Logger.getLogger(RestController.class);
    @RequestMapping(value = "/echo", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void echo(@RequestParam(value = "clientVersion", required = false) String clientVersion,
                     @RequestParam(value = "applicationName", required = false) String applicationName,
                     HttpServletRequest httpRequest) {
        LOG.info("Throwing exception...");
        throw new RestException("9999", "Invoke Exception Handler");
    }
}
</code>```

I see that spring is creating GlobalExceptionHandler object but its not being invoked.
Here is Full code

I am using Spring 4.3.0 framework and running in jetty container through maven.
Please help me

答:
You need to add

```<code><mvc:annotation-driven/>
</code>```

to your xml to enable the ControllerAdvice.
Also don't forget to add the namespace and schema definition for this

```<code><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
</code>```

Body:
Though I defined ControllerAdvice to handle exceptions, I dont see that being invoked.
Here is my code, could you please advice

    public class RestError {
        private String code;
        private String message;

    public RestError(String code, String message) {
        this.code = code;
        this.message = message;
    }

    public String getCode() { return code; }

    public String getMessage() { return message; }
}

public class RestException extends RuntimeException {

   private String errorCode;
   private String errorMessage;

    public RestException(String errorCode, String errorMessage) {
        super(errorMessage);
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }
}

ControllerAdvice

@Controller
public class RestController {

    private static final Logger LOG = Logger.getLogger(RestController.class);
    @RequestMapping(value = "/echo", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void echo(@RequestParam(value = "clientVersion", required = false) String clientVersion,
                     @RequestParam(value = "applicationName", required = false) String applicationName,
                     HttpServletRequest httpRequest) {
        LOG.info("Throwing exception...");
        throw new RestException("9999", "Invoke Exception Handler");
    }
}

I see that spring is creating GlobalExceptionHandler object but its not being invoked.
Here is Full code

I am using Spring 4.3.0 framework and running in jetty container through maven.
Please help me

Body:
You need to add

<mvc:annotation-driven/>

to your xml to enable the ControllerAdvice.
Also don't forget to add the namespace and schema definition for this

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">


问:
com.walmart.marketplace.sdk.cli.SDKClient not found
I use WalmartMarketPlaceAPI java SDK .
but it tell me this class 'com.walmart.marketplace.sdk.cli.SDKClient' not found, somebody can tell how to solve it ?

答:
Please make sure that you are using JDK version 7 or 8 only.
Also please make sure you are using command
mvn exec:java -Dexec.classpathScope=test -Dexec.mainClass="com.walmart.marketplace.sdk.cli.SDKClient" -Dexec.args="MarketplaceClientConfig.properties"
instead of using mvn exec:java -Dexec.classpathScope=test -Dexec.mainClass=“com.walmart.marketplace.sdk.cli.SDKClient” -Dexec.args=“MarketplaceClientConfig.properties” (note the difference in quotes)</p>


问:
Download Blobs from Azure using Python
I need to extract the data from PDFs(millions) in Azure Storage to analyse and separate then in folders but it's too slow. It waste 11 minutes (just) to download 1000 PDFs. Is there any way to download it faster or to move/extract the data without having to download it?
I'm using get_blob_to_path to download the Blob and slate3k to convert the PDF to TXT.

Code(Sorry, there are some words in portuguese):

```<code>    block_service = BlockBlobService(account_name=ACCOUNT_NAME, account_key=ACCOUNT_KEY)

generator = block_service.list_blobs(CONTAINER_NAME, prefix="trt2", num_results=1000, timeout=60)

for blob in generator:

    path = "temp/" + blob.name.split("/")[-1]
    block_service.get_blob_to_path(CONTAINER_NAME, blob.name, path, timeout=60)

    with open(path, 'rb') as f:
        doc = slate3k.PDF(f)
        f.close()

        text_complete = ''
        for item in doc:
            item_pat = ''
            for line in item.split('\n'):
                item_pat += line + '\n'
            text_complete += item_pat

        text_complete = text_complete.strip().lower()

        if text_complete.find("acórdão") >= 0 and text_complete.find("acordam os magistrados") >= 0:
            print("Encontrei Acórdão")
            print("Arquivo "+path)
            block_service.create_blob_from_path(CONTAINER_NAME, "trt2/Acordao/" + arquivo, path)
            block_service.delete_blob(CONTAINER_NAME, blob.name)
            os.remove(path)
        elif text_complete.find("despacho") >= 0 and text_complete.find("conclusão") < 0 and text_complete.find("embargo") < 0 and \
                        text_complete.find("ata de audiência") < 0 and text_complete.find("termo de audiência") < 0 and \
                        text_complete.find("v o t o") < 0 and text_complete.find("certidão") < 0 :
            print("Encontrei Despacho")
            print("Arquivo "+path)
            block_service.create_blob_from_path(CONTAINER_NAME, "trt2/Despacho/" + arquivo, path)
            block_service.delete_blob(CONTAINER_NAME, blob.name)
            os.remove(path)
        elif text_complete.find("sentença") >= 0 and text_complete.find("relatório") >= 0 and \
                        text_complete.find("acordam") < 0 and text_complete.find("primeira testemunha") < 0 and \
                        text_complete.find("provas a produzir") < 0 and text_complete.find("embargo") < 0 and \
                        text_complete.find("voto") < 0:
            print("Encontrei Sentença")
            print("Arquivo "+path)
            block_service.create_blob_from_path(CONTAINER_NAME, "trt2/Sentenca/" + arquivo, path)
            block_service.delete_blob(CONTAINER_NAME, blob.name)
            os.remove(path)

        else:
            block_service.create_blob_from_path(CONTAINER_NAME, "trt2/Outros/" + arquivo, path)
            block_service.delete_blob(CONTAINER_NAME, blob.name)
            os.remove(path)
</code>```

答:
I suggest using Azure Batch for this. You can spin up 100 VMs and let them do the job. No need to download the file to your local computer.

You can also do it on a single Azure VM, but it will take longer than with Azure Batch.

In both ways the files will stay within the Azure datacenter which makes it faster and you won't have to pay for the egress traffic.

Title: Download Blobs from Azure using Python

Body:
I need to extract the data from PDFs(millions) in Azure Storage to analyse and separate then in folders but it's too slow. It waste 11 minutes (just) to download 1000 PDFs. Is there any way to download it faster or to move/extract the data without having to download it?
I'm using get_blob_to_path to download the Blob and slate3k to convert the PDF to TXT.

Code(Sorry, there are some words in portuguese):

    block_service = BlockBlobService(account_name=ACCOUNT_NAME, account_key=ACCOUNT_KEY)

generator = block_service.list_blobs(CONTAINER_NAME, prefix="trt2", num_results=1000, timeout=60)

for blob in generator:

    path = "temp/" + blob.name.split("/")[-1]
    block_service.get_blob_to_path(CONTAINER_NAME, blob.name, path, timeout=60)

    with open(path, 'rb') as f:
        doc = slate3k.PDF(f)
        f.close()

        text_complete = ''
        for item in doc:
            item_pat = ''
            for line in item.split('\n'):
                item_pat += line + '\n'
            text_complete += item_pat

        text_complete = text_complete.strip().lower()

        if text_complete.find("acórdão") >= 0 and text_complete.find("acordam os magistrados") >= 0:
            print("Encontrei Acórdão")
            print("Arquivo "+path)
            block_service.create_blob_from_path(CONTAINER_NAME, "trt2/Acordao/" + arquivo, path)
            block_service.delete_blob(CONTAINER_NAME, blob.name)
            os.remove(path)
        elif text_complete.find("despacho") >= 0 and text_complete.find("conclusão") < 0 and text_complete.find("embargo") < 0 and \
                        text_complete.find("ata de audiência") < 0 and text_complete.find("termo de audiência") < 0 and \
                        text_complete.find("v o t o") < 0 and text_complete.find("certidão") < 0 :
            print("Encontrei Despacho")
            print("Arquivo "+path)
            block_service.create_blob_from_path(CONTAINER_NAME, "trt2/Despacho/" + arquivo, path)
            block_service.delete_blob(CONTAINER_NAME, blob.name)
            os.remove(path)
        elif text_complete.find("sentença") >= 0 and text_complete.find("relatório") >= 0 and \
                        text_complete.find("acordam") < 0 and text_complete.find("primeira testemunha") < 0 and \
                        text_complete.find("provas a produzir") < 0 and text_complete.find("embargo") < 0 and \
                        text_complete.find("voto") < 0:
            print("Encontrei Sentença")
            print("Arquivo "+path)
            block_service.create_blob_from_path(CONTAINER_NAME, "trt2/Sentenca/" + arquivo, path)
            block_service.delete_blob(CONTAINER_NAME, blob.name)
            os.remove(path)

        else:
            block_service.create_blob_from_path(CONTAINER_NAME, "trt2/Outros/" + arquivo, path)
            block_service.delete_blob(CONTAINER_NAME, blob.name)
            os.remove(path)


问:
Display a data.frame with mathematical notation in table header R Markdown html output
Say I'd like to display a table of coefficients from several equations in an R Markdown file (html output).

I'd like the table to look somewhat like this:

But I can't for the life of me figure out how to tell R Markdown to parse the column names in the table.

The closest I've gotten is a hacky solution using cat to print custom table from my data.frame... not ideal.  Is there a better way to do this?

Here's how I created the image above, saving my file as an .Rmd in RStudio.

```<code>---
title: "Math in R Markdown tables"
output:
  html_notebook: default
  html_document: default
---

My fancy table

```{r, echo=FALSE, include=TRUE, results="asis"}
# Make data.frame
mathy.df <- data.frame(site = c("A", "B"),
                       b0 = c(3, 4),
                       BA = c(1, 2))

# Do terrible things to print it properly
cat("Site|$\\beta_0$|$\\beta_A$")
cat("\n")
cat("----|---------|---------\n")

for (i in 1:nrow(mathy.df)){
  cat(as.character(mathy.df[i,"site"]), "|",
      mathy.df[i,"b0"], "|",
      mathy.df[i,"BA"],
      "\n", sep = "")
}
```
</code>```

答:
You can use kable() and its escape option to format math notation (see this answer to a related question). Then you assign your mathy headings as the column names, and there you go:

```<code>---
title: "Math in R Markdown tables"
output:
  html_notebook: default
  html_document: default
---

My fancy table

```{r, echo=FALSE, include=TRUE, results="asis"}
library(knitr)

mathy.df <- data.frame(site = c("A", "B"),
                       b0 = c(3, 4),
                       BA = c(1, 2))

colnames(mathy.df) <- c("Site", "$\\beta_0$", "$\\beta_A$")

kable(mathy.df, escape=FALSE)
```
</code>```

Body:
Say I'd like to display a table of coefficients from several equations in an R Markdown file (html output).

I'd like the table to look somewhat like this:

But I can't for the life of me figure out how to tell R Markdown to parse the column names in the table.

The closest I've gotten is a hacky solution using cat to print custom table from my data.frame... not ideal.  Is there a better way to do this?

Here's how I created the image above, saving my file as an .Rmd in RStudio.

---
title: "Math in R Markdown tables"
output:
  html_notebook: default
  html_document: default
---

My fancy table

```{r, echo=FALSE, include=TRUE, results="asis"}
# Make data.frame
mathy.df <- data.frame(site = c("A", "B"),
                       b0 = c(3, 4),
                       BA = c(1, 2))

# Do terrible things to print it properly
cat("Site|$\\beta_0$|$\\beta_A$")
cat("\n")
cat("----|---------|---------\n")

for (i in 1:nrow(mathy.df)){
  cat(as.character(mathy.df[i,"site"]), "|",
      mathy.df[i,"b0"], "|",
      mathy.df[i,"BA"],
      "\n", sep = "")
}
```

Body:
You can use kable() and its escape option to format math notation (see this answer to a related question). Then you assign your mathy headings as the column names, and there you go:

---
title: "Math in R Markdown tables"
output:
  html_notebook: default
  html_document: default
---

My fancy table

```{r, echo=FALSE, include=TRUE, results="asis"}
library(knitr)

mathy.df <- data.frame(site = c("A", "B"),
                       b0 = c(3, 4),
                       BA = c(1, 2))

colnames(mathy.df) <- c("Site", "$\\beta_0$", "$\\beta_A$")

kable(mathy.df, escape=FALSE)
```


问:
React Native application crashing immediately - no linked packages
I've been trying to debug an old project for quite some time. This project was crashing every time I installed and ran a release build with ./gradlew assembleRelease and react-native run-android --variant=release. The weird thing is, the debug version was running just fine (react-native run-android).

Finally, I gave up and moved all of the javascript to completely brand-new project, attaching it only via the index.js that came when I ran react-native init <project>.

Again, the project runs just fine in debug but the release build crashes immediately without any indication of what could be going wrong.

Details

I'm using react-native: 0.50.3, react: 16.1.1, and I've stripped the project down so that there are no linked packages (as far as I'm aware, my project is now completely written in javascript).

Question

I'd like to at least figure out how I might begin debugging this. I posted a question react-native build a standalone app in dev mode earlier because I'd like for the app to give me details instead of crashing. How can I figure out the root cause of the crash?

答:
I realize that this isn't necessarily a solution, but it turns out there was a version mismatch that wasn't showing itself in the debug build. I'm still not sure the exact issue is.

My advice would be to run the release build with Android Studio running. I didn't know this was possible, and as soon as I learned, the problem was fixed after I was able to identify the problematic package and updating it.


问:
Swashbuckle.AspNetCore only generating models with fields of type string
So I have a group model like this:

```<code>public class GroupDTO {
    [Required]
    public Guid? Id { get; set; }

    [Required(AllowEmptyStrings = false)]
    [StringLength(maximumLength: 50)]
    public string Name { get; set; }
}
</code>```

But the generated model by swagger looks like this:

```<code>[
  {
    "id": "string",
    "name": "string"
  }
]
</code>```

It should look something like this:

```<code>[
  {
    "id": "00000000-0000-0000-0000-000000000000",
    "name": "string"
  }
]
</code>```

Anyone got an idea?

答:
Guids are treated as strings by Swashbuckle.

Answered by @ceferrari in the comments.

Body:
So I have a group model like this:

public class GroupDTO {
    [Required]
    public Guid? Id { get; set; }

    [Required(AllowEmptyStrings = false)]
    [StringLength(maximumLength: 50)]
    public string Name { get; set; }
}

But the generated model by swagger looks like this:

[
  {
    "id": "string",
    "name": "string"
  }
]

It should look something like this:

[
  {
    "id": "00000000-0000-0000-0000-000000000000",
    "name": "string"
  }
]

Anyone got an idea?


问:
Hyperledger Fabric SDK location
In the Hyperledger Fabric architecture where is the SDK hosted?

After pouring through the Fabric guides and documents I still can't find the exact specification of where the SDK for interacting with or deploying chaincode resides in the overall network architecture.

I am curious as if it is a node on the network then I see this as a single point of failure.

答:
So, the SDK is actually the part in the business flow that interacts with the customer, and therefore it can be hosted anywhere.

It can be a web application that acts as a front end, having the fabric as the back-end

It can be a phone application that a user has

It can be even an IoT device on a RaspBerry Pi that simply logs periodically real world data into the blockchain

It can be a service that interacts with other services inside a data center.

Title: Hyperledger Fabric SDK location


问:
How to upload via REST API
I have an angular 5 app and I'm using the primeng upload tool. the api post for uploading requires three parameters: file (file), id (string), fileType (string). I can do the latter two but the file type i just don't understand. the latter two are strings, got it, but how do i address the file part?

this is my json post:

```<code>[{ "file" : <<DATA>>, "id": "1234123", "fileType": "doc" }]
</code>```

What and how to I put in something for the file type?

答:
PrimeNG FileUpload's documentation is quite good so I'd suggest taking a closer look at the documentation at: PrimeNG File Upload

For your specific requirement, I'd suggest taking PrimeNG File Upload and make it as "fancy file picker". Snippets as below:

```<code>HTML
<p-fileUpload
  name="demo[]"
  auto="true"
  customUpload="true"
  (uploadHandler)="myUploader($event)"
  multiple="multiple">
</p-fileUpload>

TS
myUploader(event) {
 consol.log(event.files) //This will return all of the files that are selected. You can omit multiple files by getting rid of `multiple` attribute from the template
//Take this event.files and do whatever you want with it
}
</code>```

Plunker example, turn on the Console

Title: How to upload via REST API

Body:
I have an angular 5 app and I'm using the primeng upload tool. the api post for uploading requires three parameters: file (file), id (string), fileType (string). I can do the latter two but the file type i just don't understand. the latter two are strings, got it, but how do i address the file part?

this is my json post:

[{ "file" : <<DATA>>, "id": "1234123", "fileType": "doc" }]

What and how to I put in something for the file type?

Body:
PrimeNG FileUpload's documentation is quite good so I'd suggest taking a closer look at the documentation at: PrimeNG File Upload

For your specific requirement, I'd suggest taking PrimeNG File Upload and make it as "fancy file picker". Snippets as below:

HTML
<p-fileUpload
  name="demo[]"
  auto="true"
  customUpload="true"
  (uploadHandler)="myUploader($event)"
  multiple="multiple">
</p-fileUpload>

TS
myUploader(event) {
 consol.log(event.files) //This will return all of the files that are selected. You can omit multiple files by getting rid of `multiple` attribute from the template
//Take this event.files and do whatever you want with it
}

Plunker example, turn on the Console


问:
Unable to reference webservice (.asmx) in my ASP.NET Project
In my current project, I have a webservice file called MyServices.asmx. This webservice I want to reference in my Default.aspx.cs file.

My Code:

```<code>    MyServices newService = new MyServices();

    newService.addUser(txFirstName.Text, txLastName.Text, txtEmail.Text,
txtUserName.Text, txtPassword.Text, txtBalance.Text);
</code>```

But when I refer to that webservice (as shown below), I get error saying:
"The type or namespace name 'MyServices' could not be found (are you missing a using directive or an assembly reference?)"

What should I do to correct this error?

Current Solution of Adding Service Reference still gives me that error. Can you please suggest what could be wrong?

答:
Assuming that you added the reference and called the reference MyServices when you added it...

MyServices is the  name you gave the reference when you added it.  You need to find the name of the actual service.

For example, we have a web services website, and it contains many different web services (asmx files).  Assume we have one called EmployeeInformationService

In Visual Studio, I might add a reference to it and choose the name "MyServices" as you did.  To reference it in code I would need to put:

```<code>MyServices.EmployeeInformationService  newService = new MyServices.EmployeeInformationService();
</code>```

Body:
In my current project, I have a webservice file called MyServices.asmx. This webservice I want to reference in my Default.aspx.cs file.

My Code:

    MyServices newService = new MyServices();

    newService.addUser(txFirstName.Text, txLastName.Text, txtEmail.Text,
txtUserName.Text, txtPassword.Text, txtBalance.Text);

But when I refer to that webservice (as shown below), I get error saying:
"The type or namespace name 'MyServices' could not be found (are you missing a using directive or an assembly reference?)"

What should I do to correct this error?

Current Solution of Adding Service Reference still gives me that error. Can you please suggest what could be wrong?

Body:
Assuming that you added the reference and called the reference MyServices when you added it...

MyServices is the  name you gave the reference when you added it.  You need to find the name of the actual service.

For example, we have a web services website, and it contains many different web services (asmx files).  Assume we have one called EmployeeInformationService

In Visual Studio, I might add a reference to it and choose the name "MyServices" as you did.  To reference it in code I would need to put:

MyServices.EmployeeInformationService  newService = new MyServices.EmployeeInformationService();