问:
addClass to every div with data-attribute tag
How can I add CSS classes like widget-00, widget-01 etc. to each of these divs via jQuery?

```<code><div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="00">
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="01">
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="02">
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="03">
</code>```

答:
the s do have closing tags, i didnt post it here.

I have tried now both snippets from you, but none of it worked unfortunately.
Personally i like the version by "Cornel Raiu" better, because there are many more  with class .mdl-form which i did not tell you (but should not be affected).

Is it possible that jQuery isn't doing anything?
I also tried some very simple stuff with no result, like:

```<code>    $(document).ready(function(){
        $( "body" ).prepend( "<p>Test</p>" );
    });
</code>```

jQuery is embeded via

```<code><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</code>```

Browser console is not logging any errors.
Maybe it is because i want to add it to an openHAB sitemap, maybe there is some restriction to it?

Body:
the s do have closing tags, i didnt post it here.

I have tried now both snippets from you, but none of it worked unfortunately.
Personally i like the version by "Cornel Raiu" better, because there are many more  with class .mdl-form which i did not tell you (but should not be affected).

Is it possible that jQuery isn't doing anything?
I also tried some very simple stuff with no result, like:

    $(document).ready(function(){
        $( "body" ).prepend( "<p>Test</p>" );
    });

jQuery is embeded via

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

Browser console is not logging any errors.
Maybe it is because i want to add it to an openHAB sitemap, maybe there is some restriction to it?


来源: stackexchange

问:
How can I assign a factor in a new variable based on whether a given string is contained in another variable (R)?
Using the European Social Survey (ESS) I am trying to clean up my data in RStudio. I used paste() to combine three separate columns, prtvtDK/prtvtNO/prtvtSE (party voted for in most recent election, Denmark/Norway/Sweden respectively) into one, fullprtvt, which has about 38000 individual cases across 8 waves.

What I want to do is assign each individual a factor of either "Populist" or "Nonpopulist" depending on which party they voted for at the last election. In their data-gathering, the party names changed a few waves in so there are multiple names for the same party, but I have a list of the ones used for the populist parties that I list below:

'Dansk Folkeparti'

'Dansk Folkeparti - Danish peoples party'

'Sverigedemokraterna'

'Progress Party (FrP)'

'Progress Party (FRP)'

Essentially, I want anyone who voted for one of the above parties to be classified as "Populist" in the new variable. I was thinking that some kind of ifelse() function or if else statement could work, but reading through other posts I saw people suggesting using the switch() function instead. What's the best way to tackle this problem?

答:
You can use grep to identify common strings in the populist-labelled parties.

Here, I am assuming your data frame is called df and that fullprtvt is a column in that data frame. You'll need to ensure it is a character column. If not, you can alter df$fullprtvt to as.character(df$fullprtvt) in the following:

```<code>pop <- grep('Dansk Folkeparti|Sverigedemokraterna|Progress Party', df$fullprtvt)
df$pop_nonpop <- rep("Non-populist", nrow(df))
df$pop_nonpop[pop] <- "Populist"
</code>```

Here's a reproducible example of some dummy data:

set.seed(69)
df <- data.frame(fullprtvt = sample(c('Dansk Folkeparti',
                                      'Dansk Folkeparti - Danish peoples party',
                                      'Sverigedemokraterna',
                                      'Progress Party (FrP)',
                                      'Progress Party (FRP)',
                                      'Moderate party',
                                      'Communist',
                                      'Socialist',
                                      'Democrat'), 10, TRUE))

df
#>                                  fullprtvt
#> 1                         Dansk Folkeparti
#> 2  Dansk Folkeparti - Danish peoples party
#> 3                                Socialist
#> 4                                Communist
#> 5                                Communist
#> 6                           Moderate party
#> 7                                Communist
#> 8  Dansk Folkeparti - Danish peoples party
#> 9                     Progress Party (FrP)
#> 10 Dansk Folkeparti - Danish peoples party
```

<p>And how the above code would work:</p>

```pop <- grep('Dansk Folkeparti|Sverigedemokraterna|Progress Party', df$fullprtvt)
df$pop_nonpop <- rep("Non-populist", nrow(df))
df$pop_nonpop[pop] <- "Populist"

df
#>                                  fullprtvt   pop_nonpop
#> 1                         Dansk Folkeparti     Populist
#> 2  Dansk Folkeparti - Danish peoples party     Populist
#> 3                                Socialist Non-populist
#> 4                                Communist Non-populist
#> 5                                Communist Non-populist
#> 6                           Moderate party Non-populist
#> 7                                Communist Non-populist
#> 8  Dansk Folkeparti - Danish peoples party     Populist
#> 9                     Progress Party (FrP)     Populist
#> 10 Dansk Folkeparti - Danish peoples party     Populist
```

Created on 2020-02-20 by the reprex package (v0.3.0)

ContentLicense: CC BY-SA 4.0

Body:
You can use grep to identify common strings in the populist-labelled parties.

Here, I am assuming your data frame is called df and that fullprtvt is a column in that data frame. You'll need to ensure it is a character column. If not, you can alter df$fullprtvt to as.character(df$fullprtvt) in the following:

pop <- grep('Dansk Folkeparti|Sverigedemokraterna|Progress Party', df$fullprtvt)
df$pop_nonpop <- rep("Non-populist", nrow(df))
df$pop_nonpop[pop] <- "Populist"

Here's a reproducible example of some dummy data:

set.seed(69)
df <- data.frame(fullprtvt = sample(c('Dansk Folkeparti',
                                      'Dansk Folkeparti - Danish peoples party',
                                      'Sverigedemokraterna',
                                      'Progress Party (FrP)',
                                      'Progress Party (FRP)',
                                      'Moderate party',
                                      'Communist',
                                      'Socialist',
                                      'Democrat'), 10, TRUE))

df
#>                                  fullprtvt
#> 1                         Dansk Folkeparti
#> 2  Dansk Folkeparti - Danish peoples party
#> 3                                Socialist
#> 4                                Communist
#> 5                                Communist
#> 6                           Moderate party
#> 7                                Communist
#> 8  Dansk Folkeparti - Danish peoples party
#> 9                     Progress Party (FrP)
#> 10 Dansk Folkeparti - Danish peoples party

And how the above code would work:

pop <- grep('Dansk Folkeparti|Sverigedemokraterna|Progress Party', df$fullprtvt)
df$pop_nonpop <- rep("Non-populist", nrow(df))
df$pop_nonpop[pop] <- "Populist"

df
#>                                  fullprtvt   pop_nonpop
#> 1                         Dansk Folkeparti     Populist
#> 2  Dansk Folkeparti - Danish peoples party     Populist
#> 3                                Socialist Non-populist
#> 4                                Communist Non-populist
#> 5                                Communist Non-populist
#> 6                           Moderate party Non-populist
#> 7                                Communist Non-populist
#> 8  Dansk Folkeparti - Danish peoples party     Populist
#> 9                     Progress Party (FrP)     Populist
#> 10 Dansk Folkeparti - Danish peoples party     Populist

Created on 2020-02-20 by the reprex package (v0.3.0)


问:
Which OlSaveAsType can I add to the MailItem SaveAs method?
I am getting the currently selected mailItem from the explorer and saving it to the local file system.  The file is then being uploaded to a server.  My problem is sometimes the server (which I have no control over) returns that the file format is invalid.

I save the mailItem with the following code:

```<code>oMailItem.SaveAs("C:\path\savedEmail.msg")
</code>```

This creates a file which is 174kb in size. If I add the OlSaveAsType of olMSG then I get the same file size.

If I save the exact same email with the Outlook UI then the chosen/suggested Message format is Unicode.  This produces a file of about 251kb ie. much bigger.  If I save it with the above code and olMSGUnicode then I also get the same file size.

I am therefore assuming that leaving out the OlSaveAsType option saves the mailItem as an olMSG.

I am currently also assuming that this may be causing some issues with the upload to the server.

What property of a mailItem tells me which OlSaveAsType to use? Can I safely use olMSGUnicode for all saves?

答:
Yes, you can safely use olMSGUnicode format on all modern versions of Outlook.

But the real problem is why the server (?!) returns an error that the format is invalid?  Was it corrupted? Can you successfully open the same file you sent to the server? You need to figure out why that error is returned.

Body:
I am getting the currently selected mailItem from the explorer and saving it to the local file system.  The file is then being uploaded to a server.  My problem is sometimes the server (which I have no control over) returns that the file format is invalid.

I save the mailItem with the following code:

oMailItem.SaveAs("C:\path\savedEmail.msg")

This creates a file which is 174kb in size. If I add the OlSaveAsType of olMSG then I get the same file size.

If I save the exact same email with the Outlook UI then the chosen/suggested Message format is Unicode.  This produces a file of about 251kb ie. much bigger.  If I save it with the above code and olMSGUnicode then I also get the same file size.

I am therefore assuming that leaving out the OlSaveAsType option saves the mailItem as an olMSG.

I am currently also assuming that this may be causing some issues with the upload to the server.

What property of a mailItem tells me which OlSaveAsType to use? Can I safely use olMSGUnicode for all saves?


问:
How to avoid making a flat list for reading each line using Openpyxl?
I am using openpyxl, could someone tell me how to make a new list when reading next line?

I don't want to have flat list.

Code:

```<code>import openpyxl

excel_filename = "sample.xlsx"
wb = openpyxl.load_workbook(excel_filename, data_only=True)
my_sheet_name = "Sheet1"
ws = wb[my_sheet_name]

print("File: {}".format(excel_filename))
data=[]
for j in range(1, ws.max_row+1 ):
    for i in range(1,ws.max_column+1):
        ihidden = ws.row_dimensions[j].hidden
        svalue = ws.cell(column=i,row=j).value
        if ihidden == True:
            shidden = "HIDDEN"
        else:
            shidden = "VISIBLE"

            data.append(svalue)

print(data)
</code>```

Sample.xlsx:

Output:

```<code>File: sample.xlsx
[1231231, None, None, 3123, 123123, None, 123, 21322, None]
</code>```

I hope it can be:

```<code>File: sample.xlsx
[[1231231, None, None],[3123, 123123, None],[123, 21322, None]]
</code>```

答:
Using list comprehension:

data = [[ws.cell(column=j,row=i).value for j in range(1,4) if not ws.row_dimensions[j].hidden] for i in range(1,4) if not ws.row_dimensions[j].hidden]
print(data)
```

<p><strong>Output</strong></p>

```>>> [[1231231, None, None], [3123, 123123, None], [123, 21322, None]]
```

Body:
I am using openpyxl, could someone tell me how to make a new list when reading next line?

I don't want to have flat list.

Code:

import openpyxl

excel_filename = "sample.xlsx"
wb = openpyxl.load_workbook(excel_filename, data_only=True)
my_sheet_name = "Sheet1"
ws = wb[my_sheet_name]

