问:
Array formula to return an ARRAY without duplicates, without VBA
I would like to know whether it's possible to return an array from a single cell formula, which is filtered to remove duplicates, and which is built purely on Excel formulas.

I'm aware of approaches to return a list of values where the duplicates are removed (see this question), where the list is spread over multiple cells. However I specifically want to return an array intermediate.

E.g. For the list in A1:A5, I can get an array of values {0.1,0.2,0.2,0.7,0.3}, from which I want a second array {0.1,0.2,0.7,0.3}, as an intermediate in an array formula. Current approaches use single-end anchored ranges (like C$1:C1) to iterate through the items in the array geometrically (by dragging down column C). I would like to leave the array un-iterated, within the formula. I can then manipulate this as I would any other array.

All this should take place in a single cell if possible.

NB

Both MacroMarc's and Barry Houdini's answers are perfectly valid, and I ran a speed check on each - there was negligible difference (any difference was smaller than the variation between test runs). Both scored ~ 1.0±0.2 ms

答:
Use this array formula to sum the unique, it requires the use of TEXTJOIN() which is only available with Office 365 Excel:

```<code>=SUM( IF(ISERROR(FIND(TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999+1,999)),MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),1,(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999))),--TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999+1,999))))
</code>```

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.

You can replace SUM with many different formula.

If one does not have Office 365 Excel then vba and or helper columns are the only method available.

Edit:

To remove the False from the array and return the 3rd non duplicate in the array we can wrap it in another TEXTJOIN:

```<code>=--TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,IF(ISERROR(FIND(TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999+1,999)),MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),1,(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999))),--TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999+1,999)),"")),(3-1)*999,999))
</code>```

The 3 in the (3-1)*999 can be replaced by anything that returns the Index number desired.

Still an array formula that needs Ctrl-Shift-Enter.

If you want to return the relative position in then use this array:

```<code>=AGGREGATE(15,6,ROW(INDIRECT("1:" & COUNTA(A:A)))/(--TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,IF(ISERROR(FIND(TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999+1,999)),MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),1,(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999))),--TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999+1,999)),"")),(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999,999))=B1),1)
</code>```

I gave you the long formula for creating the array but for the sum:

```<code>=SUMPRODUCT(A1:A5/COUNTIF(A1:A5,A1:A5))
</code>```

would be sufficient.

And for the Average:

```<code>=SUMPRODUCT(A1:A5/COUNTIF(A1:A5,A1:A5))/SUMPRODUCT(1/COUNTIF(A1:A5,A1:A5))
</code>```

There are many work arounds that are shorter and better if you know what you want.

Body:
Use this array formula to sum the unique, it requires the use of TEXTJOIN() which is only available with Office 365 Excel:

=SUM( IF(ISERROR(FIND(TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999+1,999)),MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),1,(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999))),--TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999+1,999))))

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.

You can replace SUM with many different formula.

If one does not have Office 365 Excel then vba and or helper columns are the only method available.

Edit:

To remove the False from the array and return the 3rd non duplicate in the array we can wrap it in another TEXTJOIN:

=--TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,IF(ISERROR(FIND(TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999+1,999)),MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),1,(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999))),--TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999+1,999)),"")),(3-1)*999,999))

The 3 in the (3-1)*999 can be replaced by anything that returns the Index number desired.

Still an array formula that needs Ctrl-Shift-Enter.

If you want to return the relative position in then use this array:

=AGGREGATE(15,6,ROW(INDIRECT("1:" & COUNTA(A:A)))/(--TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,IF(ISERROR(FIND(TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999+1,999)),MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),1,(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999))),--TRIM(MID(TEXTJOIN(REPT(" ",999),TRUE,A:A),(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999+1,999)),"")),(ROW(INDIRECT("1:" & COUNTA(A:A)))-1)*999,999))=B1),1)

I gave you the long formula for creating the array but for the sum:

=SUMPRODUCT(A1:A5/COUNTIF(A1:A5,A1:A5))

would be sufficient.

And for the Average:

=SUMPRODUCT(A1:A5/COUNTIF(A1:A5,A1:A5))/SUMPRODUCT(1/COUNTIF(A1:A5,A1:A5))

There are many work arounds that are shorter and better if you know what you want.


来源: stackexchange

问:
Run the last executed command in Windows command prompt
When using UNIX I use to type !! to run the last executed command.

How could I do the similar kind of operation on Windows command prompt?

答: You can just use the up and down arrows or F3</p>

ContentLicense: CC BY-SA 3.0


