问:
How to convert a UTC datetime to a local datetime using only standard library?
I have a python datetime instance that was created using datetime.utcnow() and persisted in database.

For display, I would like to convert the datetime instance retrieved from the database to local datetime using the default local timezone (i.e., as if the datetime was created using datetime.now()).

How can I convert the UTC datetime to a local datetime using only python standard library (e.g., no pytz dependency)?

It seems one solution would be to use datetime.astimezone(tz), but how would you get the default local timezone?

答:
Python 3.9 adds the zoneinfo module so now it can be done as follows (stdlib only):

```<code>from zoneinfo import ZoneInfo
from datetime import datetime

utc_unaware = datetime(2020, 10, 31, 12)  # loaded from database
utc_aware = utc_unaware.replace(tzinfo=ZoneInfo('UTC'))  # make aware
local_aware = utc_aware.astimezone(ZoneInfo('localtime'))  # convert
</code>```

Central Europe is 1 or 2 hours ahead of UTC, so local_aware is:

```<code>datetime.datetime(2020, 10, 31, 13, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='localtime'))
</code>```

as str:

```<code>2020-10-31 13:00:00+01:00
</code>```

Windows has no system time zone database, so here an extra package is needed:

```<code>pip install tzdata
</code>```

There is a backport to allow use in Python 3.6 to 3.8:

```<code>sudo pip install backports.zoneinfo
</code>```

Then:

```<code>from backports.zoneinfo import ZoneInfo
</code>```

Body:
Python 3.9 adds the zoneinfo module so now it can be done as follows (stdlib only):

from zoneinfo import ZoneInfo
from datetime import datetime

utc_unaware = datetime(2020, 10, 31, 12)  # loaded from database
utc_aware = utc_unaware.replace(tzinfo=ZoneInfo('UTC'))  # make aware
local_aware = utc_aware.astimezone(ZoneInfo('localtime'))  # convert

Central Europe is 1 or 2 hours ahead of UTC, so local_aware is:

datetime.datetime(2020, 10, 31, 13, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='localtime'))

as str:

2020-10-31 13:00:00+01:00

Windows has no system time zone database, so here an extra package is needed:

pip install tzdata

There is a backport to allow use in Python 3.6 to 3.8:

sudo pip install backports.zoneinfo

Then:

from backports.zoneinfo import ZoneInfo


来源: stackexchange

问:
How to find latest rows in my msql using a specific column value
I have a table called Access_Status containing values such as below:

I would like the table to only return the Active users which are Tom Sullivan and John Martin.

It should NOT return the Active row for Marta Jenkins since Marta is actually suspended.

What's the best approach for this?

答:
You can filter on the latest row per name with a correlated subquery, and ensure that the status is active:

```<code>select a.*
from access_status a
where
    t.last_updated_date = (
        select max(a1.last_updated_date)
        from access_status a1
        where a1.initial_id = a.initial_id
    )
    and a.access = 'ACTIVE'
</code>```

For performance, you want an index on (intial_id, last_updated_date). Adding access as a last column the index might also help.

ContentLicense: CC BY-SA 4.0

Body:
You can filter on the latest row per name with a correlated subquery, and ensure that the status is active:

select a.*
from access_status a
where
    t.last_updated_date = (
        select max(a1.last_updated_date)
        from access_status a1
        where a1.initial_id = a.initial_id
    )
    and a.access = 'ACTIVE'

For performance, you want an index on (intial_id, last_updated_date). Adding access as a last column the index might also help.


问:
Printing the DLLs imported by a PE (64 bit)
I seriously can't understand why this is happening. I'm able to correctly parse the majory of the PE format except for this. I'm trying to print all DLLs being used by a particular PE.

First I get the ImportTable from the Data Directory:

```<code>IMAGE_DATA_DIRECTORY importDir = (IMAGE_DATA_DIRECTORY)peHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
</code>```

Then I just add its address to the address where I mapped it,i.e the address returned by MapViewOfFile:

```<code>PIMAGE_IMPORT_DESCRIPTOR importDescriptor =
        (PIMAGE_IMPORT_DESCRIPTOR)((ULONG *)pe + importDir.VirtualAddress);

    printf("%s\n", (ULONGLONG *)pe + importDescriptor[0].Name);
</code>```

For some reason this is crashing, how do I go about this?

答:
Your pointer arithmetic is wrong.  (ULONG *)pe + ... and (ULONGLONG *)pe + ... don't do what you think they do.

When you advance a pointer T* by an integer N, the address stored in the pointer is advanced by N number of T elements - ie by N * sizeof(T) number of bytes.

When you type-cast pe to ULONG* and then add importDir.VirtualAddress to it, you are advancing the address stored in pe by sizeof(ULONG) * VirtualAddress number of bytes, rather than by VirtualAddress number of bytes.

Likewise, when you type-cast pe to ULONGLONG* and then add importDescriptor[0].Name to it, you are advancing the address in pe by sizeof(ULONGLONG) * Name number of bytes, rather than by Name number of bytes.

That is not what you want in this situation.  Virtual addresses in a PE are absolute offsets from the base address, so you need to advance the base address by N bytes, not multiples of N bytes, so any T* used for such a type-cast needs to be a pointer to a 1-byte data type, such as BYTE or char.

So, in your example, to advance your base address pe by N number of bytes, use BYTE* for the type cast, eg:

```<code>PIMAGE_IMPORT_DESCRIPTOR importDescriptor =
        (PIMAGE_IMPORT_DESCRIPTOR)(((LPBYTE)pe) + importDir.VirtualAddress);
...
printf("%s\n", (char*)(((LPBYTE)pe) + importDescriptor[0].Name));
</code>```

Alternatively, you can use integer arithmetic instead of pointer arithmetic, by type-casting your base address to an integer such as ULONG_PTR (a pointer-sized ULONG), eg:

```<code>PIMAGE_IMPORT_DESCRIPTOR importDescriptor =
        (PIMAGE_IMPORT_DESCRIPTOR)(((ULONG_PTR)pe) + importDir.VirtualAddress);
...
printf("%s\n", (char*)(((ULONG_PTR)pe) + importDescriptor[0].Name));
</code>```

Body:
I seriously can't understand why this is happening. I'm able to correctly parse the majory of the PE format except for this. I'm trying to print all DLLs being used by a particular PE.

First I get the ImportTable from the Data Directory:

IMAGE_DATA_DIRECTORY importDir = (IMAGE_DATA_DIRECTORY)peHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];

Then I just add its address to the address where I mapped it,i.e the address returned by MapViewOfFile:

PIMAGE_IMPORT_DESCRIPTOR importDescriptor =
        (PIMAGE_IMPORT_DESCRIPTOR)((ULONG *)pe + importDir.VirtualAddress);

    printf("%s\n", (ULONGLONG *)pe + importDescriptor[0].Name);

For some reason this is crashing, how do I go about this?

Body:
Your pointer arithmetic is wrong.  (ULONG *)pe + ... and (ULONGLONG *)pe + ... don't do what you think they do.

When you advance a pointer T* by an integer N, the address stored in the pointer is advanced by N number of T elements - ie by N * sizeof(T) number of bytes.

When you type-cast pe to ULONG* and then add importDir.VirtualAddress to it, you are advancing the address stored in pe by sizeof(ULONG) * VirtualAddress number of bytes, rather than by VirtualAddress number of bytes.

Likewise, when you type-cast pe to ULONGLONG* and then add importDescriptor[0].Name to it, you are advancing the address in pe by sizeof(ULONGLONG) * Name number of bytes, rather than by Name number of bytes.

That is not what you want in this situation.  Virtual addresses in a PE are absolute offsets from the base address, so you need to advance the base address by N bytes, not multiples of N bytes, so any T* used for such a type-cast needs to be a pointer to a 1-byte data type, such as BYTE or char.

So, in your example, to advance your base address pe by N number of bytes, use BYTE* for the type cast, eg:

PIMAGE_IMPORT_DESCRIPTOR importDescriptor =
        (PIMAGE_IMPORT_DESCRIPTOR)(((LPBYTE)pe) + importDir.VirtualAddress);
...
printf("%s\n", (char*)(((LPBYTE)pe) + importDescriptor[0].Name));

Alternatively, you can use integer arithmetic instead of pointer arithmetic, by type-casting your base address to an integer such as ULONG_PTR (a pointer-sized ULONG), eg:

PIMAGE_IMPORT_DESCRIPTOR importDescriptor =
        (PIMAGE_IMPORT_DESCRIPTOR)(((ULONG_PTR)pe) + importDir.VirtualAddress);
...
printf("%s\n", (char*)(((ULONG_PTR)pe) + importDescriptor[0].Name));


问:
list of regular expressions
I'm looking for a concise list of all the regular expression syntax (sort of like a cheatsheet) and I found this tool: http://erik.eae.net/playground/regexp/regexp.html

in which if you click on the question mark on the top right corner it will display some sort of dictionary of regular expressions...

my question is....is this list comprehensive or is it missing something?

if anyone knows a better list, please let me know as well

答:
Most of the things are there, but I suggest you go here: http://regular-expressions.mobi/quickstart.html.
In this page every single element is explained.

Good luck!

ContentLicense: CC BY-SA 3.0

Title: list of regular expressions


问:
Twitter bootstrap modal not working
I am new to Twitter Bootstrap. I am working on a modal panel, but it is not being displayed. It fades the screen, but the modal itself does not appear. I have checked the error console, and there are no errors.

My code is inside the  tag; I include the scripts like:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo $ruadmin ?>js/bootstrap.js"></script>
<script src="<?php echo $ruadmin ?>js/tablesorter/jquery.tablesorter.js"></script>
<script src="<?php echo $ruadmin ?>js/tablesorter/tables.js"></script>
</code>```

Modal page:

```<code><a data-toggle="modal" href="#myModal" class="btn btn-primary btn-large">Launch demo modal</a>

<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Welcome</h3>
  </div>
  <div class="modal-body">
    <p> Hello </p>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary">Save changes</button>
  </div>
