问:
F# Compiler Service: get a list of names visible in the scope
How can I get get a list of names visible in the scope with FSC?
I tried this:

```<code>#r "../../packages/FSharp.Compiler.Service.16.0.2/lib/net45/FSharp.Compiler.Service.dll"
open Microsoft.FSharp.Compiler
open Microsoft.FSharp.Compiler.SourceCodeServices

do
    let file = "TestFileName.fsx"
    let checker = SourceCodeServices.FSharpChecker.Create()

    let code =
        """
let testStr = "x"
t
"""
    async{
        let! options, _ = checker.GetProjectOptionsFromScript(file,code)
        let! parseRes,checkAnser = checker.ParseAndCheckFileInProject(file, 0, code, options)
        match checkAnser with
        | FSharpCheckFileAnswer.Succeeded checkRes ->
            let! decls =
                checkRes.GetDeclarationListInfo(
                    Some parseRes,  //ParsedFileResultsOpt
                    3 ,              //line
                    1 ,              //colAtEndOfPartialName
                    "t" ,            //lineText
                    [ "t" ] ,        //qualifyingNames
                    "" ,             //partialName
                    ( fun _ -> [] )  //getAllSymbols: (unit -> AssemblySymbol list)
                    )

            if Seq.isEmpty decls.Items then
                printfn "*no declarations found*"
            else
                decls.Items
                |> Seq.sortBy (fun d -> d.Name)
                |> Seq.truncate 10
                |> Seq.iter (fun d -> printfn "decl: %s" d.Name)

        | _ -> failwithf "*Parsing did not finish... "
        } |> Async.RunSynchronously
</code>```

but it only prints "no declarations found". I would expect not only testStr but also all the other names that are available by default.
I did not find an example in the documentation.

答:
With the answer of vasily-kirichenko and using the current FCS 17.0.1 I came up with this solution:</p>

```<code>#r "../../packages/FSharp.Compiler.Service.17.0.1/lib/net45/FSharp.Compiler.Service.dll"
open Microsoft.FSharp.Compiler
open Microsoft.FSharp.Compiler.SourceCodeServices

do
    let file = "TestFileName.fsx"
    let checker = SourceCodeServices.FSharpChecker.Create()

    let code =
        """
let testStr = "x"
testStr.
"""
    async{
        let! options, _ = checker.GetProjectOptionsFromScript(file,code)
        let! parseRes,checkAnser = checker.ParseAndCheckFileInProject(file, 0, code, options)
        match checkAnser with
        | FSharpCheckFileAnswer.Succeeded checkRes ->
            let! decls =
                let partialName = PartialLongName.Empty 6 //use any location before before the dot to get all declarations in scope
                //let partialName = PartialLongName.Empty 7 //use the loacation of the dot (7) to get memebers of string
                checkRes.GetDeclarationListInfo(
                    Some parseRes,  // ParsedFileResultsOpt
                    3 ,             // line
                    "testStr." ,    // lineText
                    partialName,    // PartialLongName
                    ( fun _ -> [] ) // getAllSymbols: (unit -> AssemblySymbol list)
                    )

            if Seq.isEmpty decls.Items then
                printfn "*no declarations found*"
            else
                decls.Items
                |> Seq.sortBy (fun d -> d.Name)
                |> Seq.truncate 10
                |> Seq.iter (fun d -> printfn "decl: %s" d.Name)

        | _ -> failwithf "*Parsing did not finish... "
        } |> Async.RunSynchronously
</code>```

Body:
How can I get get a list of names visible in the scope with FSC?
I tried this:

#r "../../packages/FSharp.Compiler.Service.16.0.2/lib/net45/FSharp.Compiler.Service.dll"
open Microsoft.FSharp.Compiler
open Microsoft.FSharp.Compiler.SourceCodeServices

do
    let file = "TestFileName.fsx"
    let checker = SourceCodeServices.FSharpChecker.Create()

    let code =
        """
let testStr = "x"
t
"""
    async{
        let! options, _ = checker.GetProjectOptionsFromScript(file,code)
        let! parseRes,checkAnser = checker.ParseAndCheckFileInProject(file, 0, code, options)
        match checkAnser with
        | FSharpCheckFileAnswer.Succeeded checkRes ->
            let! decls =
                checkRes.GetDeclarationListInfo(
                    Some parseRes,  //ParsedFileResultsOpt
                    3 ,              //line
                    1 ,              //colAtEndOfPartialName
                    "t" ,            //lineText
                    [ "t" ] ,        //qualifyingNames
                    "" ,             //partialName
                    ( fun _ -> [] )  //getAllSymbols: (unit -> AssemblySymbol list)
                    )

            if Seq.isEmpty decls.Items then
                printfn "*no declarations found*"
            else
                decls.Items
                |> Seq.sortBy (fun d -> d.Name)
                |> Seq.truncate 10
                |> Seq.iter (fun d -> printfn "decl: %s" d.Name)

        | _ -> failwithf "*Parsing did not finish... "
        } |> Async.RunSynchronously

but it only prints "no declarations found". I would expect not only testStr but also all the other names that are available by default.
I did not find an example in the documentation.

Body:
With the answer of vasily-kirichenko and using the current FCS 17.0.1 I came up with this solution:

#r "../../packages/FSharp.Compiler.Service.17.0.1/lib/net45/FSharp.Compiler.Service.dll"
open Microsoft.FSharp.Compiler
open Microsoft.FSharp.Compiler.SourceCodeServices

do
    let file = "TestFileName.fsx"
    let checker = SourceCodeServices.FSharpChecker.Create()

    let code =
        """
let testStr = "x"
testStr.
"""
    async{
        let! options, _ = checker.GetProjectOptionsFromScript(file,code)
        let! parseRes,checkAnser = checker.ParseAndCheckFileInProject(file, 0, code, options)
        match checkAnser with
        | FSharpCheckFileAnswer.Succeeded checkRes ->
            let! decls =
                let partialName = PartialLongName.Empty 6 //use any location before before the dot to get all declarations in scope
                //let partialName = PartialLongName.Empty 7 //use the loacation of the dot (7) to get memebers of string
                checkRes.GetDeclarationListInfo(
                    Some parseRes,  // ParsedFileResultsOpt
                    3 ,             // line
                    "testStr." ,    // lineText
                    partialName,    // PartialLongName
                    ( fun _ -> [] ) // getAllSymbols: (unit -> AssemblySymbol list)
                    )

            if Seq.isEmpty decls.Items then
                printfn "*no declarations found*"
            else
                decls.Items
                |> Seq.sortBy (fun d -> d.Name)
                |> Seq.truncate 10
                |> Seq.iter (fun d -> printfn "decl: %s" d.Name)

        | _ -> failwithf "*Parsing did not finish... "
        } |> Async.RunSynchronously


来源: stackexchange

问:
Django Forbidden (CSRF cookie not set.)
I was wondering what's up with the CSRF Cookie not set error that Django throws at me all the time. I created a view (see below) that is a callback for a payment. I have no influence of what is being sent to that view. I have checked other posts on StackOverflow, but I don't think any apply to me. Most of them can just implement a csrf protection into their forms, csrf_exempt their views, or they use rest_framework.

```<code>class PaymentWebhook(View):

    def post(self, request, *args, **kwargs):
        # ...
</code>```

Now, I'm getting this error everytime when I do nothing about this function:

```<code>Forbidden (CSRF cookie not set.): /payment/webhook
</code>```

Since this is about payments, can I just csrf_exempt this, or would that just open a security hole? By the way, I have even tried putting an exempt on this function, but it still throws that error.
Any suggestions?

答:
Here is what i did ( import csrf_exempt )</p>
```<code>from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
@api_view(['POST'])
def add(request):
</code>```

ContentLicense: CC BY-SA 3.0

Title: Django Forbidden (CSRF cookie not set.)

Body:
I was wondering what's up with the CSRF Cookie not set error that Django throws at me all the time. I created a view (see below) that is a callback for a payment. I have no influence of what is being sent to that view. I have checked other posts on StackOverflow, but I don't think any apply to me. Most of them can just implement a csrf protection into their forms, csrf_exempt their views, or they use rest_framework.

class PaymentWebhook(View):

    def post(self, request, *args, **kwargs):
        # ...

Now, I'm getting this error everytime when I do nothing about this function:

Forbidden (CSRF cookie not set.): /payment/webhook

Since this is about payments, can I just csrf_exempt this, or would that just open a security hole? By the way, I have even tried putting an exempt on this function, but it still throws that error.
Any suggestions?

Body:
Here is what i did ( import csrf_exempt )

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
@api_view(['POST'])
def add(request):

ContentLicense: CC BY-SA 4.0


问:
Data Cleaning Using Stringr
I have a data table with two columns, the first column containing an Id variable, and the second column containing a string. The string in the second column is in the format

"A:randomString|B:randomString|C:randomString".

I want to alter the table to have 4 columns: Id, A, B, and C. Id would stay the same, A would have the random string following each A:, B would have the string following each B:, and C would have the string following C:.

Is it possible to do this using stringr?

答:
You can do this using stringr::str_extract() and regular expressions utilising lookbehind and lookahead:

```<code>library(tidyverse)

df <- readr::read_csv("~/../Downloads/test1.csv")

df <- df %>%
  mutate(A = str_extract(col2, "(?<=A:).*?(?=\\|)"),
         B = str_extract(col2, "(?<=B:).*?(?=\\|)"),
         C = str_extract(col2, "(?<=C:).*?$")
  )
</code>```

Example

The sample data df is:

```<code>> df
# A tibble: 2 x 2
     Id                                  col2
  <int>                                 <chr>
1     1 A:frog's legs|B:popcorn|C:white_wine!
2     2      A:banana SUNDAE|B:!@$%^|C:123456
</code>```

Use dplyr::mutate() to create the new columns A, B and C:

```<code>> df <- df %>%
+   mutate(A = str_extract(col2, "(?<=A\\:).*?(?=\\|)"),
+          B = str_extract(col2, "(?<=B\\:).*?(?=\\|)"),
+          C = str_extract(col2, "(?<=C\\:).*?$")
+   )
</code>```

The data.frame df after this operation is:

```<code>> df
# A tibble: 2 x 5
     Id                                  col2             A       B           C
  <int>                                 <chr>         <chr>   <chr>       <chr>
1     1 A:frog's legs|B:popcorn|C:white_wine!   frog's legs popcorn white_wine!
2     2     A:banana SUNDAE|B:!@$%^|C:123456  banana SUNDAE  !@#$%^      123456
</code>```

How the regular expressions work

The regular expression uses lookbehind for A: (in the first string) and lookahead for | to match all characters in between these two. Ditto for the second string B:. For the third string it matches all characters following C: until the end of the string.

Caveat

The above assumes the separating character | will not be in the random strings. If this is not the case, then the regular expressions must be adjusted slightly to account for this:

