问:
How to use JavaScript and offsetWidth to line up tables?
I've inherited this project that goes about things in an old-fashioned way.  For instance, it uses tables for layout, which is bad enough, but then it breaks apart headers and content into two separate tables (see my code snippet).

It's not really practical to go about re-writing the markup, so the solution will have to be a JavaScript one, combined with CSS probably.  Keep in mind that I've vastly simplified the issue for the purposes here to make things less confusing; in reality, the problem stretches over many different files.

Using JavaScript (see the snippet), I'm able to mostly line up the headers with the body.  The idea is to wait until the page loads, find the widths of the body elements, and then apply them to the headers to make it look like one table.  As you can see, it doesn't exactly match up.  This is in part because of the CSS borders, but life is messy and borders happen.  It's not realistic to remove all additional CSS just to make things line up.

Can you help me get these tables to line up and look like one table?

Edit:

To be a bit clearer on the requirements, the table needs to be sized dynamically, based on the widths of the content in the body table.  The content might change, so it won't be sufficient to hard-code widths.

window.onload = function() {
  var bodyCols = document.getElementsByClassName('bodyCol');
  var headCols = document.getElementsByClassName('headCol');

  for (var i=0; i<bodyCols.length; i++) {
    headCols[i].style.minWidth = bodyCols[i].offsetWidth + 'px';
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#headTable {
  width: 100%;
}

.headCol {
  border: 5px solid red;
}

#bodyTable {
  width: 100%;
}

.bodyCol {
  border: 5px solid blue;
}</code>```

        Hey!

        Wait!

        I've got a new complaint

        Forever in debt

        to your priceless

        advice

```

答:
The following is a solution using pure JavaScript.

```<code>var bodyCols = document.querySelectorAll('.bodyCol');
var headCols = document.querySelectorAll('.headCol');

for(var i = 0; i < bodyCols.length; i++){
    console.log(headCols[i]);
  headCols[i].style.width = window.getComputedStyle(bodyCols[i]).width;
}
</code>```

See working example: https://jsfiddle.net/pbjzmanc/

Body:
I've inherited this project that goes about things in an old-fashioned way.  For instance, it uses tables for layout, which is bad enough, but then it breaks apart headers and content into two separate tables (see my code snippet).

It's not really practical to go about re-writing the markup, so the solution will have to be a JavaScript one, combined with CSS probably.  Keep in mind that I've vastly simplified the issue for the purposes here to make things less confusing; in reality, the problem stretches over many different files.

Using JavaScript (see the snippet), I'm able to mostly line up the headers with the body.  The idea is to wait until the page loads, find the widths of the body elements, and then apply them to the headers to make it look like one table.  As you can see, it doesn't exactly match up.  This is in part because of the CSS borders, but life is messy and borders happen.  It's not realistic to remove all additional CSS just to make things line up.

Can you help me get these tables to line up and look like one table?

Edit:

To be a bit clearer on the requirements, the table needs to be sized dynamically, based on the widths of the content in the body table.  The content might change, so it won't be sufficient to hard-code widths.

window.onload = function() {
  var bodyCols = document.getElementsByClassName('bodyCol');
  var headCols = document.getElementsByClassName('headCol');

  for (var i=0; i<bodyCols.length; i++) {
    headCols[i].style.minWidth = bodyCols[i].offsetWidth + 'px';
  }
}

#headTable {
  width: 100%;
}

.headCol {
  border: 5px solid red;
}

#bodyTable {
  width: 100%;
}

.bodyCol {
  border: 5px solid blue;
}

        Hey!

        Wait!

        I've got a new complaint

        Forever in debt

        to your priceless

        advice

Body:
The following is a solution using pure JavaScript.

var bodyCols = document.querySelectorAll('.bodyCol');
var headCols = document.querySelectorAll('.headCol');

for(var i = 0; i < bodyCols.length; i++){
    console.log(headCols[i]);
  headCols[i].style.width = window.getComputedStyle(bodyCols[i]).width;
}

See working example: https://jsfiddle.net/pbjzmanc/


来源: stackexchange

问:
Reading Info.plist from UITests in iOS?
Is it possible to read from the Info.plist file which is within the UITests folder file while UITesting ? If so, how.

So far I have tried that:

```<code>if let url =  Bundle.main.url(forResource: "Info", withExtension: "plist"),
        let myDict = NSDictionary(contentsOf: url) as? [String:Any] {
        print(myDict)
    }
</code>```

Though, that returns some plist which is not event the one I have in my main project folder.

答:
There is a special bundle for your test class that you will need to read (or inject). Try this out. Replace OSTests in the Bundle(for:) call below with the name of your XCTestCase subclass.

```<code>  func testExample() {
    let testBundle = Bundle(for: OSTests.self)
    if let url = testBundle.url(forResource: "Info", withExtension: "plist"),
      let myDict = NSDictionary(contentsOf: url) as? [String:Any] {
      print(myDict)
    }
  }
</code>```

Then you will need to make sure that the test bundle is copied into your test app. Select your test target. Disclose the Copy Bundle Resources section in the Build Phases tab. Click on the + icon and select your test target's Info.plist file.

Here are what my results looked like then.

ContentLicense: CC BY-SA 4.0

Title: Reading Info.plist from UITests in iOS?

Body:
Is it possible to read from the Info.plist file which is within the UITests folder file while UITesting ? If so, how.

So far I have tried that:

if let url =  Bundle.main.url(forResource: "Info", withExtension: "plist"),
        let myDict = NSDictionary(contentsOf: url) as? [String:Any] {
        print(myDict)
    }

Though, that returns some plist which is not event the one I have in my main project folder.

Body:
There is a special bundle for your test class that you will need to read (or inject). Try this out. Replace OSTests in the Bundle(for:) call below with the name of your XCTestCase subclass.

  func testExample() {
    let testBundle = Bundle(for: OSTests.self)
    if let url = testBundle.url(forResource: "Info", withExtension: "plist"),
      let myDict = NSDictionary(contentsOf: url) as? [String:Any] {
      print(myDict)
    }
  }

Then you will need to make sure that the test bundle is copied into your test app. Select your test target. Disclose the Copy Bundle Resources section in the Build Phases tab. Click on the + icon and select your test target's Info.plist file.

Here are what my results looked like then.

ContentLicense: CC BY-SA 3.0


问:
What is the lastest SEO technology used by Google?
What is the  latest SEO technology used by Google?</p>

答:
this is how different tags a ranked

1 title

2 headline(h1)

3 meta description

4 h2

5 h3 etc

ContentLicense: CC BY-SA 2.5


问:
Replace a string after a pattern preserving the end of the line in a file
I am trying to write a script that searches in a file for a pattern, and replaces the word after it, preserving the end of the line.

For example

```<code>something0 var1=some_val var2=some_other_val something_bla0
something1 var1=some_va2 something_bla1
something2 var1=some_va3 var2=some_other_val2
</code>```

To be changed to:

```<code>something0 var1=my_val var2=some_other_val something_bla0
something1 var1=my_val something_bla1
something2 var1=my_val var2=some_other_val2
</code>```

I dont know in advance the value of var1, but want to end up with var1=my_val, and have the end of the line unchanged.

Thank you!

答:
another attempt changing second field by sub</p>

```<code>awk '{sub(/=some_va./,"=my_val",$2)}1' file

something0 var1=my_val var2=some_other_val something_bla0
something1 var1=my_val something_bla1
something2 var1=my_val var2=some_other_val2
</code>```

Body:
I am trying to write a script that searches in a file for a pattern, and replaces the word after it, preserving the end of the line.

For example

something0 var1=some_val var2=some_other_val something_bla0
something1 var1=some_va2 something_bla1
something2 var1=some_va3 var2=some_other_val2

To be changed to:

something0 var1=my_val var2=some_other_val something_bla0
something1 var1=my_val something_bla1
something2 var1=my_val var2=some_other_val2

I dont know in advance the value of var1, but want to end up with var1=my_val, and have the end of the line unchanged.

Thank you!

Body:
another attempt changing second field by sub

awk '{sub(/=some_va./,"=my_val",$2)}1' file

something0 var1=my_val var2=some_other_val something_bla0
something1 var1=my_val something_bla1
something2 var1=my_val var2=some_other_val2


问:
Calling javascript function after finishing bean method
I want to execute javascript function after  bean actionListener.I am using JSF 1.2, richfaces 3.3.In my case I want to display a chart after finishing bean's method.My table tabis filling but the javascript function didn't work. This is my attempt :

```<code><h:form>
<h:commandButton value="Click" actionListener="#{bean.monActionListener}" reRender="tab">
<a4j:support event="onClick" oncomplete="show()" />
</h:commandButton>
<h:form>

<h:form id="sortie">
<rich:dataTable id="tab" rendered="#{not empty bean.listSortie}"
value="#{bean.listSortie}" var="raison">

<h:column headerClass="headerleftfacet">
    <h:outputText value="#{raison[0]}">
    </h:outputText>
</h:column>
<h:column headerClass="headermiddlefacet">
    <h:outputText  value="#{raison[1]}" >
    </h:outputText>
</h:column>

</rich:dataTable>
</code>```

答:
I resolved this problem by using <a4j:commandButton> and `:

```<code><h:form>
<h:commandButton value="Click" actionListener="#{bean.monActionListener}" reRender="tab" oncomplete="alert('ok')">

<h:form>

<a4j:outputPanel id="tab">
<h:form id="sortie">
<rich:dataTable id="tabb" rendered="#{not empty bean.listSortie}"
value="#{bean.listSortie}" var="raison">

<h:column headerClass="headerleftfacet">
<h:outputText value="#{raison[0]}">
</h:outputText>
</h:column>
<h:column headerClass="headermiddlefacet">
<h:outputText  value="#{raison[1]}" >
</h:outputText>
</h:column>

</rich:dataTable>
<h:form>
</a4j:outputPanel>
</code>```

Body:
I want to execute javascript function after  bean actionListener.I am using JSF 1.2, richfaces 3.3.In my case I want to display a chart after finishing bean's method.My table tabis filling but the javascript function didn't work. This is my attempt :

<h:form>
<h:commandButton value="Click" actionListener="#{bean.monActionListener}" reRender="tab">
<a4j:support event="onClick" oncomplete="show()" />
</h:commandButton>
<h:form>

<h:form id="sortie">
<rich:dataTable id="tab" rendered="#{not empty bean.listSortie}"
value="#{bean.listSortie}" var="raison">

<h:column headerClass="headerleftfacet">
    <h:outputText value="#{raison[0]}">
    </h:outputText>
</h:column>
<h:column headerClass="headermiddlefacet">
    <h:outputText  value="#{raison[1]}" >
    </h:outputText>
</h:column>

</rich:dataTable>

Body:
I resolved this problem by using <a4j:commandButton> and `:

<h:form>
<h:commandButton value="Click" actionListener="#{bean.monActionListener}" reRender="tab" oncomplete="alert('ok')">

<h:form>

<a4j:outputPanel id="tab">
<h:form id="sortie">
<rich:dataTable id="tabb" rendered="#{not empty bean.listSortie}"
value="#{bean.listSortie}" var="raison">

<h:column headerClass="headerleftfacet">
<h:outputText value="#{raison[0]}">
</h:outputText>
</h:column>
<h:column headerClass="headermiddlefacet">
<h:outputText  value="#{raison[1]}" >
</h:outputText>
</h:column>

</rich:dataTable>
<h:form>
</a4j:outputPanel>


问:
For Loop to Count Letters in a Word
I'm just learning python and I came to a problem that required me to put a string as an input in my "count letters function."

The function is supposed to count how many "a"s are in a word given (specifically, a fruit inputed by the user).

The final value is correct, but in my function, it lists me the programs "procedure" if you will by listing how many "a"s are at each index and adding everything that was before.

I just want one final value, not a list.

If I'm not too clear, here is my program and test it out for yourself to see what I mean, and maybe help me come to a solution?

```<code>def count_letters(a):
    count=0
    for char in a:
        if char == 'a':
            count+=1
        print count

a=raw_input("Name a fruit and I will tell you how many letters are in it." + '\n')
print count_letters(a)
</code>```

答:
Just change:

```<code>for char in a:
    if char == 'a':
        count+=1
    print count
</code>```

To:

```<code>for char in a:
    if char == 'a':
        count+=1
print count
</code>```

Otherwise you'll be printing the counter each time the for loop runs.

Also, you're calling your function with print at print count_letters(a).

You don't need this since you've put a print statement at the last line in your code. If you left the print statement there to call your function, it'll print None, since the function already have returned the count value.

So you can also change:

```<code>print count_letters(a)
</code>```

To:

```<code>count_letters(a)
</code>```

Output Example with print count_letters(a):

```<code>Name a fruit and I will tell you how many letters are in it. abacaxi
3
None
</code>```

Output Example with count_letters(a):

```<code>Name a fruit and I will tell you how many letters are in it. abacaxi
3
</code>```

Title: For Loop to Count Letters in a Word

Body:
I'm just learning python and I came to a problem that required me to put a string as an input in my "count letters function."

The function is supposed to count how many "a"s are in a word given (specifically, a fruit inputed by the user).

The final value is correct, but in my function, it lists me the programs "procedure" if you will by listing how many "a"s are at each index and adding everything that was before.

I just want one final value, not a list.

If I'm not too clear, here is my program and test it out for yourself to see what I mean, and maybe help me come to a solution?

def count_letters(a):
    count=0
    for char in a:
        if char == 'a':
            count+=1
        print count

a=raw_input("Name a fruit and I will tell you how many letters are in it." + '\n')
print count_letters(a)

Body:
Just change:

for char in a:
    if char == 'a':
        count+=1
    print count

To:

for char in a:
    if char == 'a':
        count+=1
print count

Otherwise you'll be printing the counter each time the for loop runs.

Also, you're calling your function with print at print count_letters(a).

You don't need this since you've put a print statement at the last line in your code. If you left the print statement there to call your function, it'll print None, since the function already have returned the count value.

So you can also change:

print count_letters(a)

To:

count_letters(a)

Output Example with print count_letters(a):

Name a fruit and I will tell you how many letters are in it. abacaxi
3
None

Output Example with count_letters(a):

Name a fruit and I will tell you how many letters are in it. abacaxi
3


问:
ngFor and enumerate rows
I'm creating a table using ngFor using an Observable as source:

```<code><tr *ngFor="let payment of sources$ | async">
</code>```

I'd like to add an enumerable on the first column of this table:

```<code><tr>
  <td>1</td>
</tr>
<tr>
  <td>2</td>
</tr>
<tr>
  <td>3</td>
</tr>
</code>```

Of course, each 1,2 or 3 is the position of the current payment inside the table.
Is there any elegant way to get it?

答:
It's extremely easy. Try this:

```<code><tr *ngFor="let payment of sources$; let i = index;">
  <td>{{i}}</td>
</tr>
</code>```

Index is a simple Angular2 functionality, like odd, even or last. You can read more about it in official documentation.

If you using pipe, you code should look like:

```<code><tr *ngFor="let payment of sources$ | async; let i = index;">
    <td>{{i}}</td>
</tr>
</code>```

Title: ngFor and enumerate rows

Body:
I'm creating a table using ngFor using an Observable as source:

I'd like to add an enumerable on the first column of this table:

  1

  2

  3

Of course, each 1,2 or 3 is the position of the current payment inside the table.
Is there any elegant way to get it?

Body:
It's extremely easy. Try this:

<tr *ngFor="let payment of sources$; let i = index;">
  <td>{{i}}</td>
</tr>

Index is a simple Angular2 functionality, like odd, even or last. You can read more about it in official documentation.

If you using pipe, you code should look like:

<tr *ngFor="let payment of sources$ | async; let i = index;">
    <td>{{i}}</td>
</tr>


问:
How to schedule the execution of a unix-script without using cron?
I have a Wrapper-Script running several scripts at once. I would like to schedule the wrapper to be run every friday morning. Cron jobs are disabled for this server, therefore I cannot use cron.

What would be the best way to schedule the execution of a unix-script wihtout using cron?

Cheers

答:
Possible Options to Schedule a script -

Schedule script execution using Task Scheduler of Windows, which
will login to Server to execute the script. Check this link

Expect command of unix which can allows to login to Another Server
and execute the script. Check this link


问:
Is this a legal if sentance?
I just started coding and can't get this "Heater" object to work. It just prompts the if else statement "its too hot" when trying to give temp a higher value and it does not stop/ goes below the min temp value when calling the "colder" method. Thanks</p>

```<code>public class Heater {
    private double temp;
    private double min;
    private double max;
    private double increment;

    public Heater(double min, double max) {
        temp = 15;
        increment = 5;
    }

    public void Warmer() {
        if(temp + increment <= max) {
            temp = temp + increment;
        } else if(temp + increment > max) {
            System.out.println("Too hot");
        }
    }

    public void Colder() {
        if(temp - increment >= min){
            temp = temp - increment;
        } else if (temp - increment < min){
            System.out.println("Too cold");
        }
    }

    public double getTemp() {
        return temp;
    }
}
</code>```

答:
You're not setting min and max in your constructor, so they stay at 0 by default. Try this:

```<code>public Heater(double min, double max) {
    this.min = min;
    this.max = max;
    temp = 15;
    increment = 5;
}
</code>```

Title: Is this a legal if sentance?

Body:
I just started coding and can't get this "Heater" object to work. It just prompts the if else statement "its too hot" when trying to give temp a higher value and it does not stop/ goes below the min temp value when calling the "colder" method. Thanks

public class Heater {
    private double temp;
    private double min;
    private double max;
    private double increment;

    public Heater(double min, double max) {
        temp = 15;
        increment = 5;
    }

    public void Warmer() {
        if(temp + increment <= max) {
            temp = temp + increment;
        } else if(temp + increment > max) {
            System.out.println("Too hot");
        }
    }

    public void Colder() {
        if(temp - increment >= min){
            temp = temp - increment;
        } else if (temp - increment < min){
            System.out.println("Too cold");
        }
    }

    public double getTemp() {
        return temp;
    }
}

Body:
You're not setting min and max in your constructor, so they stay at 0 by default. Try this:

public Heater(double min, double max) {
    this.min = min;
    this.max = max;
    temp = 15;
    increment = 5;
}


问:
resizing multidimensional vector
How to resize multidimensional vector such as:

```<code>  vector <vector <vector <custom_type> > > array;
</code>```

For example, I need array[3][5][10]?

答:
I would make a custom container containing a vector of vectors (of ... per dimension) and resize with resize-functions per dimension.  This way you can put the invariant of equal size per dimension in one place.  The actual resizing can then be done in a loop according to dimension.

There will be a bit of work involved in making public what needs to be accessed (operator[],...)

Title: resizing multidimensional vector

Body:
How to resize multidimensional vector such as:

  vector <vector <vector <custom_type> > > array;

For example, I need array[3][5][10]?


问:
format DD/MM/YYYY input react as user types
I have an input box in a React component. This is to take a date of birth. I want to add / after each relevant section. i.e. 30/03/2017

Something similar to this but for date of birth as opposed to credit card number.

The user should enter 30 and then it should automatically add the /. This works with my current code, however, it enters a slash after each 2 digits, however, for the year it adds the slash also after each second digit.

See complete React component below

```<code>class DateInput extends Component {

  constructor(props) {

    this.handleChange = this.handleChange.bind(this);

    this.state = {
      value: ''
    }

  }

  handleChange(val) {

    val = val.split('/').join('');
    val = val.match(new RegExp('.{1,2}', 'g')).join("/");

    this.setState({
        value: val
    });

  }

  render() {

    const {value} = this.state;
    const placeholder = 'DAY/MONTH/YEAR';

    return ( <input type = "text" value={value} placeholder={placeholder}
      onChange = {this.handleChange}/>
    );

  }

}
</code>```

答:
You can set up an onKeyDown event on the input and detect for press of backspace. Similarly you can do it for delete too. I have demonstrated in the snippet below for backspace.

class DateInput extends React.Component {

  constructor(props) {
    super();
    this.handleChange = this.handleChange.bind(this);
     this.keyPressFunc = this.keyPressFunc.bind(this)
    this.state = {
      value: ''
    }

  }
  keyPressFunc(e) {

    if(e.which === 8) {
      var val = this.state.value;
      console.log(val);
      if(val.length == 3 || val.length == 6) {
          val = val.slice(0, val.length-1);
          console.log(val)
          this.setState({value: val})
      }
    }
  }

  handleChange(e) {
    var val = e.target.value;
      console.log('called', val)
      if (val.length === 2) {

        val += '/';

      } else if (val.length === 5) {

        val += '/';

      }

      this.setState({
        value: val
      });

  }