</div>
</code>```

答:
Bootstrap Modal doesn't like Id's that start with a number.

I had a UUID as my data-target and it did not work.

```<code><button data-target="#7CB2ED35-3AE1-44FD-AEA8-D953E5C953D5">Launch Modal</button>
</code>```

I solved it by pre-pend "M-" before all my UUID's so they're still unique:

```<code><button data-target="#M-7CB2ED35-3AE1-44FD-AEA8-D953E5C953D5">Launch Modal</button>
</code>```

✌

Title: Twitter bootstrap modal not working

Body:
I am new to Twitter Bootstrap. I am working on a modal panel, but it is not being displayed. It fades the screen, but the modal itself does not appear. I have checked the error console, and there are no errors.

My code is inside the  tag; I include the scripts like:

Modal page:

Launch demo modal

    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Welcome

 Hello

    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary">Save changes</button>

Body:
Bootstrap Modal doesn't like Id's that start with a number.

I had a UUID as my data-target and it did not work.

<button data-target="#7CB2ED35-3AE1-44FD-AEA8-D953E5C953D5">Launch Modal</button>

I solved it by pre-pend "M-" before all my UUID's so they're still unique:

<button data-target="#M-7CB2ED35-3AE1-44FD-AEA8-D953E5C953D5">Launch Modal</button>

✌


答:
This approach would help you for getting rows as your need</p>

```<code>SELECT * FROM Access_Status GROUP BY Name WHERE Access="ACTIVE";
</code>```

Title: How to find latest rows in my msql using a specific column value

Body:
I have a table called Access_Status containing values such as below:

I would like the table to only return the Active users which are Tom Sullivan and John Martin.

It should NOT return the Active row for Marta Jenkins since Marta is actually suspended.

What's the best approach for this?

Body:
This approach would help you for getting rows as your need

SELECT * FROM Access_Status GROUP BY Name WHERE Access="ACTIVE";


问:
Understanding the decompilation of an object to source code
First of all, I am a student, I do not yet have extensive knowledge about C, C ++ and assembler, so I am making a extreme effort to understand it.

I have this piece of assembly code from an Intel x86-32 bit processor.

My goal is to transform it to source code.

```<code>0x80483dc <main>:    push       ebp
0x80483dd <main+1>:  mov        ebp,esp
0x80483df <main+3>:  sub        esp,0x10
0x80483e2 <main+6>:  mov        DWORD PTR [ebp-0x8],0x80484d0
0x80483e9 <main+13>: lea        eax,[ebp-0x8]
0x80483ec <main+16>: mov        DWORD PTR [ebp-0x4],eax
0x80483ef <main+19>: mov        eax,DWORD PTR [ebp-0x4]
0x80483f2 <main+22>: mov        edx,DWORD PTR [eax+0xc]
0x80483f5 <main+25>: mov        eax,DWORD PTR [ebp-0x4]
0x80483f8 <main+28>: movzx      eax,WORD PTR [eax+0x10]
0x80483fc <main+32>: cwde
0x80483fd <main+33>: add        edx, eax
0x80483ff <main+35>: mov        eax,DWORD PTR [ebp-0x4]
0x8048402 <main+38>: mov        DWORD PTR [eax+0xc],edx
0x8048405 <main+41>: mov        eax,DWORD PTR [ebp-0x4]
0x8048408 <main+44>: movzx      eax,BYTE PTR [eax]
0x804840b <main+47>: cmp        al,0x4f
0x804840d <main+49>: jne        0x8048419 <main+61>
0x804840f <main+51>: mov        eax,DWORD PTR [ebp-0x4]
0x8048412 <main+54>: movzx      eax,BYTE PTR [eax]
0x8048415 <main+57>: cmp        al,0x4b
0x8048417 <main+59>: je         0x804842d <main+81>
0x8048419 <main+61>: mov        eax,DWORD PTR [ebp-0x4]
0x804841c <main+64>: mov        eax,DWORD PTR [eax+0xc]
0x804841f <main+67>: mov        edx, eax
0x8048421 <main+69>: and        edx,0xf0f0f0f
0x8048427 <main+75>: mov        eax,DWORD PTR [ebp-0x4]
0x804842a <main+78>: mov        DWORD PTR [eax+0x4],edx
0x804842d <main+81>: mov        eax,0x0
0x8048432 <main+86>: leave
0x8048433 <main+87>: ret
</code>```

This is what I understand from the code:

There are 4 variables:

```<code>a = [ebp-0x8] ebp
b = [ebp-0x4] eax
c = [eax + 0xc] edx
d = [eax + 0x10] eax
</code>```

Values:

```<code>0x4 = 4
0x8 = 8
0xc = 12
0x10 = 16
0x4b = 75
0x4f = 79
</code>```

Types:

```<code>char (8 bits) = 1 BYTE
short (16 bits) = WORD
int (32 bit) = DWORD
long (32 bits) = DWORD
long long (32 bit) = DWORD
</code>```

This is what I was able to create:

```<code>#include <stdio.h>
int main (void)
{
   int a = 0x80484d0;
   int b
   short c;
   int d;

   c + b?
if (79 <= al) {
instructions
} else {
instructions
}

   return 0
}
</code>```

But I'm stuck. Nor can I understand what the sentence "cmp al .." compares to, what is "al"?

How do these instructions work?

EDIT1:

That said, as you comment the assembly seems to be wrong or as someone comments say, it is insane!

The code and the exercise are from the following book called: "Reversing, Reverse Engineering" on page 140 (3.8 Proposed Exercises). It would never have occurred to me that it was wrong, if so, this clearly makes it difficult for me to learn ...

So it is not possible to do a reversing to get the source code because it is not a good assembly? Maybe I am not oppressed? Is it possible to optimize it?

EDIT2:

Hi!

I did ask and finally she says this should be the c code:

```<code>inf foo(void){
    char *string;//ebp-0x8
    unsigned int *pointerstring//[ebp-0x4]
    unsigned int *position;
    *position = *(pointerstring+0xc);
    unsigned char character;
    character=(unsigned char) string[*position];
    if ((character != 0x4)||(character != 0x4b))
    {
     *(position+0x4)=(unsigned int)(*position & 0x0f0f0f0f);
    }
    return(0);
}
</code>```

Does it have any sense at all for you?, could someone please explain this to me?
Does anyone really program like this?

Thanks very much!

答:
You have analyzed variables, and that's a good place to start.  You should try to add type annotations to them, size, as you started, and, when used as pointers (like b), pointers to what kind/size.

I might update your variable chart as follows, knowing that [ebp-4] is b:

```<code>c = [b + 0xc]
d = [b + 0x10]
e = [b + 0], size = byte
</code>```

Another thing to analyze is the control flow.  For most instructions control flow is sequential, but certain instructions purposefully alter it.  Broadly speaking, when the pc is moved forward, it skips some code and when the pc is moved backward it repeats some code it already ran.  Skipping code is used to construct if-then, if-then-else, and statements that break out of loops.  Jumping back is used to continue looping.

Some instructions, called conditional branches, on some dynamic condition being true: skip forward (or backwards) and on being false do the simple sequential advancement to the next instruction (sometimes called conditional branch fall through).

The control sequences here:

```<code>...
0x8048405 <main+41>: mov        eax,DWORD PTR [ebp-0x4]    b
0x8048408 <main+44>: movzx      eax,BYTE PTR [eax]         b->e

0x804840b <main+47>: cmp        al,0x4f                    b->e <=> 'O'
0x804840d <main+49>: jne        0x8048419 <main+61>        b->e != 'O'  skip to 61

** we know that the letter, a->e, must be 'O' here

0x804840f <main+51>: mov        eax,DWORD PTR [ebp-0x4]    b
0x8048412 <main+54>: movzx      eax,BYTE PTR [eax]         b->e

0x8048415 <main+57>: cmp        al,0x4b                    b->e <=> 'K'
0x8048417 <main+59>: je         0x804842d <main+81>        b->e == 'K' skip to 81

** we know that the letter, a->e must not be 'K' here if we fall thru the above je

