问:
Edit Delphi record from C++ DLL

I'm trying to create a DLL using Visual C++ that is called from a Delphi 5 program. The Delphi program passes in a record, which is then edited in the DLL, and the Delphi program uses the results.

For example, the Delphi code is similar to the following:

```<code>Type dll_btvar = record
    age : smallint;
    name : array[0..11] of char;
    value : Double;
end;

// Import the function from the dll
function foo(CVars : dll_btvar):integer; external 'example.dll';

// Call the dll
function callFoo(var passedVar:dll_btvar):integer;
begin
    result := foo(passedVar);
    // Use passedVar.value
end;
</code>```

A sample of the C++ code:

In example.h:

```<code>#pragma once
#include "dllVar.h"
extern "C" {
    __declspec(dllexport) int foo(DLL_Var var);
}
</code>```

In example.cpp:

```<code>#include "example.h"
int foo(DLL_Var var){
    var.value = var.age + var.name[0];
    return 0;
}
</code>```

In dllVar.h:

```<code>#pragma once
#pragma pack(8)
extern "C" {
    struct DLL_Var {
        short age;
        char name[12];
        double value;
    }
}
</code>```

I use #pragma pack(8) as that value gave correct alignment so that the passed record is read correctly in the DLL.

In the sample code, when passing an age and name, I expect value to be set by the DLL, which can then be recovered in the Delphi program. Result would be some sort of error code.

Using identical code in C++ Builder 5 did work, however it is of course outdated and I haven't moved all the code in my DLL over (nor do I want to), only the minimum you see here.

I tested a couple of ways to have Delphi pass an address/pointer to the dll, however they didn't change anything.

Right now, the return value is sent correctly, but the fields of the record (i.e. value) remain unchanged.

What changes do I need to make to either the Delphi or C++ to capture changes in the passed record? I am happy to work extensively with the C++ but I'd prefer to keep the Delphi changes to a minimum since this is old software that I don't want to break.

答:
```<code>function foo(CVars : dll_btvar):integer; external 'example.dll';
</code>```

The problem starts here, in the Delphi code. The record is passed by value. That is, the caller's record variable is copied to a new variable which is then passed to the function. This means that modifications by the callee to this copy of the record are not seen by the caller. You must therefore pass the parameter as a var parameter:

```<code>function foo(var CVars : dll_btvar):integer; external 'example.dll';
</code>```

The next problem is the calling convention. You must use the same calling convention for both sides. Your code uses the default register convention on the Delphi side, which is not supported by non-Borland/Embarcadero tools. Use stdcall or cdecl instead. Let's opt for cdecl, the default for most C++ tools:

```<code>function foo(var CVars : dll_btvar):integer; cdecl; external 'example.dll';
</code>```

To make the C++ code match, pass the argument by reference:

```<code>__declspec(dllexport) int __cdecl foo(DLL_Var &var);
</code>```

Or explicitly use a pointer:

```<code>__declspec(dllexport) int __cdecl foo(DLL_Var *var);
</code>```

In the latter option, the implementation needs to be changed because of the use of a pointer:

```<code>int foo(DLL_Var *var){
    var->value = var->age + var->name[0];
    return 0;
}
</code>```

Using identical code in C++ Builder 5 did work.

No it did not, because the Delphi code in your question cannot modify the caller's record.

Title: Edit Delphi record from C++ DLL

Body:
I'm trying to create a DLL using Visual C++ that is called from a Delphi 5 program. The Delphi program passes in a record, which is then edited in the DLL, and the Delphi program uses the results.

For example, the Delphi code is similar to the following:

Type dll_btvar = record
    age : smallint;
    name : array[0..11] of char;
    value : Double;
end;

// Import the function from the dll
function foo(CVars : dll_btvar):integer; external 'example.dll';

// Call the dll
function callFoo(var passedVar:dll_btvar):integer;
begin
    result := foo(passedVar);
    // Use passedVar.value
end;

A sample of the C++ code:

In example.h:

#pragma once
#include "dllVar.h"
extern "C" {
    __declspec(dllexport) int foo(DLL_Var var);
}

In example.cpp:

#include "example.h"
int foo(DLL_Var var){
    var.value = var.age + var.name[0];
    return 0;
}

In dllVar.h:

#pragma once
#pragma pack(8)
extern "C" {
    struct DLL_Var {
        short age;
        char name[12];
        double value;
    }
}

I use #pragma pack(8) as that value gave correct alignment so that the passed record is read correctly in the DLL.

In the sample code, when passing an age and name, I expect value to be set by the DLL, which can then be recovered in the Delphi program. Result would be some sort of error code.

Using identical code in C++ Builder 5 did work, however it is of course outdated and I haven't moved all the code in my DLL over (nor do I want to), only the minimum you see here.

I tested a couple of ways to have Delphi pass an address/pointer to the dll, however they didn't change anything.

Right now, the return value is sent correctly, but the fields of the record (i.e. value) remain unchanged.

What changes do I need to make to either the Delphi or C++ to capture changes in the passed record? I am happy to work extensively with the C++ but I'd prefer to keep the Delphi changes to a minimum since this is old software that I don't want to break.

Body:
function foo(CVars : dll_btvar):integer; external 'example.dll';

The problem starts here, in the Delphi code. The record is passed by value. That is, the caller's record variable is copied to a new variable which is then passed to the function. This means that modifications by the callee to this copy of the record are not seen by the caller. You must therefore pass the parameter as a var parameter:

function foo(var CVars : dll_btvar):integer; external 'example.dll';

The next problem is the calling convention. You must use the same calling convention for both sides. Your code uses the default register convention on the Delphi side, which is not supported by non-Borland/Embarcadero tools. Use stdcall or cdecl instead. Let's opt for cdecl, the default for most C++ tools:

function foo(var CVars : dll_btvar):integer; cdecl; external 'example.dll';

To make the C++ code match, pass the argument by reference:

__declspec(dllexport) int __cdecl foo(DLL_Var &var);

Or explicitly use a pointer:

__declspec(dllexport) int __cdecl foo(DLL_Var *var);

In the latter option, the implementation needs to be changed because of the use of a pointer:

int foo(DLL_Var *var){
    var->value = var->age + var->name[0];
    return 0;
}

Using identical code in C++ Builder 5 did work.

No it did not, because the Delphi code in your question cannot modify the caller's record.


来源: stackexchange

问:
HTML form method is POST but it's submitting as OPTIONS
I have a weird thing happening to say the least.

An html form that has a method of post when submitted is using options instead, here's the html code:

```<code><form action="https://omitted" method="post" id="canvasForm">
    <div class="form-group" style="margin-top: 10%; text-align: center;">
        <h1>Canvas Integration</h1>
        <label style="text-align: right;" for="school_name" class="col-sm-4 control-label">School Prefix *</label>
        <div class="col-sm-10">
            <input type="text" style="margin-right: 1%; margin-bottom: 2%; width:60%" class="form-control" name="school_name" placeholder="School Prefix" tabindex="1" required>
            <!-- <i class="fa fa-question-circle" aria-hidden="true"></i> -->
        </div>
        <label style="text-align: right;" for="code" class="col-sm-4 control-label">Code *</label>
        <div class="col-sm-6" >
            <input id="code" type="text" class="form-control" style="margin-right: 1%; margin-bottom: 2%; width:60%" name="code" tabindex="1" placeholder="code" required>
        </div>
        <label style="text-align: right;" for="code" class="col-sm-4 control-label">School Canvas URL *</label>
        <div class="col-sm-6" >
            <input id="canvas_url" type="text" class="form-control" style="margin-right: 1%; margin-bottom: 2%; width:60%" name="canvas_url" tabindex="1" placeholder="school canvas url" required>
        </div>
        <label style="text-align: right;" for="clientid" class="col-sm-4 control-label">ID *</label>
        <div class="col-sm-6">
            <input type="text" class="form-control" style="margin-bottom: 2%;margin-right: 1%; width:60%" name="clientid" placeholder="ID" tabindex="1" required>
            <div class="tooltip">
                <i class="fa fa-question-circle" aria-hidden="true" >
                <img  class="tooltiptext" src="images/clientid.png" style="width: 550px"></i>
            </div>
        </div>
        <label style="text-align: right;" for="securitykey" class="col-sm-4 control-label">Key *</label>
        <div class="col-sm-6">
            <input type="text" class="form-control" style="margin-right: 1%; margin-bottom: 2%; width:60%" name="securitykey" placeholder="Key" tabindex="1" required>
            <div class="tooltip">
                <i class="fa fa-question-circle" aria-hidden="true" >
                <img  class="tooltiptext" src="images/securitykey.png" style="width: 550px"></i>
            </div>
        </div>
        <div class="col-sm-6">
            <input id="redirect_url" type="hidden" class="form-control" style="margin-right: 1%; margin-bottom: 2%; width:60%;float: center;" name="redirect_url" placeholder="Canvas URL" tabindex="1" required>
        </div>
    </div>
    <div class="form-group" style="text-align: center;">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-primary btn-w-md" >Submit</button>
        </div>
    </div>
    <div class="form-group" style="text-align: center;">
        <div id="response" class="col-sm-offset-2 col-sm-10">
        </div>
    </div>
</form>
</code>```

and I have some JS code that submits the form:

```<code>    form.onsubmit = function (e) {
        // stop the regular form submission
        e.preventDefault();

        // collect the form data while iterating over the inputs
        var data = {};
        for (var i = 0, ii = form.length; i < ii; ++i) {
          var input = form[i];
          if (input.name) {
            data[input.name] = input.value;
          }
        }
        // construct an HTTP request
        var xhr = new XMLHttpRequest();
        xhr.open(form.method, form.action, true);
        xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

        // send the collected data as JSON
        xhr.send(JSON.stringify(data));

        xhr.onloadend = function (response) {
          console.log('response from server',response);
          var responseHtml = document.getElementById('response');
          if(response.target.status==400){
             responseHtml.innerHTML = '<div id="response" class="alert alert-success" role="alert" >' + response.target.response +'. Please contact edquire support team at support@edquire.com.' + '</div>';
          } else if (response.target.status==200) {
             responseHtml.innerHTML = '<div id="response" class="alert alert-success" role="alert" >' + response.target.response +'! Your Canvas resource is successfully connected with us :)' + '</div>';
          } else {
             responseHtml.innerHTML = '<div id="response" class="alert alert-success" role="alert" >' + 'Something went wrong :( Please Try Again!' + '</div>';
          }
        };
    };
</code>```

when I submit it I can see that it's using options and it's not passing the input fields (check screenshot below)

答: That's how CORS works. You are submitting a POST request to a remote host. First your browser submits an OPTIONS request to check whether the remote host accepts HTTP requests from other hosts. If it does the POST request will be submitted afterwards.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a weird thing happening to say the least.