print("File: {}".format(excel_filename))
data=[]
for j in range(1, ws.max_row+1 ):
    for i in range(1,ws.max_column+1):
        ihidden = ws.row_dimensions[j].hidden
        svalue = ws.cell(column=i,row=j).value
        if ihidden == True:
            shidden = "HIDDEN"
        else:
            shidden = "VISIBLE"

            data.append(svalue)

print(data)

Sample.xlsx:

Output:

File: sample.xlsx
[1231231, None, None, 3123, 123123, None, 123, 21322, None]

I hope it can be:

File: sample.xlsx
[[1231231, None, None],[3123, 123123, None],[123, 21322, None]]

Body:
Using list comprehension:

data = [[ws.cell(column=j,row=i).value for j in range(1,4) if not ws.row_dimensions[j].hidden] for i in range(1,4) if not ws.row_dimensions[j].hidden]
print(data)

Output

>>> [[1231231, None, None], [3123, 123123, None], [123, 21322, None]]


问:
C# lambda expression unable to manage a certain string compare
I have a specific lambda what doesn't seem to want to work properly although the logic seems sound.

```<code>index = llCodeList.FindIndex(f => string.Compare(f.Threshold.ToString(), searchText, true ) >= 0);
</code>```

f.Threshold is an integer value, it seems that the conversion doesn't happen and it breaks my search function.  Can anyone shed some light on this?

答:
I think you meant to check IndexOf instead of using Compare.

```<code>index = llCodeList.FindIndex(
    f => f.Threshold.ToString().IndexOf(
        searchText, StringComparison.InvariantCultureIgnoreCase) >= 0);
</code>```

But the name FindIndex sounds like you'd want to return the actual index. My crystal ball says you're looking for something like

```<code>index = llCodeList.FindIndex(
    f => f.Threshold.ToString().IndexOf(
        searchText, StringComparison.InvariantCultureIgnoreCase));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a specific lambda what doesn't seem to want to work properly although the logic seems sound.

index = llCodeList.FindIndex(f => string.Compare(f.Threshold.ToString(), searchText, true ) >= 0);

f.Threshold is an integer value, it seems that the conversion doesn't happen and it breaks my search function.  Can anyone shed some light on this?

Body:
I think you meant to check IndexOf instead of using Compare.

index = llCodeList.FindIndex(
    f => f.Threshold.ToString().IndexOf(
        searchText, StringComparison.InvariantCultureIgnoreCase) >= 0);

But the name FindIndex sounds like you'd want to return the actual index. My crystal ball says you're looking for something like

index = llCodeList.FindIndex(
    f => f.Threshold.ToString().IndexOf(
        searchText, StringComparison.InvariantCultureIgnoreCase));


问:
Robo 3T: Populate actual values of Javascript functions calls while Exporting Collections to JSON
I am very new to Mongo and have a requirement to export collection to JSON. I ran the below code to export to JSON and it worked fine. But main issue is there are some functions for which the value is different in Robo3T GUI in comparison to what is exported.

```<code>var cursor = db.getCollection('foo').find({}, {});
while(cursor.hasNext()) {
    print(tojson(cursor.next()))
}
</code>```

But main issue is there are some functions for which the value is different in Robo3T GUI in comparison to what is exported.
Ex:
"_id" : BinData(3,"u9LO8nOI6UmsYJUin/DH8w==") is what is exported to JSON , while in GUI it is ("f2ced2bb-8873-49e9-ac60-95229ff0c7f3").

I want to export the values exactly what is seen on the Robo3T GUI.

答:
Finally after all the research got the answer. Posting it below so that others facing the same issue can leverage.
The Bindata format is BSON and the one which is visible from mongo shell is in the form of hexadecimal as NUUID, CSUUID, PYUUID or something else.
I wanted to basically convert the BinData to NUUID format.
Run the below two functions on your console:

```<code>   function Base64ToHex(base64) {
        var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var hexDigits = "0123456789abcdef";
        var hex = "";
        for (var i = 0; i < 24; ) {
            var e1 = base64Digits.indexOf(base64[i++]);
            var e2 = base64Digits.indexOf(base64[i++]);
            var e3 = base64Digits.indexOf(base64[i++]);
            var e4 = base64Digits.indexOf(base64[i++]);
            var c1 = (e1 << 2) | (e2 >> 4);
            var c2 = ((e2 & 15) << 4) | (e3 >> 2);
            var c3 = ((e3 & 3) << 6) | e4;
            hex += hexDigits[c1 >> 4];
            hex += hexDigits[c1 & 15];
            if (e3 != 64) {
                hex += hexDigits[c2 >> 4];
                hex += hexDigits[c2 & 15];
            }
            if (e4 != 64) {
                hex += hexDigits[c3 >> 4];
                hex += hexDigits[c3 & 15];
            }
        }
        return hex;
    }

BinData.prototype.toNUUID = function () {
    var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs in older versions of the shell
    var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2);
    var b = hex.substr(10, 2) + hex.substr(8, 2);
    var c = hex.substr(14, 2) + hex.substr(12, 2);
    var d = hex.substr(16, 16);
    hex = a + b + c + d;
    var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12);
    return uuid;
}
</code>```

and then call the function in your extraction as below:

```<code>var cursor = db.getCollection('collectionname').find({});
while(cursor.hasNext()) {
var b=cursor.next()
b._id=b._id.toNUUID()
    print(tojson(b))
}
</code>```

This will extract the data in the desired NUUID format or the column in JSON.

Body:
I am very new to Mongo and have a requirement to export collection to JSON. I ran the below code to export to JSON and it worked fine. But main issue is there are some functions for which the value is different in Robo3T GUI in comparison to what is exported.

var cursor = db.getCollection('foo').find({}, {});
while(cursor.hasNext()) {
    print(tojson(cursor.next()))
}

But main issue is there are some functions for which the value is different in Robo3T GUI in comparison to what is exported.
Ex:
"_id" : BinData(3,"u9LO8nOI6UmsYJUin/DH8w==") is what is exported to JSON , while in GUI it is ("f2ced2bb-8873-49e9-ac60-95229ff0c7f3").

I want to export the values exactly what is seen on the Robo3T GUI.

Body:
Finally after all the research got the answer. Posting it below so that others facing the same issue can leverage.
The Bindata format is BSON and the one which is visible from mongo shell is in the form of hexadecimal as NUUID, CSUUID, PYUUID or something else.
I wanted to basically convert the BinData to NUUID format.
Run the below two functions on your console:

   function Base64ToHex(base64) {
        var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var hexDigits = "0123456789abcdef";
        var hex = "";
        for (var i = 0; i < 24; ) {
            var e1 = base64Digits.indexOf(base64[i++]);
            var e2 = base64Digits.indexOf(base64[i++]);
            var e3 = base64Digits.indexOf(base64[i++]);
            var e4 = base64Digits.indexOf(base64[i++]);
            var c1 = (e1 << 2) | (e2 >> 4);
            var c2 = ((e2 & 15) << 4) | (e3 >> 2);
            var c3 = ((e3 & 3) << 6) | e4;
            hex += hexDigits[c1 >> 4];
            hex += hexDigits[c1 & 15];
            if (e3 != 64) {
                hex += hexDigits[c2 >> 4];
                hex += hexDigits[c2 & 15];
            }
            if (e4 != 64) {
                hex += hexDigits[c3 >> 4];
                hex += hexDigits[c3 & 15];
            }
        }
        return hex;
    }

BinData.prototype.toNUUID = function () {
    var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs in older versions of the shell
    var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2);
    var b = hex.substr(10, 2) + hex.substr(8, 2);
    var c = hex.substr(14, 2) + hex.substr(12, 2);
    var d = hex.substr(16, 16);
    hex = a + b + c + d;
    var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12);
    return uuid;
}

and then call the function in your extraction as below:

var cursor = db.getCollection('collectionname').find({});
while(cursor.hasNext()) {
var b=cursor.next()
b._id=b._id.toNUUID()
    print(tojson(b))
}

This will extract the data in the desired NUUID format or the column in JSON.


问:
Why has uvm_top disappeared?
I compiled my first IEEE 1800.2-2017 UVM code this week and was surprised to discover that uvm_top no longer exists. A quick search of IEEE 1800.2-2017 reveals no occurrence of "uvm_top" and a quick look at the source code reveals that it really has disappeared. Here are two workarounds:

Instead of, eg:

```<code>comp = uvm_top.find("*.m_agent.m_seqr"); // uvm 1.2
</code>```

you could do:

```<code>comp = uvm_root::get().find("*.m_agent.m_seqr"); // IEEE 1800.2-2017
</code>```

or, if you prefer:

```<code>uvm_root uvm_top = uvm_root::get();
comp = uvm_top.find("*.m_agent.m_seqr");
</code>```

I have two questions:

i) Why did the creators of IEEE 1800.2-2017 get rid of uvm_top?
ii) What do they intend us to do instead? (one of those things above or something else?)

答:
Speculations:

Dogmatism that global variables are evil and should be avoided (even if in this case the variable is const).

It's easier for them to generate the class reference, because the tool can handle classes and functions, but not variables inside packages.

Title: Why has uvm_top disappeared?

Body:
I compiled my first IEEE 1800.2-2017 UVM code this week and was surprised to discover that uvm_top no longer exists. A quick search of IEEE 1800.2-2017 reveals no occurrence of "uvm_top" and a quick look at the source code reveals that it really has disappeared. Here are two workarounds:

Instead of, eg:

comp = uvm_top.find("*.m_agent.m_seqr"); // uvm 1.2

you could do:

comp = uvm_root::get().find("*.m_agent.m_seqr"); // IEEE 1800.2-2017

or, if you prefer:

uvm_root uvm_top = uvm_root::get();
comp = uvm_top.find("*.m_agent.m_seqr");

I have two questions:

i) Why did the creators of IEEE 1800.2-2017 get rid of uvm_top?
ii) What do they intend us to do instead? (one of those things above or something else?)


答:
There are a few different uses of cpsr and it is not clear which one you are referring to.

The supervisor mode cpsr.

The user mode cpsr.

Some exception cpsr.

These values are stored during an exception on an ARM cpu.

See: Linux kernel ARM exception stack

This makes all 'spsr' except the svc and user mode meaningless.

Note: The ARM has banked SP, cpsr and lr.  Other referenced architectures may or may not have banked registers.  For certain, all need to restore the user mode status register or user CPSR on ARM.

The switch_to assembler is used to switch kernel state for a process.  The sp that is restored is an 8k page where the lower portion is a thread_info holding a copy of the user registers.  The switch_to() function takes a from and to thread_info held in R1 and R2.

The code,

```<code>  add     r4, r2, #24
  ldm     r4, {r4, r5, r6, r7, r8, r9, sl, fp, sp, pc}