** this line can be reached by taken branch jne or by fall thru je
0x8048419 <main+61>: mov        eax,DWORD PTR [ebp-0x4]    ******
...
</code>```

The flow of control reaches this last line tagged we know that either the letter is either not 'O' or it is not 'K'.

The construct where the jne instruction is used to skip another test is a short-circuit || operator.  Thus the control construct is:

```<code>if ( a->e != 'O' || a->e != 'K' ) {
    then-part
}
</code>```

As that these two conditional branches are the only flow control modifications in the function, there is no else part of the if, and there are no loops or other if's.

This code appears to have a slight problem.

If the value is not 'O', the then-part will fire from the first test.  However, if we reach the 2nd test, we already know the letter is 'O', so testing it for 'K' is silly and will be true ('O' is not 'K').

Thus, this if-then will always fire.

It is either very inefficient, or, there is a bug that perhaps it is the next letter along in the (presumably) string should be tested for 'K' not the same exact letter.

Body:
First of all, I am a student, I do not yet have extensive knowledge about C, C ++ and assembler, so I am making a extreme effort to understand it.

I have this piece of assembly code from an Intel x86-32 bit processor.

My goal is to transform it to source code.

0x80483dc :    push       ebp
0x80483dd :  mov        ebp,esp
0x80483df :  sub        esp,0x10
0x80483e2 :  mov        DWORD PTR [ebp-0x8],0x80484d0
0x80483e9 : lea        eax,[ebp-0x8]
0x80483ec : mov        DWORD PTR [ebp-0x4],eax
0x80483ef : mov        eax,DWORD PTR [ebp-0x4]
0x80483f2 : mov        edx,DWORD PTR [eax+0xc]
0x80483f5 : mov        eax,DWORD PTR [ebp-0x4]
0x80483f8 : movzx      eax,WORD PTR [eax+0x10]
0x80483fc : cwde
0x80483fd : add        edx, eax
0x80483ff : mov        eax,DWORD PTR [ebp-0x4]
0x8048402 : mov        DWORD PTR [eax+0xc],edx
0x8048405 : mov        eax,DWORD PTR [ebp-0x4]
0x8048408 : movzx      eax,BYTE PTR [eax]
0x804840b : cmp        al,0x4f
0x804840d : jne        0x8048419
0x804840f : mov        eax,DWORD PTR [ebp-0x4]
0x8048412 : movzx      eax,BYTE PTR [eax]
0x8048415 : cmp        al,0x4b
0x8048417 : je         0x804842d
0x8048419 : mov        eax,DWORD PTR [ebp-0x4]
0x804841c : mov        eax,DWORD PTR [eax+0xc]
0x804841f : mov        edx, eax
0x8048421 : and        edx,0xf0f0f0f
0x8048427 : mov        eax,DWORD PTR [ebp-0x4]
0x804842a : mov        DWORD PTR [eax+0x4],edx
0x804842d : mov        eax,0x0
0x8048432 : leave
0x8048433 : ret

This is what I understand from the code:

There are 4 variables:

a = [ebp-0x8] ebp
b = [ebp-0x4] eax
c = [eax + 0xc] edx
d = [eax + 0x10] eax

Values:

0x4 = 4
0x8 = 8
0xc = 12
0x10 = 16
0x4b = 75
0x4f = 79

Types:

char (8 bits) = 1 BYTE
short (16 bits) = WORD
int (32 bit) = DWORD
long (32 bits) = DWORD
long long (32 bit) = DWORD

This is what I was able to create:

#include <stdio.h>
int main (void)
{
   int a = 0x80484d0;
   int b
   short c;
   int d;

   c + b?
if (79 <= al) {
instructions
} else {
instructions
}

   return 0
}

But I'm stuck. Nor can I understand what the sentence "cmp al .." compares to, what is "al"?

How do these instructions work?

EDIT1:

That said, as you comment the assembly seems to be wrong or as someone comments say, it is insane!

The code and the exercise are from the following book called: "Reversing, Reverse Engineering" on page 140 (3.8 Proposed Exercises). It would never have occurred to me that it was wrong, if so, this clearly makes it difficult for me to learn ...

So it is not possible to do a reversing to get the source code because it is not a good assembly? Maybe I am not oppressed? Is it possible to optimize it?

EDIT2:

Hi!

I did ask and finally she says this should be the c code:

inf foo(void){
    char *string;//ebp-0x8
    unsigned int *pointerstring//[ebp-0x4]
    unsigned int *position;
    *position = *(pointerstring+0xc);
    unsigned char character;
    character=(unsigned char) string[*position];
    if ((character != 0x4)||(character != 0x4b))
    {
     *(position+0x4)=(unsigned int)(*position & 0x0f0f0f0f);
    }
    return(0);
}

Does it have any sense at all for you?, could someone please explain this to me?
Does anyone really program like this?

Thanks very much!

Body:
You have analyzed variables, and that's a good place to start.  You should try to add type annotations to them, size, as you started, and, when used as pointers (like b), pointers to what kind/size.

I might update your variable chart as follows, knowing that [ebp-4] is b:

c = [b + 0xc]
d = [b + 0x10]
e = [b + 0], size = byte

Another thing to analyze is the control flow.  For most instructions control flow is sequential, but certain instructions purposefully alter it.  Broadly speaking, when the pc is moved forward, it skips some code and when the pc is moved backward it repeats some code it already ran.  Skipping code is used to construct if-then, if-then-else, and statements that break out of loops.  Jumping back is used to continue looping.

Some instructions, called conditional branches, on some dynamic condition being true: skip forward (or backwards) and on being false do the simple sequential advancement to the next instruction (sometimes called conditional branch fall through).

The control sequences here:

...
0x8048405 <main+41>: mov        eax,DWORD PTR [ebp-0x4]    b
0x8048408 <main+44>: movzx      eax,BYTE PTR [eax]         b->e

0x804840b <main+47>: cmp        al,0x4f                    b->e <=> 'O'
0x804840d <main+49>: jne        0x8048419 <main+61>        b->e != 'O'  skip to 61

** we know that the letter, a->e, must be 'O' here

0x804840f <main+51>: mov        eax,DWORD PTR [ebp-0x4]    b
0x8048412 <main+54>: movzx      eax,BYTE PTR [eax]         b->e

0x8048415 <main+57>: cmp        al,0x4b                    b->e <=> 'K'
0x8048417 <main+59>: je         0x804842d <main+81>        b->e == 'K' skip to 81

** we know that the letter, a->e must not be 'K' here if we fall thru the above je

** this line can be reached by taken branch jne or by fall thru je
0x8048419 <main+61>: mov        eax,DWORD PTR [ebp-0x4]    ******
...

The flow of control reaches this last line tagged we know that either the letter is either not 'O' or it is not 'K'.

The construct where the jne instruction is used to skip another test is a short-circuit || operator.  Thus the control construct is:

if ( a->e != 'O' || a->e != 'K' ) {
    then-part
}

As that these two conditional branches are the only flow control modifications in the function, there is no else part of the if, and there are no loops or other if's.

This code appears to have a slight problem.

If the value is not 'O', the then-part will fire from the first test.  However, if we reach the 2nd test, we already know the letter is 'O', so testing it for 'K' is silly and will be true ('O' is not 'K').

Thus, this if-then will always fire.

It is either very inefficient, or, there is a bug that perhaps it is the next letter along in the (presumably) string should be tested for 'K' not the same exact letter.


问:
How to store a const char* in std :: string?
```<code>    char       *buffer1 = "abc";

    const char *buffer2 = (const char*) buffer;

    std :: string str (buffer2);
</code>```

This works, but I want to declare the std::string object i.e. str, once and use it many times to store different const char*.

What's the way out?

答:
Ah well, as I commented above, found the answer soon after posting the question :doh:

```<code>    const char* g;
    g = (const char*)buffer;

    std :: string str;
    str.append (g);
</code>```

So, I can call append() function as many times (after using the clear()) as I want on the same object with "const char *".

Though the "push_back" function won't work in place of "append".

Body:
    char       *buffer1 = "abc";

    const char *buffer2 = (const char*) buffer;

    std :: string str (buffer2);

This works, but I want to declare the std::string object i.e. str, once and use it many times to store different const char*.

What's the way out?

Body:
Ah well, as I commented above, found the answer soon after posting the question :doh:

    const char* g;
    g = (const char*)buffer;

    std :: string str;
    str.append (g);

So, I can call append() function as many times (after using the clear()) as I want on the same object with "const char *".

Though the "push_back" function won't work in place of "append".


问:
Accelerate 2 loops with regex to find email address on website
I need help to find email adress on website. After some research, I found the solution but it's so long, I have a lot of datas (more than 90 000) and my code never stop.

Do you know tips to optimize/accelerate my code ?

This is my list of the URL:

```<code>http://etsgaidonsarl.site-solocal.com/
http://fr-fr.facebook.com/people/
http://ipm-mondia.com/
http://lfgenieclimatique.fr/
http://vpcinstallation.site-solocal.com
http://www.cavifroid.fr/
http://www.clim-monnier.com/
http://www.climacool.net/

</code>```

I use 2 loops. The first is to find all pages of a website because the email adresse is not every time on the first page.
In the second loop, I scrall the page to find the email address, the code :

```<code>EMAIL_REGEX = r"""(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-zA-Z](?:[a-z0-9-]*[a-zA-Z])?\.)+[a-zA-Z](?:[a-z0-9-]*[a-zA-Z])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-zA-Z]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])"""
</code>```

I think my regex is too long, it can be a problem ?

```<code>session = HTMLSession()

mailing=[]
for index, i in enumerate(link): #link is the list of the URLs
    try:
        r = session.get(i)
        site=r.html.absolute_links
        linkslist = list(r.html.absolute_links)
    except:
        linkslist=list(i)
    for j in linkslist:
        try:
            r1 = session.get(j)
            for re_match in re.finditer(EMAIL_REGEX, r1.html.raw_html.decode()):
            mail=(re_match.group())
            liste=[index,mail,j]
            mailing.append(liste)
        except:
            pass

print(mailing)
df = pd.DataFrame(mailing, columns=['index1','mail','lien',])

</code>```

Thank's for your help

答:
I think multi-threading should do the job. your regex, i don't know what it does but assuming its working and helpful, the multi-threaded version should look like the following. I tested the code, it works.</p>

```<code>`from threading import Thread, Lock
from requests_html import HTMLSession
import re
lock = Lock()
link = ["http://etsgaidonsarl.site-solocal.com/",
"http://fr-fr.facebook.com/people/",
"http://ipm-mondia.com/",
"http://lfgenieclimatique.fr/",
"http://vpcinstallation.site-solocal.com",
"http://www.cavifroid.fr/",
"http://www.clim-monnier.com/",
"http://www.climacool.net/"]
linklist = []
mailing = []
main_threads = []
minor_threads = []
EMAIL_REGEX = r"""(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-zA-Z](?:[a-z0-9-]*[a-zA-Z])?\.)+[a-zA-Z](?:[a-z0-9-]*[a-zA-Z])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-zA-Z]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])"""

def links_scraper(single_url):
    try:
        session = HTMLSession()
        r = session.get(single_url)
        site=r.html.absolute_links
        the_list = list(r.html.absolute_links)
        linklist.extend(list(zip([single_url for _ in range(len(the_list))], the_list)))
    except Exception as e:
        # print("Exception:", e)
        linklist.append((single_url, single_url))

def mail_scrapper(main_url, single_link):
    try:
        session = HTMLSession()
        r1 = session.get(single_link)
        for re_match in re.finditer(EMAIL_REGEX, r1.html.raw_html.decode()):
            mail=(re_match.group())
            liste=[link.index(main_url),mail,single_link]
            mailing.append(liste)
    except Exception as e:
        # print(f"Exception: {e}")
        pass

def main():
    for l in link:
        t = Thread(target=links_scraper, args=(l,))
        t.start()
        main_threads.append(t)

    while len(main_threads) > 0:
        try:
            with lock:
                current_link = linklist.pop(0)
            minor_thread = Thread(target=mail_scrapper, args=(current_link[0], current_link[1]))
            minor_threads.append(minor_thread)
            minor_thread.start()
        except IndexError:
            pass
        for t in main_threads:
            if t.isAlive() == False:
                main_threads.pop(main_threads.index(t))

    for t in minor_threads:
        t.join()

main()
print("Mailing:", mailing)`
</code>```

Body:
I need help to find email adress on website. After some research, I found the solution but it's so long, I have a lot of datas (more than 90 000) and my code never stop.

Do you know tips to optimize/accelerate my code ?

This is my list of the URL:

http://etsgaidonsarl.site-solocal.com/
http://fr-fr.facebook.com/people/
http://ipm-mondia.com/
http://lfgenieclimatique.fr/
http://vpcinstallation.site-solocal.com
http://www.cavifroid.fr/
http://www.clim-monnier.com/
http://www.climacool.net/

I use 2 loops. The first is to find all pages of a website because the email adresse is not every time on the first page.
In the second loop, I scrall the page to find the email address, the code :

EMAIL_REGEX = r"""(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-zA-Z](?:[a-z0-9-]*[a-zA-Z])?\.)+[a-zA-Z](?:[a-z0-9-]*[a-zA-Z])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-zA-Z]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])"""

I think my regex is too long, it can be a problem ?

session = HTMLSession()

mailing=[]
for index, i in enumerate(link): #link is the list of the URLs
    try:
        r = session.get(i)
        site=r.html.absolute_links
        linkslist = list(r.html.absolute_links)
    except:
        linkslist=list(i)
    for j in linkslist:
        try:
            r1 = session.get(j)
            for re_match in re.finditer(EMAIL_REGEX, r1.html.raw_html.decode()):
            mail=(re_match.group())
            liste=[index,mail,j]
            mailing.append(liste)
        except:
            pass

print(mailing)
df = pd.DataFrame(mailing, columns=['index1','mail','lien',])

Thank's for your help

Body:
I think multi-threading should do the job. your regex, i don't know what it does but assuming its working and helpful, the multi-threaded version should look like the following. I tested the code, it works.

`from threading import Thread, Lock
from requests_html import HTMLSession
import re
lock = Lock()
link = ["http://etsgaidonsarl.site-solocal.com/",
"http://fr-fr.facebook.com/people/",
"http://ipm-mondia.com/",
"http://lfgenieclimatique.fr/",
"http://vpcinstallation.site-solocal.com",
"http://www.cavifroid.fr/",
"http://www.clim-monnier.com/",
"http://www.climacool.net/"]
linklist = []
mailing = []
main_threads = []
minor_threads = []
EMAIL_REGEX = r"""(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-zA-Z](?:[a-z0-9-]*[a-zA-Z])?\.)+[a-zA-Z](?:[a-z0-9-]*[a-zA-Z])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-zA-Z]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])"""