An html form that has a method of post when submitted is using options instead, here's the html code:

<form action="https://omitted" method="post" id="canvasForm">

Canvas Integration

        School Prefix *

            <input type="text" style="margin-right: 1%; margin-bottom: 2%; width:60%" class="form-control" name="school_name" placeholder="School Prefix" tabindex="1" required>

        Code *

            <input id="code" type="text" class="form-control" style="margin-right: 1%; margin-bottom: 2%; width:60%" name="code" tabindex="1" placeholder="code" required>

        School Canvas URL *

            <input id="canvas_url" type="text" class="form-control" style="margin-right: 1%; margin-bottom: 2%; width:60%" name="canvas_url" tabindex="1" placeholder="school canvas url" required>

        ID *

            <input type="text" class="form-control" style="margin-bottom: 2%;margin-right: 1%; width:60%" name="clientid" placeholder="ID" tabindex="1" required>

        Key *

            <input type="text" class="form-control" style="margin-right: 1%; margin-bottom: 2%; width:60%" name="securitykey" placeholder="Key" tabindex="1" required>

            <input id="redirect_url" type="hidden" class="form-control" style="margin-right: 1%; margin-bottom: 2%; width:60%;float: center;" name="redirect_url" placeholder="Canvas URL" tabindex="1" required>

            <button type="submit" class="btn btn-primary btn-w-md" >Submit</button>

</form>

and I have some JS code that submits the form:

    form.onsubmit = function (e) {
        // stop the regular form submission
        e.preventDefault();

        // collect the form data while iterating over the inputs
        var data = {};
        for (var i = 0, ii = form.length; i < ii; ++i) {
          var input = form[i];
          if (input.name) {
            data[input.name] = input.value;
          }
        }
        // construct an HTTP request
        var xhr = new XMLHttpRequest();
        xhr.open(form.method, form.action, true);
        xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

        // send the collected data as JSON
        xhr.send(JSON.stringify(data));

        xhr.onloadend = function (response) {
          console.log('response from server',response);
          var responseHtml = document.getElementById('response');
          if(response.target.status==400){
             responseHtml.innerHTML = '
' + response.target.response +'. Please contact edquire support team at support@edquire.com.' + '
';
          } else if (response.target.status==200) {
             responseHtml.innerHTML = '
' + response.target.response +'! Your Canvas resource is successfully connected with us :)' + '
';
          } else {
             responseHtml.innerHTML = '
' + 'Something went wrong :( Please Try Again!' + '
';
          }
        };
    };

when I submit it I can see that it's using options and it's not passing the input fields (check screenshot below)


问:
How to expire/delete Mongoose document (as expected after either 5 seconds or a day)
Here's a simple Schema how do I delete the document after either a day or 5 seconds?

```<code>import mongoose from 'mongoose';

const schema = new mongoose.Schema({
    id: {type: String, required: true},//yelp id
    userId: {type: mongoose.Schema.Types.ObjectId, required: true}
});
</code>```

Ideas I've tried some delete after a minute nothing deletes in a day.

```<code>// schema.index({createdAt: 1},{expireAfterSeconds: 3600});// doesnt work
// schema.index({"expires": 1}, {expireAfterSeconds: 5});
// schema.index({ first: 1, last: -1});
 // schema.index({ createdAt: { type: Date, expires: 1 }});
 // schema.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 3600 })
// schema.createIndex({"expire_at": 1 }, { expireAfterSeconds: 0 } )
</code>```

I'm hoping for a short sweet mongoose solution nothing too complicated.

答:
You can use TTL index to delete data automatically after 5 seconds.

db.eventlog.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 5 } )

Body:
Here's a simple Schema how do I delete the document after either a day or 5 seconds?

import mongoose from 'mongoose';

const schema = new mongoose.Schema({
    id: {type: String, required: true},//yelp id
    userId: {type: mongoose.Schema.Types.ObjectId, required: true}
});

Ideas I've tried some delete after a minute nothing deletes in a day.

// schema.index({createdAt: 1},{expireAfterSeconds: 3600});// doesnt work
// schema.index({"expires": 1}, {expireAfterSeconds: 5});
// schema.index({ first: 1, last: -1});
 // schema.index({ createdAt: { type: Date, expires: 1 }});
 // schema.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 3600 })
// schema.createIndex({"expire_at": 1 }, { expireAfterSeconds: 0 } )

I'm hoping for a short sweet mongoose solution nothing too complicated.


问:
mongoDB Geospatial Query $geoWithin got error 'Loop is not closed'
i am newbie for Geospatial Query of mongodb and i try search for point within polygon which have code like below :

```<code>db.properties.find({
  location:{
    $geoWithin : {
      $geometry : {
        type:"Polygon",
        coordinates: [[
            [104.9172382, 11.57934524],
            [104.9146632, 11.5724502],
            [104.92753788, 11.57976566]
        ]]
        }
      }
    }
  })
</code>```

and my data table look like below :

i want to get result of all point is inside polygon.but i really have no clue

this error alway popup

|____/ Mongo Server error (MongoQueryException): Query failed with
  error code 2 and error message 'Loop is not closed: [ [ 104.9172382,
  11.57934524 ], [ 104.9146632, 11.5724502 ], [ 104.92753788, 11.57976566 ] ]' on server

thank for any idea !

Body:
i am newbie for Geospatial Query of mongodb and i try search for point within polygon which have code like below :

db.properties.find({
  location:{
    $geoWithin : {
      $geometry : {
        type:"Polygon",
        coordinates: [[
            [104.9172382, 11.57934524],
            [104.9146632, 11.5724502],
            [104.92753788, 11.57976566]
        ]]
        }
      }
    }
  })

and my data table look like below :

i want to get result of all point is inside polygon.but i really have no clue

this error alway popup

|____/ Mongo Server error (MongoQueryException): Query failed with
  error code 2 and error message 'Loop is not closed: [ [ 104.9172382,
  11.57934524 ], [ 104.9146632, 11.5724502 ], [ 104.92753788, 11.57976566 ] ]' on server

thank for any idea !

Body:
i found answer that we need to start coordinate and close coordinates are the same value.

db.properties.find({
  location:{
    $geoWithin : {
      $geometry : {
        type:"Polygon",
        coordinates:[
            [
                [ 104.9212999921292 , 11.575955591122819 ] , // start loop
                [ 104.92129194550216 , 11.575198826419006 ] ,
                [ 104.92298978380859 , 11.575238241297862 ] ,
                [ 104.92291736416519 , 11.576023910057827 ] ,
                [ 104.9212999921292 , 11.575955591122819 ] // close loop
            ]
        ]
       }
     }
   }
})