```<code>> df
# A tibble: 2 x 2
     Id                                   col2
  <int>                                  <chr>
1     1 A:frog's l|egs|B:popcorn|C:white_wine!
2     2      A:banana SUNDAE|B:!@|$%^|C:123456
</code>```

Note the | character within the random strings above. We change the lookahead portions of the regular expressions to account for this:

```<code>> df <- df %>%
+   mutate(A = str_extract(col2, "(?<=A:).*?(?=\\|B:)"),
+          B = str_extract(col2, "(?<=B:).*?(?=\\|C:)"),
+          C = str_extract(col2, "(?<=C:).*?$")
+   )
> df
# A tibble: 2 x 5
     Id                                   col2             A       B           C
  <int>                                  <chr>         <chr>   <chr>       <chr>
1     1 A:frog's l|egs|B:popcorn|C:white_wine!  frog's l|egs popcorn white_wine!
2     2      A:banana SUNDAE|B:!@|$%^|C:123456 banana SUNDAE  !@|$%^      123456
</code>```

Title: Data Cleaning Using Stringr

Body:
You can do this using stringr::str_extract() and regular expressions utilising lookbehind and lookahead:

library(tidyverse)

df <- readr::read_csv("~/../Downloads/test1.csv")

df <- df %>%
  mutate(A = str_extract(col2, "(?<=A:).*?(?=\\|)"),
         B = str_extract(col2, "(?<=B:).*?(?=\\|)"),
         C = str_extract(col2, "(?<=C:).*?$")
  )

Example

The sample data df is:

> df
# A tibble: 2 x 2
     Id                                  col2
  <int>                                 <chr>
1     1 A:frog's legs|B:popcorn|C:white_wine!
2     2      A:banana SUNDAE|B:!@$%^|C:123456

Use dplyr::mutate() to create the new columns A, B and C:

> df <- df %>%
+   mutate(A = str_extract(col2, "(?<=A\\:).*?(?=\\|)"),
+          B = str_extract(col2, "(?<=B\\:).*?(?=\\|)"),
+          C = str_extract(col2, "(?<=C\\:).*?$")
+   )

The data.frame df after this operation is:

> df
# A tibble: 2 x 5
     Id                                  col2             A       B           C
  <int>                                 <chr>         <chr>   <chr>       <chr>
1     1 A:frog's legs|B:popcorn|C:white_wine!   frog's legs popcorn white_wine!
2     2     A:banana SUNDAE|B:!@$%^|C:123456  banana SUNDAE  !@#$%^      123456

How the regular expressions work

The regular expression uses lookbehind for A: (in the first string) and lookahead for | to match all characters in between these two. Ditto for the second string B:. For the third string it matches all characters following C: until the end of the string.

Caveat

The above assumes the separating character | will not be in the random strings. If this is not the case, then the regular expressions must be adjusted slightly to account for this:

> df
# A tibble: 2 x 2
     Id                                   col2
  <int>                                  <chr>
1     1 A:frog's l|egs|B:popcorn|C:white_wine!
2     2      A:banana SUNDAE|B:!@|$%^|C:123456

Note the | character within the random strings above. We change the lookahead portions of the regular expressions to account for this:

> df <- df %>%
+   mutate(A = str_extract(col2, "(?<=A:).*?(?=\\|B:)"),
+          B = str_extract(col2, "(?<=B:).*?(?=\\|C:)"),
+          C = str_extract(col2, "(?<=C:).*?$")
+   )
> df
# A tibble: 2 x 5
     Id                                   col2             A       B           C
  <int>                                  <chr>         <chr>   <chr>       <chr>
1     1 A:frog's l|egs|B:popcorn|C:white_wine!  frog's l|egs popcorn white_wine!
2     2      A:banana SUNDAE|B:!@|$%^|C:123456 banana SUNDAE  !@|$%^      123456


问:
UDP and socket on responce to client
I got the UDP communication up and running.
In a simple striped down version the client is basically doing this: (Yes, there are a lot of ifs and error checking in the code and No, without a lot of definitions it will not work as is. But I am more on the conseptual here than actually code)

```<code>sock = socket(AF_INET, SOCK_DGRAM, 0);
server_length = sizeof(struct sockaddr_in);
sendto(sock, "Hi", 3, 0, (struct sockaddr *)&myaddr, server_length);
numRes = recvfrom(sock, (char *)buff, (int)sizeof(buff), 0, (struct sockaddr *)&myaddr, &server_length);
</code>```

And the server is basically the same:

```<code>sock=socket(AF_INET, SOCK_DGRAM, 0);
bind(sock,(struct sockaddr *)&server,length);
resBytes=recvfrom(sock,buff,(int)sizeof(buff),0,(struct sockaddr *)&from, &fromlen);
sendto(sock, "Test",5, 0, (struct sockaddr *)&from, fromlen);
</code>```

This works. Both ends receive the data the other end sends.

Here is my problem: The server should be handling e lot of requests at the same time. I made a queue for the messages so that another thread could handle them, before I send them back to the client in yet another thread. When I do this I created a new socket for the sending, used the same "from" address that follows the message, but the client never receive it.

Is it correct to understand that replying on a UDP message has to be done with the same socket?

If I use the same socket for sending and receiving, what happens if I have three clients sending in messages, then after those are processed I will answer them in a random order. Will this work?

I can make a "server" on the client, but my guess is that any NAT would kill that idea fast.

What I try to attempt is more or less this:

```<code>sock=socket(AF_INET, SOCK_DGRAM, 0);
sock2=socket(AF_INET, SOCK_DGRAM, 0);

bind(sock,(struct sockaddr *)&server,length);
resBytes=recvfrom(sock,buff,(int)sizeof(buff),0,(struct sockaddr *)&from, &fromlen);

sendto(sock2, "Test",5, 0, (struct sockaddr *)&from, fromlen);
</code>```

If this kind of code should work, I will go back to my debugging, but right now it seems like this is not the case.

Edit:
Someone added "Multithreading" as a tag. Forget the multithread thing Its more to explain why I don't respond promptebly to the same request. I can have all the communication in one thread if thats whats needed. Sorry if this confuse people, but my main question here is: a) Can I send response down another socked without defining a "server" on the client. b) If not, how will it handle random order of reply on the same socked (IE Client A sends, Client B sends, answer to Client B, then to Client A)

答:
It is possible for a single UDP socket to receive data from multiple sources and to send data to multiple peers, as long as the socket is not connected. This means if you explicitly or implicitly bind the socket and then use sendto and recvfrom (or recv) then you can use the same socket to send and receive data from multiple peers. But, if you first connect the socket then you will only be able to receive data from a socket which is bound to the connected ip:port, i.e. usually the same socket which received the data.

To test this you can use a simply Python server (would work the same with C). This server creates two sockets: sock1 and sock2. It will receive a message on sock1 and then send a message back using first sock2 (the one which did not receive the original message) and then sock1 (the one which received the original message):

```<code>from socket import *

sock1 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
sock2 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)

sock1.bind(('127.0.0.1',9999))
data,addr = sock1.recvfrom(1024)
print("got '{}' from {}".format(data,addr))

sock2.sendto(b"send from sock2", addr)
sock1.sendto(b"send from sock1", addr)
</code>```

As the peer we have a client which depending on the configuration uses a connected socket (i.e. connect + send) or an unconnected socket (i.e. no connect and sendto):

```<code>from socket import *

connected=False
sock = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)
if connected:
    sock.connect(('127.0.0.1',9999))
    sock.send('send from connected client')
else:
    sock.sendto('send from unconnected client',('127.0.0.1',9999))
while True:
    data,addr = sock.recvfrom(1024)
    print("got '{}' from {}".format(data,addr))
</code>```

If you run the client with the connected socket (connected=True) you'll see that it will only get the message from sock1 back, because sock1 is (explicitly) bound to the ip:port the client is connected to and sock2 is (implicitly) bound to some other address:

```<code>got 'send from sock1' from ('127.0.0.1', 9999)
</code>```

If instead the client is using an unconnected socket (connected=False) then it will receive both the messages from sock1 and sock2:

```<code>got 'send from sock2' from ('127.0.0.1', 44596)
got 'send from sock1' from ('127.0.0.1', 9999)
</code>```

Title: UDP and socket on responce to client

Body:
I got the UDP communication up and running.
In a simple striped down version the client is basically doing this: (Yes, there are a lot of ifs and error checking in the code and No, without a lot of definitions it will not work as is. But I am more on the conseptual here than actually code)

sock = socket(AF_INET, SOCK_DGRAM, 0);
server_length = sizeof(struct sockaddr_in);
sendto(sock, "Hi", 3, 0, (struct sockaddr *)&myaddr, server_length);
numRes = recvfrom(sock, (char *)buff, (int)sizeof(buff), 0, (struct sockaddr *)&myaddr, &server_length);

And the server is basically the same:

sock=socket(AF_INET, SOCK_DGRAM, 0);
bind(sock,(struct sockaddr *)&server,length);
resBytes=recvfrom(sock,buff,(int)sizeof(buff),0,(struct sockaddr *)&from, &fromlen);
sendto(sock, "Test",5, 0, (struct sockaddr *)&from, fromlen);

This works. Both ends receive the data the other end sends.

Here is my problem: The server should be handling e lot of requests at the same time. I made a queue for the messages so that another thread could handle them, before I send them back to the client in yet another thread. When I do this I created a new socket for the sending, used the same "from" address that follows the message, but the client never receive it.

Is it correct to understand that replying on a UDP message has to be done with the same socket?

If I use the same socket for sending and receiving, what happens if I have three clients sending in messages, then after those are processed I will answer them in a random order. Will this work?

I can make a "server" on the client, but my guess is that any NAT would kill that idea fast.

What I try to attempt is more or less this:

sock=socket(AF_INET, SOCK_DGRAM, 0);
sock2=socket(AF_INET, SOCK_DGRAM, 0);

bind(sock,(struct sockaddr *)&server,length);
resBytes=recvfrom(sock,buff,(int)sizeof(buff),0,(struct sockaddr *)&from, &fromlen);

sendto(sock2, "Test",5, 0, (struct sockaddr *)&from, fromlen);

If this kind of code should work, I will go back to my debugging, but right now it seems like this is not the case.

Edit:
Someone added "Multithreading" as a tag. Forget the multithread thing Its more to explain why I don't respond promptebly to the same request. I can have all the communication in one thread if thats whats needed. Sorry if this confuse people, but my main question here is: a) Can I send response down another socked without defining a "server" on the client. b) If not, how will it handle random order of reply on the same socked (IE Client A sends, Client B sends, answer to Client B, then to Client A)

Body:
It is possible for a single UDP socket to receive data from multiple sources and to send data to multiple peers, as long as the socket is not connected. This means if you explicitly or implicitly bind the socket and then use sendto and recvfrom (or recv) then you can use the same socket to send and receive data from multiple peers. But, if you first connect the socket then you will only be able to receive data from a socket which is bound to the connected ip:port, i.e. usually the same socket which received the data.