</code>```

Is more like a longjmp() to a previous call to switch_to(); the code is not heading to the same place it was called from necessarily.  The SPSR which is the return to user mode CPSR (and lr).  These are saved in r1,r2 by the vector stubs.  They are restored by the restore_user_regs macro.  The instruction movs   pc, lr will restore the user CPSR and return from an exception/syscall.

The cpsr (SVC) active with kernel code is protected by the 'C' ABI which says the status bits are not valid after a function call.  It is also assumed the any svc code uses the same 'T' bit (all kernel code is either Thumb or ARM only) and the function needs to be called with 'F' and 'I' bits in a known state.  switch_to callers should use the stacking mask functions OR never have interrupts masked.  I think it is probably the last one.  If you try to mix Thumb/ARM code or use/change interrupt masking with calls to switch_to, it would be an issue; otherwise, there is no need to save/restore this value.

Title: Why the arm port of Linux kernel did not backup the "cpsr" register during the context switch?

Body:
The switch to assembly of arm32 in linux is like that:
you coud see there are no cpsr reigister backup, compare to others arch, like mips or riscv,
which corresponding mstatus and status register are all do the backup and restore during the _switch_to, so, why there are the differences?

  12948 8010d328 <__switch_to>:
  12949 8010d328:       e281c018        add     ip, r1, #24
  12950 8010d32c:       e8ac6ff0        stmia   ip!, {r4, r5, r6, r7, r8, r9, sl, fp, sp, lr}
  12951 8010d330:       e592405c        ldr     r4, [r2, #92]   ; 0x5c
  12952 8010d334:       e5925060        ldr     r5, [r2, #96]   ; 0x60
  12953 8010d338:       ee1d7f50        mrc     15, 0, r7, cr13, cr0, {2}
  12954 8010d33c:       ee0d4f70        mcr     15, 0, r4, cr13, cr0, {3}
  12955 8010d340:       ee0d5f50        mcr     15, 0, r5, cr13, cr0, {2}
  12956 8010d344:       e5817060        str     r7, [r1, #96]   ; 0x60
  12957 8010d348:       e1a05000        mov     r5, r0
  12958 8010d34c:       e2824018        add     r4, r2, #24
  12959 8010d350:       e59f000c        ldr     r0, [pc, #12]   ; 8010d364 <__switch_to+0x3c>
  12960 8010d354:       e3a01002        mov     r1, #2
  12961 8010d358:       eb00c813        bl      8013f3ac <atomic_notifier_call_chain>
  12962 8010d35c:       e1a00005        mov     r0, r5
  12963 8010d360:       e894aff0        ldm     r4, {r4, r5, r6, r7, r8, r9, sl, fp, sp, pc}
  12964 8010d364:       80b61200        .word   0x80b61200
  12965 8010d368:       e58d403c        str     r4, [sp, #60]   ; 0x3c
  12966 8010d36c:       e1a0f009        mov     pc, r9

Body:
There are a few different uses of cpsr and it is not clear which one you are referring to.

The supervisor mode cpsr.

The user mode cpsr.

Some exception cpsr.

These values are stored during an exception on an ARM cpu.

See: Linux kernel ARM exception stack

This makes all 'spsr' except the svc and user mode meaningless.

Note: The ARM has banked SP, cpsr and lr.  Other referenced architectures may or may not have banked registers.  For certain, all need to restore the user mode status register or user CPSR on ARM.

The switch_to assembler is used to switch kernel state for a process.  The sp that is restored is an 8k page where the lower portion is a thread_info holding a copy of the user registers.  The switch_to() function takes a from and to thread_info held in R1 and R2.

The code,

  add     r4, r2, #24
  ldm     r4, {r4, r5, r6, r7, r8, r9, sl, fp, sp, pc}

Is more like a longjmp() to a previous call to switch_to(); the code is not heading to the same place it was called from necessarily.  The SPSR which is the return to user mode CPSR (and lr).  These are saved in r1,r2 by the vector stubs.  They are restored by the restore_user_regs macro.  The instruction movs   pc, lr will restore the user CPSR and return from an exception/syscall.

The cpsr (SVC) active with kernel code is protected by the 'C' ABI which says the status bits are not valid after a function call.  It is also assumed the any svc code uses the same 'T' bit (all kernel code is either Thumb or ARM only) and the function needs to be called with 'F' and 'I' bits in a known state.  switch_to callers should use the stacking mask functions OR never have interrupts masked.  I think it is probably the last one.  If you try to mix Thumb/ARM code or use/change interrupt masking with calls to switch_to, it would be an issue; otherwise, there is no need to save/restore this value.


问:
random number generator without doing refresh
Hello
I want to create a web page which can continually sending random value to data base without doing refresh .

For example

```<code><html>
  <HEAD>
    <TITLE>HTML Title</TITLE>
  </HEAD>
  <BODY>

    <H3 ALIGN="CENTER">
      Ramdom number from 0 to 10 :
      <FONT COLOR="RED">
        <%= (int) (Math.random() * 10) %>
      </FONT>
    </H3>
    <H4 ALIGN="CENTER">Refresh the page to see if the number changes...</H4>
  </BODY>
</HTML>
</code>```

in which direction i should go either of using applets or something which can easily be adopted . Thanks

答:
You can use JavaScript to do this. It's extremely simple.

```<code>window.onload = function ()
{
    var output = document.getElementById('foo');

    setInterval(function ()
    {
        output.innerHTML = Math.floor(Math.random() * 10);
    }, 1000);
};
</code>```

Demo: http://jsfiddle.net/mattball/c9t3T/

Based on the HTML in your example, you should probably take some time and start learning CSS as well.

Body:
Hello
I want to create a web page which can continually sending random value to data base without doing refresh .

For example

    <TITLE>HTML Title</TITLE>

      Ramdom number from 0 to 10 :

        <%= (int) (Math.random() * 10) %>

Refresh the page to see if the number changes...

in which direction i should go either of using applets or something which can easily be adopted . Thanks

Body:
You can use JavaScript to do this. It's extremely simple.

window.onload = function ()
{
    var output = document.getElementById('foo');

    setInterval(function ()
    {
        output.innerHTML = Math.floor(Math.random() * 10);
    }, 1000);
};

Demo: http://jsfiddle.net/mattball/c9t3T/

Based on the HTML in your example, you should probably take some time and start learning CSS as well.


问:
How to properly use PayloadAction with meta type in redux-toolkit?
Simplified example

import { createSlice, PayloadAction } from '@reduxjs/toolkit';

    type Cake = {
      flavor: string;
      size: 'S' | 'M' | 'L';
    };

const initialState: { all: Cake[]; meta: { currentPage: number } } = {
  all: [],
  meta: {
    currentPage: 0,
  },
};

const cakeSlice = createSlice({
  name: 'cake',
  initialState,
  reducers: {
    fetchAll(
      state,
      action: PayloadAction<Cake[], string, { currentPage: number }>,
    ) {
      state.all = action.payload;
      state.meta = action.meta;
    },
  },
});

export default cakeSlice;```
</div>
</div>
</p>

<p>I am getting these errors.</p>

```Type '
(state: {
    all: {
        flavor: string;size: "S" | "M" | "L";
    } [];meta: {
        currentPage: number;
    };
}, action: PayloadAction < Cake[], string, {
    currentPage: number;
}, never > ) => void ' is not assignable to type '
CaseReducer < {
    all: Cake[];meta: {
        currentPage: number;
    };
}, {
    payload: any;type: string;
} > | CaseReducerWithPrepare < {
    all: Cake[];meta: {
        currentPage: number;
    };
}, {
    payload: any;type: string;
} > '
```

```Type '
(state: {
    all: {
        flavor: string;size: "S" | "M" | "L";
    } [];meta: {
        currentPage: number;
    };
}, action: PayloadAction < Cake[], string, {
    currentPage: number;
}, never > ) => void '
is not assignable to type 'CaseReducer<{ all: Cake[]; meta: { currentPage: number; }; }, { payload: any; type: string; }>'.
Types of parameters 'action'
and 'action'
are incompatible.
Type '{ payload: any; type: string; }'
is not assignable to type 'PayloadAction<Cake[], string, { currentPage: number; }, never>'.
Property 'meta'
is missing in type '{ payload: any; type: string; }'
but required in type '{ meta: { currentPage: number; }; }
'.
```

答:
The default behaviour of RTK is to create an action creator with only one argument and only a payload property. This behaviour cannot be modified by TS annotations, because TS annotations have no effect on runtime behaviour.

You can use the prepare notation to define a function that overrides this default behaviour.
This function has the same signature & behaviour as the prepare argument for createAction, so you can find most of the relevant documentation there.

In your specific case, you'd want something along the lines of

```<code>const cakeSlice = createSlice({
  name: 'cake',
  initialState,
  reducers: {
    fetchAll: {
      reducer(
        state,
        action: PayloadAction<Cake[], string, { currentPage: number }>
      ) {
        state.all = action.payload
        state.meta = action.meta
      },
      prepare(payload: Cake[], currentPage: number) {
        return { payload, meta: { currentPage } }
      }
    }
  }
})

</code>```

Here it is as a typescript playground

Body:
Simplified example

import { createSlice, PayloadAction } from '@reduxjs/toolkit';

    type Cake = {
      flavor: string;
      size: 'S' | 'M' | 'L';
    };

const initialState: { all: Cake[]; meta: { currentPage: number } } = {
  all: [],
  meta: {
    currentPage: 0,
  },
};

const cakeSlice = createSlice({
  name: 'cake',
  initialState,
  reducers: {
    fetchAll(
      state,
      action: PayloadAction<Cake[], string, { currentPage: number }>,
    ) {
      state.all = action.payload;
      state.meta = action.meta;
    },
  },
});

export default cakeSlice;

I am getting these errors.

Type '
(state: {
    all: {
        flavor: string;size: "S" | "M" | "L";
    } [];meta: {
        currentPage: number;
    };
}, action: PayloadAction < Cake[], string, {
    currentPage: number;
}, never > ) => void ' is not assignable to type '
CaseReducer < {
    all: Cake[];meta: {
        currentPage: number;
    };
}, {
    payload: any;type: string;
} > | CaseReducerWithPrepare < {
    all: Cake[];meta: {
        currentPage: number;
    };
}, {
    payload: any;type: string;
} > '

Type '
(state: {
    all: {
        flavor: string;size: "S" | "M" | "L";
    } [];meta: {
        currentPage: number;
    };
}, action: PayloadAction < Cake[], string, {
    currentPage: number;
}, never > ) => void '
is not assignable to type 'CaseReducer<{ all: Cake[]; meta: { currentPage: number; }; }, { payload: any; type: string; }>'.
Types of parameters 'action'
and 'action'
are incompatible.
Type '{ payload: any; type: string; }'
is not assignable to type 'PayloadAction<Cake[], string, { currentPage: number; }, never>'.
Property 'meta'
is missing in type '{ payload: any; type: string; }'
but required in type '{ meta: { currentPage: number; }; }
'.

Body:
The default behaviour of RTK is to create an action creator with only one argument and only a payload property. This behaviour cannot be modified by TS annotations, because TS annotations have no effect on runtime behaviour.

You can use the prepare notation to define a function that overrides this default behaviour.
This function has the same signature & behaviour as the prepare argument for createAction, so you can find most of the relevant documentation there.