问:
R: Using function arguments to update elements in a data frame
I want the elements referenced in my data frame to be replaced with the argument I put into the function, however at the moment it is just replacing the elements with the argument I used to initially define the function (I'm finding it hard to explain - hopefully my code and pictures will clarify this a bit!)

```<code>Project_assign <- function(prjct) {
  Truth_vector <- is.element((giraffe[,1]),(prjct[,1]))
  giraffe[which(Truth_vector),5] <- 'prjct'
  assign('giraffe' , giraffe , envir= .GlobalEnv)
}
Project_assign(spine_hlfs)
</code>```

This mostly works however the elements get replaced with prjct instead of spine_hlfs
 https://i.stack.imgur.com/uuPnv.png

If I can get this to work as intended, then I will next create a vector with all the project names and use lapply with this function saving me a lot of manual work every few months. I am relatively new to R so any explanations are well appreciated.

答:
Sounds like a simple replace based on matching entries between a (list of) query dataframes and a subject dataframe.

Here is an example based on some simulated data.

I first simulate data for the subject dataframe:

```<code># Sample data
giraffe <- data.frame(
    runkeys = seq(1:500),
    col1 = runif(500),
    col2 = runif(500),
    col3 = runif(500),
    col4 = runif(500));
</code>```

I then simulate runkeys data for 2 query dataframes:

```<code>spine_hlfs <- data.frame(
    runkeys = c(44, 260, 478));
ir_dia <- data.frame(
    runkeys = c(10, 20, 30))
</code>```

The query dataframes are stored in a list:

```<code>lst.runkeys <- list(
    spine_hlfs = spine_hlfs,
    ir_dia = ir_dia);
</code>```

To flag runkeys entries present in any of the query dataframes, we can use a for loop to match runkeys entries from every query dataframe:

```<code># This is the critical line that loops through the dataframe
# and flags runkeys in giraffe with the name of the query dataframe
for (i in 1:length(lst.runkeys)) {
    giraffe[match(lst.runkeys[[i]]$runkeys, giraffe$runkeys), 5] <- names(lst.runkeys)[i];
}
</code>```

This is the output of the subject dataframe after matching runkeys entries. I'm only showing rows where entries in column 5 where replaced.

```<code>giraffe[grep("(spine_hlfs|ir_dia)", giraffe[, 5]), ];
10       10 0.7401977 0.005703928 0.6778921     ir_dia
20       20 0.7954076 0.331462567 0.7637870     ir_dia
30       30 0.5772808 0.183716142 0.6984193     ir_dia
44       44 0.9701355 0.655736489 0.4917452 spine_hlfs
260     260 0.1893012 0.600140166 0.0390346 spine_hlfs
478     478 0.7655976 0.910946623 0.9779205 spine_hlfs
</code>```

Body:
I want the elements referenced in my data frame to be replaced with the argument I put into the function, however at the moment it is just replacing the elements with the argument I used to initially define the function (I'm finding it hard to explain - hopefully my code and pictures will clarify this a bit!)

Project_assign <- function(prjct) {
  Truth_vector <- is.element((giraffe[,1]),(prjct[,1]))
  giraffe[which(Truth_vector),5] <- 'prjct'
  assign('giraffe' , giraffe , envir= .GlobalEnv)
}
Project_assign(spine_hlfs)

This mostly works however the elements get replaced with prjct instead of spine_hlfs
 https://i.stack.imgur.com/uuPnv.png

If I can get this to work as intended, then I will next create a vector with all the project names and use lapply with this function saving me a lot of manual work every few months. I am relatively new to R so any explanations are well appreciated.

Body:
Sounds like a simple replace based on matching entries between a (list of) query dataframes and a subject dataframe.

Here is an example based on some simulated data.

I first simulate data for the subject dataframe:

# Sample data
giraffe <- data.frame(
    runkeys = seq(1:500),
    col1 = runif(500),
    col2 = runif(500),
    col3 = runif(500),
    col4 = runif(500));

I then simulate runkeys data for 2 query dataframes:

spine_hlfs <- data.frame(
    runkeys = c(44, 260, 478));
ir_dia <- data.frame(
    runkeys = c(10, 20, 30))

The query dataframes are stored in a list:

lst.runkeys <- list(
    spine_hlfs = spine_hlfs,
    ir_dia = ir_dia);

To flag runkeys entries present in any of the query dataframes, we can use a for loop to match runkeys entries from every query dataframe:

# This is the critical line that loops through the dataframe
# and flags runkeys in giraffe with the name of the query dataframe
for (i in 1:length(lst.runkeys)) {
    giraffe[match(lst.runkeys[[i]]$runkeys, giraffe$runkeys), 5] <- names(lst.runkeys)[i];
}

This is the output of the subject dataframe after matching runkeys entries. I'm only showing rows where entries in column 5 where replaced.

giraffe[grep("(spine_hlfs|ir_dia)", giraffe[, 5]), ];
10       10 0.7401977 0.005703928 0.6778921     ir_dia
20       20 0.7954076 0.331462567 0.7637870     ir_dia
30       30 0.5772808 0.183716142 0.6984193     ir_dia
44       44 0.9701355 0.655736489 0.4917452 spine_hlfs
260     260 0.1893012 0.600140166 0.0390346 spine_hlfs
478     478 0.7655976 0.910946623 0.9779205 spine_hlfs


问:
Multiple MySQL statements via JDBC sampler in JMeter
So I am trying to update my database using the data extracted from the HTTP request samplers. So I have the following sql query which works fine for one record:

```<code>UPDATE optim_user
SET equip_uptime = CONCAT('${timestamp_rg1}', ',', '${timestamp_ext1}'), equip_fw = CONCAT('${firmware_rg1}',',', '${firmware_ext1}')
WHERE optim_uid = '${serialnumber_soak1}';
</code>```

I want to update 50 or so records with the data extracted from my hTTP requests.
I have tried following the steps mentioned here but It did not work. Below are the screen shots of the CSV data config and the JDBC sampler

Is there a way to include multiple sql statements? Thanks.

答:
You can use case for multiple updates.in your case add multiple conditions as:

```<code> UPDATE optim_user
 SET equip_uptime = case   optim_uid
 WHEN   '${serialnumber_soak1}'  THEN
 CONCAT('${timestamp_rg1}', ',', '${timestamp_ext1}')
 End

  .....
</code>```

Body:
So I am trying to update my database using the data extracted from the HTTP request samplers. So I have the following sql query which works fine for one record:

UPDATE optim_user
SET equip_uptime = CONCAT('${timestamp_rg1}', ',', '${timestamp_ext1}'), equip_fw = CONCAT('${firmware_rg1}',',', '${firmware_ext1}')
WHERE optim_uid = '${serialnumber_soak1}';

I want to update 50 or so records with the data extracted from my hTTP requests.
I have tried following the steps mentioned here but It did not work. Below are the screen shots of the CSV data config and the JDBC sampler

Is there a way to include multiple sql statements? Thanks.

Body:
You can use case for multiple updates.in your case add multiple conditions as:

 UPDATE optim_user
 SET equip_uptime = case   optim_uid
 WHEN   '${serialnumber_soak1}'  THEN
 CONCAT('${timestamp_rg1}', ',', '${timestamp_ext1}')
 End

  .....


问:
new never fails?
In C++, we usually see and write code like,

```<code>Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}
</code>```

But in C#, I rarely see this: (at least I've never seen this)

```<code>Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}
</code>```

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.

答:
new can certainly fail.

Constructors are allowed to throw exceptions.
You can also run out of memory when creating a new object.

ContentLicense: CC BY-SA 2.5

Title: new never fails?

Body:
In C++, we usually see and write code like,

Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}

But in C#, I rarely see this: (at least I've never seen this)

Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.


问:
while(i) loop in JavaScript
I ran the below code in JavaScript

```<code>let i = 3;
while (i) {
    console.log(i--);
}
</code>```

since the while(i) is not like while(i>0) then I expected the result as 3,2,1,0,-1,-2,...

but the actual result is 3,2,1. Could anyone explain this case to me? I am confused.

答:
The while loop runs until the check condition is false.

In this case, it is the value of i.

Since Javascript is dynamically typed(ie -  we don't define the types when defining the variables) the value of i is converted into a boolean from the type it is currently in.

In this case, you are setting numerical values to i. And the number 0 is considered to be falsely. Therefore, breaking the while loop.

You can refer here for a full list of falsely value.

Title: while(i) loop in JavaScript

Body:
I ran the below code in JavaScript

let i = 3;
while (i) {
    console.log(i--);
}

since the while(i) is not like while(i>0) then I expected the result as 3,2,1,0,-1,-2,...

but the actual result is 3,2,1. Could anyone explain this case to me? I am confused.


问:
MicroC PIC16F887,Analog pin
I'm using the PIC16F887,and i'm new to this.

How to make B1 as analog pin.

How to receive information from pressure sensor to B1.

Thanks
Sorry for my bad English.

答:
One good thing about PIC controller is that, datasheet itself gives the clear steps to use its peripherals. Refer to the section 9.1 and 9.2
Datasheet

There is another wiki page which explains with c code but different PIC - however you could refer for the programming.

ADC Using PIC16F877A

Coming to your question : What you mean by B1? did you mean RB1 (or Port B, Pin 1)? if so, from the datasheet, RB1 is AN10 (Analog channel 10). So you need to set CHS<3:0> bits of ADCON0 register to b'1010'

These details from PIC controller side

You would have to read datasheet of the Pressure sensor too.

Without reading datasheets, you cannot work with the micro-controller

Sudhee

Title: MicroC PIC16F887,Analog pin


问:
Angular Observable combinelatest
I'm trying to build a component that access a service and return an observable with a list of objects to populate a table

My service has a  function :

public getTranches(): Observable<Tranche[]> {
    this.loadTranches(); //this calls the rest API to populate the variable _tranches
    return this._tranches.asObservable(); // return variable <BehaviourSubject>_tranches asObservable
  }
```

<p>My Component consists of a table displaying the data through:</p>

<pre class="lang-js prettyprint-override"><code>this.subscription = this.apiService
   .getTranches()
     .subscribe(
      (data) => {
       this.tranches = data;
       }
  );
</code>```

html:

<ng-container *ngFor="let tranche of tranches">
   // stuff
</ng-container>
```

<p>Up util here everything works fine.</p>

<p>I added a input and click events to the table headers</p>

<pre class="lang-html prettyprint-override"><code>//header example for sortby
<div (click)="this.filters.sortby = name"></div>

//input for filter
<input (keyup)="this.filters.search = $event.target.value" type="text">
</code>```

and a variable filters to store that information

can you show me how to transform the filter variable in a observable and merge it to a single subscription to feed the table so I can perform the filtering and sorting on the component?

I've tried using filter as behaviourSubject and use combineLatest to merge them unsuccessfully if that is the way to do it can I see an example?

答:
assume it start off from a onSearch function bind to a user action to trigger api call

```<code>filters=new BehaviorSubject({sortby:'',search:''})
onSearch=()=>{
filters.map(obj=>{
// asume you will need to add a object param in getTranches to deal with sortby and search
return this.apiService.getTranches(obj)
}).subscribe();
}
</code>```

in your html

```<code><div (click)="this.filters.next({sortby:name})"></div>
<input (keyup)="this.filters.next({search:$event.target.value})" type="text">
</code>```

Title: Angular Observable combinelatest

Body:
I'm trying to build a component that access a service and return an observable with a list of objects to populate a table

My service has a  function :

public getTranches(): Observable<Tranche[]> {
    this.loadTranches(); //this calls the rest API to populate the variable _tranches
    return this._tranches.asObservable(); // return variable <BehaviourSubject>_tranches asObservable
  }

My Component consists of a table displaying the data through:

this.subscription = this.apiService
   .getTranches()
     .subscribe(
      (data) => {
       this.tranches = data;
       }
  );

html:

<ng-container *ngFor="let tranche of tranches">
   // stuff
</ng-container>

Up util here everything works fine.

I added a input and click events to the table headers

//header example for sortby

//input for filter
<input (keyup)="this.filters.search = $event.target.value" type="text">

and a variable filters to store that information

can you show me how to transform the filter variable in a observable and merge it to a single subscription to feed the table so I can perform the filtering and sorting on the component?

I've tried using filter as behaviourSubject and use combineLatest to merge them unsuccessfully if that is the way to do it can I see an example?

Body:
assume it start off from a onSearch function bind to a user action to trigger api call

filters=new BehaviorSubject({sortby:'',search:''})
onSearch=()=>{
filters.map(obj=>{
// asume you will need to add a object param in getTranches to deal with sortby and search
return this.apiService.getTranches(obj)
}).subscribe();
}

in your html

<div (click)="this.filters.next({sortby:name})"></div>
<input (keyup)="this.filters.next({search:$event.target.value})" type="text">


问:
Angular condition and cssclass in same ngClass
I need to use both condition and class in same "ngClass" is there any possible way?

[ngClass]="{cssclass1 : object.cssclass1status , object.cssclass2}"

The bold part is the condition and italic part is a CSS class that can be changed. I have used this options separately like,

```<code>conditional [ngClass]="{cssclass1 : object.cssclass1status}"

object.cssclass1status : Boolean

classes [ngClass]="object.cssclass2"

object.cssclass2 : string
</code>```

答:
You have to pass in the object to a method and let the method build out the object syntax for ngClass. For example

```<code>// component.html
<div [ngClass]="getClasses(object)">...</div>

// component.ts
getClasses(obj){
    let classes = {
        'cssclass1': obj.cssclass1status // determine true/false of class one
    };

    classes[obj.cssclass2] = true; // set class name and set to true
    return classes;
}
</code>```

Here is a stackblitz demoing this.

Body:
I need to use both condition and class in same "ngClass" is there any possible way?

[ngClass]="{cssclass1 : object.cssclass1status , object.cssclass2}"

The bold part is the condition and italic part is a CSS class that can be changed. I have used this options separately like,

conditional [ngClass]="{cssclass1 : object.cssclass1status}"

object.cssclass1status : Boolean

classes [ngClass]="object.cssclass2"

object.cssclass2 : string

Body:
You have to pass in the object to a method and let the method build out the object syntax for ngClass. For example

// component.html
<div [ngClass]="getClasses(object)">...</div>

// component.ts
getClasses(obj){
    let classes = {
        'cssclass1': obj.cssclass1status // determine true/false of class one
    };

    classes[obj.cssclass2] = true; // set class name and set to true
    return classes;
}

Here is a stackblitz demoing this.


问:
Three options for SQL WHERE clause, the third of which could be LIKE either of the first two
I have a database application (MS Access) in which the hours that employees were paid for based on reported hours are compared to the hours they were on site via a fingerprinting in and out system.  The boxes that record the fingerprint punches can give three possible "punch markers" which are "in" "out" "auto".  If the security guard fails to choose in or out then the data record will have a marker of auto.

The application finds a total number of hours on site via 2 queries:

1:

```<code>WHERE Marker LIKE "in"
</code>```

2:

```<code>WHERE Marker LIKE "out"
</code>```

and then subtracting the "in" punch from the "out" punch for a particular employee.  This works fine until we have an "auto" punch.  In this case the employee is reported to have been here 0 hours.  I thought about doing:

```<code>WHERE Marker LIKE "out" or "auto"
</code>```

But I can't say for sure that the "auto" marker will be the out time.  Sometimes it should be in time.

Here is a screenshot of a small piece of the data I receive

The in out marker is here called "mode".

I would love thoughts and/or brainstorming on how I might make this work;

答:
its better if you set a new field and call it 'button_option' and set the default value as 'auto' , then use marker like a (temporary clothes hook) !!

basically record the callback value of Marker from button_option

  - if button_option = 'in'
  ,Marker = 'in' if button_option = out ,Marker = out

 - if "button_option" is 'auto' the callback will be reversed based on last value available in Marker.
    which is what the employee choose last time

then your auto recording process in ms-access > sql should look like :

```<code>iif (button_option= 'auto' && Marker = 'in', "out", "in");
</code>```

logically mean :

```<code>If [button_option] = 'auto' && [Marker] = 'in' Then
  Marker = "out"
Else
  Marker = "in"
End If
</code>```

Translation :

```<code>if employee set the button auto -AND- his last choice was 'out' then he should be 'in' cause he cant be out twice without in !!
</code>```

Example of using iif() function in a query in Microsoft Access :

Click HERE to see the Image

u can use the image example above also to callback the value without creating button_option , but it would be more messy and complicated for you

Body:
I have a database application (MS Access) in which the hours that employees were paid for based on reported hours are compared to the hours they were on site via a fingerprinting in and out system.  The boxes that record the fingerprint punches can give three possible "punch markers" which are "in" "out" "auto".  If the security guard fails to choose in or out then the data record will have a marker of auto.

The application finds a total number of hours on site via 2 queries:

1:

WHERE Marker LIKE "in"

2:

WHERE Marker LIKE "out"

and then subtracting the "in" punch from the "out" punch for a particular employee.  This works fine until we have an "auto" punch.  In this case the employee is reported to have been here 0 hours.  I thought about doing:

WHERE Marker LIKE "out" or "auto"

But I can't say for sure that the "auto" marker will be the out time.  Sometimes it should be in time.

Here is a screenshot of a small piece of the data I receive

The in out marker is here called "mode".

I would love thoughts and/or brainstorming on how I might make this work;

Body:
its better if you set a new field and call it 'button_option' and set the default value as 'auto' , then use marker like a (temporary clothes hook) !!

basically record the callback value of Marker from button_option

  - if button_option = 'in'
  ,Marker = 'in' if button_option = out ,Marker = out

 - if "button_option" is 'auto' the callback will be reversed based on last value available in Marker.
    which is what the employee choose last time

then your auto recording process in ms-access > sql should look like :

iif (button_option= 'auto' && Marker = 'in', "out", "in");

logically mean :

If [button_option] = 'auto' && [Marker] = 'in' Then
  Marker = "out"
Else
  Marker = "in"
End If

Translation :

if employee set the button auto -AND- his last choice was 'out' then he should be 'in' cause he cant be out twice without in !!

Example of using iif() function in a query in Microsoft Access :

Click HERE to see the Image

u can use the image example above also to callback the value without creating button_option , but it would be more messy and complicated for you


问:
How to create text overlay on a bootstrap panel
I'm just wondering if someone can show me the best way to show some text over a panel in jquery/javascript using some sort of overlay.

I want to disable everything in the panel and then show a big 'canceled' centered right in the middle.

Right now I have just a regular bootstrap panel like this jsfiddle

Here is some of the code I have so far

$(".panel").addClass('.disabledbutton');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.disabledbutton {
  pointer-events: none;
  opacity: 0.4;
}</code>```

      Panel title

      Panel content

```

答:
If I understand you correctly the easiest way to do this would be, to put another div inside your panel with cancelled written in it and then hide it by default and then show it when you want it to have cancelled written there so

HTML

```<code><div class="panel-body">
   <p>Panel content</p>
   <div class="panel-body_cancelled">
       <h1>CANCELLED</h1>
   </div>
</div>
</code>```

then in your CSS

```<code>.panel-body_cancelled{
    display: none;
}

.panel-body_cancelled_active{
    display: block;
    z-index: 10000;
}
</code>```

then in your jQuery say you want to activate the cancelled div with a click event

```<code>$('.yourbutton').click(function(){
    $(.panel-body_cancelled).toggleClass('panel-body_cancelled_active');
})
</code>```

Body:
I'm just wondering if someone can show me the best way to show some text over a panel in jquery/javascript using some sort of overlay.

I want to disable everything in the panel and then show a big 'canceled' centered right in the middle.

Right now I have just a regular bootstrap panel like this jsfiddle

Here is some of the code I have so far

$(".panel").addClass('.disabledbutton');

.disabledbutton {
  pointer-events: none;
  opacity: 0.4;
}

      Panel title

      Panel content

Body:
If I understand you correctly the easiest way to do this would be, to put another div inside your panel with cancelled written in it and then hide it by default and then show it when you want it to have cancelled written there so

HTML

<div class="panel-body">
   <p>Panel content</p>
   <div class="panel-body_cancelled">
       <h1>CANCELLED</h1>
   </div>
</div>

then in your CSS

.panel-body_cancelled{
    display: none;
}

.panel-body_cancelled_active{
    display: block;
    z-index: 10000;
}

then in your jQuery say you want to activate the cancelled div with a click event

$('.yourbutton').click(function(){
    $(.panel-body_cancelled).toggleClass('panel-body_cancelled_active');
})


问:
Bash script loop through netCDF files via placeholder and use cdo commands
I want to loop through 40 netCDF files. There are 20 files with the variable PRECC and 20 files with the variable PRECL("modelmember001.PRECC.192001-200512.nc", "modelmember002.PRECC.192001-200512.nc", ... ,"modelmember020.PRECC.192001-200512.nc" and for PRECL respectively).

I need to perform multiple cdo (climate data operator) commands with the loop (add PRECC and PRECL files, and change time series form 1920-2005 to 1955-2005).

This is the code that I use:

```<code>  datadir="path_to_mydatat"
    workdir="path_to_folder_for_newfiles"
    members="{001 .. 020}"

    for model in $members
    do

    echo 'working with model' ${model}

    echo cdo -s add ${datadir}/modelmember${members}.PRECC.192001-200512.nc${datadir}/modelmember${members}.PRECL.192001-200512.nc ${workdir}/modelmember${members}PRECT.192001-200512.nc
    # echo cdo -s selyear,1955/2005 ${workdir}/modelmember${members}.PRECT.192001-200512.nc ${workdir}/modelmember${members}.PRECT.195501-200512.nc
</code>```

Eventually I need 20 files with the name

```<code>"modelmember001.PRECT.195501-200512.nc", "modelmember002.PRECT.195501-200512.nc", ... , "modelmember020.PRECT.195501-200512.nc"
</code>```

This is what I get when I run my code (deliberately with an "echo" in front of the cdo line):

```<code>$./cdo_add.sh

{001 .. 020}

working with model {001

cdo -s add /path_to_mydatat/modelmember{001 .. 020}.PRECC.192001-200512.nc         /path_to_mydatat/modelmember{001 .. 020}.PRECL.192001-200512.nc  /path_to_folder_for_newfiles/modelmember{001 .. 020}.PRECT.192001-200512.nc

working with model ..

cdo -s add /path_to_mydatat/modelmember{001 .. 020}.PRECC.192001-200512.nc /path_to_mydatat/modelmember{001 .. 020}.PRECL.192001-200512.nc /path_to_folder_for_newfiles/modelmember{001 .. 020}.PRECT.192001-200512.nc

working with model 020}

cdo -s add /path_to_mydatat/modelmember{001 .. 020}.PRECC.192001-200512.nc /path_to_mydatat/modelmember{001 .. 020}.PRECL.192001-200512.nc /path_to_folder_for_newfiles/modelmember{001 .. 020}.PRECT.192001-200512.nc
</code>```

My code doesn't seem to loop through the members. There is something wrong with the way I use the placeholder "members" but I can't figure out how to fix it.
Does anyone have a suggestion?
Cheers!

答:
Your code does not seem to loop because you cannot assign a brace expansion to a variable and expect it to expand when substituted in a for loop. The following saves the literal string "{001 .. 020}" to the variable members, e.g.

```<code>members="{001 .. 020}"
</code>```

When you use members in for model in $members, normal word-splitting occurs because it is just a string and you loop once with 001, then with .. and finally with 020 -- not the expected sequence from 001, 002, 003, ... 020. (there should be no spaces between the number and .. to begin with -- but that still doesn't allow you to use the expansion in a variable)

To properly use the expansion, get rid of the members variable altogether and use {001..020} in the loop, e.g.

```<code>for model in {001..020}   ## (notice NO space between 001 and ..)
</code>```

example:

```<code>$ for m in {001..020}; do echo $m; done
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
</code>```

That will allow you to loop with your sequence in model.

From the conversation in the comments, I know understand that you have 40 files prefixed by modelmemberXXX (where XXX is 001-020) followed by .PRECC* or .PRECL* (20 files each) that you want to coordinate feeding matching pairs to a cdo command. While the preferred way would be to loop over one matching glob, e.g. for i in modelmember*.PRECC*; do, you can also use your brace expansion approach, e.g.

```<code>for i in {001..020}
do
    a=$(echo modelmember${i}.PRECC*)
    b=$(echo modelmember${i}.PRECL*)
    if [ -e "$a" ] && [ -f "$b" ]
    then
        printf "%s\n%s\n\n" "$a" "$b"
    fi
done
</code>```

(note the [ -e "$a" ] && [ -f "$b" ] test just makes sure both files in the pair exist before proceeding with the command (printf here))

Example Output

```<code>modelmember001.PRECC.192001-200512.nc
modelmember001.PRECL.192001-200512.nc

modelmember002.PRECC.192001-200512.nc
modelmember002.PRECL.192001-200512.nc

modelmember003.PRECC.192001-200512.nc
modelmember003.PRECL.192001-200512.nc
...
modelmember020.PRECC.192001-200512.nc
modelmember020.PRECL.192001-200512.nc
</code>```

You simply need to make use of $a and $b with whatever cdo_cmd you need within the loop. (as noted in the comments, you need to change to the directory containing the files, or precede the filenames with path/to/the/files)

Preferred Way

Rather than using your brace expansion, it is probably preferred to loop over one set (either PRECC or PRECL), validate the other exists, then execute the command, e.g.

```<code>for i in modelmember*.PRECC*
do
    b="${i/PRECC/PRECL}"
    if [ -e "$i" ] && [ -f "$b" ]
    then
        printf "%s\n%s\n\n" "$i" "$b"
    fi
done
</code>```

(same output)

Body:
I want to loop through 40 netCDF files. There are 20 files with the variable PRECC and 20 files with the variable PRECL("modelmember001.PRECC.192001-200512.nc", "modelmember002.PRECC.192001-200512.nc", ... ,"modelmember020.PRECC.192001-200512.nc" and for PRECL respectively).

I need to perform multiple cdo (climate data operator) commands with the loop (add PRECC and PRECL files, and change time series form 1920-2005 to 1955-2005).

This is the code that I use:

  datadir="path_to_mydatat"
    workdir="path_to_folder_for_newfiles"
    members="{001 .. 020}"

    for model in $members
    do

    echo 'working with model' ${model}

    echo cdo -s add ${datadir}/modelmember${members}.PRECC.192001-200512.nc${datadir}/modelmember${members}.PRECL.192001-200512.nc ${workdir}/modelmember${members}PRECT.192001-200512.nc
    # echo cdo -s selyear,1955/2005 ${workdir}/modelmember${members}.PRECT.192001-200512.nc ${workdir}/modelmember${members}.PRECT.195501-200512.nc

Eventually I need 20 files with the name

"modelmember001.PRECT.195501-200512.nc", "modelmember002.PRECT.195501-200512.nc", ... , "modelmember020.PRECT.195501-200512.nc"

This is what I get when I run my code (deliberately with an "echo" in front of the cdo line):

$./cdo_add.sh

{001 .. 020}

working with model {001

cdo -s add /path_to_mydatat/modelmember{001 .. 020}.PRECC.192001-200512.nc         /path_to_mydatat/modelmember{001 .. 020}.PRECL.192001-200512.nc  /path_to_folder_for_newfiles/modelmember{001 .. 020}.PRECT.192001-200512.nc

working with model ..

cdo -s add /path_to_mydatat/modelmember{001 .. 020}.PRECC.192001-200512.nc /path_to_mydatat/modelmember{001 .. 020}.PRECL.192001-200512.nc /path_to_folder_for_newfiles/modelmember{001 .. 020}.PRECT.192001-200512.nc

working with model 020}

cdo -s add /path_to_mydatat/modelmember{001 .. 020}.PRECC.192001-200512.nc /path_to_mydatat/modelmember{001 .. 020}.PRECL.192001-200512.nc /path_to_folder_for_newfiles/modelmember{001 .. 020}.PRECT.192001-200512.nc

My code doesn't seem to loop through the members. There is something wrong with the way I use the placeholder "members" but I can't figure out how to fix it.
Does anyone have a suggestion?
Cheers!

Body:
Your code does not seem to loop because you cannot assign a brace expansion to a variable and expect it to expand when substituted in a for loop. The following saves the literal string "{001 .. 020}" to the variable members, e.g.

members="{001 .. 020}"

When you use members in for model in $members, normal word-splitting occurs because it is just a string and you loop once with 001, then with .. and finally with 020 -- not the expected sequence from 001, 002, 003, ... 020. (there should be no spaces between the number and .. to begin with -- but that still doesn't allow you to use the expansion in a variable)

To properly use the expansion, get rid of the members variable altogether and use {001..020} in the loop, e.g.

for model in {001..020}   ## (notice NO space between 001 and ..)

example:

$ for m in {001..020}; do echo $m; done
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020

That will allow you to loop with your sequence in model.

From the conversation in the comments, I know understand that you have 40 files prefixed by modelmemberXXX (where XXX is 001-020) followed by .PRECC* or .PRECL* (20 files each) that you want to coordinate feeding matching pairs to a cdo command. While the preferred way would be to loop over one matching glob, e.g. for i in modelmember*.PRECC*; do, you can also use your brace expansion approach, e.g.

for i in {001..020}
do
    a=$(echo modelmember${i}.PRECC*)
    b=$(echo modelmember${i}.PRECL*)
    if [ -e "$a" ] && [ -f "$b" ]
    then
        printf "%s\n%s\n\n" "$a" "$b"
    fi
done

(note the [ -e "$a" ] && [ -f "$b" ] test just makes sure both files in the pair exist before proceeding with the command (printf here))

Example Output

modelmember001.PRECC.192001-200512.nc
modelmember001.PRECL.192001-200512.nc

modelmember002.PRECC.192001-200512.nc
modelmember002.PRECL.192001-200512.nc

modelmember003.PRECC.192001-200512.nc
modelmember003.PRECL.192001-200512.nc
...
modelmember020.PRECC.192001-200512.nc
modelmember020.PRECL.192001-200512.nc

You simply need to make use of $a and $b with whatever cdo_cmd you need within the loop. (as noted in the comments, you need to change to the directory containing the files, or precede the filenames with path/to/the/files)

Preferred Way

Rather than using your brace expansion, it is probably preferred to loop over one set (either PRECC or PRECL), validate the other exists, then execute the command, e.g.

for i in modelmember*.PRECC*
do
    b="${i/PRECC/PRECL}"
    if [ -e "$i" ] && [ -f "$b" ]
    then
        printf "%s\n%s\n\n" "$i" "$b"
    fi
done

(same output)


问:
How to run my testng classes one after the other
I am running an automated test where i have two classes in a package. Below is my testng.xml file

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<suite name="AutomationFramework">
    <test name="RegressionTesting">
        <classes>
            <class name="first_Test.testng"/>
            <class name="first_Test.TestNG2"/>
        </classes>
    </test>
</suite>
</code>```

my first class(testng) runs with Chrome, while the second (TestNG2) runs with Firefox. When I run my testng.xml file, I see both the browsers getting opened together and executing their test cases at the same time.

How can I prioritize that my first class runs in chrome and then when its finished, the second class runs.

Thanks!

答:
In the suite tag , add two attributes parallel="none" and limit the thread count to 1. The tag should look like

```<code><suite name="AutomationFramework" parallel="false" thread-count="1">
</code>```

This should disable the concurrent execution.

Body:
I am running an automated test where i have two classes in a package. Below is my testng.xml file

    <?xml version="1.0" encoding="UTF-8"?>
<suite name="AutomationFramework">
    <test name="RegressionTesting">
        <classes>
            <class name="first_Test.testng"/>
            <class name="first_Test.TestNG2"/>
        </classes>
    </test>
</suite>

my first class(testng) runs with Chrome, while the second (TestNG2) runs with Firefox. When I run my testng.xml file, I see both the browsers getting opened together and executing their test cases at the same time.

How can I prioritize that my first class runs in chrome and then when its finished, the second class runs.

Thanks!

Body:
In the suite tag , add two attributes parallel="none" and limit the thread count to 1. The tag should look like

<suite name="AutomationFramework" parallel="false" thread-count="1">

This should disable the concurrent execution.


问:
HTML5 <video> tag not working in Firefox
```<code>    <video  poster="https://res.cloudinary.com/deesul/image/upload/v1482128248/Up_ci3qna.jpg" autoplay="true" loop preload="auto" >
  <source src="https://res.cloudinary.com/deesul/video/upload/v1482630062/Up_1_ofz5ri.ogv" type="video/ogv">
 <source src="https://res.cloudinary.com/deesul/video/upload/v1482126175/Up_srxisl.webm" type='video/webm; codecs="vp8.0, vorbis"'>
  <source src="https://res.cloudinary.com/deesul/video/upload/v1482126174/Up_tle5de.mp4" type="video/mp4">
</video>
</code>```

<p>this is not displaying the poster nor the video in firefox. Please help me resolve this issue on firefox. </p>

答:
This is basic structure from MDN and W3C

<video width="600px" height="320px" class="video" controls poster="https://unsplash.it/598/320">
   <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
  <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
  <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
<source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
</video>```

Body:
    <video  poster="https://res.cloudinary.com/deesul/image/upload/v1482128248/Up_ci3qna.jpg" autoplay="true" loop preload="auto" >
  <source src="https://res.cloudinary.com/deesul/video/upload/v1482630062/Up_1_ofz5ri.ogv" type="video/ogv">
 <source src="https://res.cloudinary.com/deesul/video/upload/v1482126175/Up_srxisl.webm" type='video/webm; codecs="vp8.0, vorbis"'>
  <source src="https://res.cloudinary.com/deesul/video/upload/v1482126174/Up_tle5de.mp4" type="video/mp4">
</video>

this is not displaying the poster nor the video in firefox. Please help me resolve this issue on firefox.


答:
With the rest client, every POST request is followed by a POST.
This is done to verify few things, for example :

Whether it is a valid request

if the method is supported etc.

You can find more information on another thread here:
What is the reason behind using OPTION request before POST on CORS requests?

Title: HTML form method is POST but it's submitting as OPTIONS

Body:
I have a weird thing happening to say the least.

An html form that has a method of post when submitted is using options instead, here's the html code:

<form action="https://omitted" method="post" id="canvasForm">

Canvas Integration

        School Prefix *

            <input type="text" style="margin-right: 1%; margin-bottom: 2%; width:60%" class="form-control" name="school_name" placeholder="School Prefix" tabindex="1" required>

        Code *

            <input id="code" type="text" class="form-control" style="margin-right: 1%; margin-bottom: 2%; width:60%" name="code" tabindex="1" placeholder="code" required>

        School Canvas URL *

            <input id="canvas_url" type="text" class="form-control" style="margin-right: 1%; margin-bottom: 2%; width:60%" name="canvas_url" tabindex="1" placeholder="school canvas url" required>

        ID *

            <input type="text" class="form-control" style="margin-bottom: 2%;margin-right: 1%; width:60%" name="clientid" placeholder="ID" tabindex="1" required>

        Key *

            <input type="text" class="form-control" style="margin-right: 1%; margin-bottom: 2%; width:60%" name="securitykey" placeholder="Key" tabindex="1" required>

            <input id="redirect_url" type="hidden" class="form-control" style="margin-right: 1%; margin-bottom: 2%; width:60%;float: center;" name="redirect_url" placeholder="Canvas URL" tabindex="1" required>

            <button type="submit" class="btn btn-primary btn-w-md" >Submit</button>

</form>

and I have some JS code that submits the form:

    form.onsubmit = function (e) {
        // stop the regular form submission
        e.preventDefault();

        // collect the form data while iterating over the inputs
        var data = {};
        for (var i = 0, ii = form.length; i < ii; ++i) {
          var input = form[i];
          if (input.name) {
            data[input.name] = input.value;
          }
        }
        // construct an HTTP request
        var xhr = new XMLHttpRequest();
        xhr.open(form.method, form.action, true);
        xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

        // send the collected data as JSON
        xhr.send(JSON.stringify(data));

        xhr.onloadend = function (response) {
          console.log('response from server',response);
          var responseHtml = document.getElementById('response');
          if(response.target.status==400){
             responseHtml.innerHTML = '
' + response.target.response +'. Please contact edquire support team at support@edquire.com.' + '
';
          } else if (response.target.status==200) {
             responseHtml.innerHTML = '
' + response.target.response +'! Your Canvas resource is successfully connected with us :)' + '
';
          } else {
             responseHtml.innerHTML = '
' + 'Something went wrong :( Please Try Again!' + '
';
          }
        };
    };

when I submit it I can see that it's using options and it's not passing the input fields (check screenshot below)


问:
Finding closest match in collection of numbers
So I got asked today what was the best way to find the closes match within a collection.

For example, you've got an array like this:

```<code>1, 3, 8, 10, 13, ...
</code>```

What number is closest to 4?

Collection is numerical, unordered and can be anything. Same with the number to match.

Lets see what we can come up with, from the various languages of choice.

答:
The above code doesn't works for floating numbers.<br>
So here's my revised php code for that. </p>

```<code>function find_closest($match, $set=array()) {
    foreach ($set as $fib) {
        $diff[$fib] = abs($match - $fib);
    }
    return array_search(min($diff), $diff);
}

$set = array('2.3', '3.4', '3.56', '4.05', '5.5', '5.67');
echo find_closest(3.85, $set); //return 4.05
</code>```

OwnerDisplayName: Slace

Body:
So I got asked today what was the best way to find the closes match within a collection.

For example, you've got an array like this:

1, 3, 8, 10, 13, ...

What number is closest to 4?

Collection is numerical, unordered and can be anything. Same with the number to match.

Lets see what we can come up with, from the various languages of choice.

LastEditorDisplayName: Allain Lalonde

Body:
The above code doesn't works for floating numbers.

So here's my revised php code for that.

function find_closest($match, $set=array()) {
    foreach ($set as $fib) {
        $diff[$fib] = abs($match - $fib);
    }
    return array_search(min($diff), $diff);
}

$set = array('2.3', '3.4', '3.56', '4.05', '5.5', '5.67');
echo find_closest(3.85, $set); //return 4.05


问:
c# TCP Server Client Threading Issies
Here is the problem,
I have below scenario coded.

A TCP Listener running in thread A connecting to a Client 1

A Second TCP Listener running in thread B Connecting to multiple clients each in a different thread. By this I mean as soon as a client is
accepted in thread B, A different thread is created for further
processing of the client where it waits to get data from "TCP
Listener B" in a while loop

What I want to do and where I'm facing problem is,

I want to pass data recieved from Thread 1 by the Client 1 to clients in thread 2.

What I believe is happening,

Since I'm in Thread 1 when I get data from Client 1 in Thread 1, when I try sending data to clients in thread 2, I always get connection false.

Is this a threading issue?

How can I overcome it issue?

EDIT

It's a windows form application

Both the TCP Listener run in same application.

I'm maintaining a list of TcpClients that connect to TCP Listener B and when I get some data from thread A, I get the TCP Client from this list that I maintain and try to send the data, but cannot as connection state becomes false.

答:
As i can see, you are using threads and a Winform with socket servers and socket clients, and it could make that socket gets blocked.

Try to use a single thread to attend all your TCPListeners and TCPClients, using asynchronous methods which help to avoid socket blocking:

For TcpListener use the method: AcceptSocketAsync.

For TcpClients use the NetworkStream to use the BeginRead and BeginWrite. In this answer i show how i used them.

Title: c# TCP Server Client Threading Issies


问:
How to set time zone on Android Things rp3?
I would like to change timezone on AndroidThings device on Raspberry PI3. I have already checked here and here . This last one using adb date somedate works, but after losing power, the date resets itself.

Is there anyway that we could set timezone from Java or running a shell? The required Timezone of the device is received from server.

答:
With DP6 you can use the TimeManager API without requesting for the permission in the manifest.</p>

```<code>new TimeManager().setTimeZone(String timezone)
</code>```

Body:
With DP6 you can use the TimeManager API without requesting for the permission in the manifest.

new TimeManager().setTimeZone(String timezone)


问:
Selenium how to extract href from attributes
```<code><div class="turbolink_scroller" id="container">
 <article><div class="inner- article">
  <a style="height:81px;" href="LINK TO EXTRACT">
   <img width="81" height="81" src="//image.jpg" alt="code" />
</code>```

Hello! I'm pretty new to selenium and I've been playing around with how to get sources for my webdriver. So far, I'm trying to extract a href link given an alt code as above and I'm not sure if the documentation has a means to do this. I'm feeling that the answer is find_by_xpath but I'm not entirely sure. Thank you for any tips!

答:
The way is as follows

```<code>href = driver.find_element_by_tag_name('a').get_attribute('href')
</code>```

of course, you may have a lot of 'a' tags in a page, so you may make the path to your respective tag,

e.g

```<code>div = driver.find_element_by_id('container')
a = div.find_element_by_tag_name('a')
href = a.get_attribute('href')
</code>```

Body:
The way is as follows

href = driver.find_element_by_tag_name('a').get_attribute('href')

of course, you may have a lot of 'a' tags in a page, so you may make the path to your respective tag,

e.g

div = driver.find_element_by_id('container')
a = div.find_element_by_tag_name('a')
href = a.get_attribute('href')


问:
jquery mobile site not formatting on android device
I am using an example from www3schools to see how to create an application on an android device;

```<code>    <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet"
    href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-
    1.4.5.min.js"></script>

    <script>
    var _hmt = _hmt || [];
    (function() {
    var hm = document.createElement("script");
    hm.src = "//hm.baidu.com/hm.js?73c27e26f610eb3c9f3feb0c75b03925";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
    })();
    </script>
    </head>
    <body>

    <div data-role="page" id="pageone" data-theme="a">
    <div data-role="header">
    <h1>Page Header</h1>
    </div>

    <div data-role="main" class="ui-content">
    <p>Some Text..</p>
    <a href="#">A Standard Text Link</a>
    <a href="#" class="ui-btn">Link Button</a>
    <p>A List View:</p>
    <ul data-role="listview" data-autodividers="true" data-inset="true">
    <li><a href="#">Adele</a></li>
    <li><a href="#">Billy</a></li>
    </ul>
    <label for="fullname">Input Field:</label>
    <input type="text" name="fullname" id="fullname" placeholder="Name..">
    <label for="switch">Toggle Switch:</label>
    <select name="switch" id="switch" data-role="slider">
    <option value="on">On</option>
    <option value="off" selected>Off</option>
    </select>
    </div>

    <div data-role="footer">
    <h1>Page Footer</h1>
    </div>
    </div>

    </body>
    </html>
</code>```

The screen shot below shows the view from browser on my computer;

The screen shot below shows the browser view on my android device; running android version 7;

I am using phonegap online build to create the app which is downloaded to the android device. I can not see why this is not rendering the same in the android device. I am using the same browser in each, chrome.
Any guidance would be appreciated.

答: I have finally solved this. I was uploading just the index.html to the online phone gap build service.I now have included the other files that phonegap uses when linking to a local device. This has fixed the problem. I thought these would have been added automatically by the online build site. See screen shot below of app on phone.

Body:
I am using an example from www3schools to see how to create an application on an android device;

    <!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet"
    href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

Page Header

Some Text..

    A Standard Text Link
    Link Button

A List View:

Adele

Billy

    Input Field:
    <input type="text" name="fullname" id="fullname" placeholder="Name..">
    Toggle Switch:
    <select name="switch" id="switch" data-role="slider">
    <option value="on">On</option>
    <option value="off" selected>Off</option>
    </select>

Page Footer

The screen shot below shows the view from browser on my computer;

The screen shot below shows the browser view on my android device; running android version 7;

I am using phonegap online build to create the app which is downloaded to the android device. I can not see why this is not rendering the same in the android device. I am using the same browser in each, chrome.
Any guidance would be appreciated.


答:
If new fails, then there will be an OutOfMemoryException thrown.

So the equivalent of the C++ code you have would be this:

```<code>try {
  Sample sample = new Sample();
} catch(OutOfMemoryException e) {
  Console.WriteLine("Memory allocation failed\n");
}
</code>```

Title: new never fails?

Body:
In C++, we usually see and write code like,

Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}

But in C#, I rarely see this: (at least I've never seen this)

Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.

Body:
If new fails, then there will be an OutOfMemoryException thrown.

So the equivalent of the C++ code you have would be this:

try {
  Sample sample = new Sample();
} catch(OutOfMemoryException e) {
  Console.WriteLine("Memory allocation failed\n");
}


问:
Finding user in TFS Project programmatically
We have more than one collection under one TFS server and each collection have more than one project. I want to be able to check if entered username is part of any project level group on TFS server.
So far I am able to connect to TFS, and get all project names under the collection. I need help in finding the group name and then querying those groups to check if user is part of that group or not.

Here is the code I tried -

```<code>static void Main(string[] args)
    {
        NetworkCredential netCred = new NetworkCredential(@"username", @"pwd");
        TfsConfigurationServer configServ = new TfsConfigurationServer(new Uri("https://my-tfs.schwab.com/tfs"), netCred);

        var tfsAllCols = new List<KeyValuePair<Guid, string>>();
        try
        {
            configServ.Authenticate();
            Console.WriteLine("Autheticated in server with ad creds...");

            ReadOnlyCollection<CatalogNode> colNodes = configServ.CatalogNode.QueryChildren(
                new[] { CatalogResourceTypes.ProjectCollection },
                false,
                CatalogQueryOptions.None);
            foreach (CatalogNode node in colNodes)
            {
                var colId = new Guid(node.Resource.Properties["InstanceId"]);
                TfsTeamProjectCollection teamProjectCollection =
                    configServ.GetTeamProjectCollection(colId);

                tfsAllCols.Add(new KeyValuePair<Guid, string>(colId, teamProjectCollection.Name));

            }

    //hardcoding the colname for testing
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("https://ruby-tfs.schwab.com/tfs/colname/"), netCred);

            tpc.EnsureAuthenticated();

            // Get the catalog of team project collections
            ReadOnlyCollection<CatalogNode> projNodes = tpc.CatalogNode.QueryChildren(
            new[] { CatalogResourceTypes.TeamProject },
            false, CatalogQueryOptions.None);

        }
        catch (Exception ex)
        {

            throw ex;
        }

        Console.ReadLine();
    }
</code>```

答:
Instead of hard coding, you could use TFSSecurity command-line tool to retrieve the groups and members in team project:

Use /g to list the groups in a team project, in a team project collection, or across Team Foundation Server:

tfssecurity /g [scope] [/collection:CollectionURL] [/server:ServerURL]

Use /imx to display information about the identities that compose the expanded membership of a specified group:

```<code>> tfssecurity /imx Identity [/collection:CollectionURL][/server:ServerURL]
</code>```

If you insist hard coding, you could follow the blog below to query TFS for groups and memberships:

https://blogs.msdn.microsoft.com/vasu_sankaran/2010/10/11/querying-tfs-for-groups-and-memberships/

Update:

Body:
We have more than one collection under one TFS server and each collection have more than one project. I want to be able to check if entered username is part of any project level group on TFS server.
So far I am able to connect to TFS, and get all project names under the collection. I need help in finding the group name and then querying those groups to check if user is part of that group or not.

Here is the code I tried -

static void Main(string[] args)
    {
        NetworkCredential netCred = new NetworkCredential(@"username", @"pwd");
        TfsConfigurationServer configServ = new TfsConfigurationServer(new Uri("https://my-tfs.schwab.com/tfs"), netCred);

        var tfsAllCols = new List<KeyValuePair<Guid, string>>();
        try
        {
            configServ.Authenticate();
            Console.WriteLine("Autheticated in server with ad creds...");

            ReadOnlyCollection<CatalogNode> colNodes = configServ.CatalogNode.QueryChildren(
                new[] { CatalogResourceTypes.ProjectCollection },
                false,
                CatalogQueryOptions.None);
            foreach (CatalogNode node in colNodes)
            {
                var colId = new Guid(node.Resource.Properties["InstanceId"]);
                TfsTeamProjectCollection teamProjectCollection =
                    configServ.GetTeamProjectCollection(colId);

                tfsAllCols.Add(new KeyValuePair<Guid, string>(colId, teamProjectCollection.Name));

            }

    //hardcoding the colname for testing
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("https://ruby-tfs.schwab.com/tfs/colname/"), netCred);

            tpc.EnsureAuthenticated();

            // Get the catalog of team project collections
            ReadOnlyCollection<CatalogNode> projNodes = tpc.CatalogNode.QueryChildren(
            new[] { CatalogResourceTypes.TeamProject },
            false, CatalogQueryOptions.None);

        }
        catch (Exception ex)
        {

            throw ex;
        }

        Console.ReadLine();
    }

Body:
Instead of hard coding, you could use TFSSecurity command-line tool to retrieve the groups and members in team project:

Use /g to list the groups in a team project, in a team project collection, or across Team Foundation Server:

tfssecurity /g [scope] [/collection:CollectionURL] [/server:ServerURL]

Use /imx to display information about the identities that compose the expanded membership of a specified group:

> tfssecurity /imx Identity [/collection:CollectionURL][/server:ServerURL]

If you insist hard coding, you could follow the blog below to query TFS for groups and memberships:

https://blogs.msdn.microsoft.com/vasu_sankaran/2010/10/11/querying-tfs-for-groups-and-memberships/

Update:


问:
C#: Split comma-separated strings, but not if comma enclosed in single quotes
I am parsing a text file from some old hardware and I need to extract an array of strings from one long string.

Elements are comma-separated

Each individual string is enclosed in single quotes

'Hello', 'World'

```<code>{"'Hello', "'World'"}
</code>```

Single quotes for any other reason are illegal and there is no escaping character equivalent; you cannot write the word "Bob's" nor can do something like "Bob\'s".

Ordinarily it would be easy to get the individual elements by splitting on the comma:

```<code>string testString = "'Hello', 'World'";
ArrayList result = new ArrayList(testString.Split(',');
</code>```

But I can't do this; if a comma is in-between single quotes it is text, not a separator.

This is one element:

'Hello, World'

```<code>{"'Hello, World'"}
</code>```

How can I extract the elements checking to see if the comma is in-between single quotes?

'Hello', 'World', 'Hello, World'

```<code>{"'Hello'", "'World'", "'Hello, World'"}
</code>```

One more detail: I cannot guarantee the amount of whitespace between elements:

'Hello',     'World',  'Hello, World'

P.S. Here is the same question I asked for Swift: Swift: Split comma-separated strings, but not if comma enclosed in single quotes

答:
The easiest way would be using Json deserialzer  :

```<code>    private string[] F(string input){
        return Newtonsoft.Json.
           JsonConvert.DeserializeObject("["+input+"]",typeof(string[]));
       }
// now call F:
var result= F("'Hello','World','Hello,World'");
</code>```

Body:
I am parsing a text file from some old hardware and I need to extract an array of strings from one long string.

Elements are comma-separated

Each individual string is enclosed in single quotes

'Hello', 'World'

{"'Hello', "'World'"}

Single quotes for any other reason are illegal and there is no escaping character equivalent; you cannot write the word "Bob's" nor can do something like "Bob\'s".

Ordinarily it would be easy to get the individual elements by splitting on the comma:

string testString = "'Hello', 'World'";
ArrayList result = new ArrayList(testString.Split(',');

But I can't do this; if a comma is in-between single quotes it is text, not a separator.

This is one element:

'Hello, World'

{"'Hello, World'"}

How can I extract the elements checking to see if the comma is in-between single quotes?

'Hello', 'World', 'Hello, World'

{"'Hello'", "'World'", "'Hello, World'"}

One more detail: I cannot guarantee the amount of whitespace between elements:

'Hello',     'World',  'Hello, World'

P.S. Here is the same question I asked for Swift: Swift: Split comma-separated strings, but not if comma enclosed in single quotes

Body:
The easiest way would be using Json deserialzer  :

    private string[] F(string input){
        return Newtonsoft.Json.
           JsonConvert.DeserializeObject("["+input+"]",typeof(string[]));
       }
// now call F:
var result= F("'Hello','World','Hello,World'");


问:
Way to serve a "public" folder in github pages
I have personal blog in github repo myname.github.io, i generates my site contents using Cabin site generator which generate build files in public folder. I wanted to serve the contents from public folder for Github pages. But it is always looking at the root folder.

Is there any option to tell Github to serve contents from public folder, not from root folder?

答:
Remove the dist directory from the project’s .gitignore file (it’s ignored by default by Yeoman).

Make sure git knows about your subtree (the subfolder with your site).
git add dist && git commit -m "Initial dist subtree commit"

Use subtree push to send it to the gh-pages branch on GitHub.
git subtree push --prefix dist origin gh-pages
Source: https://gist.github.com/cobyism/4730490

Go to the settings of the project and set the gh-pages as the branch
        for the website


问:
Which parameters are local in a binary tree recursion?
```<code>import java.util.*;

    public static void main(String[] args) {

        TreeNode root = new TreeNode(8);
        root.left = new TreeNode(7);
        root.right = new TreeNode(6);
        root.left.left = new TreeNode(5);
        root.right.right = new TreeNode(4);
        List<Integer> list = postorderTraversal(root);
        System.out.println(list);
    }

    public static List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        list = helper(root, list);
        return list;
    }

    private static List<Integer> helper(TreeNode node, List<Integer> list){
        if (node != null) {
            helper(node.left, list);
            helper(node.right, list);
            list.add(node.val);
        }
        return list;
    }
}
</code>```

In this question, I don't understand why I don't have to do list = helper(node.left, list); Why is list global here and when I'm changing my root it's local and I have to do root.left = recurse(root.left) ?

答:
The statement

```<code>List<Integer> list = new ArrayList<Integer>();
</code>```

Does two things.  First it allocates a new ArrayList object on the heap. Then it stores a reference to that heap object in the local variable list.  When you invoke helper, you are passing only the reference, which can be thought of as a memory address referring to the actual object on the heap. This reference gets passed down to the recursive invocations of helper. Each invocation gets a local copy of list, but this is only a copy of the reference, not the heap object.  All those instances of list refer to the same heap object, the one you initially allocated.  This is why it "feels" like it's global, but it is most definitely not.

The same concept applies to the TreeNode references, in fact to all object references in Java.

This can be highly confusing for new Java programmers. Java is "Pass-by-value", meaning that parameters are copied when invoking a method, but when the variables are objects, the "value" is a reference and not the object itself, and only the reference is copied.  The only values that are copied for parameter passing are primitive values (boolean, char, int, long, float, double).

Body:
import java.util.*;

    public static void main(String[] args) {

        TreeNode root = new TreeNode(8);
        root.left = new TreeNode(7);
        root.right = new TreeNode(6);
        root.left.left = new TreeNode(5);
        root.right.right = new TreeNode(4);
        List<Integer> list = postorderTraversal(root);
        System.out.println(list);
    }

    public static List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        list = helper(root, list);
        return list;
    }

    private static List<Integer> helper(TreeNode node, List<Integer> list){
        if (node != null) {
            helper(node.left, list);
            helper(node.right, list);
            list.add(node.val);
        }
        return list;
    }
}

In this question, I don't understand why I don't have to do list = helper(node.left, list); Why is list global here and when I'm changing my root it's local and I have to do root.left = recurse(root.left) ?

Body:
The statement

List<Integer> list = new ArrayList<Integer>();

Does two things.  First it allocates a new ArrayList object on the heap. Then it stores a reference to that heap object in the local variable list.  When you invoke helper, you are passing only the reference, which can be thought of as a memory address referring to the actual object on the heap. This reference gets passed down to the recursive invocations of helper. Each invocation gets a local copy of list, but this is only a copy of the reference, not the heap object.  All those instances of list refer to the same heap object, the one you initially allocated.  This is why it "feels" like it's global, but it is most definitely not.

The same concept applies to the TreeNode references, in fact to all object references in Java.

This can be highly confusing for new Java programmers. Java is "Pass-by-value", meaning that parameters are copied when invoking a method, but when the variables are objects, the "value" is a reference and not the object itself, and only the reference is copied.  The only values that are copied for parameter passing are primitive values (boolean, char, int, long, float, double).


问:
Return a list of similar authors
I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors.

```<code>authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}
</code>```

And the function I came up with is this:

```<code>def get_similar(author_list, author):
    for item in author_list[author]:
        return author_list[author]
</code>```

Which only returns the items for the first key. I'd like it to return all of the similar authors, like this:

```<code>get_similar(authors, 'Harlan Ellison')

['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson',
 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
</code>```

Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut,

Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!

答:
I think this is what you are looking for.  Hopefully it gets you going.

```<code>authors = {'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'], 'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'], 'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'], 'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'], 'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt  Vonnegut', 'Neil Stephenson'], 'Douglas Adams': ['Terry  Pratchett', 'Chris Moore', 'Kurt Vonnegut']}

def get_similar(authors, author):
    retVal = []
    for k, v in authors.items():
        if k == author:
            for value in v:
                retVal.append(value)
                if value in authors:
                    for v2 in authors[value]:
                       retVal.append(v2)
return sorted(retVal)
</code>```

get_similar(authors, "Harlan Ellison") returns
['Chris Moore',
 'Douglas Adams',
 'Douglas Adams',
 'Jeff Vandemeer',
 'Kurt Vonnegut',
 'Kurt Vonnegut',
 'Neil Stephenson',
 'Neil Stephenson',
 'Richard Morgan',
 'Terry  Pratchett',
 'Terry Pratchett',
 'Tom Robbins']

I'll leave it to you to figure out how to remove the duplicates.

Title: Return a list of similar authors

Body:
I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors.

authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}

And the function I came up with is this:

def get_similar(author_list, author):
    for item in author_list[author]:
        return author_list[author]

Which only returns the items for the first key. I'd like it to return all of the similar authors, like this:

get_similar(authors, 'Harlan Ellison')

['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson',
 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']

Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut,

Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!

Body:
I think this is what you are looking for.  Hopefully it gets you going.

authors = {'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'], 'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'], 'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'], 'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'], 'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt  Vonnegut', 'Neil Stephenson'], 'Douglas Adams': ['Terry  Pratchett', 'Chris Moore', 'Kurt Vonnegut']}