To test this you can use a simply Python server (would work the same with C). This server creates two sockets: sock1 and sock2. It will receive a message on sock1 and then send a message back using first sock2 (the one which did not receive the original message) and then sock1 (the one which received the original message):

from socket import *

sock1 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
sock2 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)

sock1.bind(('127.0.0.1',9999))
data,addr = sock1.recvfrom(1024)
print("got '{}' from {}".format(data,addr))

sock2.sendto(b"send from sock2", addr)
sock1.sendto(b"send from sock1", addr)

As the peer we have a client which depending on the configuration uses a connected socket (i.e. connect + send) or an unconnected socket (i.e. no connect and sendto):

from socket import *

connected=False
sock = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)
if connected:
    sock.connect(('127.0.0.1',9999))
    sock.send('send from connected client')
else:
    sock.sendto('send from unconnected client',('127.0.0.1',9999))
while True:
    data,addr = sock.recvfrom(1024)
    print("got '{}' from {}".format(data,addr))

If you run the client with the connected socket (connected=True) you'll see that it will only get the message from sock1 back, because sock1 is (explicitly) bound to the ip:port the client is connected to and sock2 is (implicitly) bound to some other address:

got 'send from sock1' from ('127.0.0.1', 9999)

If instead the client is using an unconnected socket (connected=False) then it will receive both the messages from sock1 and sock2:

got 'send from sock2' from ('127.0.0.1', 44596)
got 'send from sock1' from ('127.0.0.1', 9999)


问:
MySQL-python install failed with exit status 1120
So I tried running pip3 install MySQL-python and I got these error messages

```<code>  mysqlclient.lib(typelib.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(viosslfactories.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(my_winfile.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(my_messnc.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(client.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(my_thr_init.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(my_init.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(default.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(default.obj) : error LNK2001: unresolved external symbol _printf
    build\lib.win32-3.6\_mysql.cp36-win32.pyd : fatal error LNK1120: 2 unresolved externals
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\link.exe' failed with exit status 1120

    ----------------------------------------
Command "c:\users\user\appdata\local\programs\python\python36-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\User\\AppData\\Local\\Temp\\pip-build-pz867vb9\\MySQL-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\User\AppData\Local\Temp\pip-87_rnd_9-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\User\AppData\Local\Temp\pip-build-pz867vb9\MySQL-python\
</code>```

I have Microsoft Visual Studio installed as well as the MySQL connector

答: MySQL-python is only for Python 2. For Python 3 you need mysqlclient, mysql-connector or PyMySQL.