问:
ActiveMQ - Sending a message to a temporary queue specified using a string (NMS in C#)
I have a synchronous message transaction within my system, and the process broadly follows this flow:

"Point A" creates a temporary queue ("destination 2") on the message broker;

Message sent from point A to destination 1 (a normal queue on the message broker), with the ReplyTo address set as destination 2;

point A blocks waiting for response on destination 2;

point B receives message from destination 1;

point B creates a work object - a property of which is the name of destination 2 (derived using .ToString()". This work object is serialized and stored in the DB;

...

Object retrieved from DB when certain parameters are met, changes ocurr, and a response is sent to destination 2 - using SessionUtil to derive a new IDestination object from the replyto address stored as a string property of the work object;

"Point A" recieves message from destination 2 and continues on.

This process can take anything from a split second to several seconds to accomplish.

I need to use the name of the return destination (destination 2), rather than the full IDestination object, as I have to serialize the object and store in the DB.

If I use a permanent queue or a topic as destination 2, the process works fine. However, it always fails when attempting to create it using the string name of the temporary queue.

There are no errors, the message just fails to arrive

Any ideas why?

Example code for sending return message shown:

```<code>IDestination myDestination = SessionUtil.GetDestination(stateSession, instance.ReplyTo, DestinationType.Queue);

stateConnection.Start();

using (IMessageProducer myProducer = stateSession.CreateProducer(myDestination))
{
myProducer.DeliveryMode = MsgDeliveryMode.NonPersistent;
var response = myProducer.CreateTextMessage();

response.NMSCorrelationID = instance.CorrelationID;
response.Properties["RoutingDestination"] = instance.RoutingOriginator;
response.Text = "Test Response";

try
{
    myProducerBroadcast.Send(response);
    myProducer.Send(response);

    Log.InfoFormat("Sent response {0} to {1}", instance.UniqueId, instance.ReplyTo);
}
catch (Exception ex)
{
    Log.Error("Unable to send execution update onwards", ex);
}
}
</code>```

("instance" is the work object - which contains the ReplyTo address and other information)

答: A temporary destination is just that, temporary.  Once the Connection object that created the Temporary Destination closes, the destination is automatically removed from the broker.  Storing the temp destination for later use is not a good idea for this reason.  Also, only the Connection that created the temp destination is allowed to consume on it.  </p>

ContentLicense: CC BY-SA 2.5

Body:
I have a synchronous message transaction within my system, and the process broadly follows this flow:

"Point A" creates a temporary queue ("destination 2") on the message broker;

Message sent from point A to destination 1 (a normal queue on the message broker), with the ReplyTo address set as destination 2;

point A blocks waiting for response on destination 2;

point B receives message from destination 1;

point B creates a work object - a property of which is the name of destination 2 (derived using .ToString()". This work object is serialized and stored in the DB;

...

Object retrieved from DB when certain parameters are met, changes ocurr, and a response is sent to destination 2 - using SessionUtil to derive a new IDestination object from the replyto address stored as a string property of the work object;

"Point A" recieves message from destination 2 and continues on.

This process can take anything from a split second to several seconds to accomplish.

I need to use the name of the return destination (destination 2), rather than the full IDestination object, as I have to serialize the object and store in the DB.

If I use a permanent queue or a topic as destination 2, the process works fine. However, it always fails when attempting to create it using the string name of the temporary queue.

There are no errors, the message just fails to arrive

Any ideas why?

Example code for sending return message shown:

IDestination myDestination = SessionUtil.GetDestination(stateSession, instance.ReplyTo, DestinationType.Queue);

stateConnection.Start();

using (IMessageProducer myProducer = stateSession.CreateProducer(myDestination))
{
myProducer.DeliveryMode = MsgDeliveryMode.NonPersistent;
var response = myProducer.CreateTextMessage();

response.NMSCorrelationID = instance.CorrelationID;
response.Properties["RoutingDestination"] = instance.RoutingOriginator;
response.Text = "Test Response";

try
{
    myProducerBroadcast.Send(response);
    myProducer.Send(response);

    Log.InfoFormat("Sent response {0} to {1}", instance.UniqueId, instance.ReplyTo);
}
catch (Exception ex)
{
    Log.Error("Unable to send execution update onwards", ex);
}
}

("instance" is the work object - which contains the ReplyTo address and other information)


问:
After each word which ends with given substring insert a word
I need after each word of the text, ending with a given substring,
insert the specified word.My code works to some extent, I think it is not good idea modifying StringBuilder object while iterating over it. As you can see it fails in the last two cases, with "kalola" and "lalilo". Thanks a lot!

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextEditor {

    public static void main(String[] args) {

        String text = "Hello Mister James! Do you use trello fregiently? "
                + "Do you know Canelo Pavelo magenta ravelo sagenta! "
                + "lolita kalola lalilo lalita 333l lo.";

        String regex = "\\b\\w+lo\\b";

        String word = " 232 ";

        StringBuilder copyOfText = new StringBuilder(text);

        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(copyOfText);

        while(matcher.find()) {
            copyOfText.insert(matcher.end(), word);
        }

        //text = copyOfText.toString();

        System.out.println(copyOfText);
    }
}
</code>```

Received output is:

Hello 232  Mister James! Do you use trello 232  fregiently? Do you
  know Canelo 232  Pavelo 232  magenta ravelo 232  sagenta! lolita kalo
  232 la lalilo lalita 333l lo.

Expected output is:

Hello 232  Mister James! Do you use trello 232  fregiently? Do you
  know Canelo 232  Pavelo 232  magenta ravelo 232  sagenta! lolita
  kalola lalilo 232 lalita 333l lo.

答:
As mentioned in the comments you can use String.replaceAll instead of iterating with a while loop:

```<code>String text = "Hello Mister James! Do you use trello fregiently? "
        + "Do you know Canelo Pavelo magenta ravelo sagenta! "
        + "lolita kalola lalilo lalita 333l lo.";

String word = "232";

System.out.println(text.replaceAll("(\\w+lo\\b)", "$1 " + word));
</code>```

Output:

Hello 232 Mister James! Do you use trello 232 fregiently? Do you know
  Canelo 232 Pavelo 232 magenta ravelo 232 sagenta! lolita kalola lalilo
  232 lalita 333l lo.

Body:
I need after each word of the text, ending with a given substring,
insert the specified word.My code works to some extent, I think it is not good idea modifying StringBuilder object while iterating over it. As you can see it fails in the last two cases, with "kalola" and "lalilo". Thanks a lot!

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextEditor {

    public static void main(String[] args) {

        String text = "Hello Mister James! Do you use trello fregiently? "
                + "Do you know Canelo Pavelo magenta ravelo sagenta! "
                + "lolita kalola lalilo lalita 333l lo.";

        String regex = "\\b\\w+lo\\b";

        String word = " 232 ";

        StringBuilder copyOfText = new StringBuilder(text);

        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(copyOfText);

        while(matcher.find()) {
            copyOfText.insert(matcher.end(), word);
        }

        //text = copyOfText.toString();

        System.out.println(copyOfText);
    }
}

Received output is:

Hello 232  Mister James! Do you use trello 232  fregiently? Do you
  know Canelo 232  Pavelo 232  magenta ravelo 232  sagenta! lolita kalo
  232 la lalilo lalita 333l lo.

Expected output is:

Hello 232  Mister James! Do you use trello 232  fregiently? Do you
  know Canelo 232  Pavelo 232  magenta ravelo 232  sagenta! lolita
  kalola lalilo 232 lalita 333l lo.

Body:
As mentioned in the comments you can use String.replaceAll instead of iterating with a while loop:

String text = "Hello Mister James! Do you use trello fregiently? "
        + "Do you know Canelo Pavelo magenta ravelo sagenta! "
        + "lolita kalola lalilo lalita 333l lo.";

String word = "232";

System.out.println(text.replaceAll("(\\w+lo\\b)", "$1 " + word));

Output:

Hello 232 Mister James! Do you use trello 232 fregiently? Do you know
  Canelo 232 Pavelo 232 magenta ravelo 232 sagenta! lolita kalola lalilo
  232 lalita 333l lo.


问:
Why is it legit to take the next two commands to fill gaps between paxos events?
There is a point in Paxos algorithm (http://research.microsoft.com/en-us/um/people/lamport/pubs/paxos-simple.pdf) that I do not understand. It's about how to deal with the gaps, the paper describe two ways as below:

The leader, as well as any other server that learns all the commands the leader knows, can now execute commands 1–135. However, it can’t execute commands 138–140, which it also knows, because commands 136 and 137 have yet to be chosen. The leader could take the next two commands requested by clients to be commands 136 and 137. Instead, we let it fill the gap immediately by proposing, as commands 136 and 137, a special “no- op” command that leaves the state unchanged. (It does this by executing phase 2 of instances 136 and 137 of the consensus algorithm.) Once these no-op commands have been chosen, commands 138–140 can be executed.

take the next two commands requested by clients

special “no- op” command

The second option has been mentioned Why is it legit to use no-op to fill gaps between paxos events.

And My question is about the first one. In my opinion, take the next two commands will violate the consistency, since the instance happened later may be have a smaller sequence number. So why it is still legit?

答:
Since all clients see the same consistent outcome there isn't a violation of consistency. So there isn't a violation of the algorithms invariants.

If you consider the scenario where all the commands come from a single client then it would be a reordering compared to the order the client sent the values. If a single client is multi-threaded and if it streams multiple concurrent requests the reordering may be harmless (or not, depending on the application semantics). If you consider that the leader uses noops then it effectively just drops some messages which may not be harmless to a client that depends on the ordering of values it streams. It depends on the application.

If you consider the scenario where all the values come from different clients then the situation is far more natural. Under averse conditions some reordering occurs. Yet under normal running that doesn't happen. The reordering it just looks like some values "took longer than normal" to be fixed by a leader while later values issued by other clients "ran faster".


问:
How to reduce/optimize memory usage when calculating area of skyline?
I'm trying to calculate the area of skyline (overlapping rectangles with same baseline)

```<code>building_count = int(input())
items = {} # dictionary, location on x axis is the key, height is the value
count = 0 # total area
for j in range(building_count):
    line = input().split(' ')
    H = int(line[0]) # height
    L = int(line[1]) # left point (start of the building)
    R = int(line[2]) # right point (end of the building)
    for k in range(R - L):
        if not (L+k in  items): # if it's not there, add it
            items[L+k] = H
        elif H > items[L+k]: # if we have a higher building on that index
            items[L+k] = H
for value in items.values(): # we add each column basically
    count += value
print(count)
</code>```

sample input would be:

5
3 -3 0
2 -1 1
4 2 4
2 3 7
3 6 8
```

and output is 29.

The issue is memory efficiency, when there are lots of values, the script simply throws MemoryError. Anyone have some ideas for optimizing memory usage?

答:
The reason for getting MemoryError is huge size of the dictionary being created. In the worst case, the dict can have 10^10 keys, which would end up taking all your memory. If there really is a need, shelve is a possible solution to make use of such large dict.

Let's say there is a building with 10 0 100 and another with 20 50 150, then that list might have info like [(-10^9, 0), (0, 10), (50, 20), (150, 0), (10^9, 0)]. As you come across more buildings, you can add more entries in this list. This will be O(n^2).

This might help you further.

Body:
I'm trying to calculate the area of skyline (overlapping rectangles with same baseline)

building_count = int(input())
items = {} # dictionary, location on x axis is the key, height is the value
count = 0 # total area
for j in range(building_count):
    line = input().split(' ')
    H = int(line[0]) # height
    L = int(line[1]) # left point (start of the building)
    R = int(line[2]) # right point (end of the building)
    for k in range(R - L):
        if not (L+k in  items): # if it's not there, add it
            items[L+k] = H
        elif H > items[L+k]: # if we have a higher building on that index
            items[L+k] = H
for value in items.values(): # we add each column basically
    count += value
print(count)

sample input would be:

5
3 -3 0
2 -1 1
4 2 4
2 3 7
3 6 8

and output is 29.

The issue is memory efficiency, when there are lots of values, the script simply throws MemoryError. Anyone have some ideas for optimizing memory usage?


问:
app_remove event in Firebase
I am using Firebase Analytics for my Xamarin Forms mobile app. The Firebase documentation says it can track the event "app_remove" . But I cant find that in firebase events dashboard .

Can someone help !

答: On iOS, when the app is removed by users, users can't go back to the app so that Firebase Analytics can log the app_remove event. In addition, the process is already terminated and there is no way to upload that event even if Analytics can log it. It's nearly impossible to log app_remove events on iOS. </p>

Title: app_remove event in Firebase


问:
Userform ListBox width changes automatically
I've got a UserForm in an Excel VBA project. This form features, amongst other items, two ListBox objects side by side with a couple buttons in between to move items between the lists.

In the form designer, I've drawn the lists exactly where I want them, and both have identical dimensions.

As both ListBoxes have to be multi-column, after retrieving the data from the database, I use a slightly modified version of JKP's ListBox AutoSize code to get the column widths, work out the column count, and finally populate the list with data.

The VBA code snippet performing this task is

```<code>' GetColumnWidths is my modified version of JKP's Autosize code
' vaData is a 2 dimensional variant array containing the data
' LISTBOX_WIDTH is a constant width value (my attempt to stop this behaviour)

With lbxList

    .ColumnWidths = GetColumnWidths(vaData)
    .ColumnCount = UBound(vaData, 2) + 1
    .List = vaData
    .Width = LISTBOX_WIDTH

End With
</code>```

When the form initially loads, the lists are blank until the user makes a selection from a ComboBox. Until they do that, everything looks fine and exactly as intended. When the user makes the selection, things change.

Apologies for my rubbish redacting, but this contains potentially commercially sensitive info, not to mention it's irrelevant for the purposes of this question.

The form looks like this when it loads initiallly:

After the user selects an item from the ComboBox, the lists populate with items. Notice the scroll bars of the right-hand list look slightly stretched and odd.

After the user clicks an item in the right-hand list, the size suddenly changes!

The only way to get the size back to normal is to move an item across to the left-hand list, then back. Once you do that, they stablise and are fine, until you close and open the form again.

For what it's worth, we're using Excel 2010 32-bit.

I've done a bit of testing and it seems that changing the ColumnWidths property affects the Width property, but setting the Width back to what it was originally after that should in theory solve the problem, but it seems only until you actually click on the ListBox.

Now, for my question... does ANYONE know what the heck is going on here? I've had two people look at this and everyone's scratching their heads! This isn't a showstopper or anything, but it's definitely odd enough. I've searched high and low for anything even remotely related to this and couldn't find a thing, so I thought I'd post it here.

To get around it, I added the MouseDown event to each ListBox and force a Width change in there. It doesn't stop it redrawing narrower, but it does reset the width properly.

Thanks!

答:
A counter-intuitive solution that has worked for me:

place the line that establishes the column widths at the end (after
loading the data)

Below an example:

```<code>With Me.ListBox2
  .ColumnCount = 13
  If Not rst.EOF Then
    .Column = rst.GetRows()
    rst.Close
  Else
    rst.Close
    GoTo CleanUp
  End If
  .ColumnWidths = "3 cm;1 cm;1 cm;1 cm;1 cm;1 cm;1 cm;1 cm;1 cm;1 cm;1 cm;1 cm;0 cm"
End With
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've got a UserForm in an Excel VBA project. This form features, amongst other items, two ListBox objects side by side with a couple buttons in between to move items between the lists.

In the form designer, I've drawn the lists exactly where I want them, and both have identical dimensions.

As both ListBoxes have to be multi-column, after retrieving the data from the database, I use a slightly modified version of JKP's ListBox AutoSize code to get the column widths, work out the column count, and finally populate the list with data.

The VBA code snippet performing this task is

' GetColumnWidths is my modified version of JKP's Autosize code
' vaData is a 2 dimensional variant array containing the data
' LISTBOX_WIDTH is a constant width value (my attempt to stop this behaviour)

With lbxList

    .ColumnWidths = GetColumnWidths(vaData)
    .ColumnCount = UBound(vaData, 2) + 1
    .List = vaData
    .Width = LISTBOX_WIDTH

End With

When the form initially loads, the lists are blank until the user makes a selection from a ComboBox. Until they do that, everything looks fine and exactly as intended. When the user makes the selection, things change.

Apologies for my rubbish redacting, but this contains potentially commercially sensitive info, not to mention it's irrelevant for the purposes of this question.

The form looks like this when it loads initiallly:

After the user selects an item from the ComboBox, the lists populate with items. Notice the scroll bars of the right-hand list look slightly stretched and odd.

After the user clicks an item in the right-hand list, the size suddenly changes!

The only way to get the size back to normal is to move an item across to the left-hand list, then back. Once you do that, they stablise and are fine, until you close and open the form again.

For what it's worth, we're using Excel 2010 32-bit.

I've done a bit of testing and it seems that changing the ColumnWidths property affects the Width property, but setting the Width back to what it was originally after that should in theory solve the problem, but it seems only until you actually click on the ListBox.

Now, for my question... does ANYONE know what the heck is going on here? I've had two people look at this and everyone's scratching their heads! This isn't a showstopper or anything, but it's definitely odd enough. I've searched high and low for anything even remotely related to this and couldn't find a thing, so I thought I'd post it here.

To get around it, I added the MouseDown event to each ListBox and force a Width change in there. It doesn't stop it redrawing narrower, but it does reset the width properly.

Thanks!

Body:
A counter-intuitive solution that has worked for me:

place the line that establishes the column widths at the end (after
loading the data)

Below an example:

With Me.ListBox2
  .ColumnCount = 13
  If Not rst.EOF Then
    .Column = rst.GetRows()
    rst.Close
  Else
    rst.Close
    GoTo CleanUp
  End If
  .ColumnWidths = "3 cm;1 cm;1 cm;1 cm;1 cm;1 cm;1 cm;1 cm;1 cm;1 cm;1 cm;1 cm;0 cm"
End With


问:
Getting a select's value with javascript
I have the following condensed form

```<code><form name="thecars">
<select name="cars">
    <option value="mustang">Mustang</option>
    <option value="pinto">Pinto</option>
    <option value="pinto">Chevelle</option>
    <option value="pinto">Other</option>
</select>
</form>
</code>```

I am trying to get the value of the selected car by the following but it is not working

```<code>selectedCar = document.forms["thecars"].elements["cars"].options[thecars.cars.options.selectedIndex].value;
</code>```

答:
You are missing an =. Change this

```<code><form name "thecars">
</code>```

To this

```<code><form name="thecars">
</code>```

Body:
I have the following condensed form

<form name="thecars">
<select name="cars">
    <option value="mustang">Mustang</option>
    <option value="pinto">Pinto</option>
    <option value="pinto">Chevelle</option>
    <option value="pinto">Other</option>
</select>
</form>

I am trying to get the value of the selected car by the following but it is not working

selectedCar = document.forms["thecars"].elements["cars"].options[thecars.cars.options.selectedIndex].value;

Body:
You are missing an =. Change this

<form name "thecars">

To this

<form name="thecars">


问:
Java - How to close RMI Registry?
I'm working on a program that uses RMI. The main process starts RMI Registry and a child process, which creates object and binds it into the registry. The biggest problem I am facing is that I can't close RMI Registry properly. I have found out that I could use

```<code>UnicastRemoteObject.unexportObject(registry, true);
</code>```

Of course, registry is returned by LocateRegistry.createRegistry function. It makes the registry close its port, but java process that runs the registry is still alive.
So the question is: how to close the RMI Registry with its process? Even when I tried to run

```<code>registry = LocateRegistry.createRegistry(1099);
UnicastRemoteObject.unexportObject(registry, true);
</code>```

(what obviously makes no sense), the process still was alive after my program finished.

答: I ran your code in 4 seconds from go to whoa, and the JVM exited. You must have had other non-daemon application threads started. You could do all that and then call System.exit(). If you find that too violent, make sure all your application threads have exited.

Title: Java - How to close RMI Registry?

Body:
I'm working on a program that uses RMI. The main process starts RMI Registry and a child process, which creates object and binds it into the registry. The biggest problem I am facing is that I can't close RMI Registry properly. I have found out that I could use

UnicastRemoteObject.unexportObject(registry, true);

Of course, registry is returned by LocateRegistry.createRegistry function. It makes the registry close its port, but java process that runs the registry is still alive.
So the question is: how to close the RMI Registry with its process? Even when I tried to run

registry = LocateRegistry.createRegistry(1099);
UnicastRemoteObject.unexportObject(registry, true);

(what obviously makes no sense), the process still was alive after my program finished.


问:
How to increase Application cache (appcache) size limit in IE11 and Microsoft Edge on Windows 10?
We ran into a unique sequence of unfortunate events with out web application's offline functionality. It needs about 85MB of content to be stored in browser application cache (HTML5). Before Windows 10 for IE11 it could be set using GPO "Set application cache storage limits for individual domains". But on Windows 10 tablets with 128GB SSD drives having only IE11 and Edge this doesn't work anymore.
It runs into 50 MB limit on the following configuration:

OS: Windows 10 Enterprise - (no problem on win8 and win7)

Browsers: IE11, Edge - (Chrome and Firefox do not have any problems)

Volume size: 128GB or less (with 256GB appCache can go up to 100MB but no further) on C drive, more than half of it is free.

The site (and the domain is included in IE list of trusted sites of course) and uses HTTPS

References:

https://msdn.microsoft.com/en-us/library/mt732551(v=vs.85).aspx

https://learn.microsoft.com/en-us/microsoft-edge/dev-guide/networking-and-connectivity/application-cache

https://technet.microsoft.com/en-us/library/jj891001.aspx

答:
Just got a call from the Microsoft IE developer support team. Turns out Windows 10 is missing some registry settings that are present in prior versions. So to increase app cache limit you have to set following:

For IE:

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Internet Explorer\BrowserStorage\AppCache
```

<p>Key "MaxTrustedDomainLimitInMB" value is size in MD and also may help to set value for the key "TotalLimitInMB"</p></li>
<li><p>For <strong>Edge</strong>: </p>

<pre class="lang-none prettyprint-override"><code>HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppContainer\Storage\microsoft.microsoftedge_8wekyb3d8bbwe\MicrosoftEdge\BrowserStorage\Appcache
</code>```

Same keys and values as for IE above

Body:
Just got a call from the Microsoft IE developer support team. Turns out Windows 10 is missing some registry settings that are present in prior versions. So to increase app cache limit you have to set following:

For IE:

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Internet Explorer\BrowserStorage\AppCache

Key "MaxTrustedDomainLimitInMB" value is size in MD and also may help to set value for the key "TotalLimitInMB"

For Edge:

HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppContainer\Storage\microsoft.microsoftedge_8wekyb3d8bbwe\MicrosoftEdge\BrowserStorage\Appcache

Same keys and values as for IE above


问:
Finding max value using reduce
New to clojure with a java background. I have the following table and need to transform the table to a hash-map that maps products to the city that has the highest sale. For example, the output should look like:

```<code>{"Pencil": "Toronto"
"Bread": "Ottawa"}

(def table [
    {:product "Pencil"
    :city "Toronto"
    :year "2010"
    :sales "2653.00"}
    {:product "Pencil"
    :city "Oshawa"
    :year "2010"
    :sales "525.00"}
    {:product "Bread"
    :city "Toronto"
    :year "2010"
    :sales "136,264.00"}
    {:product "Bread"
    :city "Oshawa"
    :year "nil"
    :sales "242,634.00"}
    {:product "Bread"
    :city "Ottawa"
    :year "2011"
    :sales "426,164.00"}])
</code>```

This is what I have so far:

```<code>(reduce (fn [product-cities {:keys [product sales]}]
         (update-in product-cities [product] (fnil conj []) sales))
       {}
       table)
</code>```

This produces the outcome:

```<code>{"Bread"
["136,264.00"
"242,634.00"
"426,164.00"],
 "Pencil" ["2653.00" "525.00"]}
</code>```

How can i compare the sales of each city and and only keep the name of the city with the highest sales? Having a really tough time with this. Thanks

答:
there is a handy function max-key in clojure.core, that is perfectly suitable for this case:

```<code>(defn process [table]
  (let [parseDouble #(Double/parseDouble (clojure.string/replace % #"," ""))]
    (->> table
         (group-by :product)
         (map (comp (juxt :product :city)
                    (partial apply max-key (comp parseDouble :sales))
                    val))
         (into {}))))

user> (process table)
;;=> {"Pencil" "Toronto", "Bread" "Ottawa"}
</code>```

the key is that (partial apply max-key (comp parseDouble :sales)) part looks for the record in a group, having maximum parsed sales value.

Title: Finding max value using reduce

Body:
New to clojure with a java background. I have the following table and need to transform the table to a hash-map that maps products to the city that has the highest sale. For example, the output should look like:

{"Pencil": "Toronto"
"Bread": "Ottawa"}

(def table [
    {:product "Pencil"
    :city "Toronto"
    :year "2010"
    :sales "2653.00"}
    {:product "Pencil"
    :city "Oshawa"
    :year "2010"
    :sales "525.00"}
    {:product "Bread"
    :city "Toronto"
    :year "2010"
    :sales "136,264.00"}
    {:product "Bread"
    :city "Oshawa"
    :year "nil"
    :sales "242,634.00"}
    {:product "Bread"
    :city "Ottawa"
    :year "2011"
    :sales "426,164.00"}])

This is what I have so far:

(reduce (fn [product-cities {:keys [product sales]}]
         (update-in product-cities [product] (fnil conj []) sales))
       {}
       table)

This produces the outcome:

{"Bread"
["136,264.00"
"242,634.00"
"426,164.00"],
 "Pencil" ["2653.00" "525.00"]}

How can i compare the sales of each city and and only keep the name of the city with the highest sales? Having a really tough time with this. Thanks

Body:
there is a handy function max-key in clojure.core, that is perfectly suitable for this case:

(defn process [table]
  (let [parseDouble #(Double/parseDouble (clojure.string/replace % #"," ""))]
    (->> table
         (group-by :product)
         (map (comp (juxt :product :city)
                    (partial apply max-key (comp parseDouble :sales))
                    val))
         (into {}))))

user> (process table)
;;=> {"Pencil" "Toronto", "Bread" "Ottawa"}

the key is that (partial apply max-key (comp parseDouble :sales)) part looks for the record in a group, having maximum parsed sales value.


问:
HTML pre-load font and use it in css
I'm aware that all of you know, if we do this in our .css file:

```<code>@font-face {
        font-family: "Akrobat-Regular";
        src: url('/assets/Akrobat-Regular.otf') format("truetype");
      }
      body {
        color: #1c1c1c;
        font-family: "Akrobat-Regular" !important;
      }
</code>```

Browser will do additional request to download font, and as a result there will be a short amount of time when default font will be used and then they will be substituted with new downloaded.

I found this way to preload font, but really don't know how top use downloaded font without additional request (don't worry, ti as slim syntax):

```<code>    link rel='preload' href='/assets/Akrobat-Regular.otf' as='font' type='font/otf'

    = stylesheet_link_tag 'application'

    css:
      @font-face {
        font-family: "Akrobat-Regular";
        src: url('/assets/Akrobat-Regular.otf') format("truetype");
      }
      body {
        color: #1c1c1c;
        font-family: "Akrobat-Regular" !important;
      }
</code>```

答:
You can use the pre loaded fonts without creating a font-face as well.

```<code><link rel="preload" href="your_font_file" as="font" type="font/woff" crossorigin="anonymous">
</code>```

Just mention the font family to use it:

```<code>font-family: "your_font";
</code>```

This way you don't need to put an additional request, as you have already loaded the font in your document.

Check the below example:

div.rob {
  font-family: "Roboto";
  font-size: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="preload" href="https://github.com/FontFaceKit/roboto/blob/gh-pages/fonts/Regular/Roboto-Regular.woff" as="font" type="font/woff" crossorigin="anonymous">

<div class="rob">
  Hola in roboto
</div>

<div>
  Normal font
</div></code>```

Title: HTML pre-load font and use it in css

Body:
I'm aware that all of you know, if we do this in our .css file:

@font-face {
        font-family: "Akrobat-Regular";
        src: url('/assets/Akrobat-Regular.otf') format("truetype");
      }
      body {
        color: #1c1c1c;
        font-family: "Akrobat-Regular" !important;
      }

Browser will do additional request to download font, and as a result there will be a short amount of time when default font will be used and then they will be substituted with new downloaded.

I found this way to preload font, but really don't know how top use downloaded font without additional request (don't worry, ti as slim syntax):

    link rel='preload' href='/assets/Akrobat-Regular.otf' as='font' type='font/otf'

    = stylesheet_link_tag 'application'

    css:
      @font-face {
        font-family: "Akrobat-Regular";
        src: url('/assets/Akrobat-Regular.otf') format("truetype");
      }
      body {
        color: #1c1c1c;
        font-family: "Akrobat-Regular" !important;
      }

Body:
You can use the pre loaded fonts without creating a font-face as well.

<link rel="preload" href="your_font_file" as="font" type="font/woff" crossorigin="anonymous">

Just mention the font family to use it:

font-family: "your_font";

This way you don't need to put an additional request, as you have already loaded the font in your document.

Check the below example:

div.rob {
  font-family: "Roboto";
  font-size: 20px;
}

<link rel="preload" href="https://github.com/FontFaceKit/roboto/blob/gh-pages/fonts/Regular/Roboto-Regular.woff" as="font" type="font/woff" crossorigin="anonymous">

<div class="rob">
  Hola in roboto
</div>

<div>
  Normal font
</div>


问:
How to resolve 'cannot find module 'serialport' using Node.js and Johnny-Five?
Main goal: using Johnny-five and node.js to run a script for my Arduino, using LeapMotion Controls

I have a folder with my

1: 'robotarm.js' script

2.the Leapjs 'lib' folder

the 'node_modules' folder in leapjs which has underscore, glmatrix and ws.

I am have uploaded the Standard Firmata on the Arduino Board and I am trying to run my Script to start the program. However when I go to terminal, get inside my proj folder and type node robotarm.js, this is what happens:

```<code> Kriss-MacBook-Pro:armproj Kris$ node robotarm.js

 module.js:340
throw err;
      ^
Error: Cannot find module 'serialport'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Board.Serial.detect (/Users/Kris/node_modules/johnny-five/lib/board.js:69:7)
at new Board (/Users/Kris/node_modules/johnny-five/lib/board.js:299:23)
at Object.<anonymous> (/Users/Kris/Desktop/armproj/robotarm.js:90:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
</code>```

答:
Just add:</p>

```<code>var board = new five.Board({ port: "COM3" });
</code>```

Body:
Main goal: using Johnny-five and node.js to run a script for my Arduino, using LeapMotion Controls

I have a folder with my

1: 'robotarm.js' script

2.the Leapjs 'lib' folder

the 'node_modules' folder in leapjs which has underscore, glmatrix and ws.

I am have uploaded the Standard Firmata on the Arduino Board and I am trying to run my Script to start the program. However when I go to terminal, get inside my proj folder and type node robotarm.js, this is what happens:

 Kriss-MacBook-Pro:armproj Kris$ node robotarm.js

 module.js:340
throw err;
      ^
Error: Cannot find module 'serialport'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Board.Serial.detect (/Users/Kris/node_modules/johnny-five/lib/board.js:69:7)
at new Board (/Users/Kris/node_modules/johnny-five/lib/board.js:299:23)
at Object.<anonymous> (/Users/Kris/Desktop/armproj/robotarm.js:90:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)

Body:
Just add:

var board = new five.Board({ port: "COM3" });


问:
Right align a view RelativeToView in a RelativeLayout
I am trying to align a view in the top right corner of another view in Xamarin.Forms. I believe this has to be possible with a RelativeLayout, but I have not figured out how to do it the right way (in XAML at best).

I have a solution that works for me for one Device, but I'm afraid that this won't port between Idioms/Platforms/Devices. Im my XAML I have defined my image in XAML

```<code><RelativeLayout HorizontalOptions="Fill" VerticalOptions="Fill" x:Name="RelativeLayout">
    <Image Source="http://lorempixel.com/300/300/nature/1/"
           RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=.5, Constant=0}"
           RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=.5, Constant=0}"
           x:Name="Image"/>
</RelativeLayout>
</code>```

In code behind I am creating the badge to add to the image

```<code>Badge badge = new Badge()
{
  Count = 4
}
RelativeLayout.Children.Add(badge,
    Constraint.RelativeToView(Image, (l, v) => v.X + v.Width - 22),
    Constraint.RelativeToView(Image, (l, v) => v.Y));
</code>```

(please do not ask me, where the 22 comes from, this is simple magic at this point, but necessary, since the badge is not layouted, yet and hence has a width of 0). It - kind of - works (see image). But - as stated before - I doubt that this will work on other Idions/Systems.

I would have believed that something like

```<code><RelativeLayout HorizontalOptions="Fill" VerticalOptions="Fill" x:Name="RelativeLayout">
    <Image Source="http://lorempixel.com/300/300/nature/1/"
           RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=.5, Constant=0}"
           RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=.5, Constant=0}"
           x:Name="Image"/>
    <views:Badge Count="4" x:Name="Badge"
                 RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToView, ElementName=Image, Property=Right}"
                 RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView, ElementName=Image, Property=Y}" />
  </RelativeLayout>
</code>```

would work, but there is no Right property and setting the XConstraint to Property=Width, Scale=1.0 does not work either, since the badge will be placed Image.Width on the RelativeLayout.

答:
like an example, Iam placing the view below a searchbar with constraints 0,0
c#

```<code> this._baseLayout.Children.Add(
                mapView,
                Constraint.RelativeToView(autoComplete, (r, v) => v.X),
                Constraint.RelativeToView(autoComplete, (r, v) => autoComplete.HeightOfSearchBar),
                heightConstraint: Constraint.RelativeToParent((r) => r.Height - autoComplete.HeightOfSearchBar),
                widthConstraint: Constraint.RelativeToView(autoComplete, (r, v) => v.Width));
xaml
</code>```

Body:
I am trying to align a view in the top right corner of another view in Xamarin.Forms. I believe this has to be possible with a RelativeLayout, but I have not figured out how to do it the right way (in XAML at best).

I have a solution that works for me for one Device, but I'm afraid that this won't port between Idioms/Platforms/Devices. Im my XAML I have defined my image in XAML

<RelativeLayout HorizontalOptions="Fill" VerticalOptions="Fill" x:Name="RelativeLayout">
    <Image Source="http://lorempixel.com/300/300/nature/1/"
           RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=.5, Constant=0}"
           RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=.5, Constant=0}"
           x:Name="Image"/>
</RelativeLayout>

In code behind I am creating the badge to add to the image

Badge badge = new Badge()
{
  Count = 4
}
RelativeLayout.Children.Add(badge,
    Constraint.RelativeToView(Image, (l, v) => v.X + v.Width - 22),
    Constraint.RelativeToView(Image, (l, v) => v.Y));

(please do not ask me, where the 22 comes from, this is simple magic at this point, but necessary, since the badge is not layouted, yet and hence has a width of 0). It - kind of - works (see image). But - as stated before - I doubt that this will work on other Idions/Systems.

I would have believed that something like

<RelativeLayout HorizontalOptions="Fill" VerticalOptions="Fill" x:Name="RelativeLayout">
    <Image Source="http://lorempixel.com/300/300/nature/1/"
           RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=.5, Constant=0}"
           RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=.5, Constant=0}"
           x:Name="Image"/>
    <views:Badge Count="4" x:Name="Badge"
                 RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToView, ElementName=Image, Property=Right}"
                 RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView, ElementName=Image, Property=Y}" />
  </RelativeLayout>

