问:
Identifier form is undefined
How can I solve the problem:

I am very new to C/C++ so I do not know what info I have to give in order to describe my problem properly. All that I was doing is trying to incorporate Windows Forms following step by step after the guy here. He got everything working and I do not even though I did exactly the same stuff as he did.

Here is the code with the error:

```<code>using namespace System;
using namespace System::Windows::Forms;

[STAThreadAttribute]
void Main(array<String^>^ args) {
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);
    Project1::MyForm form;
    Application::Run(%form);
}
</code>```

答:
You should really save yourself a lot of pain and use C# for your GUI and only use C++/CLI to wrap native unmanaged C++ code within your C# GUI.

Anyway, Project1 is not a namespace so just drop it. Try this:

```<code>using namespace System;
using namespace System::Windows::Forms;

[STAThreadAttribute]
void Main(array<String^>^ args) {
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);
    MyForm form;
    Application::Run(%form);
}
</code>```

Title: Identifier form is undefined

Body:
How can I solve the problem:

I am very new to C/C++ so I do not know what info I have to give in order to describe my problem properly. All that I was doing is trying to incorporate Windows Forms following step by step after the guy here. He got everything working and I do not even though I did exactly the same stuff as he did.

Here is the code with the error:

using namespace System;
using namespace System::Windows::Forms;

[STAThreadAttribute]
void Main(array<String^>^ args) {
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);
    Project1::MyForm form;
    Application::Run(%form);
}

Body:
You should really save yourself a lot of pain and use C# for your GUI and only use C++/CLI to wrap native unmanaged C++ code within your C# GUI.

Anyway, Project1 is not a namespace so just drop it. Try this:

using namespace System;
using namespace System::Windows::Forms;

[STAThreadAttribute]
void Main(array<String^>^ args) {
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);
    MyForm form;
    Application::Run(%form);
}


来源: stackexchange

问:
SQL Join two tables with same column names, and get sum of each column
I know that in the long run... the column names being the same is probably irrelevant.  But here's what I've got:

Master Table:

```<code>| PersonID | 1970 | 1971 | 1972 | 1973 |
|----------|------|------|------|------|
|        1 |   50 |   50 |  100 |   50 |
|        2 |   30 |   30 |   40 |   40 |
|        3 |   40 |   40 |   40 |   20 |
</code>```

Supplemental Table

```<code>| PersonID |   1972 |   1973 |
|----------|--------|--------|
|        1 |    100 | (null) |
|        2 | (null) | (null) |
|        3 | (null) |    200 |
</code>```

I'd like to have a table (a view, actually) that will join these two tables, and add the sum of the columns into a column with the same name

Combined Table:

```<code>| PersonID | 1970 | 1971 | 1972 | 1973 |
|----------|------|------|------|------|
|        1 |   50 |   50 |  200 |   50 |
|        2 |   30 |   30 |   40 |   40 |
|        3 |   40 |   40 |   40 |  220 |
</code>```

The resulting table needs to have both tables combined..  The years go all the way to 2017, and are the same name for each table.

SQLfiddle

答:
If there is only one matching row per id, then left join does it:

```<code>select t1.person_id, t1.[1970], t1.[1971],
       (t1.[1972] + coalesce(t2.[1972], 0)) as [1972],
       (t1.[1973] + coalesce(t2.[1973], 0)) as [1973]
from t1 left join
     t2
     on t1.person_id = t2.person_id
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know that in the long run... the column names being the same is probably irrelevant.  But here's what I've got:

Master Table:

| PersonID | 1970 | 1971 | 1972 | 1973 |
|----------|------|------|------|------|
|        1 |   50 |   50 |  100 |   50 |
|        2 |   30 |   30 |   40 |   40 |
|        3 |   40 |   40 |   40 |   20 |

Supplemental Table

| PersonID |   1972 |   1973 |
|----------|--------|--------|
|        1 |    100 | (null) |
|        2 | (null) | (null) |
|        3 | (null) |    200 |

I'd like to have a table (a view, actually) that will join these two tables, and add the sum of the columns into a column with the same name

Combined Table:

| PersonID | 1970 | 1971 | 1972 | 1973 |
|----------|------|------|------|------|
|        1 |   50 |   50 |  200 |   50 |
|        2 |   30 |   30 |   40 |   40 |
|        3 |   40 |   40 |   40 |  220 |

The resulting table needs to have both tables combined..  The years go all the way to 2017, and are the same name for each table.

SQLfiddle

Body:
If there is only one matching row per id, then left join does it:

select t1.person_id, t1.[1970], t1.[1971],
       (t1.[1972] + coalesce(t2.[1972], 0)) as [1972],
       (t1.[1973] + coalesce(t2.[1973], 0)) as [1973]
from t1 left join
     t2
     on t1.person_id = t2.person_id


问:
Setting threshold on max number of classes selected/activated on click on multiple divs/id's
I've been working on a skill tree 'persay' and I ran into an interesting problem.

I have my code setup to allow a user to click a talent to show that particular talent has been selected up to a max number of 4 talents total. Once you have selected 4 talents you have to deselect a talent to select a different one.

My problem comes when I duplicate the talent tree for a second talent tree on the same page(for a second hero/class essentially or a second party member out of your party). I can't figure out how to make the same 'threshold of a max of 4 talents' on other skill trees standalone. What happens is that they all share the same threshold across all trees. I have tried making separate id's each and even changing the variable names within each function.

var skillTotal = 0;
var skillSelected = 0;

$( "#selectable01>li.skill-slot" ).bind( "click", function ( e ) {
    var threshold = 4;
        var price = 1;
        if ($(this).hasClass('selected')) {
                skillTotal = skillTotal - 1;
                skillSelected--;
                $(this).toggleClass('selected');
        }
        else if (price + skillTotal <= threshold) {
                skillTotal = skillTotal + price;
                skillSelected++;
                $(this).toggleClass('selected');
        }
});

$( "#selectable02>li.skill-slot" ).bind( "click", function ( e ) {
    var threshold = 4;
        var price = 1;
        if ($(this).hasClass('selected')) {
                skillTotal = skillTotal - 1;
                skillSelected--;
                $(this).toggleClass('selected');
        }
        else if (price + skillTotal <= threshold) {
                skillTotal = skillTotal + price;
                skillSelected++;
                $(this).toggleClass('selected');
        }
});

/* NOT USING THIS CURRENTLY
$( "#campSelectable>li.camp-slot" ).bind( "click", function ( e ) {
    var campThreshold = 3;
        var campPrice = 1;
        if ($(this).hasClass('selected')) {
                campTotal = campTotal - campPrice;
                selectedCamp--;
                $(this).toggleClass('selected');
        }
        else if (campPrice + campTotal <= campThreshold) {
                campTotal = campTotal + campPrice;
                selectedCamp++;
                $(this).toggleClass('selected');
        }
}); */```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.skill-slot, .camp-slot{
  border:2px solid black;
  width:100px;
  margin: 5px;
  opacity: .4;
}

.skill-slot:hover, .camp-slot:hover {
  opacity: 1;
}

.raffle-slot.taken{
  background:red;
}
.selected{
  background: rgb(255, 128, 128);
  opacity: 1;
}</code>```

1

2

3

4

5

6

7

1

2

3

4

5

6

7

```

Here are the things I have tried:
Initially my identifier was : $( "#calc>ol>li.skill-slot" ).on so I began adding additional id's to drill down further and make sure that my functions were targeting specific div's, so I moved to this: $( "#calc>#selectable01>li.skill-slot" ).on and $( "#calc>#selectable02>li.skill-slot" ).on

The reason I didn't want to target a second ID is because I'll be using templates that are appended to the #calc div effectively replacing the current roster with a new one. I also did this for testing to see if I could resolve the issue by making them their own individual id's, which didn't work.

答:
A way simpler approach using Event delegation. Toggle .selected to either deactivate the current .skill-slot, or to activate it if there are less than 4 .selected.skill-slots in this group.