def links_scraper(single_url):
    try:
        session = HTMLSession()
        r = session.get(single_url)
        site=r.html.absolute_links
        the_list = list(r.html.absolute_links)
        linklist.extend(list(zip([single_url for _ in range(len(the_list))], the_list)))
    except Exception as e:
        # print("Exception:", e)
        linklist.append((single_url, single_url))

def mail_scrapper(main_url, single_link):
    try:
        session = HTMLSession()
        r1 = session.get(single_link)
        for re_match in re.finditer(EMAIL_REGEX, r1.html.raw_html.decode()):
            mail=(re_match.group())
            liste=[link.index(main_url),mail,single_link]
            mailing.append(liste)
    except Exception as e:
        # print(f"Exception: {e}")
        pass

def main():
    for l in link:
        t = Thread(target=links_scraper, args=(l,))
        t.start()
        main_threads.append(t)

    while len(main_threads) > 0:
        try:
            with lock:
                current_link = linklist.pop(0)
            minor_thread = Thread(target=mail_scrapper, args=(current_link[0], current_link[1]))
            minor_threads.append(minor_thread)
            minor_thread.start()
        except IndexError:
            pass
        for t in main_threads:
            if t.isAlive() == False:
                main_threads.pop(main_threads.index(t))

    for t in minor_threads:
        t.join()

main()
print("Mailing:", mailing)`


问:
Issue when migrate Spring Boot 2.2.6 to Spring Boot 2.3.0
```<code>
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springApplicationAdminRegistrar' defined in class path resource [org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.class]: Unsatisfied dependency expressed through method 'springApplicationAdminRegistrar' parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.env.Environment' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:539) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners(AbstractApplicationEventMulticaster.java:245) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:197) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:134) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:403) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:360) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.boot.availability.AvailabilityChangeEvent.publish(AvailabilityChangeEvent.java:81) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.availability.AvailabilityChangeEvent.publish(AvailabilityChangeEvent.java:67) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.doClose(ServletWebServerApplicationContext.java:167) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:978) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:814) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:325) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at sh.platform.template.Application.main(Application.java:10) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.3.0.RELEASE.jar:2.3.0.RELEASE]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.env.Environment' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1716) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1272) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:885) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:789) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    ... 28 common frames omitted

Process finished with exit code 0

</code>```

That is my demo code: https://github.com/platformsh-templates/spring-mvc-maven-mongodb/tree/update_template

I googled it, however, I did not find the issue on this migration.

答:
Missed beans from spring-data-mongodb.
In your pom.xml, replace:

```<code><dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
</dependency>
</code>```

By:

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</code>```

Body:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springApplicationAdminRegistrar' defined in class path resource [org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.class]: Unsatisfied dependency expressed through method 'springApplicationAdminRegistrar' parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.env.Environment' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:539) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners(AbstractApplicationEventMulticaster.java:245) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:197) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:134) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:403) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:360) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.boot.availability.AvailabilityChangeEvent.publish(AvailabilityChangeEvent.java:81) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.availability.AvailabilityChangeEvent.publish(AvailabilityChangeEvent.java:67) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.doClose(ServletWebServerApplicationContext.java:167) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:978) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:814) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:325) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at sh.platform.template.Application.main(Application.java:10) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.3.0.RELEASE.jar:2.3.0.RELEASE]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.env.Environment' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1716) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1272) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:885) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:789) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    ... 28 common frames omitted

Process finished with exit code 0

That is my demo code: https://github.com/platformsh-templates/spring-mvc-maven-mongodb/tree/update_template

I googled it, however, I did not find the issue on this migration.

Body:
Missed beans from spring-data-mongodb.
In your pom.xml, replace:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
</dependency>

By:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>


问:
jquery tablesorter problem
hello
i get some help here yesterday for a problem i was having tablesorter. if i run the backend query on its own it displays the results ok. but i call it from another page from dropdown it displays all records and no errors are being seen in firebug. where am i going wrong? thanks

this code works on its own.

getuserlog.php

```<code><?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'root', '');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("sample", $con);

$sql="SELECT * FROM logger_log WHERE idusr_log = '".$q."' order by datein_log desc";

$result = mysql_query($sql);

echo "<table id=\"userlog\" class=\"tablesorter\" cellspacing=\"1\">
<thead>
<tr>
<th align=\"left\">Ip Address</th>
<th align=\"left\">Date In</th>
<th align=\"left\">Date Out</th>
</tr>
</thead>";
    echo "<tbody>";
while($row = mysql_fetch_array($result))
  {

  echo "<tr>";
  echo "<td>" . $row['ip_log'] . "</td>";
  echo "<td>" . date('d/m/Y H:i:s',strtotime($row['datein_log'])) . "</td>";
  echo "<td>" . date('d/m/Y H:i:s',strtotime($row['dateout_log'])) . "</td>";
  echo "</tr>";

  }
   echo"</tbody>";
echo "</table>";

mysql_close($con);
?>
<div id="pager" class="pager">
    <form>
        <img src="css/blue/first.png" class="first"/>
        <img src="css/blue/prev.png" class="prev"/>
        <input type="text" class="pagedisplay"/>
        <img src="css/blue/next.png" class="next"/>
        <img src="css/blue/last.png" class="last"/>
        <select class="pagesize">
            <option selected="selected"  value="10">10</option>
            <option value="20">20</option>
            <option value="30">30</option>
            <option  value="40">40</option>
        </select>
    </form>
</div>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.pager.js"></script>
<link href="css/blue/style.css" rel="stylesheet" type="text/css" />
        <script>
        $(function() {
        $("#userlog")
            .tablesorter({widthFixed: true, widgets: ['zebra']})
            .tablesorterPager({container: $("#pager")});
    });

        </script>
</code>```

and this is the page i am calling it from.

userlog.php

```<code><script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuserlog.php?q="+str,true);
xmlhttp.send();
}
</script>

<div class="spacer"></div>
<div class="userlogTxt">This report shows all users who have logged in up until: <?php echo date("d/m/Y H:i:s"); ?></div>
        <br />
        <?php
            $conn = mysql_connect('localhost', 'root', '') or die(mysql_error());

            mysql_select_db("sample") or die(mysql_error());

            $result2 = mysql_query('SELECT * FROM user_usr ORDER BY name_usr ASC', $conn);
            echo '<select name="users" onchange="showUser(this.value)">';
            echo '<option value="selected">'. 'Select a user' . '</option>';
            while ($row = mysql_fetch_assoc($result2))
            {

            echo '<option value="'.$row['id_usr'].'">'.$row['name_usr'].'</option>';
            }
            echo '</select>';
        ?>
    <br /><br />
<div id="txtHint" class="userlogTxt">Logging information will be shown here.</div></div>
</code>```

@inti

it is not pulling any date from the db. just displaying header and pager.

userlog.php

```<code><script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.pager.js"></script>
<link href="css/blue/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
    function showUser(str)
        {
            $.get("getuserlog.php?q="+str,function(response) {
                $("#txtHint").html(response);
            // Tablesorter will run, just after you loaded the ajax response
            $("#userlog").tablesorter({widthFixed: true, widgets: ['zebra']})
            .tablesorterPager({container: $("#pager")
            });
                });
        }
</script>

<div class="spacer"></div>
<div class="userlogTxt">This report shows all users who have logged in up until: <?php echo date("d/m/Y H:i:s"); ?></div>
        <br />
        <?php
            $conn = mysql_connect('localhost', 'root', '') or die(mysql_error());

            mysql_select_db("sample") or die(mysql_error());

            $result2 = mysql_query('SELECT * FROM user_usr ORDER BY name_usr ASC', $conn);
            echo '<select name="users" onchange="showUser(this.value)">';
            echo '<option value="selected">'. 'Select a user' . '</option>';
            while ($row = mysql_fetch_assoc($result2))
            {

            echo '<option value="'.$row['id_usr'].'">'.$row['name_usr'].'</option>';
            }
            echo '</select>';
        ?>
    <br /><br />
<div id="txtHint" class="userlogTxt">Logging information will be shown here.</div></div>
</code>```

getuserlog.php