would work, but there is no Right property and setting the XConstraint to Property=Width, Scale=1.0 does not work either, since the badge will be placed Image.Width on the RelativeLayout.

Body:
like an example, Iam placing the view below a searchbar with constraints 0,0
c#

 this._baseLayout.Children.Add(
                mapView,
                Constraint.RelativeToView(autoComplete, (r, v) => v.X),
                Constraint.RelativeToView(autoComplete, (r, v) => autoComplete.HeightOfSearchBar),
                heightConstraint: Constraint.RelativeToParent((r) => r.Height - autoComplete.HeightOfSearchBar),
                widthConstraint: Constraint.RelativeToView(autoComplete, (r, v) => v.Width));
xaml


问:
Programmatically find Netty port spring boot 2
I would like to know how I can programmatically find the netty port while a spring boot 2 + spring cloud Finchley application is starting up? </p>

<p>I am running the service in a docker container on AWS in EC2 container service - I therefore set server.port=0, and cannot use this property to find the actual port used. </p>

答:
In spring-boot 2 you can use @LocalServerPort to wire the dynamic port used
https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/web/server/LocalServerPort.html

Body:
I would like to know how I can programmatically find the netty port while a spring boot 2 + spring cloud Finchley application is starting up?

I am running the service in a docker container on AWS in EC2 container service - I therefore set server.port=0, and cannot use this property to find the actual port used.