Body:
So I tried running pip3 install MySQL-python and I got these error messages

  mysqlclient.lib(typelib.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(viosslfactories.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(my_winfile.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(my_messnc.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(client.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(my_thr_init.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(my_init.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(default.obj) : error LNK2001: unresolved external symbol ___iob_func
    mysqlclient.lib(default.obj) : error LNK2001: unresolved external symbol _printf
    build\lib.win32-3.6\_mysql.cp36-win32.pyd : fatal error LNK1120: 2 unresolved externals
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\link.exe' failed with exit status 1120

    ----------------------------------------
Command "c:\users\user\appdata\local\programs\python\python36-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\User\\AppData\\Local\\Temp\\pip-build-pz867vb9\\MySQL-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\User\AppData\Local\Temp\pip-87_rnd_9-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\User\AppData\Local\Temp\pip-build-pz867vb9\MySQL-python\

I have Microsoft Visual Studio installed as well as the MySQL connector


问:
How to find which checkstyle version gradle is using?

In my gradle file I have:

```<code>apply plugin: 'checkstyle'
</code>```

I'm trying to create my own checkstyle rules. For this reason I have added a dependency to my gradle file.

```<code>dependencies {
     checkstyle 'com.puppycrawl.tools:checkstyle:8.2'
}
</code>```

I am trying to extend "Check" class of checkstyle. But there are a lot of version of checkstyle and I dont know which one is used by gradle.

How can I find the exact version number of checkstyle which gradle is using?

答:
There are three ways I can think of right now, least attractive first:

You can look into the Gradle source code.

You can check the Checkstyle Compatibility Matrix (column L, yellow cells).
Both say that from Gradle 3.3 onwards, the default Checkstyle version is 6.19; before, it was 5.9. Only Gradle versions prior to 2.4 used even older versions of Checkstyle.

But the recommended way is to choose the Checkstyle version explicitly, by specifying it in your build.gradle file:

```<code>checkstyle {
    configFile file('your/checkstyle.xml');
    toolVersion '8.2';    // your choice here
}
</code>```

This is better than relying on the default version, because you can use much newer versions of Checkstyle, and your Checkstyle setup won't break when you update Gradle.

Body:
In my gradle file I have:

apply plugin: 'checkstyle'

I'm trying to create my own checkstyle rules. For this reason I have added a dependency to my gradle file.

dependencies {
     checkstyle 'com.puppycrawl.tools:checkstyle:8.2'
}

I am trying to extend "Check" class of checkstyle. But there are a lot of version of checkstyle and I dont know which one is used by gradle.

How can I find the exact version number of checkstyle which gradle is using?

Body:
There are three ways I can think of right now, least attractive first:

You can look into the Gradle source code.

You can check the Checkstyle Compatibility Matrix (column L, yellow cells).
Both say that from Gradle 3.3 onwards, the default Checkstyle version is 6.19; before, it was 5.9. Only Gradle versions prior to 2.4 used even older versions of Checkstyle.

But the recommended way is to choose the Checkstyle version explicitly, by specifying it in your build.gradle file:

checkstyle {
    configFile file('your/checkstyle.xml');
    toolVersion '8.2';    // your choice here
}

This is better than relying on the default version, because you can use much newer versions of Checkstyle, and your Checkstyle setup won't break when you update Gradle.


问:
laravel csrf_token mismatch when getting url request using curl in wordpress
Sorry for my bad english. I think same question but with different idea have asked, but my idea is different. What I am asking is I have compile the laravel url in wordpress using curl request. please see my code to better understand what i am trying to say.

```<code><html lang="{{ config('app.locale') }}">
     <head>
        <!-- ImportInWordpressHeaderStart -->
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        <meta name="csrf-token" content="{{ csrf_token() }}" />
        <title>{{ config('app.name', 'Laravel') }}</title>
        <!-- ImportInWordpressHeaderEnd -->
       </head>
   <body> .......
         //here is my complete html part ignore it.

    <!-- ImportInWordpressFooterScriptStart -->
    <script type="text/javascript" src="{{ asset('frontend/js/jquery-2.1.0.min.js') }}"></script>
    <script type="text/javascript">
    $("#login form").on('submit', function (e){
                e.preventDefault();

                $.ajax({
                    type: $(this).attr('method'),
                    url: $(this).attr('action'),
                    data: $(this).serialize(),
                    dataType: "json", ........... // the rest ajax code.

    <!-- ImportInWordpressFooterScriptEnd -->
</code>```

The upper part of the code is completly in laravel which is working perfectly. Now see what i have done in wordpress theme header and footer.

```<code><?php
//Laravel Home url
$url = "http://example.com/home";
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// grab URL and pass it to the browser
$output = curl_exec($ch);

//Regular expression to excerpt the targeted portion
preg_match('/<!-- ImportInWordpressFooterStart -->(.*?)<!--ImportInWordpressFooterEnd -->/s', $output, $footer);
preg_match('/<!-- ImportInWordpressFooterScriptStart -->(.*?)<!-- ImportInWordpressFooterScriptEnd -->/s', $output, $script);
// close curl resource, and free up system resources
curl_close($ch);
?>

<?php echo $footer[0];
      wp_footer();
      echo $script[0];
?>
</code>```

Now in laravel when i clicked on login it is logged in perfectly but when i try to do the same in wordpress it gives me token mismatch error

```<code> http://example.com/wordpress
</code>```

The wordpress and laravel are both in same domain i don't want to create the same laravel header footer again in wordpress. any better idea will be appreciated. Thanks

答:
each cookie session has its own csrf token, and you seemingly make no attempt to transfer the cookie session id recieved by curl to the browser, or vise-versa. thus the browser will attempt to login with it's own cookie session, and with the csrf token of curl's cookie session, that definitely wont work.

solution: make curl fetch the csrf token using the cookies of the browser.

```<code>$str='';
foreach($_COOKIE as $n=>$v){
    $str.=$name.'='.$v.'; ';
}
curl_setopt($ch,CURLOPT_COOKIE,$str);
</code>```

note that if the page where you get the csrf token sends any new Set-Cookie headers, curl will not transfer those headers to the browser unless you write some code to explicitly do this. for example, if the url where you fetch the cookie session also regenerate the session id of the browser, and you dont transfer the new id to the browser, it will effectively logout the browser.

Body:
Sorry for my bad english. I think same question but with different idea have asked, but my idea is different. What I am asking is I have compile the laravel url in wordpress using curl request. please see my code to better understand what i am trying to say.

        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        <meta name="csrf-token" content="{{ csrf_token() }}" />
        <title>{{ config('app.name', 'Laravel') }}</title>

    .......
         //here is my complete html part ignore it.

Body:
each cookie session has its own csrf token, and you seemingly make no attempt to transfer the cookie session id recieved by curl to the browser, or vise-versa. thus the browser will attempt to login with it's own cookie session, and with the csrf token of curl's cookie session, that definitely wont work.

solution: make curl fetch the csrf token using the cookies of the browser.

$str='';
foreach($_COOKIE as $n=>$v){
    $str.=$name.'='.$v.'; ';
}
curl_setopt($ch,CURLOPT_COOKIE,$str);

note that if the page where you get the csrf token sends any new Set-Cookie headers, curl will not transfer those headers to the browser unless you write some code to explicitly do this. for example, if the url where you fetch the cookie session also regenerate the session id of the browser, and you dont transfer the new id to the browser, it will effectively logout the browser.


问:
Access controller of another application in SAPUI5
I have some SAPUI5 applications in one SAP server. All the applications will be deployed in an ERP Server Version 6.0.

All the applications has a access url in our ERP server that can be retrieved through the SAP NetWeaver. All the urls have the format commonPart/applicationName/index.html. All of these application will be accessible through a Fiori launchpad application.

Now I have a controller that has to be shared between all my applications. Is there any method that I can share this controller without copy and past?

Thanks in advance

答:
you can simply type in the following

sap.ui.controller([your namespace].[controller folder name].[controller name]).[your method name]([parameters you want to pass])

for example

sap.ui.controller(CafApp.controller.create).onCreate(url);


问:
How to access a webcam in Raspberry Pi Motion instead using the port
I am using a streaming of video, configured using this tutorial: https://pimylifeup.com/raspberry-pi-webcam-server

Can I configure the motion to access the webcam with a link like “ip:/cam1” where ip is like “146.106.91.100” instead using the port “:8081”?

Thanks!

答:
You can configure your Stream like this:

```<code>cvlc v4l2:// v4l2-dev=/dev/video0 --sout '#standard{access=http,mux=ts,dst=:8080}' :demux=h264
</code>```

or

```<code>cvlc v4l2:// v4l2-dev=/dev/video0 --sout '#standard{access=http,mux=ts,dst=:8080/cam1}' :demux=h264
</code>```

or

```<code>cvlc v4l2:// v4l2-dev=/dev/video0 --sout '#standard{access=http,mux=ts,dst=/cam1}' :demux=h264
</code>```

in the last example you have to take care that port 80 is available on your system. It is normally used by the webserver.

Body:
You can configure your Stream like this:

cvlc v4l2:// v4l2-dev=/dev/video0 --sout '#standard{access=http,mux=ts,dst=:8080}' :demux=h264

or

cvlc v4l2:// v4l2-dev=/dev/video0 --sout '#standard{access=http,mux=ts,dst=:8080/cam1}' :demux=h264

or

cvlc v4l2:// v4l2-dev=/dev/video0 --sout '#standard{access=http,mux=ts,dst=/cam1}' :demux=h264

in the last example you have to take care that port 80 is available on your system. It is normally used by the webserver.


问:
Explain this snippet which finds the maximum of two integers without using if-else or any other comparison operator?
Find the maximum of two numbers. You should not use if-else or any other comparison operator. I found this question on online bulletin board, so i thought i should ask in StackOverflow

EXAMPLE
Input: 5, 10
Output: 10

I found this solution, can someone help me understand these lines of code

```<code>int getMax(int a, int b) {
    int c = a - b;
    int k = (c >> 31) & 0x1;
    int max = a - k * c;
    return max;
}
</code>```

答:
Using the shifting idea to extract the sign as posted by others, here's another way:

```<code>max (a, b) = new[] { a, b } [((a - b) >> 31) & 1]
</code>```

This pushes the two numbers into an array with the maximum  number given by the array-element whose index is sign bit of the difference between the two numbers.

Do note that:

The difference (a - b) may overflow.

If the numbers are unsigned and the >> operator refers to a logical right-shift, the & 1 is unnecessary.

Body:
Find the maximum of two numbers. You should not use if-else or any other comparison operator. I found this question on online bulletin board, so i thought i should ask in StackOverflow

EXAMPLE
Input: 5, 10
Output: 10

I found this solution, can someone help me understand these lines of code

int getMax(int a, int b) {
    int c = a - b;
    int k = (c >> 31) & 0x1;
    int max = a - k * c;
    return max;
}

Body:
Using the shifting idea to extract the sign as posted by others, here's another way:

max (a, b) = new[] { a, b } [((a - b) >> 31) & 1]

This pushes the two numbers into an array with the maximum  number given by the array-element whose index is sign bit of the difference between the two numbers.

Do note that:

The difference (a - b) may overflow.

If the numbers are unsigned and the >> operator refers to a logical right-shift, the & 1 is unnecessary.

ContentLicense: CC BY-SA 2.5


问:
Possible with multiple database connections
New to the tSQLt world (great tool set) and encountered a minor issue with a stored procedure I am setting up a test for.

If I for some reason have a stored procedure which connects to mutiple databases or even multiple SQL servers (Linked Servers).

Is it possible to do unit tests with tSQLt in such a scenario?

答:
Without you providing sample code I am not certain of your exact use case but this information may help.

The alternative approach for cross-database testing (assuming both databases are on the same instance) is to install tSQLt in both databases.  Then you can mock the objects in the remote database in the same way that you would if they were local.

E.g. If you had a stored procedure in LocalDb that referenced a table in RemoteDb, you could do something like this:

Imagine you have a procedure that selects a row from a table called localTable in the local database and inserts that row in to a table called remoteTable in the remote database (on the same instance)

```<code>create procedure [myTests].[test mySproc inserts remoteTable from local table]
as
begin
    -- Mock the local table in the local database
    exec tSQLt.FakeTable 'dbo.localTable' ;
    -- Mock the remote table (not the three part object reference to remoteDb)
    exec RemoteDb.tSQLt.FakeTable 'dbo.remoteTable' ;

    --! Data setup ommitted

    --! exec dbo.mySproc @param = 'some value' ;

    --! Get the data from the remote table into a temp table so we can test it
    select * into #expected from RemoteDb.dbo.remoteTable;

    --! Assume we have already populated #actual with our expected results
    exec tSQLt.AssertEqualsTable '#expected', '#actual' ;
end
</code>```

The above code demonstrates the basics but I blogged about this in more detail some years ago here.

Unfortunately this approach will not work across linked servers,

Body:
Without you providing sample code I am not certain of your exact use case but this information may help.

The alternative approach for cross-database testing (assuming both databases are on the same instance) is to install tSQLt in both databases.  Then you can mock the objects in the remote database in the same way that you would if they were local.

E.g. If you had a stored procedure in LocalDb that referenced a table in RemoteDb, you could do something like this:

Imagine you have a procedure that selects a row from a table called localTable in the local database and inserts that row in to a table called remoteTable in the remote database (on the same instance)

create procedure [myTests].[test mySproc inserts remoteTable from local table]
as
begin
    -- Mock the local table in the local database
    exec tSQLt.FakeTable 'dbo.localTable' ;
    -- Mock the remote table (not the three part object reference to remoteDb)
    exec RemoteDb.tSQLt.FakeTable 'dbo.remoteTable' ;

    --! Data setup ommitted

    --! exec dbo.mySproc @param = 'some value' ;

    --! Get the data from the remote table into a temp table so we can test it
    select * into #expected from RemoteDb.dbo.remoteTable;

    --! Assume we have already populated #actual with our expected results
    exec tSQLt.AssertEqualsTable '#expected', '#actual' ;
end

The above code demonstrates the basics but I blogged about this in more detail some years ago here.

Unfortunately this approach will not work across linked servers,


问:
Quality Mono/ASP.NET Dev environment on Windows?
What is the best setup for developing ASP.NET/C# apps on Windows with the Mono runtime rather than VS and the MS runtime?

Ideally, I'd like to have the full mojo - autocomplete, debugger, Unit Tests and Apache/mod_mono or some other web server equivalent...

答: What about the mono website ?</p>

OwnerDisplayName: olevas

Body: What about the mono website ?

OwnerDisplayName: mP

LastEditorDisplayName: Dreas Grech


问:
Any way to provide Eclipse auto error-discovery feature in Vim/Emacs?
I know that Vim/Emacs offers some enticing mouse-free capabilities for typing out programs. I have tried both and I love these facilities. But when coding Java, especially when using the libraries extensively, the auto-complete and error-highlighting features of Eclipse are too useful to be set aside.
                                                                                Is there a way to combine the best of both worlds? </p>

答:
I think you have to go the other way, and put Emacs/VIM into Eclipse.

in Vim you have :make and :cn with :cN to go through compiler errors/warnings, but its not real time with auto spelling fixes like Eclipse.


问:
Angular - Getting Route Param is always 0
I have a routerlink in a  in Angular. I am trying to send some data along with the routerlink. This is the html code of the component:

html code:

```<code><a routerLink="/register" [queryParams]="{ selRole: 1 }">Register Now</a>
</code>```

In my component:

```<code>ngOnInit() {
    this.route.queryParams
        .subscribe(params => {
            this.selRole = params['selRole'] || 0;
    });
    console.log(this.selRole)
}
</code>```

But I always keep getting a 0. What exactly am I doing wrong here?

答:
Try to use the same format in [routerLink] and [queryParams] even though it is not causing the issue,

```<code><a [routerLink]="['/register']" [queryParams]="{ selRole: 1 }">Register Now</a>
</code>```

also place your console.log after assigning the params to selRole which is the root cause

```<code>ngOnInit() {
    this.route.queryParams
        .subscribe(params => {
            this.selRole = params['selRole'] || 0;
            console.log(this.selRole)
    });
}
</code>```

Body:
I have a routerlink in a  in Angular. I am trying to send some data along with the routerlink. This is the html code of the component:

html code:

Register Now

In my component:

ngOnInit() {
    this.route.queryParams
        .subscribe(params => {
            this.selRole = params['selRole'] || 0;
    });
    console.log(this.selRole)
}

But I always keep getting a 0. What exactly am I doing wrong here?

Body:
Try to use the same format in [routerLink] and [queryParams] even though it is not causing the issue,

<a [routerLink]="['/register']" [queryParams]="{ selRole: 1 }">Register Now</a>

also place your console.log after assigning the params to selRole which is the root cause

ngOnInit() {
    this.route.queryParams
        .subscribe(params => {
            this.selRole = params['selRole'] || 0;
            console.log(this.selRole)
    });
}


问:
How can I parse two strings in a table row by using beautifulsoup?
```<code>html = '''
<div class="container">
 <h2>Countries & Capitals</h2>
  <table class="two-column td-red">
  <thead><tr><th>Country</th><th>Capital city</th></tr></thead><tbody>
   <tr class="grey"><td>Afghanistan</td><td>Kabul</td></tr>
   <tr><td>Albania</td><td>Tirana</td></tr>
</tbody>
</table>
</div>
</code>```

Given this HTML, I would like to specifically parse the country name and the capital city name and put them into a dictionary so that I can get

dict["Afghanistan] = 'Kabul'

I've started by doing

```<code>soup = BeautifulSoup(open(filename), 'lxml')
countries = {}
# YOUR CODE HERE
table = soup.find_all('table')
for each in table:
    if each.find('tr'):
        continue
    else:
        print(each.prettify())
return countries
</code>```

But it's confusing since it's the first time using it.

答:
You can select the "tr" elements if they have two "td" child elements you have your data:

```<code>from bs4 import BeautifulSoup

html = """
<div class="container">
 <h2>Countries & Capitals</h2>
  <table class="two-column td-red">
  <thead><tr><th>Country</th><th>Capital city</th></tr></thead><tbody>
   <tr class="grey"><td>Afghanistan</td><td>Kabul</td></tr>
   <tr><td>Albania</td><td>Tirana</td></tr>
</tbody>
</table>
</div>
"""
soup = BeautifulSoup(html, 'lxml')
countries = {}

trs = soup.find_all('tr')
for tr in trs:
    tds = tr.find_all("td")
    if len (tds) ==2:
        countries[tds[0].text] = tds[1].text
print (countries)
</code>```

Outputs:

```<code>{'Afghanistan': 'Kabul', 'Albania': 'Tirana'}
</code>```

Body:
html = '''

Countries & Capitals

Country	Capital city

Afghanistan	Kabul

Albania	Tirana

Given this HTML, I would like to specifically parse the country name and the capital city name and put them into a dictionary so that I can get

dict["Afghanistan] = 'Kabul'

I've started by doing

soup = BeautifulSoup(open(filename), 'lxml')
countries = {}
# YOUR CODE HERE
table = soup.find_all('table')
for each in table:
    if each.find('tr'):
        continue
    else:
        print(each.prettify())
return countries

But it's confusing since it's the first time using it.

Body:
You can select the "tr" elements if they have two "td" child elements you have your data:

from bs4 import BeautifulSoup

html = """
<div class="container">
 <h2>Countries & Capitals</h2>
  <table class="two-column td-red">
  <thead><tr><th>Country</th><th>Capital city</th></tr></thead><tbody>
   <tr class="grey"><td>Afghanistan</td><td>Kabul</td></tr>
   <tr><td>Albania</td><td>Tirana</td></tr>
</tbody>
</table>
</div>
"""
soup = BeautifulSoup(html, 'lxml')
countries = {}

trs = soup.find_all('tr')
for tr in trs:
    tds = tr.find_all("td")
    if len (tds) ==2:
        countries[tds[0].text] = tds[1].text
print (countries)

Outputs:

{'Afghanistan': 'Kabul', 'Albania': 'Tirana'}


问:
set /p not taking environment variables
I am trying to match a batch script to do this tutorial automatically, for any system.

```<code>@echo off
for /f "tokens=4* delims= " %%A in ('reg query "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v "My Pictures"') do (set loc=%%A %%B)
set loc=%loc%\Spotlight
set /p loc=Location for images (default - "%loc%") [use %%loc%% for default]?:
start robocopy "%localappdata%\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets" "%temp%\spotlight"
ren %temp%\spotlight\*.* *.jpg
robocopy "%temp%\spotlight" "%loc%"
start %SystemRoot%\explorer.exe %loc%
</code>```

However, if I try typing %loc%\Spotlight2, it places it in the Desktop\%loc%\spotlight2 (desktop is the current working directory).

Is there a way to make set /p take environment variables?

答:
the usual way to enter a default is an empty input (keeps predefined varable unchanged). But there is a way to enable a variable input. Try the following and answer the question with %windir%

```<code>@echo off
setlocal
set x=%username%
set /p "x=enter value ([ENTER] for default: "%x%") "
call set x=%x%
echo %x%
</code>```

The trick is to expand the variable twice by using another layer of parsing (whith call).

Title: set /p not taking environment variables

Body:
I am trying to match a batch script to do this tutorial automatically, for any system.

@echo off
for /f "tokens=4* delims= " %%A in ('reg query "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v "My Pictures"') do (set loc=%%A %%B)
set loc=%loc%\Spotlight
set /p loc=Location for images (default - "%loc%") [use %%loc%% for default]?:
start robocopy "%localappdata%\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets" "%temp%\spotlight"
ren %temp%\spotlight\*.* *.jpg
robocopy "%temp%\spotlight" "%loc%"
start %SystemRoot%\explorer.exe %loc%

However, if I try typing %loc%\Spotlight2, it places it in the Desktop\%loc%\spotlight2 (desktop is the current working directory).

Is there a way to make set /p take environment variables?

Body:
the usual way to enter a default is an empty input (keeps predefined varable unchanged). But there is a way to enable a variable input. Try the following and answer the question with %windir%

@echo off
setlocal
set x=%username%
set /p "x=enter value ([ENTER] for default: "%x%") "
call set x=%x%
echo %x%

The trick is to expand the variable twice by using another layer of parsing (whith call).


答:
console.log(this.selRole) is run before the queryParams.subscribe is called.

The queryParams is an observable and you are subscribing to that observable. You will only get the value once that is called.

To get the value you can move the console.log into the subscribe block.

```<code>ngOnInit() {
    this.route.queryParams
        .subscribe(params => {
            this.selRole = params['selRole'] || 0;
            console.log(this.selRole)
    });
}
</code>```

Title: Angular - Getting Route Param is always 0

Body:
console.log(this.selRole) is run before the queryParams.subscribe is called.

The queryParams is an observable and you are subscribing to that observable. You will only get the value once that is called.

To get the value you can move the console.log into the subscribe block.

ngOnInit() {
    this.route.queryParams
        .subscribe(params => {
            this.selRole = params['selRole'] || 0;
            console.log(this.selRole)
    });
}


问:
Null pointer passed as argument 1
In line int d = atoi(argv[2]); there seems to be something wrong. "null pointer passed as argument 1..."

What can I do?

```<code>#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, string argv[])
{

    int num;
    int i = 1;
    int j = 1;
    int board [i][j];

   // 2nd CL argument is size of grid.

    if (argc != 2)
    {
        return false;
    }

    int d = atoi(argv[2]);

    if (d <= 0)
    {
        return false;
    }

    // setting up board.

    // number of tiles needed.
    num = d * d - 1;

    // iterating over columns and rows
    for (i = 0; i <= d; i++)
    {
        for (j = 0; j <= d; j++)
        {
            // set values.
            board[i][j] = num;
            num --;
        }
         printf ("%d", board[i][j]); // TESTING.
         printf ("\n");
    }

   // if even swap 1 & 2. Don't display 1.
}
</code>```

答: argv[0] holds the name of the command used to start your program. If you expect two command line arguments, check argc == 3 and read the command line arguments from argv[1] and argv[2].

Title: Null pointer passed as argument 1

Body:
In line int d = atoi(argv[2]); there seems to be something wrong. "null pointer passed as argument 1..."

What can I do?

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, string argv[])
{

    int num;
    int i = 1;
    int j = 1;
    int board [i][j];

   // 2nd CL argument is size of grid.

    if (argc != 2)
    {
        return false;
    }

    int d = atoi(argv[2]);

    if (d <= 0)
    {
        return false;
    }

    // setting up board.

    // number of tiles needed.
    num = d * d - 1;

    // iterating over columns and rows
    for (i = 0; i <= d; i++)
    {
        for (j = 0; j <= d; j++)
        {
            // set values.
            board[i][j] = num;
            num --;
        }
         printf ("%d", board[i][j]); // TESTING.
         printf ("\n");
    }

   // if even swap 1 & 2. Don't display 1.
}


问:
Dropdown shows Image and Name of users in CSS HTML
I want to create a dropdown box that contains of users with images. Like this image: Credits: Kendo. i want to create this type of dropdown with css only and js if needed. Is this can be done without plugin?

Here's my sample out from database and php:

$link=mysqli_connect('127.0.0.1','user','pass');
mysqli_select_db($link,"db");
$Sunshine_Award=mysqli_query($link,"select * from Sunshine_Award");
echo "<select style="width:161px; height: 33px; border-radius: 5px;"/>";
while($Sunshine_Rows=mysqli_fetch_array($Sunshine_Award))
  {

   echo "<option>".$Sunshine_Rows['name']."</option>";

  }
 echo "</select>";```

答:
$(document).ready(function(){
    $("#flip").click(function(){
        $("#panel").slideToggle("slow");
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style>
#panel, #flip {
    padding: 5px;
    text-align: center;
    background-color: green;
    border: solid 1px blue;
}

#panel {
    padding: 50px;
    display: none;
}
</style></code>```

Click to slide down panel

user name

user name

```

use your server side program to insert user name & image inside the #panel

Body:
$(document).ready(function(){
    $("#flip").click(function(){
        $("#panel").slideToggle("slow");
    });
});

<style>
#panel, #flip {
    padding: 5px;
    text-align: center;
    background-color: green;
    border: solid 1px blue;
}

#panel {
    padding: 50px;
    display: none;
}
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>

<div id="flip">Click to slide down panel</div>
<div id="panel">

<div id=users>user name</div><div id=users>user name</div></div>
</body>

use your server side program to insert user name & image inside the #panel


问:
Mocking require statements with Jest
sum.js

```<code>module.exports = function sum(a, b){
    return a + b;
};
</code>```

Thing.js

```<code>var sum = require("./sum");

module.exports = class Thing {
    add(a, b){
        return sum(a, b);
    }
}
</code>```

Thing.test.js

```<code>test('1 + 2 = 3', () => {
    //Arrange
    var Thing = require('./Thing');
    var thing = new Thing();

    //Act
    var result = thing.add(1, 2);

    //Assert
    expect(result).toBe(3);
});

test('sum mocked', () => {
    //Arrange
    jest.mock('./sum', () => {
        return jest.fn(() => 42);
    });

    var Thing = require('./Thing');
    var thing = new Thing();

    //Act
    var result = thing.add(1, 2);

    //Assert
    expect(result).toBe(42);
});
</code>```

How can I mock the sum 'require' dependency when testing? I get the following error.

```<code>sum mocked

    expect(received).toBe(expected)

    Expected value to be (using ===):
      42
    Received:
      3
</code>```

What's interesting if I run each test individually with .only, they both work just fine on their own.

In the past I've used proxyquire to do things like this but I'd like to avoid it if possible.

答:
Taken from the Jest Docs.

```<code>beforeEach(() => {
  jest.resetModules();
});

test('moduleName 1', () => {
  jest.doMock('../moduleName', () => {
    return jest.fn(() => 1);
  });
  const moduleName = require('../moduleName');
  expect(moduleName()).toEqual(1);
});

test('moduleName 2', () => {
  jest.doMock('../moduleName', () => {
    return jest.fn(() => 2);
  });
  const moduleName = require('../moduleName');
  expect(moduleName()).toEqual(2);
});
</code>```

https://facebook.github.io/jest/docs/en/jest-object.html#jestdomockmodulename-factory-options

Title: Mocking require statements with Jest

Body:
sum.js

module.exports = function sum(a, b){
    return a + b;
};

Thing.js

var sum = require("./sum");

module.exports = class Thing {
    add(a, b){
        return sum(a, b);
    }
}

Thing.test.js

test('1 + 2 = 3', () => {
    //Arrange
    var Thing = require('./Thing');
    var thing = new Thing();

    //Act
    var result = thing.add(1, 2);

    //Assert
    expect(result).toBe(3);
});

test('sum mocked', () => {
    //Arrange
    jest.mock('./sum', () => {
        return jest.fn(() => 42);
    });

    var Thing = require('./Thing');
    var thing = new Thing();

    //Act
    var result = thing.add(1, 2);

    //Assert
    expect(result).toBe(42);
});

How can I mock the sum 'require' dependency when testing? I get the following error.

sum mocked

    expect(received).toBe(expected)

    Expected value to be (using ===):
      42
    Received:
      3

What's interesting if I run each test individually with .only, they both work just fine on their own.

In the past I've used proxyquire to do things like this but I'd like to avoid it if possible.

Body:
Taken from the Jest Docs.

beforeEach(() => {
  jest.resetModules();
});

test('moduleName 1', () => {
  jest.doMock('../moduleName', () => {
    return jest.fn(() => 1);
  });
  const moduleName = require('../moduleName');
  expect(moduleName()).toEqual(1);
});

test('moduleName 2', () => {
  jest.doMock('../moduleName', () => {
    return jest.fn(() => 2);
  });
  const moduleName = require('../moduleName');
  expect(moduleName()).toEqual(2);
});

https://facebook.github.io/jest/docs/en/jest-object.html#jestdomockmodulename-factory-options


问:
cannot find id in c programming lanuage
In Code::Blocks when i run and debug my code it says in the "Build messages section" (error: Cannot find id) I reinstalled both the coding platform (code::blocks) and the compiler individually and nothing has changed.</p>

答:
Try simple program first to see if installation is correct:</p>

```<code>#include <stdio.h>

int main()
{
    printf("Hello World");

    return 0;
}
</code>```

Title: cannot find id in c programming lanuage

Body:
Try simple program first to see if installation is correct:

#include <stdio.h>

int main()
{
    printf("Hello World");

    return 0;
}


问:
Laravel migration (errno: 150 "Foreign key constraint is incorrectly formed")
I have an orders table and a have a sell_shipping_labels which references orders.id as a foreign. However when I run the Laravel migration I get the dreaded error code:

[Illuminate\Database\QueryException]

    SQLSTATE[HY000]: General error: 1005 Can't create table cheapbooks_test.#sql-b5b_b2a (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table sell_shipping_labels add constraint sell_shipping_labels_order_id_foreign foreign key (order_id) references orders (id))

[Doctrine\DBAL\Driver\PDOException]

    SQLSTATE[HY000]: General error: 1005 Can't create table cheapbooks_test.#sql-b5b_b2a (errno: 150 "Foreign key constraint is incorrectly formed")

This is my orders table schema:

```<code>   Schema::create('orders', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('book_id');
        $table->integer('status_id');
        $table->double('payment_amount')->nullable();
        $table->timestamp('received_at')->nullable();
        $table->timestamp('paid_at')->nullable();
        $table->timestamps();
        $table->softDeletes();
    });
</code>```

And this is my sell_shipping_labels schema:

```<code>Schema::create('sell_shipping_labels', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('order_id');
        $table->string('shippo_object_id');
        $table->string('label_url');
        $table->string('tracking_url');
        $table->string('tracking_number');
        $table->timestamp('arrived_at');
        $table->timestamps();
        $table->softDeletes();

        $table->foreign('order_id')->references('id')->on('orders');
    });
}
</code>```

Now I've flipped the internet upside down trying to figure out the problem. All of the post about this problem all refer to the fact that the orders table must be created BEFORE the table that has the foreign key on it but this isn't a problem for me because my files are in the correct order.

答:
Since increments() creates an unsigned integer column, you need to define the foreign key column as unsigned integer too.

Default migrations in Laravel 6+ use bigIncrements(), so you need to use unsignedBigInteger() method:

```<code>$table->unsignedBigInteger('order_id');
</code>```

https://laravel.com/docs/6.x/migrations#foreign-key-constraints

For default migrations in older versions of Laravel use unsignedInteger() method:

```<code>$table->unsignedInteger('order_id');
</code>```

Or:

```<code>$table->integer('order_id')->unsigned();
</code>```

https://laravel.com/docs/5.5/migrations#foreign-key-constraints

Body:
I have an orders table and a have a sell_shipping_labels which references orders.id as a foreign. However when I run the Laravel migration I get the dreaded error code:

[Illuminate\Database\QueryException]

    SQLSTATE[HY000]: General error: 1005 Can't create table cheapbooks_test.#sql-b5b_b2a (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table sell_shipping_labels add constraint sell_shipping_labels_order_id_foreign foreign key (order_id) references orders (id))

[Doctrine\DBAL\Driver\PDOException]

    SQLSTATE[HY000]: General error: 1005 Can't create table cheapbooks_test.#sql-b5b_b2a (errno: 150 "Foreign key constraint is incorrectly formed")

This is my orders table schema:

   Schema::create('orders', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('book_id');
        $table->integer('status_id');
        $table->double('payment_amount')->nullable();
        $table->timestamp('received_at')->nullable();
        $table->timestamp('paid_at')->nullable();
        $table->timestamps();
        $table->softDeletes();
    });

And this is my sell_shipping_labels schema:

Schema::create('sell_shipping_labels', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('order_id');
        $table->string('shippo_object_id');
        $table->string('label_url');
        $table->string('tracking_url');
        $table->string('tracking_number');
        $table->timestamp('arrived_at');
        $table->timestamps();
        $table->softDeletes();

        $table->foreign('order_id')->references('id')->on('orders');
    });
}

Now I've flipped the internet upside down trying to figure out the problem. All of the post about this problem all refer to the fact that the orders table must be created BEFORE the table that has the foreign key on it but this isn't a problem for me because my files are in the correct order.

Body:
Since increments() creates an unsigned integer column, you need to define the foreign key column as unsigned integer too.

Default migrations in Laravel 6+ use bigIncrements(), so you need to use unsignedBigInteger() method:

$table->unsignedBigInteger('order_id');

https://laravel.com/docs/6.x/migrations#foreign-key-constraints

For default migrations in older versions of Laravel use unsignedInteger() method:

$table->unsignedInteger('order_id');

Or:

$table->integer('order_id')->unsigned();

https://laravel.com/docs/5.5/migrations#foreign-key-constraints


问:
How To Add String To List<String>? List<String> is Model In Model
Thsi Is My Model:

```<code>public VoyageReservedViewModel{
               public List<string> preFactorID { get; set; }
                public int Code{ get; set; } }
</code>```

I want to Add String To List <String> by Thsi Code:

```<code> VoyageReservedViewModel Obj = new VoyageReservedViewModel();
      foreach (var item in result)
      {
          Obj.preFactorID.Add("My String Value");
      }
</code>```

But I Reseved This Error:

An exception of type 'System.NullReferenceException' occurred in
  Sample.dll but was not handled in user code

答: You instantiated VoyageReservedViewModel but never instantiated its list property preFactorID. You can't add to the list if it has not been initialised.

Body:
Thsi Is My Model:

public VoyageReservedViewModel{
               public List<string> preFactorID { get; set; }
                public int Code{ get; set; } }

I want to Add String To List <String> by Thsi Code:

 VoyageReservedViewModel Obj = new VoyageReservedViewModel();
      foreach (var item in result)
      {
          Obj.preFactorID.Add("My String Value");
      }

But I Reseved This Error:

An exception of type 'System.NullReferenceException' occurred in
  Sample.dll but was not handled in user code


问:
can't send object via websocket
So i'm trying to send an object from client->server & server->client with WebSocket. Sending object from client->server works fine, meanwhile server->client throw an exception

org.springframework.messaging.converter.MessageConversionException: Could not read JSON: Can not deserialize instance of java.lang.String out of START_OBJECT token

Here is the class i'm trying to send

```<code>@Data
@AllArgsConstructor
@NoArgsConstructor
    public class TextMessage {
    private String sender;
    private String room;
    private String message;
}
</code>```

and this is the code on the client-side

```<code>public class TelepatiClient {
    public static void main(String[] args) {
        WebSocketClient client = new StandardWebSocketClient();
        WebSocketStompClient stompClient = new WebSocketStompClient(client);
        stompClient.setMessageConverter(new MappingJackson2MessageConverter());
        stompClient.setTaskScheduler(new ConcurrentTaskScheduler());
        String url = "ws://localhost:8000/connect";
        StompSessionHandler handler = new TelepatiSessionHandler();
        stompClient.connect(url, handler);
        new Scanner(System.in).nextLine();
    }
}

public class TelepatiSessionHandler extends StompSessionHandlerAdapter {
    @Override
    public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
        session.subscribe("/room/global", this);
        session.send("/test", new TextMessage("test", "test", "test"));
    }
    @Override
    public void handleFrame(StompHeaders headers, Object payload) {
        System.out.println(payload.toString());
    }
    @Override
    public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) {
        exception.printStackTrace();
        super.handleException(session, command, headers, payload, exception);
    }
}
</code>```

and this is message controller on the server-side

```<code>@Controller
public class TelepatiController {
    @MessageMapping("/test")
    @SendTo("/room/global")
    public TextMessage getMessage(TextMessage message) {
        System.out.println("get message :" + message.toString());
        return new TextMessage("test2", "test2", "test2");
    }
}
</code>```

i was able to run System.out.println("get message :" + message.toString());, but get message convertion exception on the client-side when returning new TextMessage("test2", "test2", "test2");. From my test before, returning a String object works fine, why returning TextMessage object not working? How can i send any object (in this case TextMessage) from server->client? Thanks!

答:
Well the problem is the content. In this line:

```<code>stompClient.setMessageConverter(new MappingJackson2MessageConverter());
</code>```

You indicate that the client uses a json converter. So, your client is always expecting a JSON object.

But in your test, in this line:

```<code> return new TextMessage("test2", "test2", "test2");
</code>```

You are sending plain text. Due the StompClient is thrown an exception

org.springframework.messaging.converter.MessageConversionException

Because the message in text plain is not JSON object.

Title: can't send object via websocket

Body:
So i'm trying to send an object from client->server & server->client with WebSocket. Sending object from client->server works fine, meanwhile server->client throw an exception

org.springframework.messaging.converter.MessageConversionException: Could not read JSON: Can not deserialize instance of java.lang.String out of START_OBJECT token

Here is the class i'm trying to send

@Data
@AllArgsConstructor
@NoArgsConstructor
    public class TextMessage {
    private String sender;
    private String room;
    private String message;
}

and this is the code on the client-side

public class TelepatiClient {
    public static void main(String[] args) {
        WebSocketClient client = new StandardWebSocketClient();
        WebSocketStompClient stompClient = new WebSocketStompClient(client);
        stompClient.setMessageConverter(new MappingJackson2MessageConverter());
        stompClient.setTaskScheduler(new ConcurrentTaskScheduler());
        String url = "ws://localhost:8000/connect";
        StompSessionHandler handler = new TelepatiSessionHandler();
        stompClient.connect(url, handler);
        new Scanner(System.in).nextLine();
    }
}

public class TelepatiSessionHandler extends StompSessionHandlerAdapter {
    @Override
    public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
        session.subscribe("/room/global", this);
        session.send("/test", new TextMessage("test", "test", "test"));
    }
    @Override
    public void handleFrame(StompHeaders headers, Object payload) {
        System.out.println(payload.toString());
    }
    @Override
    public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) {
        exception.printStackTrace();
        super.handleException(session, command, headers, payload, exception);
    }
}

and this is message controller on the server-side

@Controller
public class TelepatiController {
    @MessageMapping("/test")
    @SendTo("/room/global")
    public TextMessage getMessage(TextMessage message) {
        System.out.println("get message :" + message.toString());
        return new TextMessage("test2", "test2", "test2");
    }
}

i was able to run System.out.println("get message :" + message.toString());, but get message convertion exception on the client-side when returning new TextMessage("test2", "test2", "test2");. From my test before, returning a String object works fine, why returning TextMessage object not working? How can i send any object (in this case TextMessage) from server->client? Thanks!

Body:
Well the problem is the content. In this line:

stompClient.setMessageConverter(new MappingJackson2MessageConverter());

You indicate that the client uses a json converter. So, your client is always expecting a JSON object.

But in your test, in this line:

 return new TextMessage("test2", "test2", "test2");

You are sending plain text. Due the StompClient is thrown an exception

org.springframework.messaging.converter.MessageConversionException

Because the message in text plain is not JSON object.


问:
how do vertically align login form between banner and footer
Given I have the html and css in the snippet below the question, how can I vertically centre the login view no matter what screen height is?

I have tried this for the .login-layout__positioner class:

```<code>.login-layout__positioner {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;

    top: 42%;
    transform: translateY(-42%);
}
</code>```

But this does not centre well in large screen heights?

Is there a better way?

body {
  height: 100%;
  background-color: #f7f7f4;
}

.app-layout__body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.app-layout__container {
  flex: 1 0 auto;
}

.banner__container {
  background-color: #fff
}

.banner__top {
  padding-top: 15px;
}

.login-layout__container {
  background-color: #f7f7f4;
  width: 100%;
}

.login-layout__positioner {
  text-align: center;
  margin: auto;
}

footer {
  background-color: #0065bd;
}

a {
  color: #fff;
}

ul {
  list-style: none;
  margin-left: 0;
}

li {
  display: inline;
}

.form__group {
  background-color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="root">
    <div class="main-content">
      <div class="app-layout__body">
        <div class="app-layout__container">
          <div class="banner__container">
            <div class="banner__top">
              <div>
                <div>
                  <h2>Banner</h2></div>
              </div>
            </div>
          </div>
          <div class="login-layout__container">
            <div class="login-layout__positioner">
              <div class="form__group">
                <div>
                  <form>
                    <div class="login__container">
                      <div class="login__wrapper">
                        <div>
                          <div>
                            <div class="login__form__elements">
                              <div>
                                <div>
                                  <h2 class="">Sign In</h2></div>
                              </div>
                              <div>
                                <div>
                                  <div>
                                    <label for="email" id="email-label" class="label__default label__strong label__double-margin">Email</label>
                                    <div>
                                      <input type="text" autocomplete="off" class="input__default form-control" id="email" name="email" aria-invalid="false" aria-describedby="email-error" value="">
                                    </div>
                                    <div id="email-error" aria-hidden="true" role="alert"></div>
                                  </div>
                                </div>
                              </div>
                              <div>
                                <div>
                                  <div>
                                    <label for="password" id="password-label">Password</label>
                                    <div>
                                      <input type="password" autocomplete="off" id="password" name="password" aria-invalid="false" aria-describedby="password-error" value="">
                                    </div>
                                    <div id="password-error" aria-hidden="true" role="alert"></div>
                                  </div>
                                </div>
                              </div>
                              <div>
                                <div>Forgotten your password?</div>
                                <div>
                                  <button type="submit">LOGIN</button>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </div>
        <footer>
          <div>
            <div>
              <div>
                <ul>
                  <li>About</li>
                  <li>Accessibility</li>
                  <li>Cookies</li>
                  <li>Privacy</li>
                </ul>
              </div>
            </div>
          </div>
        </footer>
      </div>
    </div>
  </div>
</body></code>```

答:
Just change some class properties which I wrote down:</p>

```<code>.login-layout__positioner {
    display: flex;
    align-items: center;
    justify-content: center;
}

.form__group {
    background-color: transparent;
}

a {
    color: #333;
}

footer a {
    color: #fff;
}
</code>```

Body:
Given I have the html and css in the snippet below the question, how can I vertically centre the login view no matter what screen height is?

I have tried this for the .login-layout__positioner class:

.login-layout__positioner {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;

    top: 42%;
    transform: translateY(-42%);
}

But this does not centre well in large screen heights?

Is there a better way?

body {
  height: 100%;
  background-color: #f7f7f4;
}

.app-layout__body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.app-layout__container {
  flex: 1 0 auto;
}

.banner__container {
  background-color: #fff
}

.banner__top {
  padding-top: 15px;
}

.login-layout__container {
  background-color: #f7f7f4;
  width: 100%;
}

.login-layout__positioner {
  text-align: center;
  margin: auto;
}

footer {
  background-color: #0065bd;
}

a {
  color: #fff;
}

ul {
  list-style: none;
  margin-left: 0;
}

li {
  display: inline;
}

.form__group {
  background-color: #fff;
}

Banner

                  <form>

Sign In

                                    Email

                                      <input type="text" autocomplete="off" class="input__default form-control" id="email" name="email" aria-invalid="false" aria-describedby="email-error" value="">

                                    Password

                                      <input type="password" autocomplete="off" id="password" name="password" aria-invalid="false" aria-describedby="password-error" value="">

Forgotten your password?

                                  <button type="submit">LOGIN</button>

                  </form>

About

Accessibility

Cookies

Privacy

Body:
Just change some class properties which I wrote down:

.login-layout__positioner {
    display: flex;
    align-items: center;
    justify-content: center;
}

.form__group {
    background-color: transparent;
}

a {
    color: #333;
}

footer a {
    color: #fff;
}


问:
What are the semantics of a virtual abstract method?
Following the quote from the user Steve314's answer on Why do we need virtual functions in C++?:

With "virtual" you get "late binding". Which implementation of the method is used gets decided at run time based on the type of the pointed-to object - what it was originally constructed as. This is not necessarily what you'd think based on the type of the pointer that points to that object.

I stumbled upon the following example:

```<code>class Shape
{
    std::string name;
    friend std::ostream& operator<<(std::ostream&, const Shape&);
public:
    Shape(const std::string&);
    virtual double circumference() = 0;
    virtual ~Shape() {}
protected:
    virtual void print(std::ostream&) const;
};
</code>```

In the classes that inherit from Shape (e.g. Circle, Square...), virtual functions are overridden. Such is the case with the method circumference().

My question is as follows: if circumference() is an abstract method that cannot be called (since Shape is an abstract class), why do we make it a virtual function and not simply leave it being abstract and override it as usual in derived classes?

If I understand correctly, we make a method virtual to ensure "late binding". E.g. If we were to have the following block of code:

```<code>Shape *circle = new Circle();
double circ = circle->circumference();
</code>```

with making circumference() virtual we ensure that the method of the class type of our pointed-to object will be called, and not the method of the "declared" type (here we want to call the method of the Circle class).

So, if calling circumference() of the class Shape in any way would cause a compile-time error (making it impossible to occur) why do we make it virtual and not just abstract?

答:
A virtual method with = 0 appended is the definition of an abstract method. There's no such thing as an abstract method without the virtual keyword.

```<code>double circumference() = 0;
</code>```

This is simply a syntax error. A non-virtual method must have a definition. It can't be abstract and have = 0.

Think of it this way:

Does the method require late binding, such that the exact implementation called will vary at runtime? If so, then mark it virtual.

If it's virtual, does the base class want to provide a default implementation? If not, then add = 0.

You can't do step 2 without step 1.

Body:
Following the quote from the user Steve314's answer on Why do we need virtual functions in C++?:

With "virtual" you get "late binding". Which implementation of the method is used gets decided at run time based on the type of the pointed-to object - what it was originally constructed as. This is not necessarily what you'd think based on the type of the pointer that points to that object.

I stumbled upon the following example:

class Shape
{
    std::string name;
    friend std::ostream& operator<<(std::ostream&, const Shape&);
public:
    Shape(const std::string&);
    virtual double circumference() = 0;
    virtual ~Shape() {}
protected:
    virtual void print(std::ostream&) const;
};

In the classes that inherit from Shape (e.g. Circle, Square...), virtual functions are overridden. Such is the case with the method circumference().

My question is as follows: if circumference() is an abstract method that cannot be called (since Shape is an abstract class), why do we make it a virtual function and not simply leave it being abstract and override it as usual in derived classes?

If I understand correctly, we make a method virtual to ensure "late binding". E.g. If we were to have the following block of code:

Shape *circle = new Circle();
double circ = circle->circumference();

with making circumference() virtual we ensure that the method of the class type of our pointed-to object will be called, and not the method of the "declared" type (here we want to call the method of the Circle class).

So, if calling circumference() of the class Shape in any way would cause a compile-time error (making it impossible to occur) why do we make it virtual and not just abstract?

Body:
A virtual method with = 0 appended is the definition of an abstract method. There's no such thing as an abstract method without the virtual keyword.

double circumference() = 0;

This is simply a syntax error. A non-virtual method must have a definition. It can't be abstract and have = 0.

Think of it this way:

Does the method require late binding, such that the exact implementation called will vary at runtime? If so, then mark it virtual.

If it's virtual, does the base class want to provide a default implementation? If not, then add = 0.

You can't do step 2 without step 1.


答:
You need to instantiate preFactorID which is a type of List<string>

```<code>   VoyageReservedViewModel Obj = new VoyageReservedViewModel();
   Obj.preFactorID = new  List<string>();
   foreach (var item in result)
   {
          Obj.preFactorID.Add("My String Value");
   }
</code>```

Title: How To Add String To List<String>? List<String> is Model In Model

Body:
You need to instantiate preFactorID which is a type of List<string>

   VoyageReservedViewModel Obj = new VoyageReservedViewModel();
   Obj.preFactorID = new  List<string>();
   foreach (var item in result)
   {
          Obj.preFactorID.Add("My String Value");
   }


问:
How to execute different code based on the device manufacturers?
I want to execute different codes for different device manufacturers.

I know I can do it by using Build.MODEL and then check which model is that user using.

But the main problem is suppose

LG Optimus Zone 3 would return VS425PP

Samsung J7 Prime would return J7 Prime

Samsung J7 2016 Edition would return SM-J710F

ZTE Z798BL would return Z798BL

In the above cases is would be difficult to find out which manufacturer does that device belong to.

Can Any one please help with this.

答:
Why don't you just read it from android.os.Build.Manufacturer or android.os.Build.Brand?
https://developer.android.com/reference/android/os/Build.html?hl=ja</p>


问:
SQL Server vs. MySQL
I am confused about the database I should choose, since the application I am doing will store and handle large amounts of data, I think SQL Server will be better than MySQL. Any recommendations?</p>

答:
Both Mysql and mssql can handle big data. but mysql is better in this ways

security: if  You choose Mssql u'll host on windows server which is considered less secure.

NB: SQL Server 2017 available on Linux. but most hosting companys haven't updated it

Cost: hosting Companies will give little free database space on Mssql compared to mysql.

example in godaddy MSSQL 1 database x 200MB(economyPlan) 2 x 200MB(deluxe) Unlimited x 200MB(ultimate).

MySQL databases 10 x 1 GB(economy) 25 x 1 GB(deluxe) Unlimited x 1 GB(ultimate).

Title: SQL Server vs. MySQL


问:
Scala apply filter based on a flag
To apply a filter only when a flag is set to true, My current solution looks like this:

```<code>val list = List(5,17,25,80)
val checkAge = false
val ageCheckedList = list.filter(i => i>18)
</code>```

The idea is that if checkAge is set to true, filter should be applied, but if checkAge is false, do not perform the filtering.

What's a concise way of expressing this? The best I've come up with is this:

```<code>ageCheckedList = list.filterNot(i => checkAge && i <= 18)
</code>```

which is very confusing to read to say the least.

答:
The following might express your intent more clearly:</p>

```<code>val ageCheckedList = if (checkAge) list.filter(_ > 18) else list
</code>```

Title: Scala apply filter based on a flag

Body:
To apply a filter only when a flag is set to true, My current solution looks like this:

val list = List(5,17,25,80)
val checkAge = false
val ageCheckedList = list.filter(i => i>18)

The idea is that if checkAge is set to true, filter should be applied, but if checkAge is false, do not perform the filtering.

What's a concise way of expressing this? The best I've come up with is this:

ageCheckedList = list.filterNot(i => checkAge && i <= 18)

which is very confusing to read to say the least.

Body:
The following might express your intent more clearly:

val ageCheckedList = if (checkAge) list.filter(_ > 18) else list


答:
Obviously, preFactorID property is null! You need to initialize it, like this:

```<code> VoyageReservedViewModel Obj = new VoyageReservedViewModel();
 Obj.preFactorID  = new List<string>();
</code>```

Or using the object initializer like this:

```<code>VoyageReservedViewModel Obj = new VoyageReservedViewModel{
  preFactorID   = new List<string>()
};
</code>```

Update I want to add something to this answer. If you just insert to this list in one specific place, if you add these IDs just in this foreach loop and you don't want to edit its values in anywhere else. I suggest that you use other type like IEnumerable<string> it gives your code more 'portability' using such a generic portable type. So your code become:

```<code>public VoyageReservedViewModel
{
   public IEnumerable<string> preFactorID { get; set; }
   public int Code{ get; set; }
}
VoyageReservedViewModel Obj = new VoyageReservedViewModel();
var list = new List<string>();
foreach (var item in result)
{
    list.Add("My String Value");
}
obj.preFactorID = list; // List<T> is an IEnumerable<T>
</code>```

Body:
Obviously, preFactorID property is null! You need to initialize it, like this:

 VoyageReservedViewModel Obj = new VoyageReservedViewModel();
 Obj.preFactorID  = new List<string>();

Or using the object initializer like this:

VoyageReservedViewModel Obj = new VoyageReservedViewModel{
  preFactorID   = new List<string>()
};

Update I want to add something to this answer. If you just insert to this list in one specific place, if you add these IDs just in this foreach loop and you don't want to edit its values in anywhere else. I suggest that you use other type like IEnumerable<string> it gives your code more 'portability' using such a generic portable type. So your code become:

public VoyageReservedViewModel
{
   public IEnumerable<string> preFactorID { get; set; }
   public int Code{ get; set; }
}
VoyageReservedViewModel Obj = new VoyageReservedViewModel();
var list = new List<string>();
foreach (var item in result)
{
    list.Add("My String Value");
}
obj.preFactorID = list; // List<T> is an IEnumerable<T>


问:
Responsive 3 columns using table-cell doesn't work for me
I have this CSS Code

```<code>#wrapper {
    width: 100%;
    height: 100%;
    overflow:hidden;
    display:table;
}

#sidebar {
    width:250px;
    vertical-align:top;
    display:table-cell;
}

#content {
    overflow: hidden;
    display:table-cell;
}

#sidecontent {
    width:250px;
    vertical-align:top;
    display:table-cell;
}
</code>```

and the HTML Code looks like this

```<code><div id="wrapper>
     <div id="sidebar">
          sidebar
     </div> <!-- sidebar -->
     <div id="content">
          content
     </div> <!-- content -->
     <div id="sidecontent">
          sidecontent
     </div> <!-- sidecontent -->
</div> <!-- wrapper -->
</code>```

in desktop resolution does 3 columns

```<code>[sidebar-fixed][content-fluid][sidecontent-fixed]
</code>```

i think i tried everything to make it look like this in laptop/mobile resolution

```<code>[sidebar-fixed][content-fluid]
[----- sidecontent-fluid ----]
</code>```

i don't know what do to next, please help.

答:
Except flex, which could be solution, you can make something like this, too. I've used display:inline-block, and calc() function to set content div width (which should be expandable).

For lower screen resolutions, you can slightly change some properties, as in example, to get desired effect.

Demo:

body {
  margin:0;
}

#wrapper {
    width: 100%;
    height: 100%;

}

#sidebar {
    width:250px;

 margin-right: -4px;
    display:inline-block;
    background:red;
}

#content {
   margin-right: -4px;
   display:inline-block;
    background:green;
  width: calc(100% - 500px);

}

#sidecontent {
    width:250px;
   margin-right: -4px;
    display:inline-block;
    background:blue;
}

@media (max-width: 480px) {
  #sidecontent {
    width:100%;
  }
  #content {
     width: calc(100% - 250px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
     <div id="sidebar">
          sidebar
     </div> <!-- sidebar -->
     <div id="content">
          content
     </div> <!-- content -->
     <div id="sidecontent">
          sidecontent
     </div> <!-- sidecontent -->
</div> <!-- wrapper --</code>```

Body:
I have this CSS Code

#wrapper {
    width: 100%;
    height: 100%;
    overflow:hidden;
    display:table;
}

#sidebar {
    width:250px;
    vertical-align:top;
    display:table-cell;
}

#content {
    overflow: hidden;
    display:table-cell;
}

#sidecontent {
    width:250px;
    vertical-align:top;
    display:table-cell;
}

and the HTML Code looks like this

          sidebar

          content

          sidecontent

in desktop resolution does 3 columns

[sidebar-fixed][content-fluid][sidecontent-fixed]

i think i tried everything to make it look like this in laptop/mobile resolution

[sidebar-fixed][content-fluid]
[----- sidecontent-fluid ----]

i don't know what do to next, please help.

Body:
Except flex, which could be solution, you can make something like this, too. I've used display:inline-block, and calc() function to set content div width (which should be expandable).

For lower screen resolutions, you can slightly change some properties, as in example, to get desired effect.

Demo:

body {
  margin:0;
}

#wrapper {
    width: 100%;
    height: 100%;

}

#sidebar {
    width:250px;

 margin-right: -4px;
    display:inline-block;
    background:red;
}

#content {
   margin-right: -4px;
   display:inline-block;
    background:green;
  width: calc(100% - 500px);

}

#sidecontent {
    width:250px;
   margin-right: -4px;
    display:inline-block;
    background:blue;
}

@media (max-width: 480px) {
  #sidecontent {
    width:100%;
  }
  #content {
     width: calc(100% - 250px);
  }
}

<div id="wrapper">
     <div id="sidebar">
          sidebar
     </div> <!-- sidebar -->
     <div id="content">
          content
     </div> <!-- content -->
     <div id="sidecontent">
          sidecontent
     </div> <!-- sidecontent -->
</div> <!-- wrapper --


问:
Undefined symbols for architecture arm64: "_OBJC_CLASS_$_RadioUIButton"
I am trying to create a custom UIButton. Here is my .h class:

```<code>@interface RadioUIButton : UIButton

@property (strong) NSString* stringTag;

@end
</code>```

When I try to access the class from FeedbackViewController.m I get this error:

Undefined symbols for architecture arm64:

  "_OBJC_CLASS_$_RadioUIButton", referenced from:
        objc-class-ref in FeedbackViewController.o ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with
  exit code 1 (use -v to see invocation)

What I have tried so far:

Enable Bitcode: set to NO

Build Active Architecture only: set to NO

None of the above worked. What else can I try?

答:
change below line

```<code>@property (strong) NSString* stringTag;
</code>```

to

@property (nonatomic, copy) NSString* stringTag;

or

```<code>@property (nonatomic, strong) NSString* stringTag;
</code>```

Body:
I am trying to create a custom UIButton. Here is my .h class:

@interface RadioUIButton : UIButton

@property (strong) NSString* stringTag;

@end

When I try to access the class from FeedbackViewController.m I get this error:

Undefined symbols for architecture arm64:

  "_OBJC_CLASS_$_RadioUIButton", referenced from:
        objc-class-ref in FeedbackViewController.o ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with
  exit code 1 (use -v to see invocation)

What I have tried so far:

Enable Bitcode: set to NO

Build Active Architecture only: set to NO

None of the above worked. What else can I try?

Body:
change below line

@property (strong) NSString* stringTag;

to

@property (nonatomic, copy) NSString* stringTag;

or

@property (nonatomic, strong) NSString* stringTag;


问:
Find maximum of 9 numbers - fast
I have 9 random integer numbers. Is there a faster way how to find maximum without explicitly compare everything?

I am performing this operation milion times per frame and this is quite slow.

```<code>function calculateMax(a, b, c,
                      d, e, f,
                      g, h, i){
    var max = (a > b) ? a : b;
    var max2 = (c > d) ? c : d;
    var max3 = (e > f) ? e : f;
    var max4 = (g > h) ? g : h;

    max = (i > max) ? i : max;
    max = (max2 > max) ? max2 : max;
    max = (max3 > max) ? max3 : max;
    max = (max4 > max) ? max4 : max;

    return max;
}
</code>```

答:
The best way would be to use native implementation:

```<code>Array.max = function( array ){
    return Math.max.apply( Math, array );
};

console.log(Array.max([1,2,9,8,3,2,1,2,5]));  // 9
</code>```

cf: https://johnresig.com/blog/fast-javascript-maxmin/

Title: Find maximum of 9 numbers - fast

Body:
I have 9 random integer numbers. Is there a faster way how to find maximum without explicitly compare everything?

I am performing this operation milion times per frame and this is quite slow.

function calculateMax(a, b, c,
                      d, e, f,
                      g, h, i){
    var max = (a > b) ? a : b;
    var max2 = (c > d) ? c : d;
    var max3 = (e > f) ? e : f;
    var max4 = (g > h) ? g : h;

    max = (i > max) ? i : max;
    max = (max2 > max) ? max2 : max;
    max = (max3 > max) ? max3 : max;
    max = (max4 > max) ? max4 : max;

    return max;
}

Body:
The best way would be to use native implementation:

Array.max = function( array ){
    return Math.max.apply( Math, array );
};

console.log(Array.max([1,2,9,8,3,2,1,2,5]));  // 9

cf: https://johnresig.com/blog/fast-javascript-maxmin/