```<code><?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'root', '');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("sample", $con);

$sql="SELECT * FROM logger_log WHERE idusr_log = '".$q."' order by datein_log desc";

$result = mysql_query($sql);

echo "<table id=\"userlog\" class=\"tablesorter\" cellspacing=\"1\">
<thead>
<tr>
<th align=\"left\">Ip Address</th>
<th align=\"left\">Date In</th>
<th align=\"left\">Date Out</th>
</tr>
</thead>";
    echo "<tbody>";
while($row = mysql_fetch_array($result))
  {

  echo "<tr>";
  echo "<td>" . $row['ip_log'] . "</td>";
  echo "<td>" . date('d/m/Y H:i:s',strtotime($row['datein_log'])) . "</td>";
  echo "<td>" . date('d/m/Y H:i:s',strtotime($row['dateout_log'])) . "</td>";
  echo "</tr>";

  }
   echo"</tbody>";
echo "</table>";

mysql_close($con);
?>
<div id="pager" class="pager">
    <form>
        <img src="css/blue/first.png" class="first"/>
        <img src="css/blue/prev.png" class="prev"/>
        <input type="text" class="pagedisplay"/>
        <img src="css/blue/next.png" class="next"/>
        <img src="css/blue/last.png" class="last"/>
        <select class="pagesize">
            <option selected="selected"  value="10">10</option>
            <option value="20">20</option>
            <option value="30">30</option>
            <option  value="40">40</option>
        </select>
    </form>
</div>
</code>```

where have i gone wrong? thanks

答:
I recommend you, to use the jQuery Ajax functions in userlog.php, and since the script inside getuserlog.php is constant, move it to the userlog.php, something like this:

```<code><script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.pager.js"></script>
<link href="css/blue/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
    function showUser(str)
    {
        $.get("getuserlog.php?q="+str,function(response) {
            $("#txtHint").html(response);
            // Tablesorter will run, just after you loaded the ajax response
            $("#userlog").tablesorter({widthFixed: true, widgets: ['zebra']})
                         .tablesorterPager({container: $("#pager")});
        });
    }
</script>
</code>```

EDIT: Put all you javascript in the main page. The ajax response should only contain the data you want to get from the server.

Title: jquery tablesorter problem

Body:
hello
i get some help here yesterday for a problem i was having tablesorter. if i run the backend query on its own it displays the results ok. but i call it from another page from dropdown it displays all records and no errors are being seen in firebug. where am i going wrong? thanks

this code works on its own.

getuserlog.php

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'root', '');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("sample", $con);

$sql="SELECT * FROM logger_log WHERE idusr_log = '".$q."' order by datein_log desc";

$result = mysql_query($sql);

echo "

Ip Address
Date In
Date Out

";
    echo "
";
while($row = mysql_fetch_array($result))
  {

  echo "
";
  echo "" . $row['ip_log'] . "	";
  echo "" . date('d/m/Y H:i:s',strtotime($row['datein_log'])) . "	";
  echo "" . date('d/m/Y H:i:s',strtotime($row['dateout_log'])) . "	";
  echo "
";

  }
   echo"
";
echo "
";

mysql_close($con);
?>

    <form>

        <input type="text" class="pagedisplay"/>

        <select class="pagesize">
            <option selected="selected"  value="10">10</option>
            <option value="20">20</option>
            <option value="30">30</option>
            <option  value="40">40</option>
        </select>
    </form>

<link href="css/blue/style.css" rel="stylesheet" type="text/css" />

and this is the page i am calling it from.

userlog.php

This report shows all users who have logged in up until: <?php echo date("d/m/Y H:i:s"); ?>

        <?php
            $conn = mysql_connect('localhost', 'root', '') or die(mysql_error());

            mysql_select_db("sample") or die(mysql_error());

            $result2 = mysql_query('SELECT * FROM user_usr ORDER BY name_usr ASC', $conn);
            echo '<select name="users" onchange="showUser(this.value)">';
            echo '<option value="selected">'. 'Select a user' . '</option>';
            while ($row = mysql_fetch_assoc($result2))
            {

            echo '<option value="'.$row['id_usr'].'">'.$row['name_usr'].'</option>';
            }
            echo '</select>';
        ?>

Logging information will be shown here.

@inti

it is not pulling any date from the db. just displaying header and pager.

userlog.php

<link href="css/blue/style.css" rel="stylesheet" type="text/css" />

This report shows all users who have logged in up until: <?php echo date("d/m/Y H:i:s"); ?>

        <?php
            $conn = mysql_connect('localhost', 'root', '') or die(mysql_error());

            mysql_select_db("sample") or die(mysql_error());

            $result2 = mysql_query('SELECT * FROM user_usr ORDER BY name_usr ASC', $conn);
            echo '<select name="users" onchange="showUser(this.value)">';
            echo '<option value="selected">'. 'Select a user' . '</option>';
            while ($row = mysql_fetch_assoc($result2))
            {

            echo '<option value="'.$row['id_usr'].'">'.$row['name_usr'].'</option>';
            }
            echo '</select>';
        ?>

Logging information will be shown here.

getuserlog.php

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'root', '');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("sample", $con);

$sql="SELECT * FROM logger_log WHERE idusr_log = '".$q."' order by datein_log desc";

$result = mysql_query($sql);

echo "

Ip Address
Date In
Date Out

";
    echo "
";
while($row = mysql_fetch_array($result))
  {

  echo "
";
  echo "" . $row['ip_log'] . "	";
  echo "" . date('d/m/Y H:i:s',strtotime($row['datein_log'])) . "	";
  echo "" . date('d/m/Y H:i:s',strtotime($row['dateout_log'])) . "	";
  echo "
";

  }
   echo"
";
echo "
";

mysql_close($con);
?>

    <form>

        <input type="text" class="pagedisplay"/>

        <select class="pagesize">
            <option selected="selected"  value="10">10</option>
            <option value="20">20</option>
            <option value="30">30</option>
            <option  value="40">40</option>
        </select>
    </form>

where have i gone wrong? thanks

Body:
I recommend you, to use the jQuery Ajax functions in userlog.php, and since the script inside getuserlog.php is constant, move it to the userlog.php, something like this:

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.pager.js"></script>
<link href="css/blue/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
    function showUser(str)
    {
        $.get("getuserlog.php?q="+str,function(response) {
            $("#txtHint").html(response);
            // Tablesorter will run, just after you loaded the ajax response
            $("#userlog").tablesorter({widthFixed: true, widgets: ['zebra']})
                         .tablesorterPager({container: $("#pager")});
        });
    }
</script>

EDIT: Put all you javascript in the main page. The ajax response should only contain the data you want to get from the server.


问:
Inserting records into postgreSQL database in Python

When I run this command in python,

```<code>command=("""INSERT INTO perms(role_id,resource_id,p_create,p_read,p_update,p_delete,p_execute) VALUES
(%s,%s,%s,%s,%s,%s,%s)""")
cur.execute(command(roleArray,reasourceArrray,data[2],data[3],data[4],data[5],data[6]))
</code>```

I get the following error

```<code>Traceback (most recent call last):
cur.execute(command(roleArray,reasourceArrray,data[2],data[3],data[4],data[5],data[6]))
psycopg2.ProgrammingError: can't adapt type 'numpy.int64'
bash: parse_git_branch: command not found
</code>```

Additional info:
RoleArray contains 792 records & looks like this
[102, 102, 102, 102, 102, 102, 103, 103, 105, 105, 106, 106, 106, 106, 106, 106, 106,...etc]

reasourceArrray contains 792 records & looks like this
[45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,...etc]

data[2],data[3],data[4],data[5],data[6] all contain 792 records & are boolean fields.

Any feedback on how to resolve the error?

UPDATE ----
  Thank you everyone for the feedback! In addition to the answer I upvoted
  check out this solution

```<code>for i, x, y in zip(RoleArray, resourceArray, range (0,len(data[2]))):
  data2Value=data[2][y]
  data3Value=data[3][y]
  data4Value=data[4][y]
  data5Value=data[5][y]
  data6Value=data[6][y]

  cur.execute("INSERT INTO perms (role_id,resource_id,p_create,p_read,p_update,p_delete,p_execute) VALUES('"
  +(i)+"','"+(x)+"','"+(str(data2Value))+"','"
  (str(data3Value))+"','"+(str(data4Value))+"','"
  (str(data5Value))+"','"+(str(data6Value))+"')")
  con.commit()
</code>```

答:
Consider executemany and properly separate query and parameters in execute call. Also convert pandas Series to lists for parameterization:

```<code>command = """INSERT INTO perms (role_id,resource_id,p_create,p_read,
                                p_update,p_delete,p_execute)
             VALUES (%s, %s, %s, %s, %s, %s, %s)
          """

cur.executemany(command, (roleArray, reasourceArrray,
                          data[2].tolist(), data[3].tolist(),
                          data[4].tolist(), data[5].tolist(),
                          data[6].tolist()))
myconn.commit()
</code>```

Body:
When I run this command in python,

command=("""INSERT INTO perms(role_id,resource_id,p_create,p_read,p_update,p_delete,p_execute) VALUES
(%s,%s,%s,%s,%s,%s,%s)""")
cur.execute(command(roleArray,reasourceArrray,data[2],data[3],data[4],data[5],data[6]))

I get the following error

Traceback (most recent call last):
cur.execute(command(roleArray,reasourceArrray,data[2],data[3],data[4],data[5],data[6]))
psycopg2.ProgrammingError: can't adapt type 'numpy.int64'
bash: parse_git_branch: command not found

Additional info:
RoleArray contains 792 records & looks like this
[102, 102, 102, 102, 102, 102, 103, 103, 105, 105, 106, 106, 106, 106, 106, 106, 106,...etc]

reasourceArrray contains 792 records & looks like this
[45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,...etc]

data[2],data[3],data[4],data[5],data[6] all contain 792 records & are boolean fields.

Any feedback on how to resolve the error?

UPDATE ----
  Thank you everyone for the feedback! In addition to the answer I upvoted
  check out this solution

for i, x, y in zip(RoleArray, resourceArray, range (0,len(data[2]))):
  data2Value=data[2][y]
  data3Value=data[3][y]
  data4Value=data[4][y]
  data5Value=data[5][y]
  data6Value=data[6][y]

  cur.execute("INSERT INTO perms (role_id,resource_id,p_create,p_read,p_update,p_delete,p_execute) VALUES('"
  +(i)+"','"+(x)+"','"+(str(data2Value))+"','"
  (str(data3Value))+"','"+(str(data4Value))+"','"
  (str(data5Value))+"','"+(str(data6Value))+"')")
  con.commit()

Body:
Consider executemany and properly separate query and parameters in execute call. Also convert pandas Series to lists for parameterization:

command = """INSERT INTO perms (role_id,resource_id,p_create,p_read,
                                p_update,p_delete,p_execute)
             VALUES (%s, %s, %s, %s, %s, %s, %s)
          """

cur.executemany(command, (roleArray, reasourceArrray,
                          data[2].tolist(), data[3].tolist(),
                          data[4].tolist(), data[5].tolist(),
                          data[6].tolist()))
myconn.commit()


问:
Get-AzureADUser - ALL - PowerShell Slow Get all users and users who made changes to account
I am working with Azure AD and need to get all users and export it into csv file and finally put it into SQL.

At this moment we have about 10,000 users. The problem is the PowerShell command [Get-AzureADUser – ALL] it’s SUPER SLOW!! It takes about 58 minutes to complete the task. Today we noticed that some users made changes to their account. I need to update the whole list to find the changes made.

My questions is:

1)  Is there a faster way I can get ALL users?

2)  How can I only find users who made changes to their account?

Powershell script:

```<code>$aadUsers = Get-AzureADUser -All $true | Select DisplayName, ObjectId, userType,GivenName
</code>```

答:
```<code>Get-msoluser -all | select DisplayName, ObjectId, userType, FirstName
Get-msoluser -all | select *
Get-msoluser -all | Where {$_.city -eq 'chicago'}
</code>```

This module seems quite a bit faster.

Body:
I am working with Azure AD and need to get all users and export it into csv file and finally put it into SQL.

At this moment we have about 10,000 users. The problem is the PowerShell command [Get-AzureADUser – ALL] it’s SUPER SLOW!! It takes about 58 minutes to complete the task. Today we noticed that some users made changes to their account. I need to update the whole list to find the changes made.

My questions is:

1)  Is there a faster way I can get ALL users?

2)  How can I only find users who made changes to their account?

Powershell script:

$aadUsers = Get-AzureADUser -All $true | Select DisplayName, ObjectId, userType,GivenName

Body:
Get-msoluser -all | select DisplayName, ObjectId, userType, FirstName
Get-msoluser -all | select *
Get-msoluser -all | Where {$_.city -eq 'chicago'}

This module seems quite a bit faster.


问:
Why does this ES6 function keep working after `return`?
I'm trying to create a simple function that checks to see if all of the items in an array are in order, but it's giving me a bit of unwanted behavior.  I've come up with this:

```<code>const isArrayInOrder = (array) => {
  let lowNum = Number.NEGATIVE_INFINITY;
  array.forEach((element, index) => {
    if (element < lowNum) {
      console.log("False");
      return false;
    }

    lowNum = element;
  });
  console.log("True!");
  return true;
};

let testArray = [1, 2, 3, 4, 7, 11, 22, 31, 800];
isArrayInOrder(testArray);

let testArray2 = [-800, -30, -5, 0, 10, 55, 200, 2000, 1999];
isArrayInOrder(testArray2);
</code>```

Calling isArrayInOrder() with testArray returns true, as expected.

Calling isArrayInOrder() with testArray2 returns false, but then goes on to unexpectedly execute the console.log("True!") command at the bottom of the function.

It seems to me once return false is hit that should be the end of the function, right? So how is it making it to this second console.log?

答:
You need to understand that return will return to the inner function.

So if you do:

```<code>const outerFunction = () => {
    const innerFunction = () => {
        return 'inner';
    }

    console.log(innerFunction()); // outputs 'inner';

     return 'outer';
}

console.log(outerFunction()); // outputs 'outer';
</code>```

What you are looking for is Array.prototype.every():

```<code>const isArrayInOrder = (array) => {
  let lowNum = Number.NEGATIVE_INFINITY;
  return array.every((element, index) => {
    if (element < lowNum) {
      return false;
    } else {
      lowNum = element;
      return true;
    }
  });
};
</code>```

Body:
I'm trying to create a simple function that checks to see if all of the items in an array are in order, but it's giving me a bit of unwanted behavior.  I've come up with this:

const isArrayInOrder = (array) => {
  let lowNum = Number.NEGATIVE_INFINITY;
  array.forEach((element, index) => {
    if (element < lowNum) {
      console.log("False");
      return false;
    }

    lowNum = element;
  });
  console.log("True!");
  return true;
};

let testArray = [1, 2, 3, 4, 7, 11, 22, 31, 800];
isArrayInOrder(testArray);

let testArray2 = [-800, -30, -5, 0, 10, 55, 200, 2000, 1999];
isArrayInOrder(testArray2);

Calling isArrayInOrder() with testArray returns true, as expected.

Calling isArrayInOrder() with testArray2 returns false, but then goes on to unexpectedly execute the console.log("True!") command at the bottom of the function.

It seems to me once return false is hit that should be the end of the function, right? So how is it making it to this second console.log?

Body:
You need to understand that return will return to the inner function.

So if you do:

const outerFunction = () => {
    const innerFunction = () => {
        return 'inner';
    }

    console.log(innerFunction()); // outputs 'inner';

     return 'outer';
}

console.log(outerFunction()); // outputs 'outer';

What you are looking for is Array.prototype.every():

const isArrayInOrder = (array) => {
  let lowNum = Number.NEGATIVE_INFINITY;
  return array.every((element, index) => {
    if (element < lowNum) {
      return false;
    } else {
      lowNum = element;
      return true;
    }
  });
};


问:
gulp gh-pages not working
everything worked fine before but today.. isn't.. not sure why, here is the error:

```<code>/Users/harpreetsingh/Downloads/folio-cedrik/node_modules/gift/lib/commit.js:145
      ref1 = /^.+? (.*) (\d+) .*$/.exec(line), m = ref1[0], actor = ref1[1], epoch = ref1[2];
                                                       ^

TypeError: Cannot read property '0' of null
    at Function.module.exports.Commit.actor (/Users/harpreetsingh/Downloads/folio-cedrik/node_modules/gift/lib/commit.js:145:56)
    at Function.module.exports.Commit.parse_commits (/Users/harpreetsingh/Downloads/folio-cedrik/node_modules/gift/lib/commit.js:111:21)
    at /Users/harpreetsingh/Downloads/folio-cedrik/node_modules/gift/lib/commit.js:71:39
    at ChildProcess.exithandler (child_process.js:189:7)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:891:16)
    at Socket.<anonymous> (internal/child_process.js:342:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
</code>```

How can this be fixed? No idea what this means.

Thank you once again.

答:
For anyone still having this problem who happens to also be using Yarn, I added a field to "resolutions" in package.json to ensure the right version of Gift wins when running yarn install:

In my package.json file I added:

```<code>{
  ...other package.json stuff...,
  "resolutions": {
    "gift": "^0.10.2"
  }
}
</code>```

This solved the problem for me.

Title: gulp gh-pages not working

Body:
everything worked fine before but today.. isn't.. not sure why, here is the error:

/Users/harpreetsingh/Downloads/folio-cedrik/node_modules/gift/lib/commit.js:145
      ref1 = /^.+? (.*) (\d+) .*$/.exec(line), m = ref1[0], actor = ref1[1], epoch = ref1[2];
                                                       ^

TypeError: Cannot read property '0' of null
    at Function.module.exports.Commit.actor (/Users/harpreetsingh/Downloads/folio-cedrik/node_modules/gift/lib/commit.js:145:56)
    at Function.module.exports.Commit.parse_commits (/Users/harpreetsingh/Downloads/folio-cedrik/node_modules/gift/lib/commit.js:111:21)
    at /Users/harpreetsingh/Downloads/folio-cedrik/node_modules/gift/lib/commit.js:71:39
    at ChildProcess.exithandler (child_process.js:189:7)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:891:16)
    at Socket.<anonymous> (internal/child_process.js:342:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)

How can this be fixed? No idea what this means.

Thank you once again.

Body:
For anyone still having this problem who happens to also be using Yarn, I added a field to "resolutions" in package.json to ensure the right version of Gift wins when running yarn install:

In my package.json file I added:

{
  ...other package.json stuff...,
  "resolutions": {
    "gift": "^0.10.2"
  }
}

This solved the problem for me.


问:
Firebase not adding realtime data
I have around 3000 entities (key-value) pairs added in firebase db for realtime.
Now I am trying to add more values from my flutter app, but its not adding(not showing). It was working fine with less number of values in db. Why is this happening with bulk data? What has to be solution?

答:
if you are NOT using FirebaseAuth then update your rules like // Not Safe

if you are Using FirebaseAuth then update your rules like // Safe

Title: Firebase not adding realtime data


答:
List of latest rows which are "ACTIVE":

```<code>SELECT ast1.*
FROM Access_Status ast1
LEFT JOIN Access_Status ast2 ON
  ast1.Initial_ID = ast2.Initial_ID AND ast1.Last_Updated_Date < ast2.Last_Updated_date
WHERE ast2.Initial_ID IS NULL
AND ast1.Access = 'ACTIVE'
-- if the intent is to have latest rows that are NOT 'SUSPENDED'
-- AND ast1.Access <> 'SUSPENDED'
;
</code>```

Body:
I have a table called Access_Status containing values such as below:

I would like the table to only return the Active users which are Tom Sullivan and John Martin.

It should NOT return the Active row for Marta Jenkins since Marta is actually suspended.

What's the best approach for this?

Body:
List of latest rows which are "ACTIVE":

SELECT ast1.*
FROM Access_Status ast1
LEFT JOIN Access_Status ast2 ON
  ast1.Initial_ID = ast2.Initial_ID AND ast1.Last_Updated_Date < ast2.Last_Updated_date
WHERE ast2.Initial_ID IS NULL
AND ast1.Access = 'ACTIVE'
-- if the intent is to have latest rows that are NOT 'SUSPENDED'
-- AND ast1.Access <> 'SUSPENDED'
;


问:
Working with Beaker Cache and SQLAlchemy
I'm trying to use beaker cache with SQLAlchemy but I've been receiving errors.

Here are my table definitions.

```<code>class Post(Base):
  ....
  ....

  user = relation(User, primaryjoin = User.id == id)
  tags = relation('Tags', backref = 'posts')

class Tags(Base):
  ...
  ...

  user = relation(User, primaryjoin = User.id == id)
  post = relation(Post, primaryjoin = Post.id == id)
</code>```

beaker cache works with other SQLAlchemy classes except these ones.

When I run the program, I receive the following error;

```<code>DetachedInstanceError: Parent instance <Post at 0x101f90b10> is not bound to a Session; lazy load operation of attribute 'user' cannot proceed.
</code>```