In your specific case, you'd want something along the lines of

const cakeSlice = createSlice({
  name: 'cake',
  initialState,
  reducers: {
    fetchAll: {
      reducer(
        state,
        action: PayloadAction<Cake[], string, { currentPage: number }>
      ) {
        state.all = action.payload
        state.meta = action.meta
      },
      prepare(payload: Cake[], currentPage: number) {
        return { payload, meta: { currentPage } }
      }
    }
  }
})

Here it is as a <a href="https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=18&pc=1#code/JYWwDg9gTgLgBAbwMZQKYEMaoMoBthKoA0cACugJ64ToAmAgkjMBAHYC+cAZlBCHAHIAAmloBXAB4ArAM4B6GBAi4A1sBgCA3AChtwVlihd0hOAGF0K1Im1w4rdCFQAuODJhR9Acx3tdSNnc4fXVgdFxsGExrAF4bO3DcVwBtAF04dBlzS1Q0ols4JyjXZDEoNANyLxc4AGY-P20A1iCkHLwCWLgUDCwOwgAKBAKHJ1cBNqsBfLsQ5nDI6Jm4UTFCKBkSgrsuVBgkAAt6XCT4u3PV9YHt87t3JZvbk2Y2V3IqGgYmFlYAHgsrHk3B5vCQEN0yhUYFUaqwxCAAEaoKBwdgAPkecAAlGdbncolgAHSJOBxZ4-QlgSjUOiY-HRQlFdCkjLfNiMvboTHsZa3MBoKloAZUj50VwA3KpEhISGoSroaquOGI5E44Z4i57MqsRBwEU02gkJklCHlOXQhXWTh+DU2852hpY-yBZSoQnULwDSY4fCEYlslqE3b7I4nAZA2pYjlRQkys3y6pYoA" rel="nofollow noreferrer">typescript playground


问:
Automating ldapsearch with bash using variables
I perform an ldapsearch like

```<code>ldapsearch -D "cn=ldapadm,dc=test,dc=com" -w ldappasswd -b "dc=test,dc=com" objectclass=*
</code>```

and it works fine.

Now I want to substitute the input with varaibles:

```<code>BASEDN="cn=ldapadm,dc=test,dc=com"
PASSWD="ldappasswd"
BINDDN="dc=test,dc=com"

ldapsearch -D "${BASEDN}" -w "${PASSWD}" -b "${BINDDN}" objectclass=*

</code>```

But I get an

```<code>ldap_bind: Invalid credentials (49)
</code>```

error...
The problematic part here is the PASSWD substitution. The other two substitutions are working fine.

I am using CentOS7 on VirtualBox.
The password does not contain special characters.

What am I missing here?

答:
```<code>set -x; ldapsearch -D "${BASEDN}" -w "${PASSWD}" -b "${BINDDN}" objectclass=*
</code>```

revealed the problem. I loaded the values from a file and there was an invisible linebreak at the end of each string.

Output:

```<code>ldapsearch -D cn=ldapadm,dc=test,dc=com\r -w ldappasswd\r -b dc=test,dc=com\r objectclass=*
</code>```

I removed \r calling

```<code>PASSWD=`echo "${value_from_file}"| sed 's/\\r//g'`
</code>```

and it worked.

Body:
I perform an ldapsearch like

ldapsearch -D "cn=ldapadm,dc=test,dc=com" -w ldappasswd -b "dc=test,dc=com" objectclass=*

and it works fine.

Now I want to substitute the input with varaibles:

BASEDN="cn=ldapadm,dc=test,dc=com"
PASSWD="ldappasswd"
BINDDN="dc=test,dc=com"

ldapsearch -D "${BASEDN}" -w "${PASSWD}" -b "${BINDDN}" objectclass=*

But I get an

ldap_bind: Invalid credentials (49)

error...
The problematic part here is the PASSWD substitution. The other two substitutions are working fine.

I am using CentOS7 on VirtualBox.
The password does not contain special characters.

What am I missing here?

Body:
set -x; ldapsearch -D "${BASEDN}" -w "${PASSWD}" -b "${BINDDN}" objectclass=*

revealed the problem. I loaded the values from a file and there was an invisible linebreak at the end of each string.

Output:

ldapsearch -D cn=ldapadm,dc=test,dc=com\r -w ldappasswd\r -b dc=test,dc=com\r objectclass=*

I removed \r calling

PASSWD=`echo "${value_from_file}"| sed 's/\\r//g'`

and it worked.


问:
Getting coordinates of the closest data point on matplotlib plot
I am using matplotlib with NavigationToolbar2QT.  The toolbar is showing the position of the cursor.  But I would like that the cursor snaps to the nearest data point (when close enough) or simply show the coordinate of nearest data point.  Can that be somehow arranged?

答:
You could subclass NavigationToolbar2QT and override the mouse_move handler. The xdata and ydata attributes contain the current mouse position in plot coordinates. You can snap that to the closest data point before passing the event to the base class mouse_move handler.

Full example, with highlighting of the closest point in the plot as a bonus:

```<code>import sys

import numpy as np

from matplotlib.backends.qt_compat import QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvas, NavigationToolbar2QT
from matplotlib.figure import Figure

class Snapper:
    """Snaps to data points"""

    def __init__(self, data, callback):
        self.data = data
        self.callback = callback

    def snap(self, x, y):
        pos = np.array([x, y])
        distances = np.linalg.norm(self.data - pos, axis=1)
        dataidx = np.argmin(distances)
        datapos = self.data[dataidx,:]
        self.callback(datapos[0], datapos[1])
        return datapos

class SnappingNavigationToolbar(NavigationToolbar2QT):
    """Navigation toolbar with data snapping"""

    def __init__(self, canvas, parent, coordinates=True):
        super().__init__(canvas, parent, coordinates)
        self.snapper = None

    def set_snapper(self, snapper):
        self.snapper = snapper

    def mouse_move(self, event):
        if self.snapper and event.xdata and event.ydata:
            event.xdata, event.ydata = self.snapper.snap(event.xdata, event.ydata)
        super().mouse_move(event)

class Highlighter:
    def __init__(self, ax):
        self.ax = ax
        self.marker = None
        self.markerpos = None

    def draw(self, x, y):
        """draws a marker at plot position (x,y)"""
        if (x, y) != self.markerpos:
            if self.marker:
                self.marker.remove()
                del self.marker
            self.marker = self.ax.scatter(x, y, color='yellow')
            self.markerpos = (x, y)
            self.ax.figure.canvas.draw()

class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self._main = QtWidgets.QWidget()
        self.setCentralWidget(self._main)
        layout = QtWidgets.QVBoxLayout(self._main)
        canvas = FigureCanvas(Figure(figsize=(5,3)))
        layout.addWidget(canvas)
        toolbar = SnappingNavigationToolbar(canvas, self)
        self.addToolBar(toolbar)

        data = np.random.randn(100, 2)
        ax = canvas.figure.subplots()
        ax.scatter(data[:,0], data[:,1])

        self.highlighter = Highlighter(ax)
        snapper = Snapper(data, self.highlighter.draw)
        toolbar.set_snapper(snapper)

if __name__ == "__main__":
    qapp = QtWidgets.QApplication(sys.argv)
    app = ApplicationWindow()
    app.show()
    qapp.exec_()
</code>```

Body:
You could subclass NavigationToolbar2QT and override the mouse_move handler. The xdata and ydata attributes contain the current mouse position in plot coordinates. You can snap that to the closest data point before passing the event to the base class mouse_move handler.

Full example, with highlighting of the closest point in the plot as a bonus:

import sys

import numpy as np

from matplotlib.backends.qt_compat import QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvas, NavigationToolbar2QT
from matplotlib.figure import Figure

class Snapper:
    """Snaps to data points"""

    def __init__(self, data, callback):
        self.data = data
        self.callback = callback

    def snap(self, x, y):
        pos = np.array([x, y])
        distances = np.linalg.norm(self.data - pos, axis=1)
        dataidx = np.argmin(distances)
        datapos = self.data[dataidx,:]
        self.callback(datapos[0], datapos[1])
        return datapos

class SnappingNavigationToolbar(NavigationToolbar2QT):
    """Navigation toolbar with data snapping"""

    def __init__(self, canvas, parent, coordinates=True):
        super().__init__(canvas, parent, coordinates)
        self.snapper = None

    def set_snapper(self, snapper):
        self.snapper = snapper

    def mouse_move(self, event):
        if self.snapper and event.xdata and event.ydata:
            event.xdata, event.ydata = self.snapper.snap(event.xdata, event.ydata)
        super().mouse_move(event)

class Highlighter:
    def __init__(self, ax):
        self.ax = ax
        self.marker = None
        self.markerpos = None

    def draw(self, x, y):
        """draws a marker at plot position (x,y)"""
        if (x, y) != self.markerpos:
            if self.marker:
                self.marker.remove()
                del self.marker
            self.marker = self.ax.scatter(x, y, color='yellow')
            self.markerpos = (x, y)
            self.ax.figure.canvas.draw()

class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self._main = QtWidgets.QWidget()
        self.setCentralWidget(self._main)
        layout = QtWidgets.QVBoxLayout(self._main)
        canvas = FigureCanvas(Figure(figsize=(5,3)))
        layout.addWidget(canvas)
        toolbar = SnappingNavigationToolbar(canvas, self)
        self.addToolBar(toolbar)

        data = np.random.randn(100, 2)
        ax = canvas.figure.subplots()
        ax.scatter(data[:,0], data[:,1])

        self.highlighter = Highlighter(ax)
        snapper = Snapper(data, self.highlighter.draw)
        toolbar.set_snapper(snapper)

if __name__ == "__main__":
    qapp = QtWidgets.QApplication(sys.argv)
    app = ApplicationWindow()
    app.show()
    qapp.exec_()


问:
Amazon MWS Scratchpad error 50001 ill formed XML
This simple code in MWS Scratchpad gives me this 50001 error
"The XML you submitted is ill-formed at the Amazon Envelope XML level at (or near) line 2, column 14."</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<messagetype>OrderFulfillment</messagetype>
<message>
 <messageid>1</messageid>
 <orderfulfillment>
      <amazonorderid>171-0326363-1826719</amazonorderid>
      <carriername>La Poste</carriername>
      <shippertrackingnumber>1K03004689202</shippertrackingnumber>
 </orderfulfillment>
</message>
</code>```

答:
Are you missing the AmazonEnvelope?

```<code><AmazonEnvelope xsi:noNamespaceSchemaLocation="amzn-envelope.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Header>
        <DocumentVersion>1.02</DocumentVersion>
        <MerchantIdentifier>XXXXXXXXXXXX</MerchantIdentifier>
    </Header>

<MessageType.....