$('#selectable01, #selectable02').on('click', '.skill-slot', function(e){
  if($(this).hasClass('selected') || $('.selected.skill-slot', e.delegateTarget).length < 4){
    $(this).toggleClass('selected');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.skill-slot, .camp-slot{
  border:2px solid black;
  width:100px;
  margin: 5px;
  opacity: .4;
}

.skill-slot:hover, .camp-slot:hover {
  opacity: 1;
}

.raffle-slot.taken{
  background:red;
}
.selected{
  background: rgb(255, 128, 128);
  opacity: 1;
}</code>```

1

2

3

4

5

6

7

1

2

3

4

5

6

7

```

Body:
I've been working on a skill tree 'persay' and I ran into an interesting problem.

I have my code setup to allow a user to click a talent to show that particular talent has been selected up to a max number of 4 talents total. Once you have selected 4 talents you have to deselect a talent to select a different one.

My problem comes when I duplicate the talent tree for a second talent tree on the same page(for a second hero/class essentially or a second party member out of your party). I can't figure out how to make the same 'threshold of a max of 4 talents' on other skill trees standalone. What happens is that they all share the same threshold across all trees. I have tried making separate id's each and even changing the variable names within each function.

var skillTotal = 0;
var skillSelected = 0;

$( "#selectable01>li.skill-slot" ).bind( "click", function ( e ) {
    var threshold = 4;
        var price = 1;
        if ($(this).hasClass('selected')) {
                skillTotal = skillTotal - 1;
                skillSelected--;
                $(this).toggleClass('selected');
        }
        else if (price + skillTotal <= threshold) {
                skillTotal = skillTotal + price;
                skillSelected++;
                $(this).toggleClass('selected');
        }
});

$( "#selectable02>li.skill-slot" ).bind( "click", function ( e ) {
    var threshold = 4;
        var price = 1;
        if ($(this).hasClass('selected')) {
                skillTotal = skillTotal - 1;
                skillSelected--;
                $(this).toggleClass('selected');
        }
        else if (price + skillTotal <= threshold) {
                skillTotal = skillTotal + price;
                skillSelected++;
                $(this).toggleClass('selected');
        }
});

/* NOT USING THIS CURRENTLY
$( "#campSelectable>li.camp-slot" ).bind( "click", function ( e ) {
    var campThreshold = 3;
        var campPrice = 1;
        if ($(this).hasClass('selected')) {
                campTotal = campTotal - campPrice;
                selectedCamp--;
                $(this).toggleClass('selected');
        }
        else if (campPrice + campTotal <= campThreshold) {
                campTotal = campTotal + campPrice;
                selectedCamp++;
                $(this).toggleClass('selected');
        }
}); */

.skill-slot, .camp-slot{
  border:2px solid black;
  width:100px;
  margin: 5px;
  opacity: .4;
}

.skill-slot:hover, .camp-slot:hover {
  opacity: 1;
}

.raffle-slot.taken{
  background:red;
}
.selected{
  background: rgb(255, 128, 128);
  opacity: 1;
}

1

2

3

4

5

6

7

1

2

3

4

5

6

7

Here are the things I have tried:
Initially my identifier was : $( "#calc>ol>li.skill-slot" ).on so I began adding additional id's to drill down further and make sure that my functions were targeting specific div's, so I moved to this: $( "#calc>#selectable01>li.skill-slot" ).on and $( "#calc>#selectable02>li.skill-slot" ).on

The reason I didn't want to target a second ID is because I'll be using templates that are appended to the #calc div effectively replacing the current roster with a new one. I also did this for testing to see if I could resolve the issue by making them their own individual id's, which didn't work.

Body:
A way simpler approach using Event delegation. Toggle .selected to either deactivate the current .skill-slot, or to activate it if there are less than 4 .selected.skill-slots in this group.

$('#selectable01, #selectable02').on('click', '.skill-slot', function(e){
  if($(this).hasClass('selected') || $('.selected.skill-slot', e.delegateTarget).length < 4){
    $(this).toggleClass('selected');
  }
});

.skill-slot, .camp-slot{
  border:2px solid black;
  width:100px;
  margin: 5px;
  opacity: .4;
}

.skill-slot:hover, .camp-slot:hover {
  opacity: 1;
}

.raffle-slot.taken{
  background:red;
}
.selected{
  background: rgb(255, 128, 128);
  opacity: 1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="calc">
<ol class="roster" id="selectable01">
<li class="skill-slot">1</li>
<li class="skill-slot">2</li>
<li class="skill-slot">3</li>
<li class="skill-slot">4</li>
<li class="skill-slot">5</li>
<li class="skill-slot">6</li>
<li class="skill-slot">7</li>
</ol>

<ol class="roster" id="selectable02">
<li class="skill-slot">1</li>
<li class="skill-slot">2</li>
<li class="skill-slot">3</li>
<li class="skill-slot">4</li>
<li class="skill-slot">5</li>
<li class="skill-slot">6</li>
<li class="skill-slot">7</li>
</ol>

</div>


问:
Python data type, what kind of data structure it is?
```<code>reshape, crop = {
1: ((1952, 3264), (1944, 3240)),
2: ((2480, 4128), (2464, 4100)),
}

offset = {1: 6404096, 2: 10270208,}[ver]

#where ver is defined as a dictionary

ver = {
    'RP_ov5647': 1,
    'RP_imx219': 2,
    }[camera.exif_tags['IFD0.Model']]
</code>```

What kind of structures are these? ver reported as type int. I'm confused.
How did [ver] work in the assignment to offset?

答:
Let's see here...

```<code>reshape, crop = {
1: ((1952, 3264), (1944, 3240)),
2: ((2480, 4128), (2464, 4100)),
}
</code>```

This here is defining a dictionary with keys 1 and 2.  Attached to each key is a tuple of tuples.  I believe there are more entries in the real code, going by the comma on the last item.  However, most of this object gets lost to garbage collection.  The tuple assignment to reshape and crop will result in only the keys being stored.  So the result of this thing is the same as:

```<code>reshape = 1
crop = 2
</code>```

Interesting if useless.  Next...

```<code>offset = {1: 6404096, 2: 10270208,}[ver]
</code>```

So this here defines another dictionary with keys 1 and 2 and long integer values associated with them.  It then indexes this dictionary with ver and assigns the value at this index to offset.  Since ver isn't defined yet, this would really result in an exception.  Let's say that the following code was given before the previous:

```<code>#where ver is defined as a dictionary

ver = {
    'RP_ov5647': 1,
    'RP_imx219': 2,
    }[camera.exif_tags['IFD0.Model']]
</code>```

Here we have yet another dictionary.  This time the keys are 'RP_ov5647' and 'RP_imx219' with values of 1 and 2.  This dictionary is indexed with a value of camera.exif_tags['IFD0.Model'].  Assuming that camera.exif_tags is an object with keyed indexes, one of the indexes is 'IFD0.Model' and the resulting value is either 'RP_ov5647' or 'RP_imx219', ver will be assigned either 1 or 2.

So that 1 or 2 will be used to index our above offset value resulting in offset being assigned either 6404096 or 10270208

In short, it's all a syntactically valid bunch of nothing.  Thanks for sharing.

Body:
reshape, crop = {
1: ((1952, 3264), (1944, 3240)),
2: ((2480, 4128), (2464, 4100)),
}

offset = {1: 6404096, 2: 10270208,}[ver]

#where ver is defined as a dictionary

ver = {
    'RP_ov5647': 1,
    'RP_imx219': 2,
    }[camera.exif_tags['IFD0.Model']]

What kind of structures are these? ver reported as type int. I'm confused.
How did [ver] work in the assignment to offset?

Body:
Let's see here...

reshape, crop = {
1: ((1952, 3264), (1944, 3240)),
2: ((2480, 4128), (2464, 4100)),
}

This here is defining a dictionary with keys 1 and 2.  Attached to each key is a tuple of tuples.  I believe there are more entries in the real code, going by the comma on the last item.  However, most of this object gets lost to garbage collection.  The tuple assignment to reshape and crop will result in only the keys being stored.  So the result of this thing is the same as:

reshape = 1
crop = 2

Interesting if useless.  Next...

offset = {1: 6404096, 2: 10270208,}[ver]

So this here defines another dictionary with keys 1 and 2 and long integer values associated with them.  It then indexes this dictionary with ver and assigns the value at this index to offset.  Since ver isn't defined yet, this would really result in an exception.  Let's say that the following code was given before the previous:

#where ver is defined as a dictionary

ver = {
    'RP_ov5647': 1,
    'RP_imx219': 2,
    }[camera.exif_tags['IFD0.Model']]

Here we have yet another dictionary.  This time the keys are 'RP_ov5647' and 'RP_imx219' with values of 1 and 2.  This dictionary is indexed with a value of camera.exif_tags['IFD0.Model'].  Assuming that camera.exif_tags is an object with keyed indexes, one of the indexes is 'IFD0.Model' and the resulting value is either 'RP_ov5647' or 'RP_imx219', ver will be assigned either 1 or 2.

So that 1 or 2 will be used to index our above offset value resulting in offset being assigned either 6404096 or 10270208

In short, it's all a syntactically valid bunch of nothing.  Thanks for sharing.


问:
Decoding bytes and SyntaxError: unexpected character after line continuation character
I have read previous questions on the subject but none mentioned bytes. I have bytestrings (?) like the following in a pandas dataframe: \u0393\u03b9\u03ce\u03c1\u03b3\u03bf\u03c2
 u039d\u03c4\u03b1\u03bb\u03ac\u03c1\u03b1\u03c2 and I've tried to convert them to human readable output. The language of the text is Greek, the data was read from a JSON file (json.load / loads didn't help much, and neither did pd.read_json).

When I am trying to print such an object, it prints the bytes.

Example code with prints:

```<code>lst = ['\\u0393\\u03b9\\u03ce\\u03c1\\u03b3\\u03bf\\u03c2 \\u039d\\u03c4\\u03b1\\u03bb\\u03ac\\u03c1\\u03b1\\u03c2',
     '\\u0393\\u03b9\\u03ce\\u03c1\\u03b3\\u03bf\\u03c2 \\u039d\\u03c4\\u03b1\\u03bb\\u03ac\\u03c1\\u03b1\\u03c2',
     '\\u0393\\u03b9\\u03ce\\u03c1\\u03b3\\u03bf\\u03c2 \\u039d\\u03c4\\u03b1\\u03bb\\u03ac\\u03c1\\u03b1\\u03c2']

df= pd.DataFrame(lst, columns=["some_bytestrings"])

print(df["some_bytestrings"])
# prints: \u0393\u03b9\u03ce\u03c1\u03b3\u03bf\u03c2 \u0...

print(df['some_bytestrings'].values[0])
# prints: \u0393\u03b9\u03ce\u03c1\u03b3\u03bf\u03c2 \u039d\u03c4\u03b1\u03bb\u03ac\u03c1\u03b1\u03c2

# eval seems to work for some previous data, don't know why
print(eval(dfsmall['some_bytestrings'].values[0]))
# ERROR ARISES HERE

print('\\u0393\\u03b9\\u03ce\\u03c1\\u03b3\\u03bf\\u03c2 \\u039d\\u03c4\\u03b1\\u03bb\\u03ac\\u03c1\\u03b1\\u03c2')
# prints \u0393\u03b9\u03ce\u03c1\u03b3\u03bf\u03c2 \u039d\u03c4\u03b1\u03bb\u03ac\u03c1\u03b1\u03c2

print(print(dfsmall['some_bytestrings'].values[0].encode().decode()))
# decoding encoding doesn't work, it prints: \u0393\u03b9\u03ce\u03c1\u03b3\u03bf\u03c2 \u039d\u03c4\u03b1\u03bb\u03ac\u03c1\u03b1\u03c2
</code>```

Note that if I take the printed output and print again, it turns out fine:

```<code>print("\u0393\u03b9\u03ce\u03c1\u03b3\u03bf\u03c2 \u039d\u03c4\u03b1\u03bb\u03ac\u03c1\u03b1\u03c2")
# prints: 'Γιώργος Νταλάρας'
</code>```

As it seems to me it has to do with how Python handles the double slashes (\\), but I cannot seem to work around a solution to this, since methods like string.replace("\\\\", "\\") don't help.

答:
You've labeled then "byte_strings" (bytes type) but from your outputs they are actually text strings (str type) that contain escape sequences.

Fortunately, python includes a codec for decoding the string escapes called unicode_escape.

You can decode these strings using the codecs module -- for example:

```<code>>>> codecs.decode('\\u0393\\u03b9\\u03ce\\u03c1\\u03b3\\u03bf\\u03c2 \\u039d\\u03c4\\u03b1\\u03bb\\u03ac\\u03c1\\u03b1\\u03c2', 'unicode_escape')
'Γιώργος Νταλάρας'
</code>```

Body:
I have read previous questions on the subject but none mentioned bytes. I have bytestrings (?) like the following in a pandas dataframe: \u0393\u03b9\u03ce\u03c1\u03b3\u03bf\u03c2
 u039d\u03c4\u03b1\u03bb\u03ac\u03c1\u03b1\u03c2 and I've tried to convert them to human readable output. The language of the text is Greek, the data was read from a JSON file (json.load / loads didn't help much, and neither did pd.read_json).

When I am trying to print such an object, it prints the bytes.

Example code with prints:

lst = ['\\u0393\\u03b9\\u03ce\\u03c1\\u03b3\\u03bf\\u03c2 \\u039d\\u03c4\\u03b1\\u03bb\\u03ac\\u03c1\\u03b1\\u03c2',
     '\\u0393\\u03b9\\u03ce\\u03c1\\u03b3\\u03bf\\u03c2 \\u039d\\u03c4\\u03b1\\u03bb\\u03ac\\u03c1\\u03b1\\u03c2',
     '\\u0393\\u03b9\\u03ce\\u03c1\\u03b3\\u03bf\\u03c2 \\u039d\\u03c4\\u03b1\\u03bb\\u03ac\\u03c1\\u03b1\\u03c2']

df= pd.DataFrame(lst, columns=["some_bytestrings"])

print(df["some_bytestrings"])
# prints: \u0393\u03b9\u03ce\u03c1\u03b3\u03bf\u03c2 \u0...

print(df['some_bytestrings'].values[0])
# prints: \u0393\u03b9\u03ce\u03c1\u03b3\u03bf\u03c2 \u039d\u03c4\u03b1\u03bb\u03ac\u03c1\u03b1\u03c2

# eval seems to work for some previous data, don't know why
print(eval(dfsmall['some_bytestrings'].values[0]))
# ERROR ARISES HERE

print('\\u0393\\u03b9\\u03ce\\u03c1\\u03b3\\u03bf\\u03c2 \\u039d\\u03c4\\u03b1\\u03bb\\u03ac\\u03c1\\u03b1\\u03c2')
# prints \u0393\u03b9\u03ce\u03c1\u03b3\u03bf\u03c2 \u039d\u03c4\u03b1\u03bb\u03ac\u03c1\u03b1\u03c2

print(print(dfsmall['some_bytestrings'].values[0].encode().decode()))
# decoding encoding doesn't work, it prints: \u0393\u03b9\u03ce\u03c1\u03b3\u03bf\u03c2 \u039d\u03c4\u03b1\u03bb\u03ac\u03c1\u03b1\u03c2

Note that if I take the printed output and print again, it turns out fine:

print("\u0393\u03b9\u03ce\u03c1\u03b3\u03bf\u03c2 \u039d\u03c4\u03b1\u03bb\u03ac\u03c1\u03b1\u03c2")
# prints: 'Γιώργος Νταλάρας'

As it seems to me it has to do with how Python handles the double slashes (\\), but I cannot seem to work around a solution to this, since methods like string.replace("\\\\", "\\") don't help.

Body:
You've labeled then "byte_strings" (bytes type) but from your outputs they are actually text strings (str type) that contain escape sequences.

Fortunately, python includes a codec for decoding the string escapes called unicode_escape.

You can decode these strings using the codecs module -- for example:

>>> codecs.decode('\\u0393\\u03b9\\u03ce\\u03c1\\u03b3\\u03bf\\u03c2 \\u039d\\u03c4\\u03b1\\u03bb\\u03ac\\u03c1\\u03b1\\u03c2', 'unicode_escape')
'Γιώργος Νταλάρας'


问:
How to comment out structure <?= ?> in Yii2
a trivial question, but all my efforts to comment out code lines like this:

```<code><?=$form->field($model, 'bew_id')->textInput(['placeholder' => 'Bew']) ?>
</code>```

failed by using PHP and/or HTML-comments.Following trys didn't success:

//

/* */

<-!- -->

Any ideas??

答:
Change <?= to <?php and then do the comment

```<code><?php /*echo  $form->field($model, 'bew_id')->textInput(['placeholder' => 'Bew']) */ ?>
</code>```

because this

```<code><?= $form->field($model, 'bew_id')->textInput(['placeholder' => 'Bew']) ?>
</code>```

is shorthand  for

```<code><?php echo $form->field($model, 'bew_id')->textInput(['placeholder' => 'Bew']) ?>
</code>```

use any comment  // or /* */

Body:
a trivial question, but all my efforts to comment out code lines like this:

<?=$form->field($model, 'bew_id')->textInput(['placeholder' => 'Bew']) ?>

failed by using PHP and/or HTML-comments.Following trys didn't success:

//

/* */

<-!- -->

Any ideas??

Body:
Change <?= to <?php and then do the comment

<?php /*echo  $form->field($model, 'bew_id')->textInput(['placeholder' => 'Bew']) */ ?>

because this

<?= $form->field($model, 'bew_id')->textInput(['placeholder' => 'Bew']) ?>

is shorthand  for

<?php echo $form->field($model, 'bew_id')->textInput(['placeholder' => 'Bew']) ?>

use any comment  // or /* */

ContentLicense: CC BY-SA 4.0


问:
jQuery scrolltop animate not animating
Here is what I have.

The clicking function works and jumps to that part of the section, but the scrolling animation isn't working.

Anything I did wrong?

```<code>    <nav class="navbar navbar-inverse navbar-fixed-top" id="my-navbar">
        <div class="container text-right">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

            </div>

<div class="collapse navbar-collapse text-left" id="navbar-collapse" >
  <ul class="nav navbar-nav">
    <li><a href="#home">Home</a></li>
    <li><a href="#skills">Skills</a></li>
    <li><a href="#feedback">Feedback</a></li>
    <li><a href="#about">About me</a></li>
    <li><a href="#contact">Contact</a></li>
  </ul>
</div>

<script>
  $("#navbar").on("click", function(e) {
    e.preventDefault();
    var section = $(this).attr("href");
    $("html, body").animate({
      scrollTop: $(section).offset().top
    }, 1500);
  });
</script>
</code>```

答:
Change the jQuery to something like this:

```<code>$(".navbar-nav a").on("click", function(e) {
    e.preventDefault();
    var section = $(this).attr("href");
    $("html, body").animate({
      scrollTop: $(section).offset().top
    }, 1500);
  });
</code>```

Your selector is wrong. You have no element with id navbar which means that your event listener isn't even firing. That's why it doesn't animate.

Title: jQuery scrolltop animate not animating

Body:
Here is what I have.

The clicking function works and jumps to that part of the section, but the scrolling animation isn't working.

Anything I did wrong?

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">

                </button>

Home

Skills

Feedback

About me

Contact

Body:
Change the jQuery to something like this:

$(".navbar-nav a").on("click", function(e) {
    e.preventDefault();
    var section = $(this).attr("href");
    $("html, body").animate({
      scrollTop: $(section).offset().top
    }, 1500);
  });

Your selector is wrong. You have no element with id navbar which means that your event listener isn't even firing. That's why it doesn't animate.


问:
CouchDB 2.0.0 make install fails on CentOS 7
I am going by the CouchDB docs install directions:
http://docs.couchdb.org/en/2.0.0/install/unix.html

I install the dependencies:

```<code>    $ sudo yum install autoconf autoconf-archive automake \
    curl-devel erlang-asn1 erlang-erts erlang-eunit \
    erlang-os_mon erlang-xmerl help2man \
    js-devel-1.8.5 libicu-devel libtool perl-Test-Harness
</code>```

Configure goes fine:

```<code>    $ ./configure
</code>```

You have configured Apache CouchDB, time to relax. Relax.

But just as I'm starting to feel relaxed I get thrown a curve ball by gmake:

```<code>    $ make release
</code>```

Uncaught error in rebar_core: {error,                                  {erl_interface,include,"code:lib_dir(erl_interface)is unable to find the erl_interface library."}}

The only clue the docs give is to try gmake if make fails but since gmake and make are the same on CentOS 7 that doesn't help.
From the output it appears to be a dependency issue but I don't pretend to understand Erlang dependencies or know anything about this particular one. I installed the packages in yum the docs suggest, I thought that should be enough.
Any help would be appreciated.

答:
To fix all build errors I have installed erlang-reltool, gcc-c++ and erlang-erl_interface besides the packages suggested in CouchDB docs.

As a side note, I have also adapted the adduser command from CouchDB docs to:

```<code>adduser --system --no-create-home --shell /bin/bash -U -c "CouchDB Administrator" couchdb
</code>```

Body:
I am going by the CouchDB docs install directions:
http://docs.couchdb.org/en/2.0.0/install/unix.html

I install the dependencies:

    $ sudo yum install autoconf autoconf-archive automake \
    curl-devel erlang-asn1 erlang-erts erlang-eunit \
    erlang-os_mon erlang-xmerl help2man \
    js-devel-1.8.5 libicu-devel libtool perl-Test-Harness

Configure goes fine:

    $ ./configure

You have configured Apache CouchDB, time to relax. Relax.

But just as I'm starting to feel relaxed I get thrown a curve ball by gmake:

    $ make release

Uncaught error in rebar_core: {error,                                  {erl_interface,include,"code:lib_dir(erl_interface)is unable to find the erl_interface library."}}

The only clue the docs give is to try gmake if make fails but since gmake and make are the same on CentOS 7 that doesn't help.
From the output it appears to be a dependency issue but I don't pretend to understand Erlang dependencies or know anything about this particular one. I installed the packages in yum the docs suggest, I thought that should be enough.
Any help would be appreciated.

Body:
To fix all build errors I have installed erlang-reltool, gcc-c++ and erlang-erl_interface besides the packages suggested in CouchDB docs.

As a side note, I have also adapted the adduser command from CouchDB docs to:

adduser --system --no-create-home --shell /bin/bash -U -c "CouchDB Administrator" couchdb


问:
SQL Get 3 letters from a String into column
I have a given Column A and I can extract the First 3 letters of it using the LEFT function in SQL my problem comes in how to put this into a New column into the same table (table A) here is the Code for extracting the 3 letters. The column does not exist and I am s using MSSQL 2016</p>

```<code>Select Left(ColA,3) As NewCol from TableA
</code>```

答:
If the column is already declared, you use update:

```<code>update tablea
    set newcol = Left(ColA, 3);
</code>```

If the column doesn't exist, then you need to add it.  So, you would first do:

```<code>alter tablea add column newcol varchar(3);
</code>```

Body:
I have a given Column A and I can extract the First 3 letters of it using the LEFT function in SQL my problem comes in how to put this into a New column into the same table (table A) here is the Code for extracting the 3 letters. The column does not exist and I am s using MSSQL 2016

Select Left(ColA,3) As NewCol from TableA

Body:
If the column is already declared, you use update:

update tablea
    set newcol = Left(ColA, 3);

If the column doesn't exist, then you need to add it.  So, you would first do:

alter tablea add column newcol varchar(3);


问:
R - Checking multiple columns for multiple values - loop
I have a data set with multiple diagnosis columns (ie. DIAG1, DIAG2, DIAG3, etc.). I am looking to create a loop that will check each column for all of my rows, but I'm looking for more than one diagnosis code within each of those columns.

For example, I want to find code xxx1 and xxx3 if present in DIAG1, DIAG2, DIAG3, etc.

My code is below where

1. df = my dataframe

2. df$illness = is the variable I want to create

3. xxxx1 = the code I'm looking for

4. [26:34, 57:72] = the columns where DIAG1, etc. exist

**EDIT:
Example data:

```<code>DIAG3  DIAG4  DIAG5  DIAG6
1231   xxx1   5468   5468
1454   2352   4542   4864
xxx2   1235   1234   3564
1234   1589   xxx1   8498
</code>```

Code I tried to perform:

```<code>for (i in 1:nrow(df)) {
df$illness[i] <- ("xxx1" %in% df[i,26:34, 57:72] | "xxx3" %in%
df[i,26:34, 57:72]}
</code>```

What I would like my loop to perform:

```<code>DIAG3  DIAG4  DIAG5  DIAG6  Illness
1231   xxx1   5468   5468   TRUE
1454   2352   4542   4864   FALSE
xxx3   1235   1234   3564   TRUE
1234   1589   xxx1   8498   TRUE
</code>```

What happens is that the code runs but never ends. I don't know where my mistake is. Thank you

答:
It looks like the sub-setting of df is wrong.
It should probably be df[i,c(26:34,57:72)]. Is the df$illness[i] supposed to be a list?

Body:
I have a data set with multiple diagnosis columns (ie. DIAG1, DIAG2, DIAG3, etc.). I am looking to create a loop that will check each column for all of my rows, but I'm looking for more than one diagnosis code within each of those columns.

For example, I want to find code xxx1 and xxx3 if present in DIAG1, DIAG2, DIAG3, etc.

My code is below where

1. df = my dataframe

2. df$illness = is the variable I want to create

3. xxxx1 = the code I'm looking for

4. [26:34, 57:72] = the columns where DIAG1, etc. exist

**EDIT:
Example data:

DIAG3  DIAG4  DIAG5  DIAG6
1231   xxx1   5468   5468
1454   2352   4542   4864
xxx2   1235   1234   3564
1234   1589   xxx1   8498

Code I tried to perform:

for (i in 1:nrow(df)) {
df$illness[i] <- ("xxx1" %in% df[i,26:34, 57:72] | "xxx3" %in%
df[i,26:34, 57:72]}

What I would like my loop to perform:

DIAG3  DIAG4  DIAG5  DIAG6  Illness
1231   xxx1   5468   5468   TRUE
1454   2352   4542   4864   FALSE
xxx3   1235   1234   3564   TRUE
1234   1589   xxx1   8498   TRUE

What happens is that the code runs but never ends. I don't know where my mistake is. Thank you


问:
Check if a String is in an ArrayList of Strings
How can I check if a String is there in the List?

I want to assign 1 to temp if there is a result, 2 otherwise.

My current code is:

```<code>Integer temp = 0;
List<String> bankAccNos = new ArrayList<String>();//assume list contains values
String bankAccNo = "abc";
for(String no : bankAccNos)
    if(no.equals(bankAccNo))
        temp = 1;
</code>```

答:
```<code>    List list1 = new ArrayList();
    list1.add("one");
    list1.add("three");
    list1.add("four");

    List list2 = new ArrayList();
    list2.add("one");
    list2.add("two");
    list2.add("three");
    list2.add("four");
    list2.add("five");

    list2.stream().filter( x -> !list1.contains(x) ).forEach(x -> System.out.println(x));
</code>```

The output is:

```<code>two
five
</code>```

Body:
How can I check if a String is there in the List?

I want to assign 1 to temp if there is a result, 2 otherwise.

My current code is:

Integer temp = 0;
List<String> bankAccNos = new ArrayList<String>();//assume list contains values
String bankAccNo = "abc";
for(String no : bankAccNos)
    if(no.equals(bankAccNo))
        temp = 1;

Body:
    List list1 = new ArrayList();
    list1.add("one");
    list1.add("three");
    list1.add("four");

    List list2 = new ArrayList();
    list2.add("one");
    list2.add("two");
    list2.add("three");
    list2.add("four");
    list2.add("five");

    list2.stream().filter( x -> !list1.contains(x) ).forEach(x -> System.out.println(x));

The output is:

two
five


问:
How to get a redirected address in C#
I can download a page from a website using </p>

```<code>sString = new System.Net.WebClient().DownloadString(Page);
</code>```

<p>But if the page redirects, how can I capture the new address.  For example, if I fetch google.com website, I would like to grab the page it redirects to so I can get the ei code.  </p>

答:
You need to examine the HTTP status contained in the HTTP response, and if it is an HTTP "302 Found", then you need to obtain the value of the "Location" header from the response.  The value will be the target of the redirection, so you then need to download the target.</p>
```<code>String content;
try
{
    content = new System.Net.WebClient().DownloadString( page );
}
catch( WebException e )
{
    HttpWebResponse response = (System.Net.HttpWebResponse)e.Response;
    ... examine status, get headers, etc ...
}
</code>```

Title: How to get a redirected address in C#

Body:
I can download a page from a website using

sString = new System.Net.WebClient().DownloadString(Page);

But if the page redirects, how can I capture the new address.  For example, if I fetch google.com website, I would like to grab the page it redirects to so I can get the ei code.

Body:
You need to examine the HTTP status contained in the HTTP response, and if it is an HTTP "302 Found", then you need to obtain the value of the "Location" header from the response.  The value will be the target of the redirection, so you then need to download the target.

String content;
try
{
    content = new System.Net.WebClient().DownloadString( page );
}
catch( WebException e )
{
    HttpWebResponse response = (System.Net.HttpWebResponse)e.Response;
    ... examine status, get headers, etc ...
}


问:
How to show the most recent timestamp for an InfluxDB measurement in Grafana table (or singlestat)?
I'm using Telegraf/InfluxDB/Grafana to register and view metrics for my servers. Occasionally one of these components crash and metrics stop flowing into InfluxDB.

To be able to notice when this happens (on top of using Monit to restart the service) I would like to create a Grafana dashboard where I have a singlestat panel for each host that shows the most recent timestamp (or better, how much time has passed) since the last metric was received. I'd also like to colorize the background of the singlestat depending on how long it's been. I would like to be able to do this for any InfluxDB metric, as different metrics can have different reasons for lagging behind.

Right now, I've tried something like this in InfluxQL, but I just get an error that at least one non-time field must be present in the query:

SELECT last(time) FROM "system" WHERE "load1" > -1 GROUP BY "host"

If I try to change it to this I get a "Multiple series error":

SELECT last(time), last("load1") FROM "system" GROUP BY "host"

Is what I'm trying to do not easily doable or am I missing something obvious?

答:
...the query syntax was taken from somewhere in this issue.
I haven't yet looked at the singlestat panel, but I suggest creating a 'scripted dashboard'.

Start by manually creating a singlestat dash with a dummy number.  Then export it to see what the json looks like.
Then, recreate that same json, with the live result from the above query, using a scripted dashboard.

Look in grafana's /public/dashboards for 'scripted.js' or  'scripted_templated.js'.  Make a copy of one of those in the same folder, then hack away to generate your json.  Here and here and here are some nice examples for the javascript magic to submit the query to influxdb and parse the result into the json for your singlestat dash.  Good luck.


答:
Assuming the column already exists:</p>

```<code>update [Table A] set ColB = Left(ColA, 3)
</code>```

Title: SQL Get 3 letters from a String into column

Body:
Assuming the column already exists:

update [Table A] set ColB = Left(ColA, 3)


问:
T-SQL Execute Recursion for Each Value in Multiple Columns
I have a dataset with two columns. A person in the first column may be in the span of control of a person in the second column (i.e. everyone is in Michael's span of control, Dwight & Stanley are in Jim's span of control):

```<code>source_id     source          target_id     target
1             Michael Scott   5             Kelly Kapoor
3             Dwight Schrute  2             Jim Halpert
4             Stanley Hudson  2             Jim Halpert
2             Jim Halpert     5             Kelly Kapoor
</code>```

I have a table that lists each person and their supervisor:

```<code>person_id       person           supervisor_id     supervisor
1               Michael Scott    0                 None
2               Jim Halpert      1                 Michael Scott
3               Dwight Schrute   2                 Jim Halpert
4               Stanley Hudson   2                 Jim Halpert
6               Ryan Howard      1                 Michael Scott
5               Kelly Kapoor     6                 Ryan Howard
</code>```

I have a block of code that uses recursion to find a single person's span of control from the preceding table:

```<code>with anchor as
(
    select person_id, supervisor_id from table where unique_id = @ID
    union all
    select a.person_id, a.supervisor_id
    from table a
    inner join Anchor b ON b.person_id = a.supervisor_id
)

select a.person_id
from anchor a
</code>```

This block of code can be turned into a stored procedure or a function. Running it for Jim (for example), returns:

```<code>person_id
3 (Dwight Schrute)
4 (Stanley Hudson)
</code>```

How do I compare each value in the initial dataset (from both the source and target columns) to the values in the column returned by the preceding block of code? In other words, for each row in source, I need to check if that name is within the span of control of target. In addition, for each row in target, I need to check if that name is within the span of control of source.

Desired End Result:

```<code>source_id     source          target_id     target         isEitherPersonInOther'sSOC
1             Michael Scott   5             Kelly Kapoor   Yes
3             Dwight Schrute  2             Jim Halpert    Yes
4             Stanley Hudson  2             Jim Halpert    Yes
2             Jim Halpert     5             Kelly Kapoor   No
</code>```

I know iterations are bad (i.e. running the stored procedure for each row with a cursor or while loop). I also know cross apply and a function together may work, but I have been unable to figure my way through that.

Thank you for any insight you all may have!

答:
There has to be a better way to do this but this is definitely one way to go about it -- note the code creates permanent tables to use in a function:</p>

```<code>    create table dbo.[source]
(
    source_id  int,
    [source] nvarchar(500),
    target_id int,
    [target] nvarchar(500)
)

insert into [source]
select 1, 'Michael Scott', 5, 'Kelly Kapoor'
union all select 3,'Dwight Schrute',2,'Jim Halpert'
union all select 4 ,'Stanley Hudson',2,'Jim Halpert'
union all select 2  ,'Jim Halpert',5,'Kelly Kapoor'

create table dbo.supervisors
(
    person_id int,
    person nvarchar(500),
    supervisor_id int,
    supervisor nvarchar(500)
)

insert into dbo.supervisors
select 1,'Michael Scott', 0,'None'
union all select 2,'Jim Halpert',1,'Michael Scott'
union all select 3,'Dwight Schrute',2,'Jim Halpert'
union all select 4,'Stanley Hudson',2,'Jim Halpert'
union all select 6,'Ryan Howard',1,'Michael Scott'
union all select 5 ,'Kelly Kapoor',6,'Ryan Howard'

go

create function dbo.fn_isinspanofcontrol
(
    @sourceid int,
    @targetid int
)
RETURNS varchar(1)

as
begin

declare @retVal varchar(1)
declare @tbl table
(
    person_id int
)

;with anchor as
            (
                select person_id, supervisor_id from supervisors where person_id = @sourceid
                union all
                select a.person_id, a.supervisor_id
                from supervisors a
                inner join Anchor b ON b.person_id = a.supervisor_id
            )
insert into @tbl
select a.person_id
from anchor a
where
    a.person_id = @targetid

;with anchor as
            (
                select person_id, supervisor_id from supervisors where person_id = @targetid
                union all
                select a.person_id, a.supervisor_id
                from supervisors a
                inner join Anchor b ON b.person_id = a.supervisor_id
            )
insert into @tbl
select a.person_id
from anchor a
where
    a.person_id = @sourceid

if exists( select 1
            from @tbl
        )
begin
    set @retVal = 'Y'
end
else
begin
    set @retVal = 'N'
end

    return @retVal

end

select
    *, dbo.fn_isinspanofcontrol(source_id,target_id)
from [source]
</code>```

Body:
I have a dataset with two columns. A person in the first column may be in the span of control of a person in the second column (i.e. everyone is in Michael's span of control, Dwight & Stanley are in Jim's span of control):

source_id     source          target_id     target
1             Michael Scott   5             Kelly Kapoor
3             Dwight Schrute  2             Jim Halpert
4             Stanley Hudson  2             Jim Halpert
2             Jim Halpert     5             Kelly Kapoor

I have a table that lists each person and their supervisor:

person_id       person           supervisor_id     supervisor
1               Michael Scott    0                 None
2               Jim Halpert      1                 Michael Scott
3               Dwight Schrute   2                 Jim Halpert
4               Stanley Hudson   2                 Jim Halpert
6               Ryan Howard      1                 Michael Scott
5               Kelly Kapoor     6                 Ryan Howard

I have a block of code that uses recursion to find a single person's span of control from the preceding table:

with anchor as
(
    select person_id, supervisor_id from table where unique_id = @ID
    union all
    select a.person_id, a.supervisor_id
    from table a
    inner join Anchor b ON b.person_id = a.supervisor_id
)

select a.person_id
from anchor a

This block of code can be turned into a stored procedure or a function. Running it for Jim (for example), returns:

person_id
3 (Dwight Schrute)
4 (Stanley Hudson)

How do I compare each value in the initial dataset (from both the source and target columns) to the values in the column returned by the preceding block of code? In other words, for each row in source, I need to check if that name is within the span of control of target. In addition, for each row in target, I need to check if that name is within the span of control of source.

Desired End Result:

source_id     source          target_id     target         isEitherPersonInOther'sSOC
1             Michael Scott   5             Kelly Kapoor   Yes
3             Dwight Schrute  2             Jim Halpert    Yes
4             Stanley Hudson  2             Jim Halpert    Yes
2             Jim Halpert     5             Kelly Kapoor   No

I know iterations are bad (i.e. running the stored procedure for each row with a cursor or while loop). I also know cross apply and a function together may work, but I have been unable to figure my way through that.

Thank you for any insight you all may have!

Body:
There has to be a better way to do this but this is definitely one way to go about it -- note the code creates permanent tables to use in a function:

    create table dbo.[source]
(
    source_id  int,
    [source] nvarchar(500),
    target_id int,
    [target] nvarchar(500)
)

insert into [source]
select 1, 'Michael Scott', 5, 'Kelly Kapoor'
union all select 3,'Dwight Schrute',2,'Jim Halpert'
union all select 4 ,'Stanley Hudson',2,'Jim Halpert'
union all select 2  ,'Jim Halpert',5,'Kelly Kapoor'

create table dbo.supervisors
(
    person_id int,
    person nvarchar(500),
    supervisor_id int,
    supervisor nvarchar(500)
)

insert into dbo.supervisors
select 1,'Michael Scott', 0,'None'
union all select 2,'Jim Halpert',1,'Michael Scott'
union all select 3,'Dwight Schrute',2,'Jim Halpert'
union all select 4,'Stanley Hudson',2,'Jim Halpert'
union all select 6,'Ryan Howard',1,'Michael Scott'
union all select 5 ,'Kelly Kapoor',6,'Ryan Howard'

go

create function dbo.fn_isinspanofcontrol
(
    @sourceid int,
    @targetid int
)
RETURNS varchar(1)

as
begin

declare @retVal varchar(1)
declare @tbl table
(
    person_id int
)

;with anchor as
            (
                select person_id, supervisor_id from supervisors where person_id = @sourceid
                union all
                select a.person_id, a.supervisor_id
                from supervisors a
                inner join Anchor b ON b.person_id = a.supervisor_id
            )
insert into @tbl
select a.person_id
from anchor a
where
    a.person_id = @targetid

;with anchor as
            (
                select person_id, supervisor_id from supervisors where person_id = @targetid
                union all
                select a.person_id, a.supervisor_id
                from supervisors a
                inner join Anchor b ON b.person_id = a.supervisor_id
            )
insert into @tbl
select a.person_id
from anchor a
where
    a.person_id = @sourceid

if exists( select 1
            from @tbl
        )
begin
    set @retVal = 'Y'
end
else
begin
    set @retVal = 'N'
end

    return @retVal

end

select
    *, dbo.fn_isinspanofcontrol(source_id,target_id)
from [source]


问:
Can anyone tell me why my filtered array is empty?
I have a table view and a search bar added to it (programmatically). I want to show the filtered results, so I've created an array(called: todoTitle) which contains titles for my todo activities (I have a separate object for them and one of its properties is title). I use updateSearchResults method and inside of it I use a filter method to return right todos. In order to check that the arrays aren't empty, I write code inside of that function to print the todos inside of each array. Here is my code inside of updateSearchResults(for:) function </p>

```<code>    //filtering through todos' titles
    filteredTodos = self.todosTitle.filter({ (title: String) -> Bool in
        if title.lowercased().contains((self.searchController.searchBar.text?.lowercased())!) {
            return true
        } else {
            print ("S \(todosTitle)")
            print ("t \(title)")
            print (filteredTodos)

            return false

        }
    })
    //updating the results TableView
    self.resultsController.tableView.reloadData()

}
</code>```

<p>`` </p>

<p>todosTitle array isn't empty, so I don't understand why my filteredTodos is empty. Does anyone have any ideas why this could happen? </p>

答:
You only need to check for if the todo item title contains the search text. Here's a simplified example that I tested with an array of strings and a search text string.  Perhaps separate out your assignment of the search text to ensure you're getting the string you expect from the searchBar.text</p>

```<code>let todosTitle = ["One", "Two", "Three"]
let searchText = "t"

//filtering through todos' titles
let filteredTodos = todosTitle.filter({ (title: String) -> Bool in
    return title.lowercased().contains(searchText.lowercased())
})

print(filteredTodos)  //["Two", "Three"]
</code>```

Body:
I have a table view and a search bar added to it (programmatically). I want to show the filtered results, so I've created an array(called: todoTitle) which contains titles for my todo activities (I have a separate object for them and one of its properties is title). I use updateSearchResults method and inside of it I use a filter method to return right todos. In order to check that the arrays aren't empty, I write code inside of that function to print the todos inside of each array. Here is my code inside of updateSearchResults(for:) function

    //filtering through todos' titles
    filteredTodos = self.todosTitle.filter({ (title: String) -> Bool in
        if title.lowercased().contains((self.searchController.searchBar.text?.lowercased())!) {
            return true
        } else {
            print ("S \(todosTitle)")
            print ("t \(title)")
            print (filteredTodos)

            return false

        }
    })
    //updating the results TableView
    self.resultsController.tableView.reloadData()

}

``

todosTitle array isn't empty, so I don't understand why my filteredTodos is empty. Does anyone have any ideas why this could happen?

Body:
You only need to check for if the todo item title contains the search text. Here's a simplified example that I tested with an array of strings and a search text string.  Perhaps separate out your assignment of the search text to ensure you're getting the string you expect from the searchBar.text

let todosTitle = ["One", "Two", "Three"]
let searchText = "t"

//filtering through todos' titles
let filteredTodos = todosTitle.filter({ (title: String) -> Bool in
    return title.lowercased().contains(searchText.lowercased())
})

print(filteredTodos)  //["Two", "Three"]


问:
bash diff fails to found existing files when providing a path variable containing tilde (~)
I have a very surprising problem while trying to execute a diff command inside a bash script.

Here is a working code illustrating the point:

```<code>#!/bin/bash
cd
mkdir foo bar
head -c 1024 /dev/urandom >foo/qux
head -c 1024 /dev/urandom >bar/qux

# works properly as expected
diff ~/{foo,bar}/qux

folder="~"

# this fails with the ~ inside a variable
diff $folder/{foo,bar}/qux

# cleaning the mess
rm -rf foo bar
</code>```

So my question is:

Why ? :-)

答:
~ is a feature of shell expansion.

Double quotes limit the expansion to only three features:

Command substitution: $(some command here) or `some command here`

Variable substitution: $VAR or ${VAR}

Arithmetic: $((2+2))

so when put inside double quotes, the ~ is not expanded

Body:
I have a very surprising problem while trying to execute a diff command inside a bash script.

Here is a working code illustrating the point:

#!/bin/bash
cd
mkdir foo bar
head -c 1024 /dev/urandom >foo/qux
head -c 1024 /dev/urandom >bar/qux

# works properly as expected
diff ~/{foo,bar}/qux

folder="~"

# this fails with the ~ inside a variable
diff $folder/{foo,bar}/qux

# cleaning the mess
rm -rf foo bar

So my question is:

Why ? :-)