def get_similar(authors, author):
    retVal = []
    for k, v in authors.items():
        if k == author:
            for value in v:
                retVal.append(value)
                if value in authors:
                    for v2 in authors[value]:
                       retVal.append(v2)
return sorted(retVal)

get_similar(authors, "Harlan Ellison") returns
['Chris Moore',
 'Douglas Adams',
 'Douglas Adams',
 'Jeff Vandemeer',
 'Kurt Vonnegut',
 'Kurt Vonnegut',
 'Neil Stephenson',
 'Neil Stephenson',
 'Richard Morgan',
 'Terry  Pratchett',
 'Terry Pratchett',
 'Tom Robbins']

I'll leave it to you to figure out how to remove the duplicates.


问:
Subplots with two y axes (each) - plotly and python/pandas
Are there guidelines on how to set up secondary Y-axes in python for plotly?
I am assinging axis style through an iterative loop, as follows:

```<code>all_plots = ['plot1','plot2'...'plot20']
fig = tools.make_subplots(rows=nrow, cols=ncol, shared_xaxes=False, shared_yaxes=False, subplot_titles=all_plots)
for i in all_plots:
    fig['layout']['yaxis'+str(j)].update()
</code>```

How does the assignment of y axes work?

If my subplot included, say, 4 rows and 5 columns for a total of 20 subplots, do I have to assume that plotly needs to receive odd and even numbers, meaning:
yaxis1 and yaxis2 for plot1