  render() {

    const {value} = this.state;
    const placeholder = 'DAY / MONTH / YEAR';

    return ( <input type = "text" value={value} placeholder={placeholder}
      onChange = {this.handleChange} onKeyDown={this.keyPressFunc}/>
    );

  }

}
ReactDOM.render(<DateInput/>, document.getElementById('app'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div></code>```

Body:
I have an input box in a React component. This is to take a date of birth. I want to add / after each relevant section. i.e. 30/03/2017

Something similar to this but for date of birth as opposed to credit card number.

The user should enter 30 and then it should automatically add the /. This works with my current code, however, it enters a slash after each 2 digits, however, for the year it adds the slash also after each second digit.

See complete React component below

class DateInput extends Component {

  constructor(props) {

    this.handleChange = this.handleChange.bind(this);

    this.state = {
      value: ''
    }

  }

  handleChange(val) {

    val = val.split('/').join('');
    val = val.match(new RegExp('.{1,2}', 'g')).join("/");

    this.setState({
        value: val
    });

  }

  render() {

    const {value} = this.state;
    const placeholder = 'DAY/MONTH/YEAR';

    return ( <input type = "text" value={value} placeholder={placeholder}
      onChange = {this.handleChange}/>
    );

  }

}

Body:
You can set up an onKeyDown event on the input and detect for press of backspace. Similarly you can do it for delete too. I have demonstrated in the snippet below for backspace.

class DateInput extends React.Component {

  constructor(props) {
    super();
    this.handleChange = this.handleChange.bind(this);
     this.keyPressFunc = this.keyPressFunc.bind(this)
    this.state = {
      value: ''
    }

  }
  keyPressFunc(e) {

    if(e.which === 8) {
      var val = this.state.value;
      console.log(val);
      if(val.length == 3 || val.length == 6) {
          val = val.slice(0, val.length-1);
          console.log(val)
          this.setState({value: val})
      }
    }
  }

  handleChange(e) {
    var val = e.target.value;
      console.log('called', val)
      if (val.length === 2) {

        val += '/';

      } else if (val.length === 5) {

        val += '/';

      }

      this.setState({
        value: val
      });

  }

  render() {

    const {value} = this.state;
    const placeholder = 'DAY / MONTH / YEAR';

    return ( <input type = "text" value={value} placeholder={placeholder}
      onChange = {this.handleChange} onKeyDown={this.keyPressFunc}/>
    );

  }

}
ReactDOM.render(<DateInput/>, document.getElementById('app'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


问:
Finding non-binary tree depth
Can I find non-binary tree depth.
Every node can have multiple children. We don't know how much is the maximum count of nodes. </p>

```<code>public class Node
{
    private List<Node> nodes;
    private string nodeName;

    public Node(string nodeName)
    {
        nodes = new List<Node>();
        this.nodeName = nodeName;
    }

    public List<Node> Nodes
    {
        get { return this.nodes; }
        set { this.nodes = value; }
    }

    protected string NodeName
    {
        get { return this.nodeName; }
    }
}
</code>```

答:
You can do something like this to calculate the maximum depth (including the root node):

```<code>public static int Depth(Node root, int depth)
{
    int result = depth + 1;

    foreach (var node in root.Nodes)
        result = Math.Max(result, Depth(node, depth + 1));

    return result;
}
</code>```

You would call it passing in 0 for the initial depth:

```<code>int depth = Depth(root, 0);
</code>```

If you just want to count ALL the nodes rather than the depth:

```<code>public static int CountExcludingRoot(Node root)
{
    return root.Nodes.Sum(node => 1 + CountExcludingRoot(node));
}
</code>```

(This excludes the root node, so you need to add one to the value returned to get the total of all nodes including the root).

Title: Finding non-binary tree depth

Body:
Can I find non-binary tree depth.
Every node can have multiple children. We don't know how much is the maximum count of nodes.

public class Node
{
    private List<Node> nodes;
    private string nodeName;

    public Node(string nodeName)
    {
        nodes = new List<Node>();
        this.nodeName = nodeName;
    }

    public List<Node> Nodes
    {
        get { return this.nodes; }
        set { this.nodes = value; }
    }

    protected string NodeName
    {
        get { return this.nodeName; }
    }
}

Body:
You can do something like this to calculate the maximum depth (including the root node):

public static int Depth(Node root, int depth)
{
    int result = depth + 1;

    foreach (var node in root.Nodes)
        result = Math.Max(result, Depth(node, depth + 1));

    return result;
}

You would call it passing in 0 for the initial depth:

int depth = Depth(root, 0);

If you just want to count ALL the nodes rather than the depth:

public static int CountExcludingRoot(Node root)
{
    return root.Nodes.Sum(node => 1 + CountExcludingRoot(node));
}

(This excludes the root node, so you need to add one to the value returned to get the total of all nodes including the root).


问:
Find the Gridview control from another Gridview Control
```<code>HTMl:-<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" DataKeyNames="BillOfLadingID" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField ItemStyle-Width="300px" DataField="BillOfLadingID" HeaderText="B/L Number" HeaderStyle-CssClass="GridClass" />
                    <asp:TemplateField HeaderText="Select" ItemStyle-VerticalAlign="Middle" ItemStyle-HorizontalAlign="Center">
                        <ItemTemplate>
                            <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" >
                                <Columns>
                                    <asp:BoundField ItemStyle-Width="300px" DataField="ContainerType" HeaderText="Container Type" HeaderStyle-CssClass="GridClass" />
                                    <asp:BoundField ItemStyle-Width="300px" DataField="NumberOfContainer" HeaderText="Number Of Container" HeaderStyle-CssClass="GridClass" />
                                    <asp:TemplateField HeaderText="Select" ItemStyle-VerticalAlign="Middle" ItemStyle-HorizontalAlign="Center">
                                        <ItemTemplate>
                                            <asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="false">
                                                <Columns>
                                                    <asp:BoundField ItemStyle-Width="300px" DataField="InvoiceChargesType" HeaderText="Perticulars" HeaderStyle-CssClass="GridClass" />
                                                    <asp:BoundField ItemStyle-Width="300px" DataField="PerUnit" HeaderText="Per Unit" HeaderStyle-CssClass="GridClass" />
                                                    <asp:BoundField ItemStyle-Width="300px" DataField="InvoiceINR" HeaderText="INR" HeaderStyle-CssClass="GridClass" />
                                                    <asp:BoundField ItemStyle-Width="300px" DataField="InvoiceUSD" HeaderText="USD" HeaderStyle-CssClass="GridClass" />
                                                </Columns>
                                            </asp:GridView>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>
                        </ItemTemplate>
                    </asp:TemplateField>
            </Columns>
        </asp:GridView>

C#:- protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            BLID = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
            GridView gvOrders = e.Row.FindControl("GridView2") as GridView;
            gvOrders.DataSource = GetData(string.Format("select BookingWiseContainerTbl.ContainerType,BookingWiseContainerTbl.NumberOfContainer from BookingWiseContainerTbl,LinerBLTbl where LinerBLTbl.BookingID=BookingWiseContainerTbl.LineBookingID and LinerBLTbl.BillOfLadingID='{0}'", BLID));
            gvOrders.DataBind();

            GridView gvOrders1 = gvOrders.FindControl("GridView3") as GridView;
            gvOrders1.DataSource = GetData(string.Format("select LinerInvoiceWiseChargesTbl.InvoiceChargesType,concat(LinerInvoiceWiseChargesTbl.InvoiceCurrency,'-', LinerInvoiceWiseChargesTbl.InvoiceCharges)as PerUnit,LinerInvoiceWiseChargesTbl.InvoiceINR,LinerInvoiceWiseChargesTbl.InvoiceUSD  from LinerBLTbl,LinerInvoiceWiseChargesTbl  where LinerBLTbl.BillOfLadingID=LinerInvoiceWiseChargesTbl.InvoiceBillOfLadingID and LinerBLTbl.BillOfLadingID='" + BLID + "'"));
            gvOrders1.DataBind();
        }
    }
</code>```

I am using three gridview. In Template Field form another gridview. Now I am trying to bind all gridview data on GridView1 onrowdatabound, I got the gridview2 id on gridview1 on rowdatabound but not gridview3.

How to find the Gridview3 control on gridview1 rowdatabound. I try this but gvOrders1 is showing null. How to solve this?

答:
You will require to use RowDataBound event of GridView2 to bind GridView3 since GridView3 is nested one to it. Here is a sort of similar code:</p>

```<code><asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" DataKeyNames="BillOfLadingID" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField ItemStyle-Width="300px" DataField="BillOfLadingID" HeaderText="B/L Number" HeaderStyle-CssClass="GridClass" />
        <asp:TemplateField HeaderText="Select" ItemStyle-VerticalAlign="Middle" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView2_RowDataBound">
                    <Columns>
                        <asp:BoundField ItemStyle-Width="300px" DataField="ContainerType" HeaderText="Container Type" HeaderStyle-CssClass="GridClass" />
                        <asp:BoundField ItemStyle-Width="300px" DataField="NumberOfContainer" HeaderText="Number Of Container" HeaderStyle-CssClass="GridClass" />
                        <asp:TemplateField HeaderText="Select" ItemStyle-VerticalAlign="Middle" ItemStyle-HorizontalAlign="Center">
                            <ItemTemplate>
                                <asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="false">
                                    <Columns>
                                        <asp:BoundField ItemStyle-Width="300px" DataField="InvoiceChargesType" HeaderText="Perticulars" HeaderStyle-CssClass="GridClass" />
                                        <asp:BoundField ItemStyle-Width="300px" DataField="PerUnit" HeaderText="Per Unit" HeaderStyle-CssClass="GridClass" />
                                        <asp:BoundField ItemStyle-Width="300px" DataField="InvoiceINR" HeaderText="INR" HeaderStyle-CssClass="GridClass" />
                                        <asp:BoundField ItemStyle-Width="300px" DataField="InvoiceUSD" HeaderText="USD" HeaderStyle-CssClass="GridClass" />
                                    </Columns>
                                </asp:GridView>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