问:
convert row into column in access
I have a dataset in the below format:

```<code> ID   A  B  C  D
 1    x  x  x  x
 2    x  x  x  x
 3    x  x  x  x
 4    x  x  x  x
</code>```

I want to convert it into a format where ID is duplicated with the values of the rows, e.g. to look something like below:

```<code>ID    Letter    Value
1       A         x
1       B         x
1       C         x
1       D         x
2       A         x
2       B         x
2       C         x
2       D         X
</code>```

and so on....

Many thanks in advance.

答:
The UNION statement will allow you to do that:

```<code>SELECT * FROM (
    SELECT [ID], "A" As [Letter], [A] As [Value] FROM [yourTable]
    UNION ALL
    SELECT [ID], "B" As [Letter], [B] As [Value] FROM [yourTable]
    UNION ALL
    SELECT [ID], "C" As [Letter], [C] As [Value] FROM [yourTable]
    UNION ALL
    SELECT [ID], "D" As [Letter], [D] As [Value] FROM [yourTable]
) ORDER BY [ID], [Letter]
</code>```

Title: convert row into column in access

Body:
I have a dataset in the below format:

 ID   A  B  C  D
 1    x  x  x  x
 2    x  x  x  x
 3    x  x  x  x
 4    x  x  x  x

I want to convert it into a format where ID is duplicated with the values of the rows, e.g. to look something like below:

ID    Letter    Value
1       A         x
1       B         x
1       C         x
1       D         x
2       A         x
2       B         x
2       C         x
2       D         X

and so on....

Many thanks in advance.

Body:
The UNION statement will allow you to do that:

SELECT * FROM (
    SELECT [ID], "A" As [Letter], [A] As [Value] FROM [yourTable]
    UNION ALL
    SELECT [ID], "B" As [Letter], [B] As [Value] FROM [yourTable]
    UNION ALL
    SELECT [ID], "C" As [Letter], [C] As [Value] FROM [yourTable]
    UNION ALL
    SELECT [ID], "D" As [Letter], [D] As [Value] FROM [yourTable]
) ORDER BY [ID], [Letter]


问:
How to transfer time from one view controller to another?
in my current project I have implemented a timer on one view.
When I click the button that leads to the next view, I want it to show the time the previous view had at the end.

This is my current code:

```<code>import UIKit

class ViewController2: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var myTableView: UITableView!

@IBOutlet weak var labelMinute: UILabel!
@IBOutlet weak var labelHour: UILabel!
@IBOutlet weak var labelSecond: UILabel!

weak var timer: Timer?
var startTime: Double = 0
var time: Double = 0
var elapsed: Double = 0
var status: Bool = false

var psgTextField: UITextField?
var emTextField: UITextField?

public var passengers2 = [""]

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return passengers2.count
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell2 = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell2")
    cell2.textLabel?.text = passengers2[indexPath.row]

    return (cell2)
}

@objc func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){

    if editingStyle == UITableViewCellEditingStyle.delete {

        let alertController = UIAlertController(title: "Do you really want to leave?",
                                                message: nil,
                                                preferredStyle: .alert)

        alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        alertController.addAction(UIAlertAction(title: "Leave", style: .default, handler: { action in self.passengers2.remove(at: indexPath.row)
            self.myTableView.deleteRows(at: [indexPath], with: .automatic)
        } ))

        self.present(alertController, animated: true)

    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    startTime = Date().timeIntervalSinceReferenceDate - elapsed
    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)

    status = true

}

@objc func updateCounter() {

    // Calculate total time since timer started in seconds
    time = Date().timeIntervalSinceReferenceDate - startTime

    // Calculate minutes
    let minutes = UInt8(time / 60.0)
    time -= (TimeInterval(minutes) * 60)

    // Calculate seconds
    let hours = UInt8(time / 3600)
    time -= TimeInterval(hours)

    let seconds = UInt8(time)
    time -= TimeInterval(seconds)

    // Format time vars with leading zero
    let strMinutes = String(format: "%02d", minutes)
    let strHour = String(format: "%02d", hours)
    let strSecond = String(format: "%02d", seconds)

    // Add time vars to relevant labels
    labelMinute.text = strMinutes
    labelHour.text = strHour
    labelSecond.text = strSecond

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let thirdController = segue.destination as! ViewController3
    thirdController.timeHour.text = labelHour.text

    let fourthController = segue.destination as! ViewController3
    fourthController.timeMinute.text = labelMinute.text
}
}
</code>```

Without the last "override" function, the timer on my first view works perfectly, but for some reason it won't transfer the time to the labels on my second view ("timeHour", "timeMinute").

Xcode gives me the errorThread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0), but the cases I found in the internet were different from mine.

Does someone know where the problem is?

答:
My guess is that your outlets in the destination view controller haven't been connected yet when you try to access them.  Try adding this line of code:

```<code>thirdController.loadViewIfNeeded()
</code>```

Below your existing line of code:

```<code>let thirdController = segue.destination as! ViewController3
</code>```

Body:
in my current project I have implemented a timer on one view.
When I click the button that leads to the next view, I want it to show the time the previous view had at the end.

This is my current code:

import UIKit

class ViewController2: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var myTableView: UITableView!

@IBOutlet weak var labelMinute: UILabel!
@IBOutlet weak var labelHour: UILabel!
@IBOutlet weak var labelSecond: UILabel!

weak var timer: Timer?
var startTime: Double = 0
var time: Double = 0
var elapsed: Double = 0
var status: Bool = false

var psgTextField: UITextField?
var emTextField: UITextField?

public var passengers2 = [""]

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return passengers2.count
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell2 = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell2")
    cell2.textLabel?.text = passengers2[indexPath.row]

    return (cell2)
}

@objc func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){

    if editingStyle == UITableViewCellEditingStyle.delete {

        let alertController = UIAlertController(title: "Do you really want to leave?",
                                                message: nil,
                                                preferredStyle: .alert)

        alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        alertController.addAction(UIAlertAction(title: "Leave", style: .default, handler: { action in self.passengers2.remove(at: indexPath.row)
            self.myTableView.deleteRows(at: [indexPath], with: .automatic)
        } ))

        self.present(alertController, animated: true)

    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    startTime = Date().timeIntervalSinceReferenceDate - elapsed
    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)

    status = true

}

@objc func updateCounter() {

    // Calculate total time since timer started in seconds
    time = Date().timeIntervalSinceReferenceDate - startTime

    // Calculate minutes
    let minutes = UInt8(time / 60.0)
    time -= (TimeInterval(minutes) * 60)

    // Calculate seconds
    let hours = UInt8(time / 3600)
    time -= TimeInterval(hours)

    let seconds = UInt8(time)
    time -= TimeInterval(seconds)

    // Format time vars with leading zero
    let strMinutes = String(format: "%02d", minutes)
    let strHour = String(format: "%02d", hours)
    let strSecond = String(format: "%02d", seconds)

    // Add time vars to relevant labels
    labelMinute.text = strMinutes
    labelHour.text = strHour
    labelSecond.text = strSecond

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let thirdController = segue.destination as! ViewController3
    thirdController.timeHour.text = labelHour.text

    let fourthController = segue.destination as! ViewController3
    fourthController.timeMinute.text = labelMinute.text
}
}

Without the last "override" function, the timer on my first view works perfectly, but for some reason it won't transfer the time to the labels on my second view ("timeHour", "timeMinute").

Xcode gives me the errorThread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0), but the cases I found in the internet were different from mine.

Does someone know where the problem is?

Body:
My guess is that your outlets in the destination view controller haven't been connected yet when you try to access them.  Try adding this line of code:

thirdController.loadViewIfNeeded()

Below your existing line of code:

let thirdController = segue.destination as! ViewController3


问:
How to load data retrieved from Firebase in UIPickerView?
I populate a UIPickerView with data from bookingInfo  and it works as expected. However, I need to add one more row in the UIPickerView and assign it a "default value".
In order to do this in numberOfRowsInComponent I return bookingInfo.count + 1
 The problem is that I get error index out of range in the switch statement. I am not sure if it is because firebase retrieves the data asynchronously.