....

yaxis39 and yaxis40 for plot20

答:
It is possible, to do this, but its not particularly intuitive.  Take this example where I create a plot 2x2 subplots, and add a secondary y axis to the plot in position 2,2.

When you create a subplots, they are assigned y axes: "y1","y2","y3","y4" on the left side of each subplot.  To a secondary y axes, you need to use fig['layout'].updateto create new axes "y5", "y6", "y7", "y8" which correspond to "y1","y2","y3","y4".  So the bottom right subplot would have axes y4(right) and y8(left).  In the example below, I only create a secondary y axis for the last plot, but expanding it to more/all the subplots is pretty straightforward.

It is important to note, that creating the secondary axes, and assigning it in trace5 doesn't automatically place it on the proper axes.  You still have to manually assign it with fig['data'][4].update(yaxis='y'+str(8)) to plot it relative to the left axis.

```<code>fig = tools.make_subplots(rows=2, cols=2,subplot_titles=('Air Temperature', 'Photon Flux Density',
                                                         'Ground Temps','Water Table & Precip'))

fig['layout']['xaxis1'].update( range=[174, 256])
fig['layout']['xaxis3'].update(title='Day of Year', range=[174, 256])
fig['layout']['yaxis1'].update(title='Degrees C',range=[-5,30])
fig['layout']['yaxis2'].update(title='mmol m<sup>-2</sup> m<sup>-d</sup>', range=[0, 35])
fig['layout']['yaxis3'].update(title='Ground Temps', range=[0, 11])
fig['layout']['yaxis4'].update(title='depth cm', range=[-20, 0])
fig['layout']['yaxis8'].update(title='rainfall cm', range=[0, 1.6])
fig['layout'].update(showlegend=False, title='Climate Conditions')

# In this example, I am only doing it for the last subplot, but if you wanted to do if for all,
# Just change to range(1,5)

for k in range(4,5):
    fig['layout'].update({'yaxis{}'.format(k+4): dict(anchor='x'+str(k),
                                                          overlaying='y'+str(k),
                                                          side='right',
                                                         )
                            })

trace1 = go.Scatter(
        y=Daily['AirTC_Avg'],
        x=Daily.index,
        marker = dict(
        size = 10,
        color = 'rgba(160, 0, 0, .8)',),
        error_y=dict(
            type='data',
            array=Daily_Max['AirTC_Avg']-Daily_Min['AirTC_Avg'],
            visible=True,
        color = 'rgba(100, 0, 0, .5)',
        ),
    name = 'Air Temp'
    )

trace2 = go.Bar(
        y=Daily['PPFD']/1000,
        x=Daily.index,
        name='Photon Flux',
        marker=dict(
            color='rgb(180, 180, 0)'
        ),

    yaxis='y2',
)

trace3 = go.Scatter(
        y=Daily['Temp_2_5_1'],
        x=Daily.index,
        name='Soil Temp',
        marker=dict(
            color='rgb(180, 0, 0)'
        ),

    yaxis='y3',
)

trace4 = go.Scatter(
        y=Daily['Table_1']*100,
        x=Daily.index,
        name='Water Table',
        marker=dict(
            color='rgb(0, 0, 180)'
        ),

    yaxis='y4',
)

trace5 = go.Bar(
        y=Daily['Rain']/10,
        x=Daily.index,
        name='Rain',
        marker=dict(
            color='rgb(0, 100, 180)'
        ),

    yaxis='y8',
)

fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 1, 2)
fig.append_trace(trace3, 2, 1)
fig.append_trace(trace4, 2, 2)
fig.append_trace(trace5, 2, 2)

## This part is important!!! you have to manually assing the data to the axis even
# though you do it when defining trace 5
fig['data'][4].update(yaxis='y'+str(8))
plot(fig, filename='FI_Climate')
</code>```