问:
Using a string to specify an object in Java
I have a Combo Bx (Dropdown box) with an index range of 0-20. If there anyways I can use that index to specify which object I want data from? All of the objects use the same naming convention obj0, obj1, obj2, etc. Basically something like this...</p>

```<code>public abstract class Person {

    private String name;
    private String title;
    private String email;
    private String job;

    public Person(String name, String title, String email, String job){
        this.name = name;
        this.title = title;
        this.email = email;
        this.job = job;
    }
    //Getters and Setters
}

public class main extends javax.swing.JFrame {
...misc code...

private void btn_startActionPerformed(java.awt.event.ActionEvent evt) {

    Person obj0 = new Person("Jon Doe",
                             "Program Coordinator",
                             "jon.doe@test.com",
                             "Faculty");

    Person obj1 = ...
    ...
    Person obj20 = ...

/*
Onclick it uses the index of the current index in the combobox (dropdown)
to specify which object to get the data from.
*/
private void btn_GetActionPerformed(java.awt.event.ActionEvent evt) {

    //Uses the obj naming convention plus the index
    string foo = "obj" + toString(combobox_Name.getSelectedIndex());

    //Fills the textbox using the above string and the getName method
    txtbox_username.setText(ToObject(foo).getName);
}
</code>```

答:
I have created a basic design of what I think you want:

This code creates 20 objects, adds them to a combobox and uses their predefined name when selected to change a textfield.

```<code>import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

class ObjExample {

    String name;

    public ObjExample(String name) {
        this.name = name;
    }

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

}

public class Main extends JFrame implements ActionListener {

    JComboBox jcb = new JComboBox();
    JTextField jtf = new JTextField("Text Field");

    public Main() {

        setSize(200, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        for (int i = 0; i <= 20; i++) {
            jcb.addItem(new ObjExample(Integer.toString(i)));
        }

        jcb.addActionListener(this);

        add(jcb);
        add(jtf);

        setVisible(true);
    }

    public static void main(String[] args) {
        new Main();
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == jcb) {
            ObjExample obj = (ObjExample) jcb.getSelectedItem();
            jtf.setText(obj.toString());
        }
    }

}
</code>```

Body:
I have a Combo Bx (Dropdown box) with an index range of 0-20. If there anyways I can use that index to specify which object I want data from? All of the objects use the same naming convention obj0, obj1, obj2, etc. Basically something like this...

public abstract class Person {

    private String name;
    private String title;
    private String email;
    private String job;

    public Person(String name, String title, String email, String job){
        this.name = name;
        this.title = title;
        this.email = email;
        this.job = job;
    }
    //Getters and Setters
}