```<code>class ContactUs: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

var currentUid:String!
var dbRef:FIRDatabaseReference!
var bookingInfo = [FireBaseData]() // this array will hold all bookings for the logged in user
@IBOutlet weak var bookingsPickerView: UIPickerView!

 override func viewDidLoad() {
    super.viewDidLoad()

    bookingsPickerView.delegate = self
    bookingsPickerView.dataSource = self

    guard let uid = FIRAuth.auth()?.currentUser?.uid else {
        return
  }
    self.currentUid = uid
    dbRef = FIRDatabase.database().reference().child("Cleaners")
    startObservingDB() // observe the database for value changes
}//end of viewDidLoad

   func numberOfComponents(in pickerView: UIPickerView) -> Int {
       return 1
  }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return bookingInfo.count + 1 //if I don't add 1 my code will run properly
 }

 func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

    let label = UILabel(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(300), height: CGFloat(37)))

    if bookingInfo.isEmpty == false {

        switch row{
         case 0...bookingInfo.count:
            //Prints index out of range
            let booking = self.bookingInfo[row]
            label.text = String(booking.BookingNumber) + " " + String(booking.DateAndTime)

        default:
            label.text = "default Value"
        }
     }
     return label
   }
}// end of class ContactUs

extension ContactUs {

//observe firebase at a specific reference for values changes
func startObservingDB() {

    dbRef.child(currentUid).child("bookings").observe(.value, with: { (snapshot: FIRDataSnapshot) in

        //instance of FireBaseData holding all bookings under currentUid
        var newBookingInfo = [FireBaseData]()

            //iterate over each booking which is located under 'bookings'
            for booking in snapshot.children {
                var bookingItem = FireBaseData(snapshot: booking as! FIRDataSnapshot)
                newBookingInfo.append(bookingItem)
            }

        //assign newBookingInfo to global variable
        self.bookingInfo = newBookingInfo

   //sort the array in place so that the most recent date will appear first
        self.bookingInfo.sort(by: {(DateAndTimeObject_1,DateAndTimeObject_2) -> Bool in
            DateAndTimeObject_1.TimeStampDateAndTime > DateAndTimeObject_2.TimeStampDateAndTime
        })

        // after Firebase retrieves all bookings, reload the componets in the picker view so that the methods belonging to protocol UIPickerViewDelegate will be called
        self.bookingsPickerView.reloadAllComponents()
    }, withCancel: { (Error:Any) in
        print("Error firebase \(Error)")
    })
 } // end of startObservingDB()

}//end of extension
</code>```

Update

Thanks to @livtay my code works. How can I have "Other" value show on the first row when bookingInfo array is not empty rather than on the last row as it shows now?

   My progress so far.

```<code>   func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

    let label = UILabel(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(300), height: CGFloat(37)))
        label.textAlignment = .left

    if bookingInfo.isEmpty == true {
         label.text = "Other"
         self.pickerViewTitle = "Other"

        } else {

        switch row{
          case 0...bookingInfo.count - 1:
              let booking = self.bookingInfo[row]
              self.pickerViewTitle = String(booking.BookingNumber) + " " + String(booking.DateAndTime)
              label.text = self.pickerViewTitle

        default:
            label.text = "Other"
             self.pickerViewTitle = "Other"
        }
    }
    return label
}
</code>```

答:
Try changing

```<code>case 0...bookingInfo.count:
</code>```

to

```<code>case 0...bookingInfo.count - 1:
</code>```

because the array is including 0 in its count.
For example, if the array has 1 object, you'll be counting 0...1, but the only index in the array is 0.

EDIT: For second part of question:

In your switch statement put the code in your default case under

```<code>case 0:
</code>```

and then the rest under

```<code>case 1...bookingInfo.count:
</code>```

and you're going to want to change the logic to:

```<code>let booking = self.bookingInfo[row - 1]
</code>```

Body:
I populate a UIPickerView with data from bookingInfo  and it works as expected. However, I need to add one more row in the UIPickerView and assign it a "default value".
In order to do this in numberOfRowsInComponent I return bookingInfo.count + 1
 The problem is that I get error index out of range in the switch statement. I am not sure if it is because firebase retrieves the data asynchronously.

class ContactUs: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

var currentUid:String!
var dbRef:FIRDatabaseReference!
var bookingInfo = [FireBaseData]() // this array will hold all bookings for the logged in user
@IBOutlet weak var bookingsPickerView: UIPickerView!

 override func viewDidLoad() {
    super.viewDidLoad()

    bookingsPickerView.delegate = self
    bookingsPickerView.dataSource = self

    guard let uid = FIRAuth.auth()?.currentUser?.uid else {
        return
  }
    self.currentUid = uid
    dbRef = FIRDatabase.database().reference().child("Cleaners")
    startObservingDB() // observe the database for value changes
}//end of viewDidLoad

   func numberOfComponents(in pickerView: UIPickerView) -> Int {
       return 1
  }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return bookingInfo.count + 1 //if I don't add 1 my code will run properly
 }

 func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

    let label = UILabel(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(300), height: CGFloat(37)))

    if bookingInfo.isEmpty == false {

        switch row{
         case 0...bookingInfo.count:
            //Prints index out of range
            let booking = self.bookingInfo[row]
            label.text = String(booking.BookingNumber) + " " + String(booking.DateAndTime)

        default:
            label.text = "default Value"
        }
     }
     return label
   }
}// end of class ContactUs

extension ContactUs {

//observe firebase at a specific reference for values changes
func startObservingDB() {

    dbRef.child(currentUid).child("bookings").observe(.value, with: { (snapshot: FIRDataSnapshot) in

        //instance of FireBaseData holding all bookings under currentUid
        var newBookingInfo = [FireBaseData]()

            //iterate over each booking which is located under 'bookings'
            for booking in snapshot.children {
                var bookingItem = FireBaseData(snapshot: booking as! FIRDataSnapshot)
                newBookingInfo.append(bookingItem)
            }

        //assign newBookingInfo to global variable
        self.bookingInfo = newBookingInfo

   //sort the array in place so that the most recent date will appear first
        self.bookingInfo.sort(by: {(DateAndTimeObject_1,DateAndTimeObject_2) -> Bool in
            DateAndTimeObject_1.TimeStampDateAndTime > DateAndTimeObject_2.TimeStampDateAndTime
        })

        // after Firebase retrieves all bookings, reload the componets in the picker view so that the methods belonging to protocol UIPickerViewDelegate will be called
        self.bookingsPickerView.reloadAllComponents()
    }, withCancel: { (Error:Any) in
        print("Error firebase \(Error)")
    })
 } // end of startObservingDB()

}//end of extension

Update

Thanks to @livtay my code works. How can I have "Other" value show on the first row when bookingInfo array is not empty rather than on the last row as it shows now?

   My progress so far.

   func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

    let label = UILabel(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(300), height: CGFloat(37)))
        label.textAlignment = .left

    if bookingInfo.isEmpty == true {
         label.text = "Other"
         self.pickerViewTitle = "Other"

        } else {

        switch row{
          case 0...bookingInfo.count - 1:
              let booking = self.bookingInfo[row]
              self.pickerViewTitle = String(booking.BookingNumber) + " " + String(booking.DateAndTime)
              label.text = self.pickerViewTitle

        default:
            label.text = "Other"
             self.pickerViewTitle = "Other"
        }
    }
    return label
}

Body:
Try changing

case 0...bookingInfo.count:

to

case 0...bookingInfo.count - 1:

because the array is including 0 in its count.
For example, if the array has 1 object, you'll be counting 0...1, but the only index in the array is 0.

EDIT: For second part of question:

In your switch statement put the code in your default case under

case 0:

and then the rest under

case 1...bookingInfo.count:

and you're going to want to change the logic to:

let booking = self.bookingInfo[row - 1]


问:
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference: fab
I'm trying to create a floatingactionbutton with a listener to open a new view.

```<code>public class ConnectionMenu extends AppCompatActivity {
ConnectionManager conn = new ConnectionManager();
CredentialManager cred = new CredentialManager();
FloatingActionButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_connection_menu);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    final EditText field1 = findViewById(R.id.editText);
    final EditText field2 = findViewById(R.id.editText2);
    final EditText field3 = findViewById(R.id.editText3);

    FloatingActionButton fab = findViewById(R.id.fab);
    Button button = findViewById(R.id.button2);
    final Spinner spinner = findViewById(R.id.spinner);
    final Intent intent = new Intent(this, CredentialMenu.class);
    Object[] credentials = cred.getAllnames();

    ArrayAdapter<Object> adapter = new ArrayAdapter<>(this,
            android.R.layout.simple_spinner_item, R.id.spinner, credentials);
    spinner.setAdapter(adapter);
    fab.setOnClickListener(new View.OnClickListener() { //fails here!!!!
        @Override
        public void onClick(View view) {
            startActivity(intent);
        }
</code>```

But the exception in the title is throwed. The structure of my xml files is:

activity_connection_menu.xml:

```<code><?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="net.ddns.andrewnetwork.raspberrymonitor.View.ConnectionMenu">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_connection_menu" />
</code>```

content_connection_menu.xml

```<code>...
        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="match_parent"
            android:layout_height="84dp"
            android:layout_marginLeft="32dp"
            android:layout_marginStart="32dp"
            android:layout_weight="1"
            android:clickable="true"
            android:focusable="true"
            app:backgroundTint="@color/colorPrimaryDark"
            app:srcCompat="@android:drawable/ic_menu_add" />

    </LinearLayout>

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:layout_marginTop="40dp"
        android:layout_weight="1"
        android:text="@string/button1"
        app:layout_constraintEnd_toEndOf="parent"
        tools:layout_editor_absoluteY="206dp" />

</LinearLayout>
</code>```

Seems like that the fab variable is instantiated but actually null in its contents. Any ideas?

答:
Either post your complete error.
Or there is at least one TextView which you have not initialized but used somewhere in code (MOST LIKELY AT THE INDICATED LINE OF THE ERROR)
find that text view and initialize it ie </p>

```<code>tv = (TextView) findViewById(R.id.yourID);
</code>```

Body:
I'm trying to create a floatingactionbutton with a listener to open a new view.