string BLID = string.Empty;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            BLID = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
            GridView gvOrders = e.Row.FindControl("GridView2") as GridView;
            gvOrders.DataSource = GetData(string.Format("select BookingWiseContainerTbl.ContainerType,BookingWiseContainerTbl.NumberOfContainer from BookingWiseContainerTbl,LinerBLTbl where LinerBLTbl.BookingID=BookingWiseContainerTbl.LineBookingID and LinerBLTbl.BillOfLadingID='{0}'", BLID));
            gvOrders.DataBind();
        }
    }

    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            GridView gvOrders1 = (sender as GridView).FindControl("GridView3") as GridView;
            gvOrders1.DataSource = GetData(string.Format("select LinerInvoiceWiseChargesTbl.InvoiceChargesType,concat(LinerInvoiceWiseChargesTbl.InvoiceCurrency,'-', LinerInvoiceWiseChargesTbl.InvoiceCharges)as PerUnit,LinerInvoiceWiseChargesTbl.InvoiceINR,LinerInvoiceWiseChargesTbl.InvoiceUSD  from LinerBLTbl,LinerInvoiceWiseChargesTbl  where LinerBLTbl.BillOfLadingID=LinerInvoiceWiseChargesTbl.InvoiceBillOfLadingID and LinerBLTbl.BillOfLadingID='" + BLID + "'"));
            gvOrders1.DataBind();
        }
    }
</code>```

Body:
HTMl:-<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" DataKeyNames="BillOfLadingID" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField ItemStyle-Width="300px" DataField="BillOfLadingID" HeaderText="B/L Number" HeaderStyle-CssClass="GridClass" />
                    <asp:TemplateField HeaderText="Select" ItemStyle-VerticalAlign="Middle" ItemStyle-HorizontalAlign="Center">
                        <ItemTemplate>
                            <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" >
                                <Columns>
                                    <asp:BoundField ItemStyle-Width="300px" DataField="ContainerType" HeaderText="Container Type" HeaderStyle-CssClass="GridClass" />
                                    <asp:BoundField ItemStyle-Width="300px" DataField="NumberOfContainer" HeaderText="Number Of Container" HeaderStyle-CssClass="GridClass" />
                                    <asp:TemplateField HeaderText="Select" ItemStyle-VerticalAlign="Middle" ItemStyle-HorizontalAlign="Center">
                                        <ItemTemplate>
                                            <asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="false">
                                                <Columns>
                                                    <asp:BoundField ItemStyle-Width="300px" DataField="InvoiceChargesType" HeaderText="Perticulars" HeaderStyle-CssClass="GridClass" />
                                                    <asp:BoundField ItemStyle-Width="300px" DataField="PerUnit" HeaderText="Per Unit" HeaderStyle-CssClass="GridClass" />
                                                    <asp:BoundField ItemStyle-Width="300px" DataField="InvoiceINR" HeaderText="INR" HeaderStyle-CssClass="GridClass" />
                                                    <asp:BoundField ItemStyle-Width="300px" DataField="InvoiceUSD" HeaderText="USD" HeaderStyle-CssClass="GridClass" />
                                                </Columns>
                                            </asp:GridView>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>
                        </ItemTemplate>
                    </asp:TemplateField>
            </Columns>
        </asp:GridView>

C#:- protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            BLID = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
            GridView gvOrders = e.Row.FindControl("GridView2") as GridView;
            gvOrders.DataSource = GetData(string.Format("select BookingWiseContainerTbl.ContainerType,BookingWiseContainerTbl.NumberOfContainer from BookingWiseContainerTbl,LinerBLTbl where LinerBLTbl.BookingID=BookingWiseContainerTbl.LineBookingID and LinerBLTbl.BillOfLadingID='{0}'", BLID));
            gvOrders.DataBind();

            GridView gvOrders1 = gvOrders.FindControl("GridView3") as GridView;
            gvOrders1.DataSource = GetData(string.Format("select LinerInvoiceWiseChargesTbl.InvoiceChargesType,concat(LinerInvoiceWiseChargesTbl.InvoiceCurrency,'-', LinerInvoiceWiseChargesTbl.InvoiceCharges)as PerUnit,LinerInvoiceWiseChargesTbl.InvoiceINR,LinerInvoiceWiseChargesTbl.InvoiceUSD  from LinerBLTbl,LinerInvoiceWiseChargesTbl  where LinerBLTbl.BillOfLadingID=LinerInvoiceWiseChargesTbl.InvoiceBillOfLadingID and LinerBLTbl.BillOfLadingID='" + BLID + "'"));
            gvOrders1.DataBind();
        }
    }

I am using three gridview. In Template Field form another gridview. Now I am trying to bind all gridview data on GridView1 onrowdatabound, I got the gridview2 id on gridview1 on rowdatabound but not gridview3.

How to find the Gridview3 control on gridview1 rowdatabound. I try this but gvOrders1 is showing null. How to solve this?

Body:
You will require to use RowDataBound event of GridView2 to bind GridView3 since GridView3 is nested one to it. Here is a sort of similar code:

<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" DataKeyNames="BillOfLadingID" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField ItemStyle-Width="300px" DataField="BillOfLadingID" HeaderText="B/L Number" HeaderStyle-CssClass="GridClass" />
        <asp:TemplateField HeaderText="Select" ItemStyle-VerticalAlign="Middle" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView2_RowDataBound">
                    <Columns>
                        <asp:BoundField ItemStyle-Width="300px" DataField="ContainerType" HeaderText="Container Type" HeaderStyle-CssClass="GridClass" />
                        <asp:BoundField ItemStyle-Width="300px" DataField="NumberOfContainer" HeaderText="Number Of Container" HeaderStyle-CssClass="GridClass" />
                        <asp:TemplateField HeaderText="Select" ItemStyle-VerticalAlign="Middle" ItemStyle-HorizontalAlign="Center">
                            <ItemTemplate>
                                <asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="false">
                                    <Columns>
                                        <asp:BoundField ItemStyle-Width="300px" DataField="InvoiceChargesType" HeaderText="Perticulars" HeaderStyle-CssClass="GridClass" />
                                        <asp:BoundField ItemStyle-Width="300px" DataField="PerUnit" HeaderText="Per Unit" HeaderStyle-CssClass="GridClass" />
                                        <asp:BoundField ItemStyle-Width="300px" DataField="InvoiceINR" HeaderText="INR" HeaderStyle-CssClass="GridClass" />
                                        <asp:BoundField ItemStyle-Width="300px" DataField="InvoiceUSD" HeaderText="USD" HeaderStyle-CssClass="GridClass" />
                                    </Columns>
                                </asp:GridView>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

string BLID = string.Empty;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            BLID = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
            GridView gvOrders = e.Row.FindControl("GridView2") as GridView;
            gvOrders.DataSource = GetData(string.Format("select BookingWiseContainerTbl.ContainerType,BookingWiseContainerTbl.NumberOfContainer from BookingWiseContainerTbl,LinerBLTbl where LinerBLTbl.BookingID=BookingWiseContainerTbl.LineBookingID and LinerBLTbl.BillOfLadingID='{0}'", BLID));
            gvOrders.DataBind();
        }
    }

    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            GridView gvOrders1 = (sender as GridView).FindControl("GridView3") as GridView;
            gvOrders1.DataSource = GetData(string.Format("select LinerInvoiceWiseChargesTbl.InvoiceChargesType,concat(LinerInvoiceWiseChargesTbl.InvoiceCurrency,'-', LinerInvoiceWiseChargesTbl.InvoiceCharges)as PerUnit,LinerInvoiceWiseChargesTbl.InvoiceINR,LinerInvoiceWiseChargesTbl.InvoiceUSD  from LinerBLTbl,LinerInvoiceWiseChargesTbl  where LinerBLTbl.BillOfLadingID=LinerInvoiceWiseChargesTbl.InvoiceBillOfLadingID and LinerBLTbl.BillOfLadingID='" + BLID + "'"));
            gvOrders1.DataBind();
        }
    }


问:
Hive query drops null values with "not column=value" where clause
table1 data sample:

```<code>year month day utmsource
2017 03    26  NULL
2017 03    27  NULL
2017 03    27  facebook
2017 03    27  newsletter
2017 03    27  banner
2017 03    27  facebook
</code>```

expected selection:

```<code>year month day utmsource
2017 03    27  NULL
2017 03    27  newsletter
2017 03    27  banner
</code>```

My Hive queries:

```<code>-- result = 0, it did not include the NULL utmsource record
SELECT SUM(CASE WHEN utmsource IS NULL THEN 1 ELSE 0 END) as amountnull
FROM table1
WHERE year=2017 AND month=03 AND day=27 AND NOT utmsource="facebook"

-- result = 1 the NULL utmsource record is included
SELECT SUM(CASE WHEN utmsource IS NULL THEN 1 ELSE 0 END) as amountnull
FROM table1
WHERE year=2017 AND month=03 AND day=27 AND (utmsource IS NULL OR NOT utmsource="facebook")

-- also returns 0, the NULL utmsource record is not included
SELECT SUM(CASE WHEN utmsource IS NULL THEN 1 ELSE 0 END) as amountnull
FROM table1
WHERE year=2017 AND month=03 AND day=27 AND NOT utmsource <=> 'facebook';
</code>```

Questions:

Could someone explain this behaviour?

Can i change a setting to
retrieve the result of query 2 without adding the extra OR
functionality in my query? => not equals includes null values in result

答:
What you want is a NULL-safe equality (or inequality) operator.  In ANSI SQL, there is an operator called is distinct from.  Hive appears to use the MySQL version, which is <=>.  So, you can do:

```<code>SELECT SUM(CASE WHEN utmsource IS NULL THEN 1 ELSE 0 END) as amountnull
FROM tablename
WHERE year=2017 AND month=03 AND day=27 AND NOT utmsource <=> 'facebook';
</code>```

This operator is described in the documentation.

I should also point out that you might find this a simpler formulation for the SELECT:

```<code>SELECT (COUNT(*) - COUNT(utmsource)) as amountnull
FROM tablename
WHERE year=2017 AND month=03 AND day=27 AND NOT utmsource <=> 'facebook';
</code>```

Although, overall, this would appear to be the simplest:

```<code>SELECT COUNT(*)as amountnull
FROM tablename
WHERE year=2017 AND month=03 AND day=27 AND utmsource IS NULL;
</code>```

The comparison to 'Facebook' is unnecessary.

Body:
table1 data sample:

year month day utmsource
2017 03    26  NULL
2017 03    27  NULL
2017 03    27  facebook
2017 03    27  newsletter
2017 03    27  banner
2017 03    27  facebook

expected selection:

year month day utmsource
2017 03    27  NULL
2017 03    27  newsletter
2017 03    27  banner

My Hive queries:

-- result = 0, it did not include the NULL utmsource record
SELECT SUM(CASE WHEN utmsource IS NULL THEN 1 ELSE 0 END) as amountnull
FROM table1
WHERE year=2017 AND month=03 AND day=27 AND NOT utmsource="facebook"

-- result = 1 the NULL utmsource record is included
SELECT SUM(CASE WHEN utmsource IS NULL THEN 1 ELSE 0 END) as amountnull
FROM table1
WHERE year=2017 AND month=03 AND day=27 AND (utmsource IS NULL OR NOT utmsource="facebook")

-- also returns 0, the NULL utmsource record is not included
SELECT SUM(CASE WHEN utmsource IS NULL THEN 1 ELSE 0 END) as amountnull
FROM table1
WHERE year=2017 AND month=03 AND day=27 AND NOT utmsource <=> 'facebook';

Questions:

Could someone explain this behaviour?

Can i change a setting to
retrieve the result of query 2 without adding the extra OR
functionality in my query? => not equals includes null values in result

Body:
What you want is a NULL-safe equality (or inequality) operator.  In ANSI SQL, there is an operator called is distinct from.  Hive appears to use the MySQL version, which is <=>.  So, you can do:

SELECT SUM(CASE WHEN utmsource IS NULL THEN 1 ELSE 0 END) as amountnull
FROM tablename
WHERE year=2017 AND month=03 AND day=27 AND NOT utmsource <=> 'facebook';

This operator is described in the documentation.

I should also point out that you might find this a simpler formulation for the SELECT:

SELECT (COUNT(*) - COUNT(utmsource)) as amountnull
FROM tablename
WHERE year=2017 AND month=03 AND day=27 AND NOT utmsource <=> 'facebook';

Although, overall, this would appear to be the simplest:

SELECT COUNT(*)as amountnull
FROM tablename
WHERE year=2017 AND month=03 AND day=27 AND utmsource IS NULL;

The comparison to 'Facebook' is unnecessary.


问:
Picture Control background is gray and I want it white
My application has a picture control, whose background is gray and I want it to be white. I already tried several things, like: derive a class and override OnPaint method; respond to WM_CTLCOLOR message (adding ON_WM_CTLCOLOR()and processing it), but no success.

Entry on Message map:

```<code>ON_WM_CTLCOLOR()
</code>```

Implementation:

```<code>BOOL CMyDialog::OnInitDialog()
{
    __super::OnInitDialog();

    white.CreateSolidBrush(RGB(255,255,255));

    //...

    return TRUE;  // return TRUE  unless you set the focus to a control
}

HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
    if (pWnd == GetDlgItem(IDC_PICTURE))
    {
        return white;
    }

    return __super::OnCtlColor(pDC, pWnd, nCtlColor);
}
</code>```

Header file class definition:

```<code>CBrush white;

HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
</code>```

答:
After some debugging using Spy++, I've realized the Picture Control is a Static Control and the message I have to process is not WM_CTLCOLOR but WM_CTLCOLORSTATIC

So, on the dialog that contains it I changed the message map from

```<code>ON_WM_CTLCOLOR()
</code>```

to

```<code>ON_MESSAGE(WM_CTLCOLORSTATIC, OnCtlColorStatic)
</code>```

On the implementation, change the method from

```<code>HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
    if (pWnd == GetDlgItem(IDC_PICTURE))
    {
        return white;
    }

    return __super::OnCtlColor(pDC, pWnd, nCtlColor);
}
</code>```

to

```<code>LRESULT CMyDialog::OnCtlColorStatic(WPARAM wParam, LPARAM lParam)
{
    HWND hWnd = (HWND)lParam;

    if (::GetDlgCtrlID(hWnd) == IDC_PICTURE)
        return (LRESULT)white.GetSafeHandle();

    return DefWindowProc(WM_CTLCOLORSTATIC, wParam, lParam);
}
</code>```

And in the header file, change also the method from

```<code>HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
</code>```

to

```<code>LRESULT OnCtlColorStatic(WPARAM wParam, LPARAM lParam);
</code>```

Notice a subtle difference: the old one worked by returning the HBRUSH brush handle directly; the new one expects a function returning a LRESULT typed variable, so the cast.

The result is what I was expecting:

UPDATE: I recently needed to do a thing where I had to set the Text Color of a Static and discovered that I can get its device context also:

```<code>HDC hDC= (HDC)wParam;
HWND hWnd = (HWND)lParam;
</code>```

So, after I could easily do it by:

```<code>SetBkMode(hDC, TRANSPARENT);
SetTextColor(hDC, RGB(0,127,127));
</code>```

Body:
My application has a picture control, whose background is gray and I want it to be white. I already tried several things, like: derive a class and override OnPaint method; respond to WM_CTLCOLOR message (adding ON_WM_CTLCOLOR()and processing it), but no success.

Entry on Message map:

ON_WM_CTLCOLOR()

Implementation:

BOOL CMyDialog::OnInitDialog()
{
    __super::OnInitDialog();

    white.CreateSolidBrush(RGB(255,255,255));

    //...

    return TRUE;  // return TRUE  unless you set the focus to a control
}

HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
    if (pWnd == GetDlgItem(IDC_PICTURE))
    {
        return white;
    }

    return __super::OnCtlColor(pDC, pWnd, nCtlColor);
}

Header file class definition:

CBrush white;

HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);

Body:
After some debugging using Spy++, I've realized the Picture Control is a Static Control and the message I have to process is not WM_CTLCOLOR but WM_CTLCOLORSTATIC

So, on the dialog that contains it I changed the message map from

ON_WM_CTLCOLOR()

to

ON_MESSAGE(WM_CTLCOLORSTATIC, OnCtlColorStatic)

On the implementation, change the method from

HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
    if (pWnd == GetDlgItem(IDC_PICTURE))
    {
        return white;
    }

    return __super::OnCtlColor(pDC, pWnd, nCtlColor);
}

to

LRESULT CMyDialog::OnCtlColorStatic(WPARAM wParam, LPARAM lParam)
{
    HWND hWnd = (HWND)lParam;

    if (::GetDlgCtrlID(hWnd) == IDC_PICTURE)
        return (LRESULT)white.GetSafeHandle();

    return DefWindowProc(WM_CTLCOLORSTATIC, wParam, lParam);
}

And in the header file, change also the method from

HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);

to

LRESULT OnCtlColorStatic(WPARAM wParam, LPARAM lParam);

Notice a subtle difference: the old one worked by returning the HBRUSH brush handle directly; the new one expects a function returning a LRESULT typed variable, so the cast.

The result is what I was expecting:

UPDATE: I recently needed to do a thing where I had to set the Text Color of a Static and discovered that I can get its device context also:

HDC hDC= (HDC)wParam;
HWND hWnd = (HWND)lParam;

So, after I could easily do it by:

SetBkMode(hDC, TRANSPARENT);
SetTextColor(hDC, RGB(0,127,127));


问:
Save multiple values in table
Given:

a user defined function that receives a string and returns multiple (5) values

a dataframe with one string column

I read every column from the dataframe, and call the function with the column as parameter.

The output should be saved as a table.
How can I achieve this?

答:
```<code>from pyspark.sql import Row
df = sc.parallelize(['a','b','c']).map(lambda row : Row(key=row)).toDF()
df.show()
</code>```

:

```<code>+---+
|key|
+---+
|  a|
|  b|
|  c|
+---+
</code>```

:

```<code>def func (args):
    # function that will return 5 multiple values
    lista = Row(result=",".join([ args.key+str(x) for x in range(5)]))
    return lista

new_table = df.rdd.map(func).toDF()
new_table.show()
</code>```

:

```<code>+--------------+
|        result|
+--------------+
|a0,a1,a2,a3,a4|
|b0,b1,b2,b3,b4|
|c0,c1,c2,c3,c4|
+--------------+
</code>```

:

```<code>new_table.saveAsTable("results")
</code>```

Title: Save multiple values in table

Body:
from pyspark.sql import Row
df = sc.parallelize(['a','b','c']).map(lambda row : Row(key=row)).toDF()
df.show()

:

+---+
|key|
+---+
|  a|
|  b|
|  c|
+---+

:

def func (args):
    # function that will return 5 multiple values
    lista = Row(result=",".join([ args.key+str(x) for x in range(5)]))
    return lista

new_table = df.rdd.map(func).toDF()
new_table.show()

:

+--------------+
|        result|
+--------------+
|a0,a1,a2,a3,a4|
|b0,b1,b2,b3,b4|
|c0,c1,c2,c3,c4|
+--------------+

:

new_table.saveAsTable("results")


问:
How do I get most recent row in select statement on Oracle Apex 5?
When the user fills out a form, a column picks up the most recent data from certain columns and concatenates the columns into a new column (the record's id). Now I have the right columns being selected, but the issue I'm having is that for every form that is filled the code only gets the row from the very first record that was ever filled out. Apparently TOP and LIMIT don't work on Oracle Apex 5, and it seems that ROWNUM = 1 is what is causing the problem here.

```<code>DECLARE
  IDENTITY VARCHAR2(40);
BEGIN
  SELECT CONCAT(COL1, CONCAT('-', CONCAT(COL2, COL3)))
 INTO IDENTITY FROM TABLE
 WHERE ROWNUM = 1;
 RETURN IDENTITY;
END;
</code>```

答:
You have not specified oracle version.  Pre-12c, you have to sort the result first, then return the first row.  This is called a Top-N query.  You need to supply the search column in the queries below.

```<code>DECLARE
  IDENTITY VARCHAR2(40);
BEGIN
 SELECT NEW_ID
 INTO IDENTITY
 FROM (SELECT COL1 || '-' || COL2 || COL3 as NEW_ID
       FROM TABLE
       ORDER BY <sort column> )
 WHERE ROWNUM = 1;
 RETURN IDENTITY;
END;
</code>```

If you are using 12c, you can use FETCH FIRST ROW ONLY

```<code>DECLARE
  IDENTITY VARCHAR2(40);
BEGIN
 SELECT COL1 || '-' || COL2 || COL3
 INTO IDENTITY
 FROM TABLE
 ORDER BY <sort column>
 FETCH FIRST ROW ONLY;
 RETURN IDENTITY;