Body:
Are there guidelines on how to set up secondary Y-axes in python for plotly?
I am assinging axis style through an iterative loop, as follows:

all_plots = ['plot1','plot2'...'plot20']
fig = tools.make_subplots(rows=nrow, cols=ncol, shared_xaxes=False, shared_yaxes=False, subplot_titles=all_plots)
for i in all_plots:
    fig['layout']['yaxis'+str(j)].update()

How does the assignment of y axes work?

If my subplot included, say, 4 rows and 5 columns for a total of 20 subplots, do I have to assume that plotly needs to receive odd and even numbers, meaning:
yaxis1 and yaxis2 for plot1

....

yaxis39 and yaxis40 for plot20

Body:
It is possible, to do this, but its not particularly intuitive.  Take this example where I create a plot 2x2 subplots, and add a secondary y axis to the plot in position 2,2.

When you create a subplots, they are assigned y axes: "y1","y2","y3","y4" on the left side of each subplot.  To a secondary y axes, you need to use fig['layout'].updateto create new axes "y5", "y6", "y7", "y8" which correspond to "y1","y2","y3","y4".  So the bottom right subplot would have axes y4(right) and y8(left).  In the example below, I only create a secondary y axis for the last plot, but expanding it to more/all the subplots is pretty straightforward.