public class ConnectionMenu extends AppCompatActivity {
ConnectionManager conn = new ConnectionManager();
CredentialManager cred = new CredentialManager();
FloatingActionButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_connection_menu);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    final EditText field1 = findViewById(R.id.editText);
    final EditText field2 = findViewById(R.id.editText2);
    final EditText field3 = findViewById(R.id.editText3);

    FloatingActionButton fab = findViewById(R.id.fab);
    Button button = findViewById(R.id.button2);
    final Spinner spinner = findViewById(R.id.spinner);
    final Intent intent = new Intent(this, CredentialMenu.class);
    Object[] credentials = cred.getAllnames();

    ArrayAdapter<Object> adapter = new ArrayAdapter<>(this,
            android.R.layout.simple_spinner_item, R.id.spinner, credentials);
    spinner.setAdapter(adapter);
    fab.setOnClickListener(new View.OnClickListener() { //fails here!!!!
        @Override
        public void onClick(View view) {
            startActivity(intent);
        }

But the exception in the title is throwed. The structure of my xml files is:

activity_connection_menu.xml:

<?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="net.ddns.andrewnetwork.raspberrymonitor.View.ConnectionMenu">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_connection_menu" />

content_connection_menu.xml

...
        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="match_parent"
            android:layout_height="84dp"
            android:layout_marginLeft="32dp"
            android:layout_marginStart="32dp"
            android:layout_weight="1"
            android:clickable="true"
            android:focusable="true"
            app:backgroundTint="@color/colorPrimaryDark"
            app:srcCompat="@android:drawable/ic_menu_add" />

    </LinearLayout>

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:layout_marginTop="40dp"
        android:layout_weight="1"
        android:text="@string/button1"
        app:layout_constraintEnd_toEndOf="parent"
        tools:layout_editor_absoluteY="206dp" />

</LinearLayout>

Seems like that the fab variable is instantiated but actually null in its contents. Any ideas?

Body:
Either post your complete error.
Or there is at least one TextView which you have not initialized but used somewhere in code (MOST LIKELY AT THE INDICATED LINE OF THE ERROR)
find that text view and initialize it ie

tv = (TextView) findViewById(R.id.yourID);


问:
Session IDs Growing Very Large Randomly
We have a table and logging mechanism that logs customers that log in with a Session ID. However, one thing we notice is that sometimes the Session ID information tends to grow quite large growing beyond a 255 character ID. How can we stop it from doing this?</p>

答:
This page seems to discuss the subject http://forums.asp.net/p/1264093/2370866.aspx

It seems you need to make your own session manager

Title: Session IDs Growing Very Large Randomly


问:
Trigger that prevent adding new rows if ID number is too high
I have table "Months" with 12 rows(obviously) and I want to add a trigger that prevent adding new row if ID number is over 12

```<code>CREATE TRIGGER "no_more_months" BEFORE INSERT ON "months"
 FOR EACH ROW BEGIN
IF NEW.ID_Month>12 THEN
SIGNAL SQLSTATE '12345'
SET MESSAGE_TEXT = 'check constraint on Months failed';
END IF;
END;
</code>```

But somehow it doesn't work and still adds new rows

答:
As said in the comment section, just a constraint should do the job.

```<code>ALTER TABLE [dbo].[Months]
    ADD CONSTRAINT CK_Months_ID_Months CHECK ([ID_Months] <= 12 AND [ID_Months] > 0);
</code>```

If you absolutely need a custom error message look at this article : MySql Signals

Body:
I have table "Months" with 12 rows(obviously) and I want to add a trigger that prevent adding new row if ID number is over 12

CREATE TRIGGER "no_more_months" BEFORE INSERT ON "months"
 FOR EACH ROW BEGIN
IF NEW.ID_Month>12 THEN
SIGNAL SQLSTATE '12345'
SET MESSAGE_TEXT = 'check constraint on Months failed';
END IF;
END;

But somehow it doesn't work and still adds new rows

Body:
As said in the comment section, just a constraint should do the job.

ALTER TABLE [dbo].[Months]
    ADD CONSTRAINT CK_Months_ID_Months CHECK ([ID_Months] <= 12 AND [ID_Months] > 0);

If you absolutely need a custom error message look at this article : MySql Signals


问:
what is the recommended way for using the Kotlin double-bang for nullable class member
In kotlin if the variable is nullable the kotlin will ask for either using !! or check the null before using it.
In the case of having nullable class member, inside the class anywhere refereeing this member kotlin will warn for checking the nullable.

```<code>class ClassWithNullableMemebr {
      Var nullableMember: OtherClass? = null;

      constructor (obj: OtherClass) {
          nullableMember = obj
      }
      fun foo() {
          nullableMember!!.doSomething()
      }
      fun getTheOtherClassMember : OtherClass {
          return nullableMember!!
      }
 }
</code>```

If the nullableMember is guaranteed to initialized in constructor, how to avoid the use of !!.

In Java or other language they could check null once and throw if by design the member should never be null. Then inside the class the member will be just be referenced without worry.

Someone suggested do

```<code>if (nullableMember != null) {
    nullableMember!!.doSomething()
}
</code>```

This will still need the !! even after the check, and it makes the code looks not pretty.

For this case really using ?. is not much different than using !! since the nullableMember is assigned in the constructor, and the function return it can not avoid the !!.

I think if this nullableMember is guaranteed not null after instantiate the class the using !! shouldn't be considered to be bad coding style. And there is no other way to avoid it.

Does anyone have suggestion to avoid the use of '!!' in the case like this?

答:
If you are sure that variable will have not-null value, you should define it as not-nullable.

After this, there are two ways to avoid compiler warning and in sight variable initialization:

Usage of lateinit modifier

lateinit var nullableMember: OtherClass

Please note if you try to access this variable before its initialization, exception will be thrown

Usage of notNull() delegate

var nullableMember: OtherClass by Delegates.notNull()

Differences between these two you can find here.

If there is a need to set the value of this variable to null somewhere in the code, I am afraid that you'll have to use !! because there is no nicer way of doing this.

Body:
In kotlin if the variable is nullable the kotlin will ask for either using !! or check the null before using it.
In the case of having nullable class member, inside the class anywhere refereeing this member kotlin will warn for checking the nullable.

class ClassWithNullableMemebr {
      Var nullableMember: OtherClass? = null;

      constructor (obj: OtherClass) {
          nullableMember = obj
      }
      fun foo() {
          nullableMember!!.doSomething()
      }
      fun getTheOtherClassMember : OtherClass {
          return nullableMember!!
      }
 }

If the nullableMember is guaranteed to initialized in constructor, how to avoid the use of !!.

In Java or other language they could check null once and throw if by design the member should never be null. Then inside the class the member will be just be referenced without worry.

Someone suggested do

if (nullableMember != null) {
    nullableMember!!.doSomething()
}

This will still need the !! even after the check, and it makes the code looks not pretty.

For this case really using ?. is not much different than using !! since the nullableMember is assigned in the constructor, and the function return it can not avoid the !!.

I think if this nullableMember is guaranteed not null after instantiate the class the using !! shouldn't be considered to be bad coding style. And there is no other way to avoid it.

Does anyone have suggestion to avoid the use of '!!' in the case like this?


问:
Validation pattern for date in DD/MM/YYYY format using angular2
How to add validation pattern for Date in DD/MM/YYYY format using angular2 Validator.pattern.

I have the "required" validator in place. Cannot find one for date pattern. Code as below:

```<code>this.txtDob = new Control("", Validators.compose([Validators.required]));
</code>```

答:
You can also create a service( not mandatory, i.e the following could easily be changed to a regular function ) as follows:</p>

```<code>import { Injectable } from '@angular/core';
import { FormControl } from '@angular/forms';

    interface Validator<T extends FormControl> {
      (c: T): { [error: string]: any };
    }

    @Injectable()
    export class DateValidatorClass {

      constructor() { }
      dateValidator(c: FormControl) {

        const dateRegEx = new RegExp(yourRegExInHere);;

        return c.value.test(dateRegEx) ? null : {
          dateValidator: {
            valid: false
          }
    };
  }
}
</code>```

Body:
How to add validation pattern for Date in DD/MM/YYYY format using angular2 Validator.pattern.

I have the "required" validator in place. Cannot find one for date pattern. Code as below:

this.txtDob = new Control("", Validators.compose([Validators.required]));

Body:
You can also create a service( not mandatory, i.e the following could easily be changed to a regular function ) as follows:

import { Injectable } from '@angular/core';
import { FormControl } from '@angular/forms';

    interface Validator<T extends FormControl> {
      (c: T): { [error: string]: any };
    }

    @Injectable()
    export class DateValidatorClass {

      constructor() { }
      dateValidator(c: FormControl) {

        const dateRegEx = new RegExp(yourRegExInHere);;

        return c.value.test(dateRegEx) ? null : {
          dateValidator: {
            valid: false
          }
    };
  }
}


问:
Filter a legend Item with Chartjs.org V2.7
I am building a series of doughnut charts and I would like to remove the second item in the legend, so when I generate the legend with the generateLegend() method I just want to get the first value.

In the documentation there is an option that reads

Filters legend items out of the legend. Receives 2 parameters, a Legend Item and the chart data

But I can't find an example how to use it. In this Pen you can see the 2 labels in the middle, I just want to show the first label. I tried different approaches with no success. Just deleting the item doesn't work for me because the
 item still there. Here's the code I am using.

```<code>$id = function(id) {
  return document.getElementById(id);
};

var langDataEs = {
  type: "doughnut",
  data: {
    datasets: [
      {
        data: [75, 25],
        backgroundColor: ["#8dc63f", "#1d1d1d"]
      }
    ],
    labels: ["es", "learning"]
  },
  options: {
    legend: {
      display: false,
      /* I would like to remove the item "learning" */
      filter: function() {

      },
    },
    responsive: true
  }
};

langChartEs = new Chart($id("langEs").getContext("2d"), langDataEs);
$id("es").innerHTML = langChartEs.generateLegend();
</code>```

Thanks in advance for any pointers.

答:
The filter function works exactly like the Javascript's native Array.prototype.filter. So just return true if you want to show the legend at a particular index.

EDIT: The filter function would come inside the labels field.

```<code> legend: {
      display: true,
      labels: {
           filter: function(legendItem, data) {
                return legendItem.index != 1
           }
      }
 }
</code>```

Body:
I am building a series of doughnut charts and I would like to remove the second item in the legend, so when I generate the legend with the generateLegend() method I just want to get the first value.

In the documentation there is an option that reads

Filters legend items out of the legend. Receives 2 parameters, a Legend Item and the chart data

But I can't find an example how to use it. In this Pen you can see the 2 labels in the middle, I just want to show the first label. I tried different approaches with no success. Just deleting the item doesn't work for me because the
 item still there. Here's the code I am using.

$id = function(id) {
  return document.getElementById(id);
};

var langDataEs = {
  type: "doughnut",
  data: {
    datasets: [
      {
        data: [75, 25],
        backgroundColor: ["#8dc63f", "#1d1d1d"]
      }
    ],
    labels: ["es", "learning"]
  },
  options: {
    legend: {
      display: false,
      /* I would like to remove the item "learning" */
      filter: function() {

      },
    },
    responsive: true
  }
};

langChartEs = new Chart($id("langEs").getContext("2d"), langDataEs);
$id("es").innerHTML = langChartEs.generateLegend();

Thanks in advance for any pointers.

Body:
The filter function works exactly like the Javascript's native Array.prototype.filter. So just return true if you want to show the legend at a particular index.

EDIT: The filter function would come inside the labels field.

 legend: {
      display: true,
      labels: {
           filter: function(legendItem, data) {
                return legendItem.index != 1
           }
      }
 }


问:
What should I do with stopped, dead, threads? Alive == False
I spawned some threads using ThreadStart and a few of them died for various reasons (the work is complete, or there was an error)

Since I still have a reference to this thread, what should I do do complete the termination of this object?  What can I do to restart it?

答:
You don't need to do anything to complete the termination.

You can't restart a thread which has finished - but you could create a new thread to do the same task, assuming you know what that task was.


问:
Reducing nested promises
I am reducing an array of nested promises in the following way:

```<code>const promises = items.map((item, index) => {
    console.log(index);

    return doAsyncThing(item).then(() => {
       console.log(index);
    });
});

return promises.reduce((acc, p) => acc.then(() => p), Promise.resolve());
</code>```

I want the console.log entries to print out

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

but instead they are printing out

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

How can I restructure my code so that the entirety of operation 0 is completed before operation 1, which is completed before option 2, etc...?

答:
The Problem

The problem with your implementation is that all of the promises are created at the same time, and that will cause them to place their asynchronous actions in the event queue at that time. In your case, this is happening in the map function. Let's walk through this.

```<code>// your current code
const promises = items.map((item, index) => {
  console.log(index);       // this happens immediately and waits for nothing, which is why you see `0  1  2` in the console

  return doAsyncThing(item) // right here the async action is created
    .then(() => {           // this will run as soon as the async action is finished
      console.log(index);
    });
});
</code>```

After this step, promises is already an array of promises, all of which have already queued up their asynchronous actions, not waiting for any others to be completed.

Solution

You have the right idea with the reduce, but by the time your reduce runs, all of the promises are already created, and will run in whatever order they finish. If you want to enforce order, you will need to use the reduce to create the promises initially:

```<code>const promises = items.reduce((acc, item, index) => {
  console.log(index) // still runs immediately
  return acc
    .then(() => doAsyncThing(item)) // creates the promise after acc finishes
    .then(() => console.log(index));    // runs after doAsyncThing finishes
}, Promise.resolve());
</code>```

This will produce the output 0  1  2  0  1  2 in your console, but action 1 will still not be run until action 0 finishes, and action 2 will not be run until action 1 finishes. I hope this helps!

Title: Reducing nested promises

Body:
I am reducing an array of nested promises in the following way:

const promises = items.map((item, index) => {
    console.log(index);

    return doAsyncThing(item).then(() => {
       console.log(index);
    });
});

return promises.reduce((acc, p) => acc.then(() => p), Promise.resolve());

I want the console.log entries to print out

0 0 1 1 2 2

but instead they are printing out

0 1 2 2 1 0

How can I restructure my code so that the entirety of operation 0 is completed before operation 1, which is completed before option 2, etc...?

Body:
The Problem

The problem with your implementation is that all of the promises are created at the same time, and that will cause them to place their asynchronous actions in the event queue at that time. In your case, this is happening in the map function. Let's walk through this.

// your current code
const promises = items.map((item, index) => {
  console.log(index);       // this happens immediately and waits for nothing, which is why you see `0  1  2` in the console

  return doAsyncThing(item) // right here the async action is created
    .then(() => {           // this will run as soon as the async action is finished
      console.log(index);
    });
});

After this step, promises is already an array of promises, all of which have already queued up their asynchronous actions, not waiting for any others to be completed.

Solution

You have the right idea with the reduce, but by the time your reduce runs, all of the promises are already created, and will run in whatever order they finish. If you want to enforce order, you will need to use the reduce to create the promises initially:

const promises = items.reduce((acc, item, index) => {
  console.log(index) // still runs immediately
  return acc
    .then(() => doAsyncThing(item)) // creates the promise after acc finishes
    .then(() => console.log(index));    // runs after doAsyncThing finishes
}, Promise.resolve());

This will produce the output 0  1  2  0  1  2 in your console, but action 1 will still not be run until action 0 finishes, and action 2 will not be run until action 1 finishes. I hope this helps!


问:
I want to output a list of every Case_Number with Code 1 that has a higher UniqueID value than its Code 2 counterpart's UniqueID value
I have a table which looks something like this:

```<code>    Case_Number  |  Code  |  UniqueID
        a             1       1372
        a             2       1352
        a             3       1325
        b             1       1642
        b             2       1651
        b             3       1623
        c             1       1743
        c             2       1739
        c             3       1720
       ...           ...        ...
</code>```

From this database I want to output a list of every Case_Number where the UniqueID value of Code 1 is higher than the UniqueID value of Code 2 (But ignoring the UniqueID value of Code 2, or any other Code x that might be in the table). Meaning that if the UniqueID value of Code 2 is higher than Code 1, which is the case with Case_Number b in the example above, it should not show up in the list.

So, querying the above table would result in this:

```<code>    Case_Number  |  Code  |  UniqueID
        a             1       1372
        c             1       1743
</code>```

答:
The query below gives you the expected result

```<code>CREATE TABLE CaseTab
(Case_Number VARCHAR(10),
 Code        INT,
 UniqueID    INT);

INSERT INTO CaseTab VALUES ('a',             1,       1372);
INSERT INTO CaseTab VALUES ('a',             2,       1352);
INSERT INTO CaseTab VALUES ('a',             3,       1325);
INSERT INTO CaseTab VALUES ('b',             1,       1642);
INSERT INTO CaseTab VALUES ('b',             2,       1651);
INSERT INTO CaseTab VALUES ('b',             3,       1623);
INSERT INTO CaseTab VALUES ('c',             1,       1743);
INSERT INTO CaseTab VALUES ('c',             2,       1739);
INSERT INTO CaseTab VALUES ('c',             3,       1720);

WITH v_code_gt_1 AS
(SELECT Case_Number, MAX(UniqueID) AS UniqueID
   FROM CaseTab
  WHERE Code > 1
  GROUP BY Case_Number)
SELECT c1.Case_Number, c1.UniqueID
  FROM CaseTab c1 JOIN
       v_code_gt_1 c2
       ON (c1.Case_Number = c2.Case_Number)
 WHERE c1.UniqueID > c2.UniqueID
   AND c1.Code = 1;
</code>```

Basically the query gets the max UniqueID for all cases where code is greater than 1 and compares against the Unique ID for Code 1.

You haven't stated whether there can be cases with code = 1, but no other codes. If so, use LEFT JOIN as below.

```<code>WITH v_code_gt_1 AS
(SELECT Case_Number, MAX(UniqueID) AS UniqueID
   FROM CaseTab
  WHERE Code > 1
  GROUP BY Case_Number)
SELECT c1.Case_Number, c1.UniqueID
  FROM CaseTab c1 LEFT JOIN
       v_code_gt_1 c2
       ON (c1.Case_Number = c2.Case_Number)
 WHERE c1.UniqueID > ISNULL(c2.UniqueID, 0)
   AND c1.Code = 1;
</code>```

Body:
I have a table which looks something like this:

    Case_Number  |  Code  |  UniqueID
        a             1       1372
        a             2       1352
        a             3       1325
        b             1       1642
        b             2       1651
        b             3       1623
        c             1       1743
        c             2       1739
        c             3       1720
       ...           ...        ...

From this database I want to output a list of every Case_Number where the UniqueID value of Code 1 is higher than the UniqueID value of Code 2 (But ignoring the UniqueID value of Code 2, or any other Code x that might be in the table). Meaning that if the UniqueID value of Code 2 is higher than Code 1, which is the case with Case_Number b in the example above, it should not show up in the list.

So, querying the above table would result in this:

    Case_Number  |  Code  |  UniqueID
        a             1       1372
        c             1       1743

Body:
The query below gives you the expected result

CREATE TABLE CaseTab
(Case_Number VARCHAR(10),
 Code        INT,
 UniqueID    INT);

INSERT INTO CaseTab VALUES ('a',             1,       1372);
INSERT INTO CaseTab VALUES ('a',             2,       1352);
INSERT INTO CaseTab VALUES ('a',             3,       1325);
INSERT INTO CaseTab VALUES ('b',             1,       1642);
INSERT INTO CaseTab VALUES ('b',             2,       1651);
INSERT INTO CaseTab VALUES ('b',             3,       1623);
INSERT INTO CaseTab VALUES ('c',             1,       1743);
INSERT INTO CaseTab VALUES ('c',             2,       1739);
INSERT INTO CaseTab VALUES ('c',             3,       1720);

WITH v_code_gt_1 AS
(SELECT Case_Number, MAX(UniqueID) AS UniqueID
   FROM CaseTab
  WHERE Code > 1
  GROUP BY Case_Number)
SELECT c1.Case_Number, c1.UniqueID
  FROM CaseTab c1 JOIN
       v_code_gt_1 c2
       ON (c1.Case_Number = c2.Case_Number)
 WHERE c1.UniqueID > c2.UniqueID
   AND c1.Code = 1;

Basically the query gets the max UniqueID for all cases where code is greater than 1 and compares against the Unique ID for Code 1.

You haven't stated whether there can be cases with code = 1, but no other codes. If so, use LEFT JOIN as below.

WITH v_code_gt_1 AS
(SELECT Case_Number, MAX(UniqueID) AS UniqueID
   FROM CaseTab
  WHERE Code > 1
  GROUP BY Case_Number)
SELECT c1.Case_Number, c1.UniqueID
  FROM CaseTab c1 LEFT JOIN
       v_code_gt_1 c2
       ON (c1.Case_Number = c2.Case_Number)
 WHERE c1.UniqueID > ISNULL(c2.UniqueID, 0)
   AND c1.Code = 1;