public class main extends javax.swing.JFrame {
...misc code...

private void btn_startActionPerformed(java.awt.event.ActionEvent evt) {

    Person obj0 = new Person("Jon Doe",
                             "Program Coordinator",
                             "jon.doe@test.com",
                             "Faculty");

    Person obj1 = ...
    ...
    Person obj20 = ...

/*
Onclick it uses the index of the current index in the combobox (dropdown)
to specify which object to get the data from.
*/
private void btn_GetActionPerformed(java.awt.event.ActionEvent evt) {

    //Uses the obj naming convention plus the index
    string foo = "obj" + toString(combobox_Name.getSelectedIndex());

    //Fills the textbox using the above string and the getName method
    txtbox_username.setText(ToObject(foo).getName);
}

Body:
I have created a basic design of what I think you want:

This code creates 20 objects, adds them to a combobox and uses their predefined name when selected to change a textfield.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

class ObjExample {

    String name;

    public ObjExample(String name) {
        this.name = name;
    }

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

}

public class Main extends JFrame implements ActionListener {

    JComboBox jcb = new JComboBox();
    JTextField jtf = new JTextField("Text Field");

    public Main() {

        setSize(200, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        for (int i = 0; i <= 20; i++) {
            jcb.addItem(new ObjExample(Integer.toString(i)));
        }

        jcb.addActionListener(this);

        add(jcb);
        add(jtf);

        setVisible(true);
    }

    public static void main(String[] args) {
        new Main();
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == jcb) {
            ObjExample obj = (ObjExample) jcb.getSelectedItem();
            jtf.setText(obj.toString());
        }
    }

}


问:
Why do we do a POST to confirm deletion in asp.net MVC?
The following is a note from Professional ASP.NET MVC 2 by Scott Hanselman ++

You might ask — why did we go through
  the effort of creating a <form> within
  our Delete Confi rmation screen? Why
  not just use a standard hyperlink to
  link to an action method that does the
  actual delete operation? The reason is
  because we want to be careful to guard
  against Web-crawlers and search
  engines discovering our URLs and
  inadvertently causing data to be
  deleted when they follow the links.
  HTTP-GET-based URLs are considered
  safe for them to access/crawl, and
  they are supposed to not follow
  HTTP-POST ones. A good rule is to make
  sure that you always put destructive
  or data-modifying operations behind
  HTTP-POST requests.

If web-crawlers and search engine have no access to the page containing deletion button, is it safe to use a standard hyperlink to link to an action method doing the actual delete operation?

答: @xport: POST take 2 times to executed one action, and GET only take 1 time. In POST, the first time, it will contact to server for authenticate action, and after that it will executing this action. In GET situation, it only call to action that not authenticate. So in usual, POST spend more time to execute action than GET (2 round trips). If you have some actions as DELETE, UPDATE, ADD,... you must execute it with POST and if some actions only select data from database, only GET. That is my understand in GET and POST.</p>

ContentLicense: CC BY-SA 2.5


问:
How often is file loaded from imported module?
I am curious how often a file would actually be loaded into memory when its needed from a module.  Here is the scenario:

lookup.py

```<code>import json

mapping_dict = json.load(open('map.json'))

def map_file(file_name):
    return(mapping_dict[file_name])

def other_function():
    --do something--
</code>```

main.py

```<code>import lookup

--something something--

for f in files:
    print(lookup.map_file(f))
</code>```

So my question is how many times is mapping_dict from lookup.py loaded?  Once upon the initial import?  Every time map_file is called? Every time any function in lookup.py is called (map_file and other_function in this case).

Some combination of the above?

答:
Each module is loaded only once. The import statement first checks if the module exists in sys.modules, if it is, it just performs a dictionary lookup. If the item is not found, it loads the module. You can force module re-importation using reload (Python-2 only) or by deleting the entry in sys.modules (this is a bit of a hack).

```<code>In [1]: import sys as s1

In [2]: s1.modules['sys']
Out[2]: <module 'sys' (built-in)>

In [3]: del s1.modules['sys']

In [4]: id(s1)            # different than s2 and s3
Out[4]: 140359411362736

In [5]: import sys as s2  # same as s3

In [6]: id(s2)
Out[6]: 140359175854240

In [7]: s1 == s2
Out[7]: False

In [8]: s2
Out[8]: <module 'sys' (built-in)>

In [9]: import sys as s3

In [10]: id(s3)
Out[10]: 140359175854240
</code>```

Please note that reloading a given module will not reload any of the libraries it imports (Python2-only below, in Python3, you can use importlib.reload):

```<code>>>> import sysconfig
>>> s = reload(sysconfig)
>>> id(sysconfig) == id(s)
False
>>> id(sysconfig.sys) == id(s.sys)
True
</code>```

Body:
I am curious how often a file would actually be loaded into memory when its needed from a module.  Here is the scenario:

lookup.py

import json

mapping_dict = json.load(open('map.json'))

def map_file(file_name):
    return(mapping_dict[file_name])

def other_function():
    --do something--

main.py

import lookup

--something something--

for f in files:
    print(lookup.map_file(f))

So my question is how many times is mapping_dict from lookup.py loaded?  Once upon the initial import?  Every time map_file is called? Every time any function in lookup.py is called (map_file and other_function in this case).

Some combination of the above?

Body:
Each module is loaded only once. The import statement first checks if the module exists in sys.modules, if it is, it just performs a dictionary lookup. If the item is not found, it loads the module. You can force module re-importation using reload (Python-2 only) or by deleting the entry in sys.modules (this is a bit of a hack).

In [1]: import sys as s1

In [2]: s1.modules['sys']
Out[2]: <module 'sys' (built-in)>

In [3]: del s1.modules['sys']

In [4]: id(s1)            # different than s2 and s3
Out[4]: 140359411362736

In [5]: import sys as s2  # same as s3

In [6]: id(s2)
Out[6]: 140359175854240

In [7]: s1 == s2
Out[7]: False

In [8]: s2
Out[8]: <module 'sys' (built-in)>

In [9]: import sys as s3

In [10]: id(s3)
Out[10]: 140359175854240

Please note that reloading a given module will not reload any of the libraries it imports (Python2-only below, in Python3, you can use importlib.reload):

>>> import sysconfig
>>> s = reload(sysconfig)
>>> id(sysconfig) == id(s)
False
>>> id(sysconfig.sys) == id(s.sys)
True


问:
Shiny server functions with 2 outputs
I'm trying to return two tables based on one input.  Basically, I'm reading in a CSV and I want to display the values in the CSV in a table, then in a second table display a count of the number of rows in the CSV.

Right now I have

ui.R

```<code>ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Choose CSV File",
                accept = c(
                  "text/csv",
                  "text/comma-separated-values,text/plain",
                  ".csv")
      ),
      tags$hr(),
      checkboxInput("header", "Header", TRUE)
    ),
    mainPanel(
      tableOutput("rawData"),
      tableOutput("rawDataSize")
    )
  )
)
</code>```

and server.R

```<code>server <- function(input, output) {

  output$rawData <- renderTable({
    inFile <- reactive({input$file1})
    data <- reactive({
      if (is.null(inFile))
      return(NULL)
      read.csv(inFile$datapath, header = input$header)
    })
  })

  output$rawDataSize <- renderTable({
    dim(data)[1]
  })

}
</code>```

Unfortunately, this returns Warning: Error in as.data.frame.default: cannot coerce class "c("reactiveExpr", "reactive")" to a data.frame

答:
1- A reactive is a function, so always add () when calling it.

2- Avoid nesting reactives:

```<code>server <- function(input, output) {
  inFile <- reactive(input$file1)

  data <- reactive({
      if (is.null(inFile()))
          return(NULL)
      read.csv(inFile()$datapath, header = input$header)
      })

  output$rawData <- renderTable(data())

  output$rawDataSize <- renderTable(dim(data())[1])
}
</code>```

Title: Shiny server functions with 2 outputs

Body:
I'm trying to return two tables based on one input.  Basically, I'm reading in a CSV and I want to display the values in the CSV in a table, then in a second table display a count of the number of rows in the CSV.

Right now I have

ui.R

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Choose CSV File",
                accept = c(
                  "text/csv",
                  "text/comma-separated-values,text/plain",
                  ".csv")
      ),
      tags$hr(),
      checkboxInput("header", "Header", TRUE)
    ),
    mainPanel(
      tableOutput("rawData"),
      tableOutput("rawDataSize")
    )
  )
)