It is important to note, that creating the secondary axes, and assigning it in trace5 doesn't automatically place it on the proper axes.  You still have to manually assign it with fig['data'][4].update(yaxis='y'+str(8)) to plot it relative to the left axis.

fig = tools.make_subplots(rows=2, cols=2,subplot_titles=('Air Temperature', 'Photon Flux Density',
                                                         'Ground Temps','Water Table & Precip'))

fig['layout']['xaxis1'].update( range=[174, 256])
fig['layout']['xaxis3'].update(title='Day of Year', range=[174, 256])
fig['layout']['yaxis1'].update(title='Degrees C',range=[-5,30])
fig['layout']['yaxis2'].update(title='mmol m<sup>-2</sup> m<sup>-d</sup>', range=[0, 35])
fig['layout']['yaxis3'].update(title='Ground Temps', range=[0, 11])
fig['layout']['yaxis4'].update(title='depth cm', range=[-20, 0])
fig['layout']['yaxis8'].update(title='rainfall cm', range=[0, 1.6])
fig['layout'].update(showlegend=False, title='Climate Conditions')

# In this example, I am only doing it for the last subplot, but if you wanted to do if for all,
# Just change to range(1,5)

for k in range(4,5):
    fig['layout'].update({'yaxis{}'.format(k+4): dict(anchor='x'+str(k),
                                                          overlaying='y'+str(k),
                                                          side='right',
                                                         )
                            })