</AmazonEnvelope>
</code>```

https://docs.developer.amazonservices.com/en_US/feeds/Feeds_SubmitFeed.html

Body:
This simple code in MWS Scratchpad gives me this 50001 error
"The XML you submitted is ill-formed at the Amazon Envelope XML level at (or near) line 2, column 14."

<?xml version="1.0" encoding="utf-8"?>
<messagetype>OrderFulfillment</messagetype>
<message>
 <messageid>1</messageid>
 <orderfulfillment>
      <amazonorderid>171-0326363-1826719</amazonorderid>
      <carriername>La Poste</carriername>
      <shippertrackingnumber>1K03004689202</shippertrackingnumber>
 </orderfulfillment>
</message>

Body:
Are you missing the AmazonEnvelope?

<AmazonEnvelope xsi:noNamespaceSchemaLocation="amzn-envelope.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Header>
        <DocumentVersion>1.02</DocumentVersion>
        <MerchantIdentifier>XXXXXXXXXXXX</MerchantIdentifier>
    </Header>

<MessageType.....

</AmazonEnvelope>

https://docs.developer.amazonservices.com/en_US/feeds/Feeds_SubmitFeed.html


问:
Flutter I can't release or debug when I add Connectivity
SOLUTION for this problem
I deleted the JDK 13. I installed JDK 8.
I gave the environment variable for the Flutter SDK. in user variables
flutter
C: \ flutter \ bin

I gave the environment variable for JAVA_HOME. in system variables
JAVA_HOME
C: \ Program Files \ Java \ jdk1.8.0_241

Then I accepted Android licenses with cmd.
(flutter doctor --android-licenses)

Now I can use flutter connectivity.
The problem is solved. Thank you.

-------------------------------------------------

I cannot debug or release to my app when I add Connectivity to my app's pubspec.yaml

Flutter Doctor

```<code>[flutter] flutter doctor -v
[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.657], locale tr-TR)
    • Flutter version 1.12.13+hotfix.8 at C:\flutter
    • Framework revision 0b8abb4724 (9 days ago), 2020-02-11 11:44:36 -0800
    • Engine revision e1e6ced81d
    • Dart version 2.7.0

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at C:\Users\Faruk Aydin\AppData\Local\Android\sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 29.0.2
    • Java binary at: C:\Program Files\Java\jdk-13.0.2\bin\java
    • Java version Java(TM) SE Runtime Environment (build 13.0.2+8)
    X Android license status unknown.
      Try re-installing or updating your Android SDK Manager.
      See https://developer.android.com/studio/#downloads or visit https://flutter.dev/setup/#android-setup for detailed instructions.

[!] Android Studio (version 3.5)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 42.1.1
    • Dart plugin version 191.8593
    X Unable to find bundled Java version.
    • Try updating or re-installing Android Studio.

[√] VS Code (version 1.42.1)
    • VS Code at C:\Users\Faruk Aydin\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.8.1

[√] Connected device (1 available)
    • Redmi 8A • f12007c00606 • android-arm • Android 9 (API 28)

! Doctor found issues in 2 categories.
exit code 0
</code>```

Body:
SOLUTION for this problem
I deleted the JDK 13. I installed JDK 8.
I gave the environment variable for the Flutter SDK. in user variables
flutter
C: \ flutter \ bin

I gave the environment variable for JAVA_HOME. in system variables
JAVA_HOME
C: \ Program Files \ Java \ jdk1.8.0_241

Then I accepted Android licenses with cmd.
(flutter doctor --android-licenses)

Now I can use flutter connectivity.
The problem is solved. Thank you.

-------------------------------------------------

I cannot debug or release to my app when I add Connectivity to my app's pubspec.yaml

Flutter Doctor

[flutter] flutter doctor -v
[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.657], locale tr-TR)
    • Flutter version 1.12.13+hotfix.8 at C:\flutter
    • Framework revision 0b8abb4724 (9 days ago), 2020-02-11 11:44:36 -0800
    • Engine revision e1e6ced81d
    • Dart version 2.7.0

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at C:\Users\Faruk Aydin\AppData\Local\Android\sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 29.0.2
    • Java binary at: C:\Program Files\Java\jdk-13.0.2\bin\java
    • Java version Java(TM) SE Runtime Environment (build 13.0.2+8)
    X Android license status unknown.
      Try re-installing or updating your Android SDK Manager.
      See https://developer.android.com/studio/#downloads or visit https://flutter.dev/setup/#android-setup for detailed instructions.

[!] Android Studio (version 3.5)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 42.1.1
    • Dart plugin version 191.8593
    X Unable to find bundled Java version.
    • Try updating or re-installing Android Studio.

[√] VS Code (version 1.42.1)
    • VS Code at C:\Users\Faruk Aydin\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.8.1

[√] Connected device (1 available)
    • Redmi 8A • f12007c00606 • android-arm • Android 9 (API 28)

! Doctor found issues in 2 categories.
exit code 0


问:
Make an Excel COM add-in a VSTO add-in
I have coded an Excel add-in using Visual C#. This add-in appears as a COM add-in in Excel. However, I am quite sure that it used to appear as an Excel/VSTO Add-In in Excel before an update of Visual Studio. (I know that I was able to access the Globals class. This thread says that Globals can only be accessed in Excel add-ins.)

So my question is: How can I make my COM add-in an Excel/VSTO add-in?

答: Well, if you used Microsoft.Office.Interop.Excel.... thats COM... Interoperability. VSTO is a COM.

Title: Make an Excel COM add-in a VSTO add-in


问:
Why setState(hook) in function component cause an infinite loop?
Here is the code:

import React, { useState } from 'react'

function App() {
  const [a, setA] = useState(1)
  setA(2)
  return (

{a}

  );
}
```

Error. Too many re-renders. React limits the number of renders to prevent an infinite loop.

Why it can cause an infinite loop?

I think the reason is that function component just as a render function, so it will cause infinite loop when setState in render functions.

Is there any official explanation?

答:
When calling setA you actually update a state variable and trigger a re-render of you component.

When the component re-render it will call setA (just before the rendering) and will trigger a re-render again.

Can you see the infinite loop ?

Traditionally you update a state variable into a callback (i.e when the user click on a button) or under certains conditions.

In your example, you can directly set a to 2

```<code>function App() {
  const [a, setA] = useState(2)
  return (
    <div>
      <h1>{a}</h1>
    </div>
  );
}
</code>```

If you want to have the first render with a = 1, then immediatly have a = 2, you can use an effect which will be executed only once (because of the empty array for the second argument)

```<code>function App() {
  const [a, setA] = useState(2)
  useEffect(() => setA(2), [])

  return (
    <div>
      <h1>{a}</h1>
    </div>
  );
}
</code>```

Body:
Here is the code:

import React, { useState } from 'react'

function App() {
  const [a, setA] = useState(1)
  setA(2)
  return (

{a}

  );
}

Error. Too many re-renders. React limits the number of renders to prevent an infinite loop.

Why it can cause an infinite loop?

I think the reason is that function component just as a render function, so it will cause infinite loop when setState in render functions.

Is there any official explanation?

Body:
When calling setA you actually update a state variable and trigger a re-render of you component.

When the component re-render it will call setA (just before the rendering) and will trigger a re-render again.

Can you see the infinite loop ?

Traditionally you update a state variable into a callback (i.e when the user click on a button) or under certains conditions.

In your example, you can directly set a to 2

function App() {
  const [a, setA] = useState(2)
  return (
    <div>
      <h1>{a}</h1>
    </div>
  );
}

If you want to have the first render with a = 1, then immediatly have a = 2, you can use an effect which will be executed only once (because of the empty array for the second argument)

function App() {
  const [a, setA] = useState(2)
  useEffect(() => setA(2), [])

  return (
    <div>
      <h1>{a}</h1>
    </div>
  );
}


问:
Using Styleguidist in conjunction with Ant UI in React
I am creating a style guide that uses Ant UI as a baseline. The issue I'm running into is getting the theme configuration started when I run yarn run styleguide.
Here is some documentation --
https://ant.design/docs/react/use-with-create-react-app

I have used this boilerplate as a template but the versions they are using are deprecated and older / not up to date with the latest styleguidist documentation and I would like to use the latest versions of everything --
https://github.com/newswim/styleguidist-ant-design/tree/master

I'm not sure how to translate the older version above to the newer version. When I run yarn run start, it uses the new variable because react-app-rewired is in that command but I need it to work with styleguidist with the latest versions of everything.

Thanks.

package.json

```<code>  "name": "components",
  "version": "0.1.0",
  "private": false,
  "dependencies": {
    "@types/classnames": "^2.2.9",
    "@types/jest": "24.0.22",
    "@types/node": "12.12.6",
    "@types/react": "16.9.11",
    "@types/react-dom": "16.9.4",
    "antd": "^3.25.0",
    "babel-plugin-import": "^1.12.2",
    "classnames": "^2.2.6",
    "customize-cra": "^0.8.0",
    "less": "^3.10.3",
    "less-loader": "^5.0.0",
    "prop-types": "^15.7.2",
    "react": "^16.11.0",
    "react-app-rewire-less": "^2.1.3",
    "react-app-rewired": "^2.1.5",
    "react-docgen-typescript": "^1.15.1",
    "react-dom": "^16.11.0",
    "react-scripts": "3.2.0",
    "react-styleguidist": "^10.2.0",
    "todomvc-app-css": "^2.3.0",
    "typescript": "3.7.2"
  },
  "scripts": {
    "styleguide": "styleguidist server",
    "styleguide:build": "styleguidist build",
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

config-overrides.js

```<code>
module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true,
  }),
  addLessLoader({
    javascriptEnabled: true,
    modifyVars: { '@primary-color': '#ffffff' },
  }),
);
</code>```

styleguide.config.js

```<code>module.exports = {
  title: 'UI Components',
  pagePerSection: true,
  version: 'v1.0.0',
  propsParser: require('react-docgen-typescript').withCustomConfig(
    './tsconfig.json'
  ).parse,
  sections: [
      {
          name: "Introduction",
          content: "docs/introduction.md"
      },
      {
          name: "Documentation",
          sections: [
              {
                  name: "Installation",
                  content: "docs/installation.md",
                  description: "The description for the installation section"
              }
          ]
      },
      {
          name: "UI Components",
          content: "docs/reactui.md",
          components: "src/components/**/!(*.spec).tsx",
          ignore: [
              "src/components/App.js",
              "src/components/Footer.js",
              "src/components/Header.js"
          ],
          exampleMode: "expand", // 'hide' | 'collapse' | 'expand'
          usageMode: "expand" // 'hide' | 'collapse' | 'expand'
      }
  ]
}
</code>```

答:
Styleguidist overrides your config-overrides.js file and removes babel-plugin-import of antd.

Try adding dangerouslyUpdateWebpackConfig to your styleguide.config.js, similar to config-overrides.js just for styleguide.

For example:

const { addBabelPlugin, addLessLoader } = require('customize-cra');

module.exports = {
  dangerouslyUpdateWebpackConfig(webpackConfig, env) {
    webpackConfig = addBabelPlugin(
      ['import', { libraryName: 'antd', style: true }],
    )(webpackConfig);
    return webpackConfig;
  },
};```