I've searched on StackOverFlow and have found in another thread that I need to disable lazy loading so I've changed the line

```<code>user = relation(User, primaryjoin = User.id == id)
</code>```

to

```<code>user = relation(User, primaryjoin = User.id == id, lazy='dynamic')
</code>```

but this occurs to following error in template(post.user.fullname);

```<code>AttributeError: 'AppenderQuery' object has no attribute 'fullname'
</code>```

What am I doing wrong?

答:
when you grab objects from cache, you should associate them with a session object, eg.</p>

```<code>obj_from_cache = get_from_cache(key)
session.merge(obj_from_cache)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to use beaker cache with SQLAlchemy but I've been receiving errors.

Here are my table definitions.

class Post(Base):
  ....
  ....

  user = relation(User, primaryjoin = User.id == id)
  tags = relation('Tags', backref = 'posts')

class Tags(Base):
  ...
  ...

  user = relation(User, primaryjoin = User.id == id)
  post = relation(Post, primaryjoin = Post.id == id)

beaker cache works with other SQLAlchemy classes except these ones.

When I run the program, I receive the following error;

DetachedInstanceError: Parent instance <Post at 0x101f90b10> is not bound to a Session; lazy load operation of attribute 'user' cannot proceed.

I've searched on StackOverFlow and have found in another thread that I need to disable lazy loading so I've changed the line

user = relation(User, primaryjoin = User.id == id)

to

user = relation(User, primaryjoin = User.id == id, lazy='dynamic')

but this occurs to following error in template(post.user.fullname);

AttributeError: 'AppenderQuery' object has no attribute 'fullname'

What am I doing wrong?

Body:
when you grab objects from cache, you should associate them with a session object, eg.

obj_from_cache = get_from_cache(key)
session.merge(obj_from_cache)


问:
seff job efficiency report for all jobs in an array
I'm looking to gather the efficiency report for the all jobs in a job array. There's not really options for the seff command. When I run the seff command for an array job id, I only get the efficiency report for one job within the array.

Does anyone have an ideas on how I can get the efficiency report for all the jobs within the array or to gather cumulative statistics like mean, min and max for memory and CPU for all the jobs in a job array?

See my output below:

```<code>[user@cluster]$ seff 26838
Job ID: 26838
Array Job ID: 26835_1
Cluster: cluster
User/Group: user/HPCusers
State: COMPLETED (exit code 0)
Cores: 1
CPU Utilized: 00:05:29
CPU Efficiency: 103.13% of 00:05:19 core-walltime
Job Wall-clock time: 00:05:19
Memory Utilized: 125.11 MB
Memory Efficiency: 8.94% of 1.37 GB
</code>```

答:
From a comment in the code for seff is "roughly equivalent":

```<code>sacct -P -n -a --format JobID,User,Group,State,Cluster,AllocCPUS,REQMEM,TotalCPU,Elapsed,MaxRSS,ExitCode,NNodes,NTasks -j <job_id>
</code>```

But, unlike seff, it outputs info for each step in a job. I'm hoping it also outputs info for each job in a job array...

Body:
I'm looking to gather the efficiency report for the all jobs in a job array. There's not really options for the seff command. When I run the seff command for an array job id, I only get the efficiency report for one job within the array.

Does anyone have an ideas on how I can get the efficiency report for all the jobs within the array or to gather cumulative statistics like mean, min and max for memory and CPU for all the jobs in a job array?

See my output below:

[user@cluster]$ seff 26838
Job ID: 26838
Array Job ID: 26835_1
Cluster: cluster
User/Group: user/HPCusers
State: COMPLETED (exit code 0)
Cores: 1
CPU Utilized: 00:05:29
CPU Efficiency: 103.13% of 00:05:19 core-walltime
Job Wall-clock time: 00:05:19
Memory Utilized: 125.11 MB
Memory Efficiency: 8.94% of 1.37 GB

Body:
From a comment in the code for seff is "roughly equivalent":

sacct -P -n -a --format JobID,User,Group,State,Cluster,AllocCPUS,REQMEM,TotalCPU,Elapsed,MaxRSS,ExitCode,NNodes,NTasks -j <job_id>

But, unlike seff, it outputs info for each step in a job. I'm hoping it also outputs info for each job in a job array...


问:
How to use an SVG file in a SvgIcon in Material-UI
I've got an SVG file and I want to make an SvgIcon component out of it, how should I do that?

In the documentation, all the examples use either predefined Material Icons or a strange notation of <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" /> which I have no idea what it is!

答:
Open your svg file in a editor (example: vscode). You will see a file structure of something similar like this ->

```<code><svg width="27" height="28" viewBox="0 0 27 28" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5.91942 27.5138L6.15827 26.984L8.69599 21.1562H8.68852L13.5027 10.3812L18.3542 21.1562H18.3467L21.1083 27.5138H26.2509L15.8687 4.72523L13.5698 0L0.933594 27.5138H5.91942Z" fill="#A7A9AC"/>
</svg>
</code>```

Then go to your react components, replace path with your own path. This should work. Add styles for custom change of design.

Body:
Open your svg file in a editor (example: vscode). You will see a file structure of something similar like this ->

<svg width="27" height="28" viewBox="0 0 27 28" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5.91942 27.5138L6.15827 26.984L8.69599 21.1562H8.68852L13.5027 10.3812L18.3542 21.1562H18.3467L21.1083 27.5138H26.2509L15.8687 4.72523L13.5698 0L0.933594 27.5138H5.91942Z" fill="#A7A9AC"/>
</svg>

Then go to your react components, replace path with your own path. This should work. Add styles for custom change of design.


问:
Removing whitespaces in a txt line and adding the values to a list
I have the following line of text from a .txt file

```<code>  0.14999999999999999       0.20000000000000001       0.29999999999999999       0.34999999999999998       0.50000000000000000       0.59999999999999998       0.69999999999999996       0.72999999999999998       0.84999999999999998       0.90000000000000002     \n
</code>```

I've been facing a problem on how to make this first line into a list. I've tried line.strip() but that only took care of the first and last spaces. There are still spaces left that I couldn't get rid of. As seen below:

```<code>'0.14999999999999999       0.20000000000000001       0.29999999999999999       0.34999999999999998       0.50000000000000000       0.59999999999999998       0.69999999999999996       0.72999999999999998       0.84999999999999998       0.90000000000000002'
</code>```

I also can't just replace all " " with "" as all numbers would get crumpled together. I also can't assume the number of whitespaces, nor the number of spaces before the ".", as I may have numbers greater than or equal to 10 down the line.

Body:
I have the following line of text from a .txt file

  0.14999999999999999       0.20000000000000001       0.29999999999999999       0.34999999999999998       0.50000000000000000       0.59999999999999998       0.69999999999999996       0.72999999999999998       0.84999999999999998       0.90000000000000002     \n

I've been facing a problem on how to make this first line into a list. I've tried line.strip() but that only took care of the first and last spaces. There are still spaces left that I couldn't get rid of. As seen below:

'0.14999999999999999       0.20000000000000001       0.29999999999999999       0.34999999999999998       0.50000000000000000       0.59999999999999998       0.69999999999999996       0.72999999999999998       0.84999999999999998       0.90000000000000002'

I also can't just replace all " " with "" as all numbers would get crumpled together. I also can't assume the number of whitespaces, nor the number of spaces before the ".", as I may have numbers greater than or equal to 10 down the line.

Body:
Use re.split.

Here is example.

a = '0.14999999999999999       0.20000000000000001       0.29999999999999999       0.34999999999999998       0.50000000000000000       0.59999999999999998       0.69999999999999996       0.72999999999999998       0.84999999999999998       0.90000000000000002'

import re
output = re.split(' +', a)

the output is

['0.14999999999999999',
 '0.20000000000000001',
 '0.29999999999999999',
 '0.34999999999999998',
 '0.50000000000000000',
 '0.59999999999999998',
 '0.69999999999999996',
 '0.72999999999999998',
 '0.84999999999999998',
 '0.90000000000000002'].

If you want every element in the output becomes float, then use map.

output = list(map(float, output))


问:
How to read & write Local MySQL Server 8 from Google Colab with Pyspark?
I have been trying but failing to write/read tables from MySQL Server 8.0.19 on localhost on Windows 10 with pyspark from Google colab. There's also a lot of similar questions and with some suggested answers but none of the solutions seem to work here. Here is my code:

```<code>    <...installations  ...>

        from pyspark.sql import SparkSession

        spark = SparkSession\
        .builder\
        .appName("Word Count")\
        .config("spark.driver.extraClassPath", "/content/spark-2.4.5-bin-hadoop2.7/jars/mysql-connector-java-8.0.19.jar")\
        .getOrCreate()
</code>```

An here is the connection string:

```<code>MyjdbcDF = spark.read.format("jdbc")\
                    .option("url", "jdbc:mysql://127.0.0.1:3306/mydb?user=testuser&password=pwtest")\
                    .option("dbtable", "collisions")\
                    .option("driver","com.mysql.cj.jdbc.Driver")\
                    .load()
</code>```

I have as well used the .option("driver","com.mysql.jdbc.Driver") but still keep getting this error:

```<code>Py4JJavaError: An error occurred while calling o154.load.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

...
...
...
Caused by: java.net.ConnectException: Connection refused (Connection refused)
</code>```

From this, I guess that MySQL Sever is not reachable.
I have Telnetted to port 3306 & it confirmed that MySQL Server is accepting connections from client machine. I have read that running: netsh advfirewall firewall add rule name="MySQL Server" action=allow protocol=TCP dir=in localport=3306 will permitting firewall rule for MySQL Server incase it was being blocked, yet no change.

Can somebody help outpy?

答:
After about several days of trials I discovered a solution, that is why I am going to answer my own question. I was able to connect using a WAMP server (thanks to @Shubham Jain for suggesting) and as well as without a WAMP server. This answer is without WAMP server.

Downloaded ngrok from https://ngrok.com/,

Unzipped it,

Saved it on my local windows,

Authinticate with:

     ./ngrok authtoken xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

(pretty straight forward instructions available on the website)

Still on my local Windows, I copied and ran ngrok tcp 3306 on the command line

C:\Users\userMe> ngrok tcp 3306

and it gave someting like:

```<code>ngrok by @inconshreveable
Session Status                online
Account                       userMe (Plan: Free)
Version                       2.3.35
Region                        United States (us)
Web Interface                 http://localhost:4041
Forwarding                    tcp://0.tcp.ngrok.io:17992 -> localhost:3306