END;
</code>```

Body:
When the user fills out a form, a column picks up the most recent data from certain columns and concatenates the columns into a new column (the record's id). Now I have the right columns being selected, but the issue I'm having is that for every form that is filled the code only gets the row from the very first record that was ever filled out. Apparently TOP and LIMIT don't work on Oracle Apex 5, and it seems that ROWNUM = 1 is what is causing the problem here.

DECLARE
  IDENTITY VARCHAR2(40);
BEGIN
  SELECT CONCAT(COL1, CONCAT('-', CONCAT(COL2, COL3)))
 INTO IDENTITY FROM TABLE
 WHERE ROWNUM = 1;
 RETURN IDENTITY;
END;

Body:
You have not specified oracle version.  Pre-12c, you have to sort the result first, then return the first row.  This is called a Top-N query.  You need to supply the search column in the queries below.

DECLARE
  IDENTITY VARCHAR2(40);
BEGIN
 SELECT NEW_ID
 INTO IDENTITY
 FROM (SELECT COL1 || '-' || COL2 || COL3 as NEW_ID
       FROM TABLE
       ORDER BY <sort column> )
 WHERE ROWNUM = 1;
 RETURN IDENTITY;
END;

If you are using 12c, you can use FETCH FIRST ROW ONLY

DECLARE
  IDENTITY VARCHAR2(40);
BEGIN
 SELECT COL1 || '-' || COL2 || COL3
 INTO IDENTITY
 FROM TABLE
 ORDER BY <sort column>
 FETCH FIRST ROW ONLY;
 RETURN IDENTITY;
END;


问:
Check if key exists in memcache cluster using PHP
I'm debugging the caching layer of a PHP application. It uses a cluster of memcache servers to cache values. I want to verify that a specific object gets purged correctly.

My idea was to connect to the right memcache server with telnet and check manually if the key exists.
I know the key that is passed to Memcache::set, but not which server to connect to. How do I know on which memcache server the data gets stored?

答: If it's cluster than it's synchronizing data in al instances or have one centralized storage for data (internal realisation - not important for you). You will get data in all instances.</p>


问:
Propublica API authenticate key with javascript
Sorry if this is a simple question, but I'm trying to send a GET request to the ProPublica API. They gave me a key, but the documentation does not say how to authenticate with this key when I try and hit the endpoints of the API. If anyone can make sense of this, I'd appreciate it!

I would like to hit this route:

```<code>GET https://api.propublica.org/congress/v1/members/{chamber}/{state}/current.json
</code>```

The documentation only mentions curl:

```<code>curl "https://api.propublica.org/congress/v1/members/senate/RI/current.json"
  -H "X-API-Key: PROPUBLICA_API_KEY"
</code>```

答:
Thanks to Amol for the reply, here is a working version that writes to the console. Make sure you have jQuery, or test it in a browser's dev tools on a site that has jQuery.</p>

```<code>$.ajax({
         url: "https://api.propublica.org/congress/v1/members/senate/RI/current.json",
         type: "GET",
         dataType: 'json',
         headers: {'X-API-Key': 'YOUR KEY HERE'}
       }).done(function(data){
       console.log(data)
       });
</code>```

Body:
Sorry if this is a simple question, but I'm trying to send a GET request to the ProPublica API. They gave me a key, but the documentation does not say how to authenticate with this key when I try and hit the endpoints of the API. If anyone can make sense of this, I'd appreciate it!

I would like to hit this route:

GET https://api.propublica.org/congress/v1/members/{chamber}/{state}/current.json

The documentation only mentions curl:

curl "https://api.propublica.org/congress/v1/members/senate/RI/current.json"
  -H "X-API-Key: PROPUBLICA_API_KEY"

Body:
Thanks to Amol for the reply, here is a working version that writes to the console. Make sure you have jQuery, or test it in a browser's dev tools on a site that has jQuery.

$.ajax({
         url: "https://api.propublica.org/congress/v1/members/senate/RI/current.json",
         type: "GET",
         dataType: 'json',
         headers: {'X-API-Key': 'YOUR KEY HERE'}
       }).done(function(data){
       console.log(data)
       });


问:
force download youtube videos from url in browser (client-site) in javascript
I am working on youtube video downloader site that is using node based server-site. I am using npm package called ytdl-core and this module is returning download link. But, when I click on that link it redirects me to "video preview" instead of "trigger download",

```<code>ytdl(url, function(err, format) {
  if (err) {res.send('the url is invalid please try again...');}
  console.log((format.formats).length);//i am getting value... in console but not outside of the function..
  //this object contains all the download links
  var links = []
  for( var i= 0, len = (format.formats).length; i < len; i++) {
    var el = format.formats[i].container;
    if ( el === 'mp4') {
      var download_url = format.formats[i];
      //this push will store the all links in 'links' object..
      links.push(download_url);
    }
  }
  console.log(links);
});
</code>```

So when I paste the link into my browser, it redirects me to preview instead of trigger download. I am getting link that looks like this:

```<code>https://r8---sn-gxap5ojx-cage.googlevideo.com/videoplayback?upn=P6gEaXLtqOc&ei=ROrcWMzGKsjfoAPtl6XYAg&id=o-AIBZRxwo9AvJU4q02_xR0lfxJbSV3pxpga67Si4bLieu&key=yt6&ip=139.59.64.12&ipbits=0&pl=20&requiressl=yes&initcwndbps=8882500&ratebypass=yes&sparams=clen%2Cdur%2Cei%2Cgir%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpcm2cms%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&itag=18&expire=1490894500&mime=video%2Fmp4&pcm2cms=yes&source=youtube&mv=m&mt=1490872775&ms=au&lmt=1487309879666192&clen=8449602&gir=yes&mn=sn-gxap5ojx-cage&mm=31&dur=221.518&signature=6ED71F39CAA3B6719A8BAAEABD51D568ABF4D7A3.B3EED034140574BAC9733EC5CC28EF4AC9E3F758&title=Kygo Selena Gomez It Ain t Me with Selena Gomez Audio
</code>```

My question is, how can I force download that video to client's browser by clicking button?

答:
If you are using express it may be helpful to use res.download(). It would work along the lines of this.

```<code>res.download(downloadLink, downloadTitle, function(err){
  if (err) {
    // Handle error, but keep in mind the response may be partially-sent
    // so check res.headersSent
  } else {
    // decrement a download credit, etc.
  }
});
</code>```

Good luck! Hope this helps!

Body:
I am working on youtube video downloader site that is using node based server-site. I am using npm package called ytdl-core and this module is returning download link. But, when I click on that link it redirects me to "video preview" instead of "trigger download",

ytdl(url, function(err, format) {
  if (err) {res.send('the url is invalid please try again...');}
  console.log((format.formats).length);//i am getting value... in console but not outside of the function..
  //this object contains all the download links
  var links = []
  for( var i= 0, len = (format.formats).length; i < len; i++) {
    var el = format.formats[i].container;
    if ( el === 'mp4') {
      var download_url = format.formats[i];
      //this push will store the all links in 'links' object..
      links.push(download_url);
    }
  }
  console.log(links);
});

So when I paste the link into my browser, it redirects me to preview instead of trigger download. I am getting link that looks like this:

https://r8---sn-gxap5ojx-cage.googlevideo.com/videoplayback?upn=P6gEaXLtqOc&ei=ROrcWMzGKsjfoAPtl6XYAg&id=o-AIBZRxwo9AvJU4q02_xR0lfxJbSV3pxpga67Si4bLieu&key=yt6&ip=139.59.64.12&ipbits=0&pl=20&requiressl=yes&initcwndbps=8882500&ratebypass=yes&sparams=clen%2Cdur%2Cei%2Cgir%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpcm2cms%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&itag=18&expire=1490894500&mime=video%2Fmp4&pcm2cms=yes&source=youtube&mv=m&mt=1490872775&ms=au&lmt=1487309879666192&clen=8449602&gir=yes&mn=sn-gxap5ojx-cage&mm=31&dur=221.518&signature=6ED71F39CAA3B6719A8BAAEABD51D568ABF4D7A3.B3EED034140574BAC9733EC5CC28EF4AC9E3F758&title=Kygo Selena Gomez It Ain t Me with Selena Gomez Audio

My question is, how can I force download that video to client's browser by clicking button?

Body:
If you are using express it may be helpful to use res.download(). It would work along the lines of this.

res.download(downloadLink, downloadTitle, function(err){
  if (err) {
    // Handle error, but keep in mind the response may be partially-sent
    // so check res.headersSent
  } else {
    // decrement a download credit, etc.
  }
});

Good luck! Hope this helps!


问:
start the service when app gets closed
I want to start a service when I press the home button or just press back (when the app is in the background but not killed)
how can I do a function that checks that ?
thanks to all</p>

答:
Use Foreground service using startForeground() method and START_STICKY flag. In breif, you have to say to the user 'my app is still working'.

Or the other implementation is to use AlarmManager if you want to charge the task for the future.

Title: start the service when app gets closed


问:
How does 'parseInt(String, radix)' work?
I understand that the parseInt method is used to convert strings to int, but I do not know how. I understand that if you say:

```<code>System.out.println(Integer.parseInt("52", 10));
</code>```

will give you 52 in base 10. What I am unaware of is if you say replace base 10 with 15, how does it exactly compute. From some research, I found people saying that you must use ASCII values. If it helps, I am trying to be able to solve this on paper solely, without the work of any more code.

答:
parseInt(String s, int radix) methods works like so:

The radix parameter is checked. It should be in the
range 2 - 36

Each character of the string is parsed and verified to be a valid digit (within the bound defined by the radix)

The result is multiplied for the radix and incrementally added to a results variable

The results variable is returned

The algorithm is quite simple. An important piece of the work is done by the part that verifies whether the digit is valid.

Around this code there are a few checks that will eventually cause a NumberFormatException, e.g. the presence of valid signs (+ or -) before the digit, the presence of leading zeros, overflows, etc.

Body:
I understand that the parseInt method is used to convert strings to int, but I do not know how. I understand that if you say:

System.out.println(Integer.parseInt("52", 10));

will give you 52 in base 10. What I am unaware of is if you say replace base 10 with 15, how does it exactly compute. From some research, I found people saying that you must use ASCII values. If it helps, I am trying to be able to solve this on paper solely, without the work of any more code.


问:
geolocation and a floorplan - javascript marauders map
If someone gave you point A(lat,lon) and point B(lat,lon) on a floor plan image, and you have the width and height of the floorplan image, can you then use geolocation to track where they are as they walk around?

Are there any projects you know of that attempt to solve this?

答: I don't have much experience with geolocation in JavaScript, but if you can map locations in real life to your image then it should work fine.</p>


问:
Hibernate or JPA?
With Spring 3.0 is it recommended to use hibernate or JPA.What are the advantages and disadvantages of both of them when used with Spring 3.0 ?

Note : We are also suppose to use it with Spring Data Access.

答:
My preference is JPA with EclipseLink. Reasons:

JPA is standard, Hibernate is not

Use EclipseLink because JPA with Hibernate has some weird implementation. EclipseLink is also the reference implementation for JPA 2.0

Bozho: there are some that I found, unfortunately it is not so obvious because it only happens in some extreme cases. Some that I can think:

Convert JQL to CriteriaBuilder

ElementCollection works fine with JoinTable, which is wrong! ElementCollection should be accompanied by CollectionTable.

Title: Hibernate or JPA?


问:
Outlook REST API. How to start new thread on forward message?
First i want to ask how the Outlook client decides if a message that the user wrote should be in the same thread(conversation) or in a new one on forward of a message.

From my observations it checks the subject, but does it check also something else.
I'm using the Outlook rest api v2 and beta versions.
To force the api to create the message in new thread i tried setting the subject in the following patern:

Fwd: { subject of the message i forward} or
Fwr: { subject of the message i forward}

The only successful approach was to add some character to the end of the subject text, but i'm afraid that this might be considered as a bug from some users.

So is there some way to create the message in a new thread when calling /messages/{message_id}/createforward endpoint?

Looking forward for an answer to this.

答:
I used a different approach when it came to Forward/Reply messages, because I had some issues with Attachments. It seems that my approach could be useful in your case as well.

When I want to forward a message, I retrieve all the attachments of the message and I add 'FW:' at the beginning of the subject, and then I use https://outlook.office365.com/api/v2.0/me/sendmail as If I am sending a new email! That will start a new thread! I hope it works for you.


问:
Bulk insert from Excel to SQLite without TXT or CSV file
I have a problem and I hope to get some input from any of you.

Basically, I need to write a code in VBA which enables me to take a table of data from excel to sqlite.

I have managed to do it using this code:

Sub Scrivi()
    Dim objConnection As Object, objRecordset As Object
    Dim strDatabase As String

    Set objConnection = CreateObject("ADODB.Connection")

    strDatabase = "DRIVER={SQLite3 ODBC Driver};Database=" & Application.ActiveWorkbook.Path & "\TestDB.db;"

    Query = "drop table FUND; create table FUND (Fund_Code, Fund_Name, End_Date, PRIMARY KEY('Fund_Code'));"
    riga = 3
    colonna = 1
    While Not (IsNull(ActiveSheet.Cells(row, column).Value) Or IsEmpty(ActiveSheet.Cells(row, column).Value))
        Query = Query & "insert into FUND values('" & Cells(row, column) & "','" & Cells(row, column + 1) & "','" & Cells(row, column + 2) & "');"
        row = row + 1
    Wend

    objConnection.Open strDatabase
    objConnection.Execute Query
    objConnection.Close
End Sub
```