Body:
I am creating a style guide that uses Ant UI as a baseline. The issue I'm running into is getting the theme configuration started when I run yarn run styleguide.
Here is some documentation --
https://ant.design/docs/react/use-with-create-react-app

I have used this boilerplate as a template but the versions they are using are deprecated and older / not up to date with the latest styleguidist documentation and I would like to use the latest versions of everything --
https://github.com/newswim/styleguidist-ant-design/tree/master

I'm not sure how to translate the older version above to the newer version. When I run yarn run start, it uses the new variable because react-app-rewired is in that command but I need it to work with styleguidist with the latest versions of everything.

Thanks.

package.json

  "name": "components",
  "version": "0.1.0",
  "private": false,
  "dependencies": {
    "@types/classnames": "^2.2.9",
    "@types/jest": "24.0.22",
    "@types/node": "12.12.6",
    "@types/react": "16.9.11",
    "@types/react-dom": "16.9.4",
    "antd": "^3.25.0",
    "babel-plugin-import": "^1.12.2",
    "classnames": "^2.2.6",
    "customize-cra": "^0.8.0",
    "less": "^3.10.3",
    "less-loader": "^5.0.0",
    "prop-types": "^15.7.2",
    "react": "^16.11.0",
    "react-app-rewire-less": "^2.1.3",
    "react-app-rewired": "^2.1.5",
    "react-docgen-typescript": "^1.15.1",
    "react-dom": "^16.11.0",
    "react-scripts": "3.2.0",
    "react-styleguidist": "^10.2.0",
    "todomvc-app-css": "^2.3.0",
    "typescript": "3.7.2"
  },
  "scripts": {
    "styleguide": "styleguidist server",
    "styleguide:build": "styleguidist build",
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

config-overrides.js

module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true,
  }),
  addLessLoader({
    javascriptEnabled: true,
    modifyVars: { '@primary-color': '#ffffff' },
  }),
);

styleguide.config.js

module.exports = {
  title: 'UI Components',
  pagePerSection: true,
  version: 'v1.0.0',
  propsParser: require('react-docgen-typescript').withCustomConfig(
    './tsconfig.json'
  ).parse,
  sections: [
      {
          name: "Introduction",
          content: "docs/introduction.md"
      },
      {
          name: "Documentation",
          sections: [
              {
                  name: "Installation",
                  content: "docs/installation.md",
                  description: "The description for the installation section"
              }
          ]
      },
      {
          name: "UI Components",
          content: "docs/reactui.md",
          components: "src/components/**/!(*.spec).tsx",
          ignore: [
              "src/components/App.js",
              "src/components/Footer.js",
              "src/components/Header.js"
          ],
          exampleMode: "expand", // 'hide' | 'collapse' | 'expand'
          usageMode: "expand" // 'hide' | 'collapse' | 'expand'
      }
  ]
}


问:
How can I get JQuery to replace the non URL parts of the string when fetching the background images url
I have this code which extracts the element for the background image, however it pulls in the " url' " parts of the code too. I just need the actual image address

I have tried to use the replace function but it doesn't do anything to the string when i check the output.

```<code>var jsonData =
{ "image": jQuery('#block-content').css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1'),
var script = document.createElement('script');
script.type = 'application/ld+json';
script.text = JSON.stringify(jsonData);
jQuery("head").append(script);
</code>```

The image inside the element is //imageaddress.jpg so it's extracting it as

```<code>https://example.com/recipes/url(https://example.com/sites/image.jpg?itok=jfzYQHZx)
</code>```

How can i fix this so that it just gives me

```<code>https://example.com/sites/image.jpg?itok=jfzYQHZx
</code>```

答:
hope this help you.

var tmp = 'https://example.com/recipes/url(https://example.com/sites/image.jpg?itok=jfzYQHZx)';
tmp = tmp.substring(tmp.indexOf("(h") + 1);
tmp = tmp.substring(0, tmp.length - 1);
console.log(tmp);```

Body:
I have this code which extracts the element for the background image, however it pulls in the " url' " parts of the code too. I just need the actual image address

I have tried to use the replace function but it doesn't do anything to the string when i check the output.

var jsonData =
{ "image": jQuery('#block-content').css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1'),
var script = document.createElement('script');
script.type = 'application/ld+json';
script.text = JSON.stringify(jsonData);
jQuery("head").append(script);

The image inside the element is //imageaddress.jpg so it's extracting it as

https://example.com/recipes/url(https://example.com/sites/image.jpg?itok=jfzYQHZx)

How can i fix this so that it just gives me

https://example.com/sites/image.jpg?itok=jfzYQHZx


问:
GWT CellBrowser- how to always show all values?
GWT's CellBrowser is a great way of presenting dynamic data.

However when the browser contains more rows than some (seemingly) arbitrary maximum, it offers a "Show More" label that the user can click to fetch the unseen rows.

How can I disable this behavior, and force it to always show every row?

答:
My workaround is to navigate through elements of treeview dom to get "show more" element with

```<code>public static List<Element> findElements(Element element) {
    ArrayList<Element> result = new ArrayList<Element>();
    findShowMore(result, element);  return result; }

private static void findShowMore(ArrayList res, Element element) {
    String c;

    if (element == null) {      return;     }

    if (element.getInnerText().equals("Show more")) {       res.add(element);
    }

    for (int i = 0; i < DOM.getChildCount(element); i++) {      Element
child = DOM.getChild(element, i);       findShowMore(res, child);   } }
</code>```

and than use:

```<code>if (show) {   element.getStyle().clearDisplay(); } else {
element.getStyle().setDisplay(Display.NONE); }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
My workaround is to navigate through elements of treeview dom to get "show more" element with

public static List<Element> findElements(Element element) {
    ArrayList<Element> result = new ArrayList<Element>();
    findShowMore(result, element);  return result; }

private static void findShowMore(ArrayList res, Element element) {
    String c;

    if (element == null) {      return;     }

    if (element.getInnerText().equals("Show more")) {       res.add(element);
    }

    for (int i = 0; i < DOM.getChildCount(element); i++) {      Element
child = DOM.getChild(element, i);       findShowMore(res, child);   } }

and than use:

if (show) {   element.getStyle().clearDisplay(); } else {
element.getStyle().setDisplay(Display.NONE); }


问:
Python: AttributeError: 'bool' object has no attribute 'all'
I'm adaptying the code of a guy that studies with me, for my problem.

This is his code:

```<code>     if not((paux1 == paux2).all()):
        pop[int(saidaFO[pos,0]),:] = paux2
        pos -= 1
</code>```

And it works, and when I give a print, I have this result by paux1: [-2.3668  1.3174].
I'm working in a different problem, and in my case, when I print paux1, I have this: [0.2107491848569726, 443, 3]

So, when I try to do the same comparation:

if not((paux1 == paux2).all()):

I got this error: "AttributeError: 'bool' object has no attribute 'all' "
I'm not understand what is going on... Could someone help me, please?
I didn't understand so well how the .all() works... Maybe a equivalent code can work...

答:
Another source of error is if the two np.array don't have the same shape. For instance:

```<code>(np.array([[1,1]])==np.array([1,2,3])).all()
</code>```

returns:

```<code>    ---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-400-ea9825114062> in <module>
----> 1 (np.array([[1,1]])==np.array([1,2,3])).all()

AttributeError: 'bool' object has no attribute 'all'
</code>```

Body:
I'm adaptying the code of a guy that studies with me, for my problem.

This is his code:

     if not((paux1 == paux2).all()):
        pop[int(saidaFO[pos,0]),:] = paux2
        pos -= 1

And it works, and when I give a print, I have this result by paux1: [-2.3668  1.3174].
I'm working in a different problem, and in my case, when I print paux1, I have this: [0.2107491848569726, 443, 3]

So, when I try to do the same comparation:

if not((paux1 == paux2).all()):

I got this error: "AttributeError: 'bool' object has no attribute 'all' "
I'm not understand what is going on... Could someone help me, please?
I didn't understand so well how the .all() works... Maybe a equivalent code can work...

Body:
Another source of error is if the two np.array don't have the same shape. For instance:

(np.array([[1,1]])==np.array([1,2,3])).all()

returns:

    ---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-400-ea9825114062> in <module>
----> 1 (np.array([[1,1]])==np.array([1,2,3])).all()

AttributeError: 'bool' object has no attribute 'all'


问:
Using Wildfly modules instead of wildfly-X-client-bom dependencies
I have two Wildfly servers. Server A connects to JMS topics and EJB's on Server B.  They are both Wildfly 8.2.0.Final.

The client (a .war) on Server A has these maven dependencies:

```<code>  <dependency>
     <groupId>org.wildfly</groupId>
     <artifactId>wildfly-ejb-client-bom</artifactId>
     <version>8.2.0.Final</version>
     <type>pom</type>
  </dependency>
  <dependency>
     <groupId>org.wildfly</groupId>
     <artifactId>wildfly-jms-client-bom</artifactId>
     <version>8.2.0.Final</version>
     <type>pom</type>
  </dependency>
</code>```

Is it possible to get rid of those, and just ask for specific Wildfly modules to be loaded in jboss-deployment-structure.xml instead?  It seems like these Maven dependencies would increase the size of my .war.

Thanks!

Edit:

To look up EJB's on Server B, I'm using the "1. EJB client library" technique listed here: http://blog.akquinet.de/2014/09/26/jboss-eap-wildfly-three-ways-to-invoke-remote-ejbs/.  My code is very similar to the example:

```<code>Properties prop = new Properties();
prop.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
Context context = new InitialContext(prop);
</code>```

And:

```<code>remote.connections=default
remote.connection.default.host=127.0.0.1
remote.connection.default.port=8080
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false
remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER}

remote.connection.default.username=${username}
remote.connection.default.password=${password}
</code>```

And: context.lookup("ejb:/myapp/remote/calculator!de.akquinet.jbosscc.ejb.Calculator");

To connect to a JMS topic on Server B I'm using:

```<code>     final InitialContext initialContext = new InitialContext( m_jndiProperties );
     final ConnectionFactory connectionFactory = getConnectionFactory( initialContext );
     final Connection connection = connectionFactory.createConnection( m_clientKey.getUsername(), m_clientKey.getPassword() );

     try
     {
        final Topic updateTopic = getUpdateTopic( initialContext );
        final TopicSubscriber subscriber;

        if( m_isDurableSubscription )
        {
           connection.setClientID( m_clientKey.getJmsClientId() );
           connection.setExceptionListener( m_exceptionListener );
           final Session subscriberSession = connection.createSession( false, Session.AUTO_ACKNOWLEDGE );
           subscriber = subscriberSession.createDurableSubscriber( updateTopic, m_clientKey.getJmsSubscriptionId() );
        }
        else
        {
           connection.setExceptionListener( m_exceptionListener );
           final Session subscriberSession = connection.createSession( false, Session.AUTO_ACKNOWLEDGE );
           subscriber = ( (TopicSession)subscriberSession ).createSubscriber( updateTopic );
        }

        connection.stop();
        subscriber.setMessageListener( m_msgListener );

        m_connection = connection;

        maybeLogMessage( m_logger, GenericLogLevel.INFO, "Successfully subscribed to topic: '" + topicName + "'." );
     }
     catch( JMSException | NamingException e )
     {
        //noinspection ThrowableResultOfMethodCallIgnored
        JMSCloser.close( connection );
        throw e;
     }
</code>```