and server.R

server <- function(input, output) {

  output$rawData <- renderTable({
    inFile <- reactive({input$file1})
    data <- reactive({
      if (is.null(inFile))
      return(NULL)
      read.csv(inFile$datapath, header = input$header)
    })
  })

  output$rawDataSize <- renderTable({
    dim(data)[1]
  })

}

Unfortunately, this returns Warning: Error in as.data.frame.default: cannot coerce class "c("reactiveExpr", "reactive")" to a data.frame

Body:
1- A reactive is a function, so always add () when calling it.

2- Avoid nesting reactives:

server <- function(input, output) {
  inFile <- reactive(input$file1)

  data <- reactive({
      if (is.null(inFile()))
          return(NULL)
      read.csv(inFile()$datapath, header = input$header)
      })

  output$rawData <- renderTable(data())

  output$rawDataSize <- renderTable(dim(data())[1])
}


问:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()'
```<code>Process: com.example.vicevirus.myapplication, PID: 13471
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
              at com.example.vicevirus.myapplication.RegisterActivity$1.onComplete(RegisterActivity.java:48)
              at com.google.android.gms.tasks.zzc$1.run(Unknown Source)
              at android.os.Handler.handleCallback(Handler.java:751)
              at android.os.Handler.dispatchMessage(Handler.java:95)
              at android.os.Looper.loop(Looper.java:154)
              at android.app.ActivityThread.main(ActivityThread.java:6119)
              at java.lang.reflect.Method.invoke(Native Method)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

This is on android monitor. How do I solve this?

```<code>package com.example.vicevirus.myapplication;

import android.app.ProgressDialog;
         import android.support.annotation.NonNull;
         import android.support.v7.app.AppCompatActivity;
         import android.os.Bundle;
         import android.view.View;
         import android.widget.EditText;
         import android.widget.Toast;
         import com.google.android.gms.tasks.OnCompleteListener;
         import com.google.android.gms.tasks.OnSuccessListener;
         import com.google.android.gms.tasks.Task;
         import com.google.firebase.auth.AuthResult;
         import com.google.firebase.auth.FirebaseAuth;
         import com.google.firebase.database.DatabaseReference;
         import com.google.firebase.database.FirebaseDatabase;