Now I would like to change the iterative part in which I say row = row + 1 with a sort of bulk insert in which the program takes the whole table instead of doing it row by row.

I do not want a creation of csv/txt file if it is possible.

Thank you very much, any input would be appreciated.

答:
you could append all data from worksheet.range into array(variant)

```<code>Dim arr as Variant
arr = Application.Transpose(range(your_range_of_data).values)
</code>```

and then, using data in array, build SQL query string using this pattern

```<code>INSERT INTO table
(column1, column2, ... )
VALUES
(expression1, expression2, ... ),
(expression1, expression2, ... ),
...;
</code>```

VBA Function (written 'on the knee', so it might require a little bit of tweaking, sorry)

```<code>Function buildQueryFromArray(arr as Variant, table as String, columns as String) as String
    Dim strSqlQuery as String * 4096
    Dim i as Integer

    strSqlQuery = "INSERT INTO " & table & " (" & columns & ") VALUES"
    For i=LBound(arr, 1) to UBound(arr, 1)
        strSqlQuery = strSqlQuery & "(" & arr(i,1) & ", " & arr(i,2) & "etc" & "),"
    Next i
    buildQueryFromArray = Left(strSqlQuery, len(strSqlQuery)-1) & ";"
End Function
</code>```

reason for using array instead of grabbing data directly from worksheet is: its much much faster. You can read more here: http://www.cpearson.com/excel/ArraysAndRanges.aspx

lemme know if that works for you : )

EDIT:

Ad1: you're right, we actually don't want to transpose it. however, I got used to write this way because of the reasons which are well described in post #7 in this topic: mrexcel.com/forum/ Why we use application.transpose?

Ad2: no, it doesn't have to be in function if this is your question, but it makes code cleaner and more reusable. Below you can find inline solution:

```<code>Sub Scrivi()
Dim objConnection As Object, objRecordset As Object
Dim strDatabase As String, strQuery as String

Set objConnection = CreateObject("ADODB.Connection")

strDatabase = "DRIVER={SQLite3 ODBC Driver};Database=" & Application.ActiveWorkbook.Path & "\TestDB.db;"

strQuery = "drop table FUND; create table FUND (Fund_Code, Fund_Name, End_Date, PRIMARY KEY('Fund_Code')); insert into FUND values"

'determine how many rows of data there is
Dim lastRow as Integer
lastRow = ActiveSheet.Range("A:A").Find("*", LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

'transfer all data from range to array
'range: from A3 to Cx, where x equals to lastRow
Dim arr as Variant
arr =

 ActiveSheet.Range("A3:C" & lastRow).Value

    'add all records from arr into single SQL query
    'Lbound(xArray, xDimension)/Ubound(xArray, xDimension) - returns integer equal to first/last xArray item in xDimension. Everyday-use function. Google some more to have better insight of whats going on
    Dim i as Integer
    For i=Lbound(arr,1) to Ubound(arr,1)
    strQuery = strQuery & "(" & arr(i,1) & "," & _
                                arr(i,2) & "," & _
                                arr(i,3) & "),"
Next i

'from the strQuery - swap last comma for semi-colon
strQuery = Left(strQuery, len(strQuery)-1) & ";"

objConnection.Open strDatabase
objConnection.Execute strQuery
objConnection.Close
</code>```

Lemme know if everything is clear :)

Body:
I have a problem and I hope to get some input from any of you.

Basically, I need to write a code in VBA which enables me to take a table of data from excel to sqlite.

I have managed to do it using this code:

Sub Scrivi()
    Dim objConnection As Object, objRecordset As Object
    Dim strDatabase As String

    Set objConnection = CreateObject("ADODB.Connection")

    strDatabase = "DRIVER={SQLite3 ODBC Driver};Database=" & Application.ActiveWorkbook.Path & "\TestDB.db;"

    Query = "drop table FUND; create table FUND (Fund_Code, Fund_Name, End_Date, PRIMARY KEY('Fund_Code'));"
    riga = 3
    colonna = 1
    While Not (IsNull(ActiveSheet.Cells(row, column).Value) Or IsEmpty(ActiveSheet.Cells(row, column).Value))
        Query = Query & "insert into FUND values('" & Cells(row, column) & "','" & Cells(row, column + 1) & "','" & Cells(row, column + 2) & "');"
        row = row + 1
    Wend

    objConnection.Open strDatabase
    objConnection.Execute Query
    objConnection.Close
End Sub

Now I would like to change the iterative part in which I say row = row + 1 with a sort of bulk insert in which the program takes the whole table instead of doing it row by row.

I do not want a creation of csv/txt file if it is possible.

Thank you very much, any input would be appreciated.

Body:
you could append all data from worksheet.range into array(variant)

Dim arr as Variant
arr = Application.Transpose(range(your_range_of_data).values)

and then, using data in array, build SQL query string using this pattern

INSERT INTO table
(column1, column2, ... )
VALUES
(expression1, expression2, ... ),
(expression1, expression2, ... ),
...;

VBA Function (written 'on the knee', so it might require a little bit of tweaking, sorry)

Function buildQueryFromArray(arr as Variant, table as String, columns as String) as String
    Dim strSqlQuery as String * 4096
    Dim i as Integer

    strSqlQuery = "INSERT INTO " & table & " (" & columns & ") VALUES"
    For i=LBound(arr, 1) to UBound(arr, 1)
        strSqlQuery = strSqlQuery & "(" & arr(i,1) & ", " & arr(i,2) & "etc" & "),"
    Next i
    buildQueryFromArray = Left(strSqlQuery, len(strSqlQuery)-1) & ";"
End Function

reason for using array instead of grabbing data directly from worksheet is: its much much faster. You can read more here: http://www.cpearson.com/excel/ArraysAndRanges.aspx

lemme know if that works for you : )

EDIT:

Ad1: you're right, we actually don't want to transpose it. however, I got used to write this way because of the reasons which are well described in post #7 in this topic: mrexcel.com/forum/ Why we use application.transpose?

Ad2: no, it doesn't have to be in function if this is your question, but it makes code cleaner and more reusable. Below you can find inline solution:

Sub Scrivi()
Dim objConnection As Object, objRecordset As Object
Dim strDatabase As String, strQuery as String

Set objConnection = CreateObject("ADODB.Connection")

strDatabase = "DRIVER={SQLite3 ODBC Driver};Database=" & Application.ActiveWorkbook.Path & "\TestDB.db;"

strQuery = "drop table FUND; create table FUND (Fund_Code, Fund_Name, End_Date, PRIMARY KEY('Fund_Code')); insert into FUND values"

'determine how many rows of data there is
Dim lastRow as Integer
lastRow = ActiveSheet.Range("A:A").Find("*", LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

'transfer all data from range to array
'range: from A3 to Cx, where x equals to lastRow
Dim arr as Variant
arr =

 ActiveSheet.Range("A3:C" & lastRow).Value

    'add all records from arr into single SQL query
    'Lbound(xArray, xDimension)/Ubound(xArray, xDimension) - returns integer equal to first/last xArray item in xDimension. Everyday-use function. Google some more to have better insight of whats going on
    Dim i as Integer
    For i=Lbound(arr,1) to Ubound(arr,1)
    strQuery = strQuery & "(" & arr(i,1) & "," & _
                                arr(i,2) & "," & _
                                arr(i,3) & "),"
Next i

'from the strQuery - swap last comma for semi-colon
strQuery = Left(strQuery, len(strQuery)-1) & ";"

objConnection.Open strDatabase
objConnection.Execute strQuery
objConnection.Close

Lemme know if everything is clear :)


问:
Endless loop in angularfire2 subscription
I am getting data and add data to the same node within an subscription. How can I avoid the endless loop?</p>

```<code>this.af.database.list('objects/').subscribe(x=>{   / the subscription is only needed once
  this.af.database.list('objects/').push({newobject: ''};
};
</code>```

答:
Shoot me if I'm wrong, or don't, but I believe you can use the first() method:

```<code>this.af.database.list('objects/').first().subscribe(x=>{
  this.af.database.list('objects/').push({newobject: ''};
};
</code>```