The code to do these lookups is in a maven library that my .war uses.  The library goes into WEB-INF/lib/ as usual.

答:
this worked for me:

I replaced wildfly-jms-client-bom :

```<code><dependency>
    <groupId>org.jboss.eap</groupId>
    <artifactId>wildfly-jms-client-bom</artifactId>
    <version>7.1.0.GA-redhat-11</version>
    <type>pom</type>
</dependency>
</code>```

with javaee-api:

```<code><dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>
</code>```

and added an explicit dependency on module org.apache.activemq.artemis (the following ultimately adds Dependencies: org.apache.activemq.artemis in META-INF/MANIFEST.MF inside the war file):

```<code><plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.2.3</version>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <archive>
            <manifestEntries>
                <Dependencies>org.apache.activemq.artemis</Dependencies>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>
</code>```

Body:
I have two Wildfly servers. Server A connects to JMS topics and EJB's on Server B.  They are both Wildfly 8.2.0.Final.

The client (a .war) on Server A has these maven dependencies:

  <dependency>
     <groupId>org.wildfly</groupId>
     <artifactId>wildfly-ejb-client-bom</artifactId>
     <version>8.2.0.Final</version>
     <type>pom</type>
  </dependency>
  <dependency>
     <groupId>org.wildfly</groupId>
     <artifactId>wildfly-jms-client-bom</artifactId>
     <version>8.2.0.Final</version>
     <type>pom</type>
  </dependency>

Is it possible to get rid of those, and just ask for specific Wildfly modules to be loaded in jboss-deployment-structure.xml instead?  It seems like these Maven dependencies would increase the size of my .war.

Thanks!

Edit:

To look up EJB's on Server B, I'm using the "1. EJB client library" technique listed here: http://blog.akquinet.de/2014/09/26/jboss-eap-wildfly-three-ways-to-invoke-remote-ejbs/.  My code is very similar to the example:

Properties prop = new Properties();
prop.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
Context context = new InitialContext(prop);

And:

remote.connections=default
remote.connection.default.host=127.0.0.1
remote.connection.default.port=8080
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false
remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS=${host.auth:JBOSS-LOCAL-USER}

remote.connection.default.username=${username}
remote.connection.default.password=${password}

And: context.lookup("ejb:/myapp/remote/calculator!de.akquinet.jbosscc.ejb.Calculator");

To connect to a JMS topic on Server B I'm using:

     final InitialContext initialContext = new InitialContext( m_jndiProperties );
     final ConnectionFactory connectionFactory = getConnectionFactory( initialContext );
     final Connection connection = connectionFactory.createConnection( m_clientKey.getUsername(), m_clientKey.getPassword() );

     try
     {
        final Topic updateTopic = getUpdateTopic( initialContext );
        final TopicSubscriber subscriber;

        if( m_isDurableSubscription )
        {
           connection.setClientID( m_clientKey.getJmsClientId() );
           connection.setExceptionListener( m_exceptionListener );
           final Session subscriberSession = connection.createSession( false, Session.AUTO_ACKNOWLEDGE );
           subscriber = subscriberSession.createDurableSubscriber( updateTopic, m_clientKey.getJmsSubscriptionId() );
        }
        else
        {
           connection.setExceptionListener( m_exceptionListener );
           final Session subscriberSession = connection.createSession( false, Session.AUTO_ACKNOWLEDGE );
           subscriber = ( (TopicSession)subscriberSession ).createSubscriber( updateTopic );
        }

        connection.stop();
        subscriber.setMessageListener( m_msgListener );

        m_connection = connection;

        maybeLogMessage( m_logger, GenericLogLevel.INFO, "Successfully subscribed to topic: '" + topicName + "'." );
     }
     catch( JMSException | NamingException e )
     {
        //noinspection ThrowableResultOfMethodCallIgnored
        JMSCloser.close( connection );
        throw e;
     }

The code to do these lookups is in a maven library that my .war uses.  The library goes into WEB-INF/lib/ as usual.

Body:
this worked for me:

I replaced wildfly-jms-client-bom :

<dependency>
    <groupId>org.jboss.eap</groupId>
    <artifactId>wildfly-jms-client-bom</artifactId>
    <version>7.1.0.GA-redhat-11</version>
    <type>pom</type>
</dependency>

with javaee-api:

<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>

and added an explicit dependency on module org.apache.activemq.artemis (the following ultimately adds Dependencies: org.apache.activemq.artemis in META-INF/MANIFEST.MF inside the war file):

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.2.3</version>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <archive>
            <manifestEntries>
                <Dependencies>org.apache.activemq.artemis</Dependencies>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>


问:
Make the console wait for a user input to close
I have a console application that after performing its tasks, must give feedback to the user, such as "operation completed" or "operation failed" and the detailed error.

The thing is, if I just "let it run", the output message will be printed but the console will close shortly afterwards, leaving no time to read the message.

As far as I remember, in C++, every console application will end with a "press any key to exit" or something like that. In C# I can simulate this behavior with a

```<code>Console.ReadKey();
</code>```

But how can I do it in Java? I'm using the Scanner class, but given that "input" is my instance of Scanner:

```<code>input.next()
System.exit(0);
</code>```

"Any key" will work, except for return, which is quite a big deal here. Any pointers?

答: In Java this would be System.in.read()

Body:
I have a console application that after performing its tasks, must give feedback to the user, such as "operation completed" or "operation failed" and the detailed error.

The thing is, if I just "let it run", the output message will be printed but the console will close shortly afterwards, leaving no time to read the message.

As far as I remember, in C++, every console application will end with a "press any key to exit" or something like that. In C# I can simulate this behavior with a

Console.ReadKey();

But how can I do it in Java? I'm using the Scanner class, but given that "input" is my instance of Scanner:

input.next()
System.exit(0);

"Any key" will work, except for return, which is quite a big deal here. Any pointers?

Body: In Java this would be System.in.read()


问:
What is the meaning of routerLinkActiveOptions?
I found some navigation bar code.
In the first list element i know that routerLinkActive will give the active class when the link is clicked.
But in the second list element i dont understant the meaninf of
  [routerLinkActiveOptions]="{ exact : true}"

What is is doing?

```<code><ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link"
         [routerLink]="['/welcome']"
         routerLinkActive="active">Home</a>
    </li>
    <li class="nav-item">
      <a class="nav-link"
         [routerLink]="['/products']"
         routerLinkActive="active"
         [routerLinkActiveOptions]="{ exact : true}">Product List</a>
    </li>
</ul>

</code>```

答:
{ exact: true } will match only the route in routerLink.

If you have the link without exact specified or set to false:

```<code><a class="nav-link"
  [routerLink]="['/products']"
  routerLinkActive="active">
  Product List
</a>
</code>```

The active class would be added to the link for the following example urls:

/products

/products?sort=price

/products/55

With exact set to true only /products would be matched.

Body:
I found some navigation bar code.
In the first list element i know that routerLinkActive will give the active class when the link is clicked.
But in the second list element i dont understant the meaninf of
  [routerLinkActiveOptions]="{ exact : true}"

What is is doing?

      Home

      Product List

Body:
{ exact: true } will match only the route in routerLink.

If you have the link without exact specified or set to false:

<a class="nav-link"
  [routerLink]="['/products']"
  routerLinkActive="active">
  Product List
</a>

The active class would be added to the link for the following example urls:

/products

/products?sort=price

/products/55

With exact set to true only /products would be matched.


问:
Download folder in python
I try download this zip. I used selenium and requests, but neither of them works and I don't know why.
Thank you for your advice.</p>

```<code>from selenium import webdriver
import requests

url = 'http://vdp.cuzk.cz/vymenny_format/csv/20200131_OB_ADR_csv.zip'
driver = webdriver.Chrome('drivers\chromedriver.exe')
driver.get(url)

requests.get(url)
</code>```

答:
First of all, you don't need requests to download a file (in this case at least). As I don't know the errors you are getting, I would suggest double-checking the path to your chromedriver.exe and you should escape backslashes.

```<code>driver = webdriver.Chrome('drivers\\chromedriver.exe')
</code>```

I tried your code (while entering the location of chromedriver on my computer) and it worked - I was able to download the file.

Title: Download folder in python

Body:
I try download this zip. I used selenium and requests, but neither of them works and I don't know why.
Thank you for your advice.

from selenium import webdriver
import requests

url = 'http://vdp.cuzk.cz/vymenny_format/csv/20200131_OB_ADR_csv.zip'
driver = webdriver.Chrome('drivers\chromedriver.exe')
driver.get(url)

requests.get(url)

Body:
First of all, you don't need requests to download a file (in this case at least). As I don't know the errors you are getting, I would suggest double-checking the path to your chromedriver.exe and you should escape backslashes.

driver = webdriver.Chrome('drivers\\chromedriver.exe')

I tried your code (while entering the location of chromedriver on my computer) and it worked - I was able to download the file.


问:
Named Colors crash in Interface Builder builds
In the app I'm working on, we use named colors to manage our color scheme, which we use in code like so:

```<code>extension UIColor {
    static let primaryColor = UIColor(named: "primaryColor")!
}
</code>```

This works fine in most places, but breaks when we use it as a default somewhere in a custom view that is loaded in Interface Builder, because the asset catalog containing the color can't be loaded in Interface Builder builds.

We now consider a number of workarounds to avoid the force unwrap, but really we'd like the asset catalog to simply be loaded in Interface Builder builds like everywhere else.

Is there any way to do this?

Edit:

To clarify, the colors are fine when set through the UI in Interface Builder. The crashes happen when we set it in code like this:

```<code>class CustomView: UIView {
    init() {
        self.backgroundColor = .primaryColor
    }
}
</code>```

Edit 2:

I filed a radar: rdar://41244137

答:
Named color works fine in Interface Builder when I use Bundle(for: AppDelegate.self) instead of default bundle (Bundle.main):

UIColor(named: "primaryColor", in: Bundle(for: AppDelegate.self), compatibleWith: nil)

Body:
In the app I'm working on, we use named colors to manage our color scheme, which we use in code like so:

extension UIColor {
    static let primaryColor = UIColor(named: "primaryColor")!
}

This works fine in most places, but breaks when we use it as a default somewhere in a custom view that is loaded in Interface Builder, because the asset catalog containing the color can't be loaded in Interface Builder builds.

We now consider a number of workarounds to avoid the force unwrap, but really we'd like the asset catalog to simply be loaded in Interface Builder builds like everywhere else.

Is there any way to do this?

Edit:

To clarify, the colors are fine when set through the UI in Interface Builder. The crashes happen when we set it in code like this:

class CustomView: UIView {
    init() {
        self.backgroundColor = .primaryColor
    }
}

Edit 2:

I filed a radar: rdar://41244137


问:
NetBeans cannot find my Maven dependency
I have created a Maven project, and have added my required dependencies. When I attempt to build the project, I get the following errors:

My dependencies do show that the org.apache.poi library is there:

Which includes the requisite packages:

Here are my includes:

```<code>import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
</code>```

I'm relatively new to Java, and very new to Maven, but when I right click on
Dependencies and Add Dependency, I enter the appropriate groupID and ArtifactID and version, (as listed in Maven Central) and it automatically downloads the file. Not sure what else I'm missing. Any help is appreciated.

Edit: I should note that I also tried Manually installing artifact and got the same result.

Edit: Here's the dependency section of my pom.xml file. I'm curious why maven only added two, when I have many more libs, but that seems to be another issue. POI is listed here and it's the one that the compiler is complaining about.

```<code><dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.16</version>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.16</version>
        <type>pom</type>
    </dependency>
</dependencies>
</code>```

答: Sometimes Netbeans gets confused as you are editing the pom and doesn't download from maven. Simply do a "clean and build" of your project and it will download the dependency.</p>

Body:
I have created a Maven project, and have added my required dependencies. When I attempt to build the project, I get the following errors:

My dependencies do show that the org.apache.poi library is there:

Which includes the requisite packages:

Here are my includes:

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;

I'm relatively new to Java, and very new to Maven, but when I right click on
Dependencies and Add Dependency, I enter the appropriate groupID and ArtifactID and version, (as listed in Maven Central) and it automatically downloads the file. Not sure what else I'm missing. Any help is appreciated.

Edit: I should note that I also tried Manually installing artifact and got the same result.

Edit: Here's the dependency section of my pom.xml file. I'm curious why maven only added two, when I have many more libs, but that seems to be another issue. POI is listed here and it's the one that the compiler is complaining about.

<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.16</version>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.16</version>
        <type>pom</type>
    </dependency>
</dependencies>


问:
How to Manage Multiple Private Apps on Multiple play store of different customers using Android Management Apis?
Hi Based on Documentation https://developers.google.com/android/management/apps

It's not clear how multiple play store accounts can be used, with Single Enterprise  that is created using Android Management API's

Suppose we build a solution using Android Management API's and now we have many customers each one will have there own set of private apps then how the app publication will work?

Where these customers/organisations will publish their apps ? if they use their own play store accounts to publish app then do we need to share our Emm's enterprise ID with them so that they can whitelist their private app's for our solution's enterprise ?

will it not leak apps among different customers ?

For Example
There are two Organisations Alpha an Beta

Alpha published private app App  A & B and made it available to our EMM's Enterprise  ID

now Beta Published C & D using same steps

While creating Policy Alpha used Package name of A, B & C(somehow he got to know this package name) then will it not install app C in his policy ?

Please help Documentation is not very clear about app publication.

答:
In order to keep separate approved apps, private apps and policies, you should create a separate Enterprise for each customer.

When a private app is published via managed google play emm iframe, your organization is automatically whitelisted for that app. However when publishing via Play Console you have to target that app to your organization (enterprise id).

For example, two enterprises, Alpha and Beta:

Alpha Enterprise has published private Apps A and B.  Apps A and B are by default whitelisted to Alpha Enterprise,

Beta Enterprise has published private Apps C and D.  Apps C and D are by default whitelisted to Beta Enterprise.

If you try to add App C in your policy for Alpha Enterprise, it will not be installed unless Beta Enterprise whitelists App C to be available for Alpha Enterprise.

For a guide on publishing private apps, you may refer to this:
https://support.google.com/googleplay/work/topic/9496238

For distribution/whitelisting of private apps to other organizations (enterprises), you may check this link:
https://support.google.com/googleplay/work/answer/9495634?hl=en&ref_topic=6145152


问:
Testing the User Model with Rspec, Devise, and Factory Girl
I think there is a problem with my user factory being built. I'm getting an error saying that the password cannot be blank, but it's clearly set in my factories.rb. Does anyone see anything that I may be missing? Or a reason as to why the spec is failing? I do a very similar thing for one of my other models, and it seems to be successful. I'm not sure if the error is being caused by devise or not.

Rspec Error

```<code>User should create a new instance of a user given valid attributes
Failure/Error: User.create!(@user.attributes)
ActiveRecord::RecordInvalid:
  Validation failed: Password can't be blank
# ./spec/models/user_spec.rb:28:in `block (2 levels) in <top (required)>'
</code>```

Factories.rb

```<code>Factory.define :user do |user|
  user.name                   "Test User"
  user.email                  "user@example.com"
  user.password               "password"
  user.password_confirmation  "password"
end
</code>```

user_spec.rb

```<code>require 'spec_helper'

describe User do
  before(:each) do
    @user = Factory.build(:user)
  end

  it "should create a new instance of a user given valid attributes" do
    User.create!(@user.attributes)
  end
end
</code>```

user.rb

```<code>class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me
end
</code>```

答:
In Factory Girl, this create attributes:

```<code>@user_attr = Factory.attributes_for(:user)
</code>```

And this create a new instance:

```<code>@user = Factory(:user)
</code>```

So change the above and try:

```<code>User.create!(@user_attr)
</code>```

In depth, what you're trying to do fails because:

you were creating a new unsaved instance

password is a virtual attribute

the attributes of the instance do not contain the virtual attributes (I guess)

Body:
I think there is a problem with my user factory being built. I'm getting an error saying that the password cannot be blank, but it's clearly set in my factories.rb. Does anyone see anything that I may be missing? Or a reason as to why the spec is failing? I do a very similar thing for one of my other models, and it seems to be successful. I'm not sure if the error is being caused by devise or not.

Rspec Error

User should create a new instance of a user given valid attributes
Failure/Error: User.create!(@user.attributes)
ActiveRecord::RecordInvalid:
  Validation failed: Password can't be blank
# ./spec/models/user_spec.rb:28:in `block (2 levels) in <top (required)>'

Factories.rb

Factory.define :user do |user|
  user.name                   "Test User"
  user.email                  "user@example.com"
  user.password               "password"
  user.password_confirmation  "password"
end

user_spec.rb

require 'spec_helper'

describe User do
  before(:each) do
    @user = Factory.build(:user)
  end

  it "should create a new instance of a user given valid attributes" do
    User.create!(@user.attributes)
  end
end

user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me
end

Body:
In Factory Girl, this create attributes:

@user_attr = Factory.attributes_for(:user)

And this create a new instance:

@user = Factory(:user)

So change the above and try:

User.create!(@user_attr)

In depth, what you're trying to do fails because:

you were creating a new unsaved instance

password is a virtual attribute

the attributes of the instance do not contain the virtual attributes (I guess)


答:
Why can't the section .strtab be extracted?

Possibly because of this bug in binutils.

How can I extract this section?

Try:

```<code>readelf -x.strtab main.o
</code>```

Title: How to extract all of the sections in an obj file

Body:
I'm working on an X86_64 Ubuntu machine. I know that we can use the command to extract some sections from an obj file.

Saying that I have an obj file, named main.o, now I can do things below:

me@my-machine:~/tmp$ readelf -S main.o

There are 13 section headers, starting at offset 0x428:

Section Headers:
  [Nr] Name              Type             Address           Offset
       Size              EntSize          Flags  Link  Info  Align
  [ 0]                   NULL             0000000000000000  00000000
       0000000000000000  0000000000000000           0     0     0
  [ 1] .text             PROGBITS         0000000000000000  00000040
       0000000000000055  0000000000000000  AX       0     0     1
  [ 2] .rela.text        RELA             0000000000000000  00000318
       0000000000000078  0000000000000018   I      11     1     8
  [ 3] .data             PROGBITS         0000000000000000  00000098
       0000000000000008  0000000000000000  WA       0     0     4
  [ 4] .bss              NOBITS           0000000000000000  000000a0
       0000000000000004  0000000000000000  WA       0     0     4
  [ 5] .rodata           PROGBITS         0000000000000000  000000a0
       0000000000000004  0000000000000000   A       0     0     1
  [ 6] .comment          PROGBITS         0000000000000000  000000a4
       0000000000000036  0000000000000001  MS       0     0     1
  [ 7] .note.GNU-stack   PROGBITS         0000000000000000  000000da
       0000000000000000  0000000000000000           0     0     1
  [ 8] .eh_frame         PROGBITS         0000000000000000  000000e0
       0000000000000058  0000000000000000   A       0     0     8
  [ 9] .rela.eh_frame    RELA             0000000000000000  00000390
       0000000000000030  0000000000000018   I      11     8     8
  [10] .shstrtab         STRTAB           0000000000000000  000003c0
       0000000000000061  0000000000000000           0     0     1
  [11] .symtab           SYMTAB           0000000000000000  00000138
       0000000000000180  0000000000000018          12    11     8
  [12] .strtab           STRTAB           0000000000000000  000002b8
       000000000000005d  0000000000000000           0     0     1
Key to Flags:
  W (write), A (alloc), X (execute), M (merge), S (strings), l (large)
  I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
  O (extra OS processing required) o (OS specific), p (processor specific)

Then I can extract some sections with the help of the command objdump, for example,

me@my-machine:~/tmp$ objdump -s -j .data main.o

main.o:     file format elf64-x86-64

Contents of section .data:
 0000 54000000 55000000                    T...U...

As we can see, I extract the section .data here.

However, if I try to extract another section, it doesn't seem to work as expected.

me@my-machine:~/tmp$ objdump -s -j .strtab main.o

main.o:     file format elf64-x86-64

objdump: section '.strtab' mentioned in a -j option, but not found in any input file

Why can't the section .strtab be extracted? How can I extract this section?

Body:
Why can't the section .strtab be extracted?

Possibly because of this bug in binutils.

How can I extract this section?

Try:

readelf -x.strtab main.o


答:
In Postgres you can do this using date_trunc()

```<code>update the_table
  set date = date_trunc('second', date);
</code>```

In Oracle you can cast it to a timestamp without milliseconds

```<code>update the_table
  set date = cast(date as timestamp(0));
</code>```

(The above is actually standard ANSI SQL and would work in Postgres as well)

Title: How to update the millisecond part of timestamp in sql?

Body:
I have a table like this, I need to update all millisecond value with zeros. How this can be achieved?

+-------------+-------------------------+
|     USER    |              DATE       |
+-------------+-------------------------+
| TEST        | 2020-02-20 19:19:16.130 |
| TEST        | 2020-02-20 19:19:31.113 |
+-------------+-------------------------+

Body:
In Postgres you can do this using date_trunc()

update the_table
  set date = date_trunc('second', date);

In Oracle you can cast it to a timestamp without milliseconds

update the_table
  set date = cast(date as timestamp(0));

(The above is actually standard ANSI SQL and would work in Postgres as well)