public class RegisterActivity extends AppCompatActivity {
    private EditText email,name,password;
    DatabaseReference databaseReference;
    FirebaseAuth mAuth;
    private DatabaseReference userIdRef;
    ProgressDialog registerDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        email=(EditText)findViewById(R.id.email);
        name=(EditText)findViewById(R.id.name);
        password=(EditText)findViewById(R.id.password);
        databaseReference= FirebaseDatabase.getInstance().getReference().child("chat_users");
        mAuth=FirebaseAuth.getInstance();
        registerDialog=new ProgressDialog(this);
        registerDialog.setMessage("Registering..");
    }
    public void submit(View view) {
        registerDialog.show();
        mAuth.createUserWithEmailAndPassword(email.getText().toString(),password.getText().toString()).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if(task.isComplete())
                {
                    registerDialog.dismiss();
                    Toast.makeText(getApplicationContext(),"Registered successfully",Toast.LENGTH_SHORT).show();
                    userIdRef=databaseReference.child(mAuth.getCurrentUser().getUid());
                    userIdRef.child("name").setValue(name.getText().toString());
                    finish();
                }
                registerDialog.dismiss();
            }
        });
    }
}
</code>```

答:
The problem seems to be that your user is not yet logged in or even registered. So calling mAuth.getCurrentUser() returns null.

Check out this page of the FireBase documentation about how you need to implement the registering of users. It could be that this is failing. The check task.isSuccessful() is necessary to check this.

Body:
Process: com.example.vicevirus.myapplication, PID: 13471
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
              at com.example.vicevirus.myapplication.RegisterActivity$1.onComplete(RegisterActivity.java:48)
              at com.google.android.gms.tasks.zzc$1.run(Unknown Source)
              at android.os.Handler.handleCallback(Handler.java:751)
              at android.os.Handler.dispatchMessage(Handler.java:95)
              at android.os.Looper.loop(Looper.java:154)
              at android.app.ActivityThread.main(ActivityThread.java:6119)
              at java.lang.reflect.Method.invoke(Native Method)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

This is on android monitor. How do I solve this?

package com.example.vicevirus.myapplication;

import android.app.ProgressDialog;
         import android.support.annotation.NonNull;
         import android.support.v7.app.AppCompatActivity;
         import android.os.Bundle;
         import android.view.View;
         import android.widget.EditText;
         import android.widget.Toast;
         import com.google.android.gms.tasks.OnCompleteListener;
         import com.google.android.gms.tasks.OnSuccessListener;
         import com.google.android.gms.tasks.Task;
         import com.google.firebase.auth.AuthResult;
         import com.google.firebase.auth.FirebaseAuth;
         import com.google.firebase.database.DatabaseReference;
         import com.google.firebase.database.FirebaseDatabase;

public class RegisterActivity extends AppCompatActivity {
    private EditText email,name,password;
    DatabaseReference databaseReference;
    FirebaseAuth mAuth;
    private DatabaseReference userIdRef;
    ProgressDialog registerDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        email=(EditText)findViewById(R.id.email);
        name=(EditText)findViewById(R.id.name);
        password=(EditText)findViewById(R.id.password);
        databaseReference= FirebaseDatabase.getInstance().getReference().child("chat_users");
        mAuth=FirebaseAuth.getInstance();
        registerDialog=new ProgressDialog(this);
        registerDialog.setMessage("Registering..");
    }
    public void submit(View view) {
        registerDialog.show();
        mAuth.createUserWithEmailAndPassword(email.getText().toString(),password.getText().toString()).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if(task.isComplete())
                {
                    registerDialog.dismiss();
                    Toast.makeText(getApplicationContext(),"Registered successfully",Toast.LENGTH_SHORT).show();
                    userIdRef=databaseReference.child(mAuth.getCurrentUser().getUid());
                    userIdRef.child("name").setValue(name.getText().toString());
                    finish();
                }
                registerDialog.dismiss();
            }
        });
    }
}


答:
Move inFile <- reactive({input$file1}) outside of renderTable. Then, to use this reactive object, you need to treat it like a function. inFile()$datapath. Same for your data reactive object.

So, your server() ends up looking something like:

```<code>server <- function(input, output) {

  inFile <- reactive({input$file1})

  data <- reactive({
    if (is.null(inFile())) return(NULL)
    read.csv(inFile()$datapath, header = input$header)
  })

  output$rawData <- renderTable({
    data()
  })

  output$rawDataSize <- renderTable({
    dim(data())[1]
  })

}
</code>```

Title: Shiny server functions with 2 outputs

Body:
Move inFile <- reactive({input$file1}) outside of renderTable. Then, to use this reactive object, you need to treat it like a function. inFile()$datapath. Same for your data reactive object.

So, your server() ends up looking something like:

server <- function(input, output) {

  inFile <- reactive({input$file1})

  data <- reactive({
    if (is.null(inFile())) return(NULL)
    read.csv(inFile()$datapath, header = input$header)
  })

  output$rawData <- renderTable({
    data()
  })

  output$rawDataSize <- renderTable({
    dim(data())[1]
  })

}


问:
Create a View From Max1 of One Column and the Max2 of Another if there are multiple Max1 for group
From my table, I want to select for each project ID the ID with the latest deploymentDate and if there are two identical latest deployment dates for the same project ID, select the ID with the latest submittedOn datetime. So if my table looks like this:

```<code>    id  | projectId  |  deploymentDate  | submittedOn         |
    1   | 1          |  2017-01-02      | 2017-01-02 13:00:00 |
    2   | 1          |  2017-01-04      | 2017-01-04 11:00:00 |
    3   | 2          |  2017-01-06      | 2017-01-06 17:00:00 |
    4   | 2          |  2017-01-06      | 2017-01-01 12:00:00 |
    5   | 3          |  2017-01-02      | 2017-01-02 13:30:00 |
    6   | 3          |  2017-01-02      | 2017-01-05 15:00:00 |
    7   | 3          |  2017-01-02      | 2017-01-04 10:00:00 |
</code>```

The desired rows are:

```<code>    id  | projectId  |  deploymentDate  | submittedOn         |
    2   | 1          |  2017-01-04      | 2017-01-04 11:00:00 |
    3   | 2          |  2017-01-06      | 2017-01-06 17:00:00 |
    6   | 3          |  2017-01-02      | 2017-01-05 15:00:00 |
</code>```

答:
You can try the below.  Adjust the sorting in the row_number as needed.</p>

```<code>select
    a.id,
    a.projectid,
    a.deploymentdate,
    a.submittedOn
from project a
inner join
    (select
            a.id,
            row_number() over (partition by projectid order by deploymentdate desc, submittedOn desc, id) as rid
    from project
    ) as b
    on b.id = a.id
    and b.rid = 1
</code>```

Body:
From my table, I want to select for each project ID the ID with the latest deploymentDate and if there are two identical latest deployment dates for the same project ID, select the ID with the latest submittedOn datetime. So if my table looks like this:

    id  | projectId  |  deploymentDate  | submittedOn         |
    1   | 1          |  2017-01-02      | 2017-01-02 13:00:00 |
    2   | 1          |  2017-01-04      | 2017-01-04 11:00:00 |
    3   | 2          |  2017-01-06      | 2017-01-06 17:00:00 |
    4   | 2          |  2017-01-06      | 2017-01-01 12:00:00 |
    5   | 3          |  2017-01-02      | 2017-01-02 13:30:00 |
    6   | 3          |  2017-01-02      | 2017-01-05 15:00:00 |
    7   | 3          |  2017-01-02      | 2017-01-04 10:00:00 |

The desired rows are:

    id  | projectId  |  deploymentDate  | submittedOn         |
    2   | 1          |  2017-01-04      | 2017-01-04 11:00:00 |
    3   | 2          |  2017-01-06      | 2017-01-06 17:00:00 |
    6   | 3          |  2017-01-02      | 2017-01-05 15:00:00 |

Body:
You can try the below.  Adjust the sorting in the row_number as needed.

select
    a.id,
    a.projectid,
    a.deploymentdate,
    a.submittedOn
from project a
inner join
    (select
            a.id,
            row_number() over (partition by projectid order by deploymentdate desc, submittedOn desc, id) as rid
    from project
    ) as b
    on b.id = a.id
    and b.rid = 1


问:
how many binary trees are possible that satisfies a given preorder and postorder traversal?
For example

preorder->0,1,2

postorder->2,1,0

```<code>      0
     /
    1
   /
  2

      0
     /
    1
     \
      2

      0
       \
        1
       /
      2

      0
       \
        1
         \
          2
</code>```

These are the 4 binary trees possible for above case.How many trees are possible in general for any preorder and postorder traversals?

答:
There are two answers to your question:

For given postorder and preorder traversals of a binary tree, you can only find a single tree. (note the emphasis on binary! I only allow the root to have degree 2)

A proof sketch is given in this answer, where you can also find a reconstruction algorithm.

If your tree is allowed to have inner nodes of degree 2, i.e. nodes with only one child, then you can place it either on the left or on the right side, the corresponding subtree's position in the pre- and postorder traversal won't change. So if you have k such nodes, you have 2^k equivalent trees

Body:
For example

preorder->0,1,2

postorder->2,1,0

      0
     /
    1
   /
  2

      0
     /
    1
     \
      2

      0
       \
        1
       /
      2

      0
       \
        1
         \
          2

These are the 4 binary trees possible for above case.How many trees are possible in general for any preorder and postorder traversals?


问:
Set focus to different column in DataGridView
Column 0 in a DataGridView control is Read Only.  I want the focus to move to column 1 if the user selects column 0 with the mouse or presses the tab key from the last column in the previous row.  I tried the following code in the CellEnter event but it causes an exception "Operation is not valid because it results in a reentrant call to the CurrentCellAddressCore function". Column 1 is named "patternsTerminator".

```<code>private void dataGridView_patterns_CellEnter(object sender, DataGridViewCellEventArgs e)
{
    int currentRow = e.RowIndex;

    try
    {
        if (this.dataGridView_patterns.CurrentCell.ColumnIndex == 0)
            this.dataGridView_patterns.CurrentCell = this.dataGridView_patterns.Rows[currentRow].Cells["patternsTerminator"];
    }
    catch (Exception ex)
    {
        MessageBox.Show(this, ex.Message, errCaption, button, icon);
    }
}
</code>```

I understand why the exception occurs.  When the focus moves to column 1, the CellEnter event is called again, and the exception prevents recursive calls to the CellEnter event.

I tried the following as a workaround but it ignores the tab key.  When I click in column 0, SendKeys is called but the cursor stays in column 0.

```<code>if (this.dataGridView_patterns.CurrentCell.ColumnIndex == 0)
    SendKeys.Send("{TAB}");
</code>```

I have read many of the threads on this and other websites but can't get it to work.  Any suggestions would be greatly appreciated.

Thank you!

答:
Adding to Jared's answer, I tested the following code and it works.  The only difference between this and Jared's answer is that columnIndex is referred to by its name instead of by its index value.  Thanks again, Jared.</p>

```<code>        try
        {
            // Display the pattern number in column 0
            this.dataGridView_patterns.Rows[currentRow].Cells["patternNumber"].Value = currentRow + 1;

            // Move the current cell focus to column 1 (Terminator pattern) on current row
            if (e.ColumnIndex == 0)
            {
                this.BeginInvoke(new MethodInvoker(() =>
                {
                    moveCellTo(dataGridView_patterns, e.RowIndex, "patternsTer");
                }));
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(this, ex.Message, errCaption, button, icon);
        }
    }

    private void moveCellTo(DataGridView dgCurrent, int rowIndex, string columnName)
    {
        dgCurrent.CurrentCell = dgCurrent.Rows[rowIndex].Cells[columnName];
    }
</code>```

Body:
Column 0 in a DataGridView control is Read Only.  I want the focus to move to column 1 if the user selects column 0 with the mouse or presses the tab key from the last column in the previous row.  I tried the following code in the CellEnter event but it causes an exception "Operation is not valid because it results in a reentrant call to the CurrentCellAddressCore function". Column 1 is named "patternsTerminator".

private void dataGridView_patterns_CellEnter(object sender, DataGridViewCellEventArgs e)
{
    int currentRow = e.RowIndex;

    try
    {
        if (this.dataGridView_patterns.CurrentCell.ColumnIndex == 0)
            this.dataGridView_patterns.CurrentCell = this.dataGridView_patterns.Rows[currentRow].Cells["patternsTerminator"];
    }
    catch (Exception ex)
    {
        MessageBox.Show(this, ex.Message, errCaption, button, icon);
    }
}

I understand why the exception occurs.  When the focus moves to column 1, the CellEnter event is called again, and the exception prevents recursive calls to the CellEnter event.

I tried the following as a workaround but it ignores the tab key.  When I click in column 0, SendKeys is called but the cursor stays in column 0.

if (this.dataGridView_patterns.CurrentCell.ColumnIndex == 0)
    SendKeys.Send("{TAB}");

I have read many of the threads on this and other websites but can't get it to work.  Any suggestions would be greatly appreciated.

Thank you!

Body:
Adding to Jared's answer, I tested the following code and it works.  The only difference between this and Jared's answer is that columnIndex is referred to by its name instead of by its index value.  Thanks again, Jared.

        try
        {
            // Display the pattern number in column 0
            this.dataGridView_patterns.Rows[currentRow].Cells["patternNumber"].Value = currentRow + 1;

            // Move the current cell focus to column 1 (Terminator pattern) on current row
            if (e.ColumnIndex == 0)
            {
                this.BeginInvoke(new MethodInvoker(() =>
                {
                    moveCellTo(dataGridView_patterns, e.RowIndex, "patternsTer");
                }));
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(this, ex.Message, errCaption, button, icon);
        }
    }

    private void moveCellTo(DataGridView dgCurrent, int rowIndex, string columnName)
    {
        dgCurrent.CurrentCell = dgCurrent.Rows[rowIndex].Cells[columnName];
    }


问:
Quick Union Functional Style
I am trying to mix study with pleasure by implementing the exercises from Sedgewick and Wayne's "Algorithm's 4th Edition" in scala (and, to the best of my know-how, in a functional style).

At the exercises 1.5.7 I blocked and hope that someone could help me out. So the task is to write the QuickUnion implementation. You may find Java implementation here.

I've written my scala version and it seems to make sense, but the console output is outright discouraging. I am creating an array of 625 initial components but ... the number of components at the end is .. below zero

Without further ado this is my implementation:

```<code>package ca.vgorcinschi.algorithms1_5_7.quickUnionUF

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