trace1 = go.Scatter(
        y=Daily['AirTC_Avg'],
        x=Daily.index,
        marker = dict(
        size = 10,
        color = 'rgba(160, 0, 0, .8)',),
        error_y=dict(
            type='data',
            array=Daily_Max['AirTC_Avg']-Daily_Min['AirTC_Avg'],
            visible=True,
        color = 'rgba(100, 0, 0, .5)',
        ),
    name = 'Air Temp'
    )

trace2 = go.Bar(
        y=Daily['PPFD']/1000,
        x=Daily.index,
        name='Photon Flux',
        marker=dict(
            color='rgb(180, 180, 0)'
        ),

    yaxis='y2',
)

trace3 = go.Scatter(
        y=Daily['Temp_2_5_1'],
        x=Daily.index,
        name='Soil Temp',
        marker=dict(
            color='rgb(180, 0, 0)'
        ),

    yaxis='y3',
)

trace4 = go.Scatter(
        y=Daily['Table_1']*100,
        x=Daily.index,
        name='Water Table',
        marker=dict(
            color='rgb(0, 0, 180)'
        ),

    yaxis='y4',
)

trace5 = go.Bar(
        y=Daily['Rain']/10,
        x=Daily.index,
        name='Rain',
        marker=dict(
            color='rgb(0, 100, 180)'
        ),

    yaxis='y8',
)

fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 1, 2)
fig.append_trace(trace3, 2, 1)
fig.append_trace(trace4, 2, 2)
fig.append_trace(trace5, 2, 2)

## This part is important!!! you have to manually assing the data to the axis even
# though you do it when defining trace 5
fig['data'][4].update(yaxis='y'+str(8))
plot(fig, filename='FI_Climate')