Body:
I am getting data and add data to the same node within an subscription. How can I avoid the endless loop?

this.af.database.list('objects/').subscribe(x=>{   / the subscription is only needed once
  this.af.database.list('objects/').push({newobject: ''};
};

Body:
Shoot me if I'm wrong, or don't, but I believe you can use the first() method:

this.af.database.list('objects/').first().subscribe(x=>{
  this.af.database.list('objects/').push({newobject: ''};
};


问:
how to view custom provider's events(collected without provider registered) by wpa
I try to use manifested base event to log event for debugging and analyzing.
But I have a problem: when I record with my provider registered, everything is fine, when open .etl file in WPA, I can view as much info as I can.
But if I collect events without my provider registered, when I open .etl file in WPA, everything is not human friendly.
So, must I register my provider before I start collect events? I hope not, because if so, I have to take the risk to leak my .man file, so others may use it to get the detail trace log as well. that's not acceptable!

I don't want my .man file packaged in install file, so I do not need to worry about leak it. and of course I can't register my provider as well.

Is there a way to view the .etl (collect without my provider registed first) as well as possible?

thanks in advance.

below are pictures that may make what i said more easy to understand.

image of record without my provider registered:

image of record with my provider registered:

答:
I found answer at msdn forums, here is the same question asked by myself.

xperf -merge is the key!

whole steps as follow:

install my software and start collect event data on custom's machine. (no need to register my provider.)
call xperf -start mysession -on MY_PROVIDER_GUID start collecting event data.

after run some time, call xperf -stop mysession -d poor.etl to stop collecting and save to poor.etl file.

copy poor.etl to my dev machine(my provider already registered) and callxperf -merge poor.etl good.etl

open good.etl with wpa, I can see every details as I expected.

that's all. hope it will help other guy like me. thanks everyone.


问:
Does tf.train.MonitoredTrainingSession() support GRPC?
We need to define multiple clients (each creates and builds Tensorflow Session/graph) using "Between-graph Replication" in Distributed Tensorflow. Typically, the client and worker are in the same process, and tf.train.MonitoredTrainingSession() coordinates those Tensorflow Sessions.

Now if each client and worker is not in the same process, and I want client to use grpc to remotely drive worker tasks, I wonder if tf.train.MonitoredTrainingSession() or some APIs support this feature, or if anyone has any other solutions or ideas. (I know tf.Session(<grpc_url>) supports grpc, but it does not coordinate multiple Tensorflow Sessions)

答:
Yes, tf.train.MonitoredTrainingSession can use gRPC. However, you must create the tf.train.Server object manually (typically one per process), as shown in the Distributed TensorFlow tutorial.

Once you have created a tf.train.Server, the most common way to configure a tf.train.MonitoredTrainingSession for distributed training is to call tf.train.MonitoredTrainingSession(master=server.target), where server is one of the servers in the "worker" job.


问:
What Java/Design Patterns can be used for Long Running Synchronous Processes?
I am encountering a situation at work similar to the thread over here. The difference is that we are not using a web service. But rather we are using a web app. We have a requirement that lets a user download 8000 records with at least 30 columns which is written to an excel file via jxl.

This is a long running process that is not being done asynchronously for reasons I don't know. It also has a huge memory footprint ~ 500 - 800 MB. To top it all of, it takes on average 2 minutes and 10 seconds to finish.

What we are currently doing is delegating this requirement out of process from the application server via jms. The app server sends the request to the broker and then a consumer gets the request from the queue, processes it and sends back the url of the excel file.

I have some qualms about this because I have read been reading about JMS and most of the usecases suggested involve asynchronous requests so that users won't have to wait for a long time like for instance sending email, sending a request for approval, invoicing. There are lot of examples in this thread and the use cases suggested can be done asynchronously. So our current solution sounds like a hack rather than a true solution.

Any suggestions, patterns that can be done to further improve this process?

EDIT:  I unfortunately can't do away with the "synchronicity" if you may call it that of the feature because it's a business requirement. So I am looking for answers/tweaks/tricks/patterns that can enhance the performance and lessen the heap memory usage of the process instead.

答:
Did I understand this right?

The user makes a request. During this request

a JMS message is sent

an Excel file created

a JMS message returned

and then the URL is sent to the user?

If so, I agree, that's an awful abuse of the asynchroneous nature of JMS.

What I would do is:

Immediately show the user a result page with a text like your request is being processed and then

either use AJAX to poll the server for the result URL (possibly showing the user a status bar)

or send the URL to the client via email


问:
format DD/MM/YYYY input react as user types
I have an input box in a React component. This is to take a date of birth. I want to add / after each relevant section. i.e. 30/03/2017

Something similar to this but for date of birth as opposed to credit card number.

The user should enter 30 and then it should automatically add the /. This works with my current code, however, it enters a slash after each 2 digits, however, for the year it adds the slash also after each second digit.

See complete React component below

```<code>class DateInput extends Component {

  constructor(props) {

    this.handleChange = this.handleChange.bind(this);

    this.state = {
      value: ''
    }

  }

  handleChange(val) {

    val = val.split('/').join('');
    val = val.match(new RegExp('.{1,2}', 'g')).join("/");

    this.setState({
        value: val
    });

  }

  render() {

    const {value} = this.state;
    const placeholder = 'DAY/MONTH/YEAR';

    return ( <input type = "text" value={value} placeholder={placeholder}
      onChange = {this.handleChange}/>
    );

  }

}
</code>```

答:
Your Issue:
The issue in your code is in the handleChange function. When you try to delete the '/' the function gets called (because its bound to onChange) and adds a new '/' again.

Date inputs in general:
Date-inputs can be very tricky as the formatting differs from country to country. Not only the seperator but also the order of day, month and year is different.

As I don't know what your Application is doing in the end I can't really give a straight answer here. If your Page/Application will be used not only in the US but around the world I would very much recommend to use one of the many plugins out there to take care of your formatting issue.

For Example: https://github.com/RobinHerbots/Inputmask
Demo here: http://robinherbots.github.io/Inputmask/

Hope this helps. Good luck and don't get to frustrated over date inputs (I've been there ;))

Body:
I have an input box in a React component. This is to take a date of birth. I want to add / after each relevant section. i.e. 30/03/2017

Something similar to this but for date of birth as opposed to credit card number.

The user should enter 30 and then it should automatically add the /. This works with my current code, however, it enters a slash after each 2 digits, however, for the year it adds the slash also after each second digit.

See complete React component below

class DateInput extends Component {

  constructor(props) {

    this.handleChange = this.handleChange.bind(this);

    this.state = {
      value: ''
    }

  }

  handleChange(val) {

    val = val.split('/').join('');
    val = val.match(new RegExp('.{1,2}', 'g')).join("/");

    this.setState({
        value: val
    });

  }

  render() {

    const {value} = this.state;
    const placeholder = 'DAY/MONTH/YEAR';

    return ( <input type = "text" value={value} placeholder={placeholder}
      onChange = {this.handleChange}/>
    );

  }

}


问:
How to convert result_array() to result() object in codeigniter
I need JSON output like this,

```<code>{"restaurant":[{"id":"89","owner_id":"2161","name":"Bakso ",...}{"id":"90","owner_id":"3400","name":"Soto"}]}
</code>```

And I do using this query and work perfectly:

```<code>$latest_rest = $this->Restaurants_model->getLatestRestaurants($limit)->result();
$jsonObject = array('restaurant'=>$latest_rest);
</code>```

but i have query with result_array(), because I must filtering this data through function that return result_array();

how do I convert result_array() to result() in CodeIgniter?

答:
If it is mandatory to get result in array in beginning then to get json data you can first encode data into json and later can decode as:

```<code>$object = json_decode(json_encode($array));
</code>```

And, if it is not necessary in beginning then you can get result in object directly as:

```<code>$this->db->select('*')->from..........;
$query = $this->db->get();
return $query->result(); // instead of result_array();
</code>```

Body:
I need JSON output like this,

{"restaurant":[{"id":"89","owner_id":"2161","name":"Bakso ",...}{"id":"90","owner_id":"3400","name":"Soto"}]}

And I do using this query and work perfectly:

$latest_rest = $this->Restaurants_model->getLatestRestaurants($limit)->result();
$jsonObject = array('restaurant'=>$latest_rest);

but i have query with result_array(), because I must filtering this data through function that return result_array();

how do I convert result_array() to result() in CodeIgniter?

Body:
If it is mandatory to get result in array in beginning then to get json data you can first encode data into json and later can decode as:

$object = json_decode(json_encode($array));

And, if it is not necessary in beginning then you can get result in object directly as:

$this->db->select('*')->from..........;
$query = $this->db->get();
return $query->result(); // instead of result_array();


问:
How to typecast for mysql in()
I'm building a php script that creates a query string like,

```<code>$products = array(873, 874, 875);
$sql = 'select * from product_thumbnails where product in (' . implode($products, ', ') . ')';
</code>```

which creates a query like

```<code>'select * from product_thumbnails where product in (873, 874, 875)'
</code>```

The datatype for product is int. Are the params to the in() function treated as strings? If so, that would leave mysql to compare ints to strings and thus probably lead to a slow query as the app grows. Is there a way to typecast the params or to tell mysql to treat them as ints? Or is mysql smart enough to juggle this on its own?

Edit

Thanks much to Jerodev and jilesh for the answer- Mysql will treat these as ints. If you wanted a string instead, just use quotes inside the query string like

```<code>' in ("stringtype", "stringtype") '
</code>```

答:
In MySQL syntax...  When expecting a number, you can provide a number 123 or a string "123".

When expecting a string, you can provide either, but when comparing a VARCHAR to an unquoted number (123), it goes to the extra effort of converting the VARCHAR to numeric, which often gives you the wrong answer:  "abc" is treated as 0, or at least something confusing: "123abc" is treated as 123.

Title: How to typecast for mysql in()

Body:
I'm building a php script that creates a query string like,

$products = array(873, 874, 875);
$sql = 'select * from product_thumbnails where product in (' . implode($products, ', ') . ')';

which creates a query like

'select * from product_thumbnails where product in (873, 874, 875)'

The datatype for product is int. Are the params to the in() function treated as strings? If so, that would leave mysql to compare ints to strings and thus probably lead to a slow query as the app grows. Is there a way to typecast the params or to tell mysql to treat them as ints? Or is mysql smart enough to juggle this on its own?

Edit

Thanks much to Jerodev and jilesh for the answer- Mysql will treat these as ints. If you wanted a string instead, just use quotes inside the query string like

' in ("stringtype", "stringtype") '