class QuickUnionUF(size: Int) extends AbstractUF(size) {

  override val array = (0 to size).toArray

  override def find(p: Int): Int = {
    validate(p)
    Stream.iterate(p)(p => array(p)).dropWhile { _ != array(p) }.head
  }

  override def connected(p: Int, q: Int): Boolean = find(p) == find(q)

  override def union(p: Int, q: Int) = {
    /*
     * need to declare Futures outisde
     * for-comprehension loop to run in parallel
     */
    val fRootP = Future { find(p) }
    val fRootQ = Future { find(q) }

    for {
      rootP <- fRootP
      rootQ <- fRootQ
      if (rootP != rootQ)
    } {
      array(rootP) = rootQ
      count -= 1
    }
  }

}
</code>```

The parent abstract class and the underlying trait are both in my github repository. For ease of reading I am copying below the Main class:

```<code>import scala.io.Source
import ca.vgorcinschi.algorithms1_5_7.quickUnionUF.QuickUnionUF
import scala.util.matching.Regex

object Main extends App {
  val allLines = Source.fromFile("src/main/resources/mediumUF.txt").getLines().toList
  //get & print the initial number of components
  val size = allLines.head.trim.toInt
  println(s"Le nombre initial de composants est $size")

  val uf = new QuickUnionUF(size)

  val Integer = new Regex("(-)?(\\d+)")

  for (line <- allLines.tail) {
    val p = Integer findFirstIn line

    assert(p.isDefined)

    val intP = p.get toInt
    val q = Integer findFirstIn line.substring(p.get.length).replace("\\s+", "")

    assert(q.isDefined)

    val intQ = q.get.toInt
    if (!uf.connected(intP, intQ)) {
      uf.union(intP, intQ)
      println(s"L`union fait sur $intP et $intQ")
      println(s"Le nombre des composants est maintenant - ${uf.counter()}")
    }
  }
}
</code>```

In addition these are the first and the last lines of the run output:

```<code>> runMain Main
[info] Compiling 1 Scala source to /home/vgorcinschi/workspace-scala/Algorithms/Chapter 1 Fundamentals/algorithms1_5_7/target/scala-2.12/classes...
[info] Running Main
Le nombre initial de composants est 625
L`union fait sur 528 et 503
Le nombre des composants est maintenant - 624
L`union fait sur 548 et 523
Le nombre des composants est maintenant - 623
L`union fait sur 389 et 414
Le nombre des composants est maintenant - 622
L`union fait sur 446 et 421
Le nombre des composants est maintenant - 621
L`union fait sur 552 et 553
Le nombre des composants est maintenant - 620
L`union fait sur 154 et 155
...
Le nombre des composants est maintenant - -67
L`union fait sur 463 et 464
Le nombre des composants est maintenant - -67
L`union fait sur 10 et 35
Le nombre des composants est maintenant - -67
L`union fait sur 619 et 594
Le nombre des composants est maintenant - -67
L`union fait sur 403 et 402
Le nombre des composants est maintenant - -67
</code>```

I do fear that the shoe pinches somewhere around my futures or the stream based find, but I can't seem to figure it out...

答:
I think I got it. The solution was odd because it makes me wonder how does the original solution even worked. Basically I just rewrote the counter() in the parent class to return a array.distinct.length , i.e. the distinct integers or the roots:

```<code>/*
 * takes the initial number of components
 * as its argument
 */
abstract class AbstractUF(var count: Int) extends UF{

  override def counter() = array.distinct.length

  val array: Array[Int]

...
}
</code>```

Output:

```<code>Le nombre initial de composants est 625
L`union fait sur 528 et 503
Le nombre des composants est maintenant - 625
L`union fait sur 548 et 523
Le nombre des composants est maintenant - 624
L`union fait sur 389 et 414
Le nombre des composants est maintenant - 623
L`union fait sur 446 et 421
Le nombre des composants est maintenant - 622
L`union fait sur 552 et 553
Le nombre des composants est maintenant - 621
L`union fait sur 154 et 155
Le nombre des composants est maintenant - 620
...
Le nombre des composants est maintenant - 266
L`union fait sur 295 et 320
Le nombre des composants est maintenant - 266
L`union fait sur 160 et 159
Le nombre des composants est maintenant - 266
L`union fait sur 463 et 464
Le nombre des composants est maintenant - 266
L`union fait sur 10 et 35
Le nombre des composants est maintenant - 266
L`union fait sur 619 et 594
Le nombre des composants est maintenant - 265
L`union fait sur 403 et 402
Le nombre des composants est maintenant - 265
</code>```

Title: Quick Union Functional Style

Body:
I am trying to mix study with pleasure by implementing the exercises from Sedgewick and Wayne's "Algorithm's 4th Edition" in scala (and, to the best of my know-how, in a functional style).

At the exercises 1.5.7 I blocked and hope that someone could help me out. So the task is to write the QuickUnion implementation. You may find Java implementation here.

I've written my scala version and it seems to make sense, but the console output is outright discouraging. I am creating an array of 625 initial components but ... the number of components at the end is .. below zero

Without further ado this is my implementation:

package ca.vgorcinschi.algorithms1_5_7.quickUnionUF

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

class QuickUnionUF(size: Int) extends AbstractUF(size) {

  override val array = (0 to size).toArray

  override def find(p: Int): Int = {
    validate(p)
    Stream.iterate(p)(p => array(p)).dropWhile { _ != array(p) }.head
  }

  override def connected(p: Int, q: Int): Boolean = find(p) == find(q)

  override def union(p: Int, q: Int) = {
    /*
     * need to declare Futures outisde
     * for-comprehension loop to run in parallel
     */
    val fRootP = Future { find(p) }
    val fRootQ = Future { find(q) }

    for {
      rootP <- fRootP
      rootQ <- fRootQ
      if (rootP != rootQ)
    } {
      array(rootP) = rootQ
      count -= 1
    }
  }

}

The parent abstract class and the underlying trait are both in my github repository. For ease of reading I am copying below the Main class:

import scala.io.Source
import ca.vgorcinschi.algorithms1_5_7.quickUnionUF.QuickUnionUF
import scala.util.matching.Regex

object Main extends App {
  val allLines = Source.fromFile("src/main/resources/mediumUF.txt").getLines().toList
  //get & print the initial number of components
  val size = allLines.head.trim.toInt
  println(s"Le nombre initial de composants est $size")

  val uf = new QuickUnionUF(size)

  val Integer = new Regex("(-)?(\\d+)")

  for (line <- allLines.tail) {
    val p = Integer findFirstIn line

    assert(p.isDefined)

    val intP = p.get toInt
    val q = Integer findFirstIn line.substring(p.get.length).replace("\\s+", "")

    assert(q.isDefined)

    val intQ = q.get.toInt
    if (!uf.connected(intP, intQ)) {
      uf.union(intP, intQ)
      println(s"L`union fait sur $intP et $intQ")
      println(s"Le nombre des composants est maintenant - ${uf.counter()}")
    }
  }
}

In addition these are the first and the last lines of the run output:

> runMain Main
[info] Compiling 1 Scala source to /home/vgorcinschi/workspace-scala/Algorithms/Chapter 1 Fundamentals/algorithms1_5_7/target/scala-2.12/classes...
[info] Running Main
Le nombre initial de composants est 625
L`union fait sur 528 et 503
Le nombre des composants est maintenant - 624
L`union fait sur 548 et 523
Le nombre des composants est maintenant - 623
L`union fait sur 389 et 414
Le nombre des composants est maintenant - 622
L`union fait sur 446 et 421
Le nombre des composants est maintenant - 621
L`union fait sur 552 et 553
Le nombre des composants est maintenant - 620
L`union fait sur 154 et 155
...
Le nombre des composants est maintenant - -67
L`union fait sur 463 et 464
Le nombre des composants est maintenant - -67
L`union fait sur 10 et 35
Le nombre des composants est maintenant - -67
L`union fait sur 619 et 594
Le nombre des composants est maintenant - -67
L`union fait sur 403 et 402
Le nombre des composants est maintenant - -67

I do fear that the shoe pinches somewhere around my futures or the stream based find, but I can't seem to figure it out...

Body:
I think I got it. The solution was odd because it makes me wonder how does the original solution even worked. Basically I just rewrote the counter() in the parent class to return a array.distinct.length , i.e. the distinct integers or the roots:

/*
 * takes the initial number of components
 * as its argument
 */
abstract class AbstractUF(var count: Int) extends UF{

  override def counter() = array.distinct.length

  val array: Array[Int]

...
}

Output:

Le nombre initial de composants est 625
L`union fait sur 528 et 503
Le nombre des composants est maintenant - 625
L`union fait sur 548 et 523
Le nombre des composants est maintenant - 624
L`union fait sur 389 et 414
Le nombre des composants est maintenant - 623
L`union fait sur 446 et 421
Le nombre des composants est maintenant - 622
L`union fait sur 552 et 553
Le nombre des composants est maintenant - 621
L`union fait sur 154 et 155
Le nombre des composants est maintenant - 620
...
Le nombre des composants est maintenant - 266
L`union fait sur 295 et 320
Le nombre des composants est maintenant - 266
L`union fait sur 160 et 159
Le nombre des composants est maintenant - 266
L`union fait sur 463 et 464
Le nombre des composants est maintenant - 266
L`union fait sur 10 et 35
Le nombre des composants est maintenant - 266
L`union fait sur 619 et 594
Le nombre des composants est maintenant - 265
L`union fait sur 403 et 402
Le nombre des composants est maintenant - 265


问:
How to modify all text elements; visual studio c++
I'm trying to create color themes for my winForms application. Essentially what will happen is you select one of the themes in the settings and the application will update with the selected color pallet.

My problem is that the program has hundreds of text elements (labels, listboxes, textboxes, etc.). Rather than writing a line of code for each text element (per color theme), I was wondering if there was some way to modify all text elements at once.

I was hoping maybe there is a way to group text elements into 'Title', 'Subtitle', 'Main', categories and then assigning the new color values to the groups.

Thanks.

答:
System::Windows::Forms::Form class has a read-only property called Controls.  This is a collection of all child controls on the form.

In C# you can do like this.  I am pretty sure you can do the same thing in C++/CLI:

```<code>var cols = new Dictionary<string, Color>()
{
    { "red", Color.Red },
    { "green", Color.Green },
    { "blue", Color.Blue },
};

var theme = "green";

foreach(var ctrl in Controls)
{
    if (ctrl is TextBox)
        ((TextBox)ctrl).BackColor = cols[theme];
}
</code>```

Body:
System::Windows::Forms::Form class has a read-only property called Controls.  This is a collection of all child controls on the form.

In C# you can do like this.  I am pretty sure you can do the same thing in C++/CLI:

var cols = new Dictionary<string, Color>()
{
    { "red", Color.Red },
    { "green", Color.Green },
    { "blue", Color.Blue },
};

var theme = "green";

foreach(var ctrl in Controls)
{
    if (ctrl is TextBox)
        ((TextBox)ctrl).BackColor = cols[theme];
}