Connections                   ttl     opn     rt1     rt5     p50     p90
                              0       0       0.00    0.00    0.00    0.00
</code>```

Where 0.tcp.ngrok.io:17992 is the only thing I am interested in and where 3306 is MySQL's and only port I am interested at exposing to the internet to link with my Google Colab.

So, at the end of the day, my PySpark READ connection will look like:

```<code>jdbcDF = spark.read.format("jdbc")\
                    .option("url", "jdbc:mysql://0.tcp.ngrok.io:17992/mydb?user=testUser&password=pestpw")\
                    .option("dbtable", "pipeLineTable")\
                    .option("driver","com.mysql.cj.jdbc.Driver")\
                    .load();
</code>```

The WRITE connection will be:

```<code>jdbcDF.write.mode("overwrite")\
    .format("jdbc")\
    .option("url",  f"jdbc:mysql://0.tcp.ngrok.io:17992/mydb")\
    .option("dbtable", "fromGcTable")\
    .option("user", "testUser")\
    .option("password", "testpw")\
    .option("driver","com.mysql.cj.jdbc.Driver")\
    .save()
</code>```

In both connection strings, note the 0.tcp.ngrok.io:17992 that replaces localhost:3306

Body:
I have been trying but failing to write/read tables from MySQL Server 8.0.19 on localhost on Windows 10 with pyspark from Google colab. There's also a lot of similar questions and with some suggested answers but none of the solutions seem to work here. Here is my code:

    <...installations  ...>

        from pyspark.sql import SparkSession

        spark = SparkSession\
        .builder\
        .appName("Word Count")\
        .config("spark.driver.extraClassPath", "/content/spark-2.4.5-bin-hadoop2.7/jars/mysql-connector-java-8.0.19.jar")\
        .getOrCreate()

An here is the connection string:

MyjdbcDF = spark.read.format("jdbc")\
                    .option("url", "jdbc:mysql://127.0.0.1:3306/mydb?user=testuser&password=pwtest")\
                    .option("dbtable", "collisions")\
                    .option("driver","com.mysql.cj.jdbc.Driver")\
                    .load()

I have as well used the .option("driver","com.mysql.jdbc.Driver") but still keep getting this error:

Py4JJavaError: An error occurred while calling o154.load.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

...
...
...
Caused by: java.net.ConnectException: Connection refused (Connection refused)

From this, I guess that MySQL Sever is not reachable.
I have Telnetted to port 3306 & it confirmed that MySQL Server is accepting connections from client machine. I have read that running: netsh advfirewall firewall add rule name="MySQL Server" action=allow protocol=TCP dir=in localport=3306 will permitting firewall rule for MySQL Server incase it was being blocked, yet no change.

Can somebody help outpy?

Body:
After about several days of trials I discovered a solution, that is why I am going to answer my own question. I was able to connect using a WAMP server (thanks to @Shubham Jain for suggesting) and as well as without a WAMP server. This answer is without WAMP server.

Downloaded ngrok from https://ngrok.com/,

Unzipped it,

Saved it on my local windows,

Authinticate with:

     ./ngrok authtoken xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

(pretty straight forward instructions available on the website)

Still on my local Windows, I copied and ran ngrok tcp 3306 on the command line

C:\Users\userMe> ngrok tcp 3306

and it gave someting like:

ngrok by @inconshreveable
Session Status                online
Account                       userMe (Plan: Free)
Version                       2.3.35
Region                        United States (us)
Web Interface                 http://localhost:4041
Forwarding                    tcp://0.tcp.ngrok.io:17992 -> localhost:3306

Connections                   ttl     opn     rt1     rt5     p50     p90
                              0       0       0.00    0.00    0.00    0.00

Where 0.tcp.ngrok.io:17992 is the only thing I am interested in and where 3306 is MySQL's and only port I am interested at exposing to the internet to link with my Google Colab.

So, at the end of the day, my PySpark READ connection will look like:

jdbcDF = spark.read.format("jdbc")\
                    .option("url", "jdbc:mysql://0.tcp.ngrok.io:17992/mydb?user=testUser&password=pestpw")\
                    .option("dbtable", "pipeLineTable")\
                    .option("driver","com.mysql.cj.jdbc.Driver")\
                    .load();

The WRITE connection will be:

jdbcDF.write.mode("overwrite")\
    .format("jdbc")\
    .option("url",  f"jdbc:mysql://0.tcp.ngrok.io:17992/mydb")\
    .option("dbtable", "fromGcTable")\
    .option("user", "testUser")\
    .option("password", "testpw")\
    .option("driver","com.mysql.cj.jdbc.Driver")\
    .save()

In both connection strings, note the 0.tcp.ngrok.io:17992 that replaces localhost:3306


问:
Julia Quick way to initialise an empty array that's the same size as another?
I have an array

```<code>array1 = Array{Int,2}(undef, 2, 3)
</code>```

Is there a way to quickly make a new array that's the same size as the first one? E.g. something like

```<code>array2 = Array{Int,2}(undef, size(array1))
</code>```

current I have to do this which is pretty cumbersome, and even worse for higher dimension arrays

```<code>array2 = Array{Int,2}(undef, size(array1)[1], size(array1)[2])
</code>```

答:
What you're looking for is similar(array1).

You can even change up the array type by passing in a type, e.g.

```<code>similar(array1, Float64)
similar(array1, Int64)
</code>```

Body:
I have an array

array1 = Array{Int,2}(undef, 2, 3)

Is there a way to quickly make a new array that's the same size as the first one? E.g. something like

array2 = Array{Int,2}(undef, size(array1))

current I have to do this which is pretty cumbersome, and even worse for higher dimension arrays

array2 = Array{Int,2}(undef, size(array1)[1], size(array1)[2])

Body:
What you're looking for is similar(array1).

You can even change up the array type by passing in a type, e.g.

similar(array1, Float64)
similar(array1, Int64)


问:
New Web NG SDK (Using with Vue.js)
I notice a new web SDK for web(NG). Looks good. I have looking to use it with a Vue application.

To display a video stream the function needs the ID if a Div container. e.g.

this.localVideoTrack.play("local-video")

Vue does not work this way (i.e. manipulate directly via dom elements, does anybody know how I can update a Vue component to display the video stream?

答:
Using the .play() method and passing in the id of the div you wish to use does work in Vue, you can check this Agora Vue Demo App, check Line 337 within AgoraVideoCall.vue

```<code>$.streamList.map((item, index) => {
  let id = item.getId();
  let dom = document.querySelector("#ag-item-" + id);
  if (!dom) {
    dom = document.createElement("section");
    dom.setAttribute("id", "ag-item-" + id);
    dom.setAttribute("class", "ag-item");
    canvas.appendChild(dom);
    item.play("ag-item-" + id);
  }
  if (index === no - 1) {
    dom.setAttribute("style", `grid-area: span 12/span 24/13/25`);
  } else {
    dom.setAttribute(
      "style",
      `grid-area: span 3/span 4/${4 + 3 * index}/25;
    z-index:1;width:calc(100% - 20px);height:calc(100% - 20px)`
    );
  }
  item.player.resize && item.player.resize();
});
</code>```

Title: New Web NG SDK (Using with Vue.js)

Body:
Using the .play() method and passing in the id of the div you wish to use does work in Vue, you can check this Agora Vue Demo App, check Line 337 within AgoraVideoCall.vue

$.streamList.map((item, index) => {
  let id = item.getId();
  let dom = document.querySelector("#ag-item-" + id);
  if (!dom) {
    dom = document.createElement("section");
    dom.setAttribute("id", "ag-item-" + id);
    dom.setAttribute("class", "ag-item");
    canvas.appendChild(dom);
    item.play("ag-item-" + id);
  }
  if (index === no - 1) {
    dom.setAttribute("style", `grid-area: span 12/span 24/13/25`);
  } else {
    dom.setAttribute(
      "style",
      `grid-area: span 3/span 4/${4 + 3 * index}/25;
    z-index:1;width:calc(100% - 20px);height:calc(100% - 20px)`
    );
  }
  item.player.resize && item.player.resize();
});


问:
Apollo client does not use the expected uri to connect the remote GraphQL server
I am new to Apollo. I set the uri for the remote GraphQL server as instructed in the Apollo documentation: Apollo Angular Doc: Setup and options

```<code>const uri = 'http://ip_address:port_number/.../graphql';
</code>```

But I got the following error when trying to send a post request to the remote server:

```<code>POST http://localhost:4200/ 404 (Not Found)
scheduleTask    @   zone-evergreen.js:2845
scheduleTask    @   zone-evergreen.js:385
...
</code>```

Looks like the uri I set in graphql.module.ts has no effect. Any suggestion?

Thanks!

答:
I did some try and error and found that the problem is gone if I changed the single quote to double quote when specifying the uri:

```<code>const uri = "http://ip_address:port_number/.../graphql";
</code>```

Hope it will help other people running into the same issue.

Body:
I am new to Apollo. I set the uri for the remote GraphQL server as instructed in the Apollo documentation: Apollo Angular Doc: Setup and options

const uri = 'http://ip_address:port_number/.../graphql';

But I got the following error when trying to send a post request to the remote server:

POST http://localhost:4200/ 404 (Not Found)
scheduleTask    @   zone-evergreen.js:2845
scheduleTask    @   zone-evergreen.js:385
...

Looks like the uri I set in graphql.module.ts has no effect. Any suggestion?

Thanks!

Body:
I did some try and error and found that the problem is gone if I changed the single quote to double quote when specifying the uri:

const uri = "http://ip_address:port_number/.../graphql";

Hope it will help other people running into the same issue.


问:
list of regular expressions
I'm looking for a concise list of all the regular expression syntax (sort of like a cheatsheet) and I found this tool: http://erik.eae.net/playground/regexp/regexp.html

in which if you click on the question mark on the top right corner it will display some sort of dictionary of regular expressions...

my question is....is this list comprehensive or is it missing something?

if anyone knows a better list, please let me know as well

答: There are a number of different dialects - for example, you could write \s or [:space:] to match whitespace, but the mentioned source covers all principal constructs, and more importantly, is sufficient to create all regular expressions.

Title: list of regular expressions