问:
Making a valid password checker. Can not get my program to get through the if conditions to print a valid password
I have been assigned the following exercise as homework:

Some Web sites impose certain rules for passwords. Write a function that checks whether a string is a valid password. Suppose the password rules are as follows:

A password must have at least eight characters.

A password must consist of only letters and digits.

A password must contain at least two digits.
  Write a program that prompts the user to enter a password and displays valid password if the rules are followed or invalid password otherwise.

I know there's a more efficient and proper way of doing this but i'm just starting out so I don't necessarily need to be those right now. Just want to finish this question.

The counter/ accumulator works and I don't get any errors but I can not fulfill the if condition correctly so that this program prints "valid password"

```<code>password = str(input("Enter in a password to be checked: "))

def valid_password_checker(password):

    from string import ascii_lowercase as alphabet

    digits = '0123456789'  # creates a string of digits
    digit = 0  # acc for digits
    length = 0 # acc for length

    for char in password:  # calls on each character in string
        if char in alphabet:
            length += 1
        if char in digits:
            digit += 1
            if digit >= 2:
                flag = True
                if length >= 8 and digit is True:
                    print("valid password")
                else:
                    print("Password does not contain enough characters or digits.")
            else:
                print("Password does not contain enough digits.")

valid_password_checker(password)
</code>```

答:
The problem with your existing code is that the variable digit is a number, and therefore doing digit is True as you have done in your if statement, always return False. If you remove digit is True, then your existing solution will work. Take a look however at my version:

```<code>def valid(password):
    digits = 0
    characters = 0

    for char in password:
        if char.isalpha():
            characters += 1
        elif char.isdigit():
            digits += 1
            characters += 1

    if characters >= 8:
        if digits >= 2:
            print("Password is valid")
        else:
            print("Password doesn't contain enough digits")
    else:
        print("Password doesn't contain enough characters")
</code>```

I have made the following modifications from your original:

Used the built-in function str.isdigit() for checking if a character is a digit.

Used the built-in function str.isalpha() for checking if a character is a letter of the alphabet

Moved everything but the counting operations outside of the for loop, so that the function doesn't print multiple things

If you want, you can undo the first two changes, if you're worried about your teacher knowing you asked for help. However, I wouldn't turn in the solution that prints "Password doesn't contain enough digits" as many times as there are characters in the inputted password.

Body:
I have been assigned the following exercise as homework:

Some Web sites impose certain rules for passwords. Write a function that checks whether a string is a valid password. Suppose the password rules are as follows:

A password must have at least eight characters.

A password must consist of only letters and digits.

A password must contain at least two digits.
  Write a program that prompts the user to enter a password and displays valid password if the rules are followed or invalid password otherwise.

I know there's a more efficient and proper way of doing this but i'm just starting out so I don't necessarily need to be those right now. Just want to finish this question.

The counter/ accumulator works and I don't get any errors but I can not fulfill the if condition correctly so that this program prints "valid password"

password = str(input("Enter in a password to be checked: "))

def valid_password_checker(password):

    from string import ascii_lowercase as alphabet

    digits = '0123456789'  # creates a string of digits
    digit = 0  # acc for digits
    length = 0 # acc for length

    for char in password:  # calls on each character in string
        if char in alphabet:
            length += 1
        if char in digits:
            digit += 1
            if digit >= 2:
                flag = True
                if length >= 8 and digit is True:
                    print("valid password")
                else:
                    print("Password does not contain enough characters or digits.")
            else:
                print("Password does not contain enough digits.")

valid_password_checker(password)

Body:
The problem with your existing code is that the variable digit is a number, and therefore doing digit is True as you have done in your if statement, always return False. If you remove digit is True, then your existing solution will work. Take a look however at my version:

def valid(password):
    digits = 0
    characters = 0

    for char in password:
        if char.isalpha():
            characters += 1
        elif char.isdigit():
            digits += 1
            characters += 1

    if characters >= 8:
        if digits >= 2:
            print("Password is valid")
        else:
            print("Password doesn't contain enough digits")
    else:
        print("Password doesn't contain enough characters")

I have made the following modifications from your original:

Used the built-in function str.isdigit() for checking if a character is a digit.

Used the built-in function str.isalpha() for checking if a character is a letter of the alphabet

Moved everything but the counting operations outside of the for loop, so that the function doesn't print multiple things

If you want, you can undo the first two changes, if you're worried about your teacher knowing you asked for help. However, I wouldn't turn in the solution that prints "Password doesn't contain enough digits" as many times as there are characters in the inputted password.


来源: stackexchange

问:
Transferring an object via REST
I've been trying to send an object from one application to another using rest.

Sender:

```<code>@Controller
public class Sender {
    @RequestMapping(value = "/comMessageApp-api/getMessages")
    public String restGetMessages() {
        String url = "http://localhost:8079/comMessageApp-api/responseMessages";
        HttpEntity<Dto2> entity = new HttpEntity<>(new Dto2());
        ResponseEntity<Dto2> response = restTemplate.exchange(url, HttpMethod.POST, entity, Dto2.class);
    }
}
</code>```

Receiver:

```<code>@RestController
public class Receiver {
    @RequestMapping(value = "/comMessageApp-api/responseMessages")
    public void restResponseMessages(HttpEntity<Dto2> request) {
        System.out.println(request.getBody());
    }
}
</code>```

DTO:

```<code>public class Dto2 {
    private String string = "Test string";

    public Dto2() {
    }

    public String getString() {
        return string;
    }

    public void setString(String string) {
        this.string = string;
    }
}
</code>```

Jackson is used serialization/deserialization.

Any ideas, why request.getBody() printed in the Receiver is null???
I tried to send the object inside HttpEntity and inside RequestEntity. No success in both cases. On the receiving side I always get null.

答: try to use @RequestMapping(method = RequestMethod.POST, produces = "application/json", consumes = "application/json")

ContentLicense: CC BY-SA 3.0

Title: Transferring an object via REST

Body:
I've been trying to send an object from one application to another using rest.

Sender:

@Controller
public class Sender {
    @RequestMapping(value = "/comMessageApp-api/getMessages")
    public String restGetMessages() {
        String url = "http://localhost:8079/comMessageApp-api/responseMessages";
        HttpEntity<Dto2> entity = new HttpEntity<>(new Dto2());
        ResponseEntity<Dto2> response = restTemplate.exchange(url, HttpMethod.POST, entity, Dto2.class);
    }
}

Receiver:

@RestController
public class Receiver {
    @RequestMapping(value = "/comMessageApp-api/responseMessages")
    public void restResponseMessages(HttpEntity<Dto2> request) {
        System.out.println(request.getBody());
    }
}

DTO:

public class Dto2 {
    private String string = "Test string";

    public Dto2() {
    }

    public String getString() {
        return string;
    }

    public void setString(String string) {
        this.string = string;
    }
}

Jackson is used serialization/deserialization.

Any ideas, why request.getBody() printed in the Receiver is null???
I tried to send the object inside HttpEntity and inside RequestEntity. No success in both cases. On the receiving side I always get null.


问:
MATLAB Eye Recognition
Is it possible to detect eye in the video mode in MATLAB?
 I am trying to detect the eye and make some predictions based on the movement of the eye.
 But am not sure on how to do that. Can someone help me in how to start about that?
 Thanks in advance.

答:
eye detection will be possible with MATLAB and you can come up with that. But there is a difference between recognition and detection that you need to consider carefully. Detection is checking if an object is available in the image whereas recognition is determining what the different objects in the image are.
I hope it'll increase someone's knowledge.</p>

ContentLicense: CC BY-SA 2.5

Title: MATLAB Eye Recognition


问:
Laravel - socket - ratchet - api authentication
I develop a Laravel REST API  for an iOS application (being developed by another guy). This means no web-part at all, the application communicates via CURL requests to API. Though cookies are used.

Now I need to check online/offline user status, where socket comes. And I cannot understand how I can authenticate a user on a socket connect.

At all examples I've managed to find a JS script handles authentication at Laravel via PHP sessions and cookies.

So in my scenario for REST API the iOS app gets ACCESS_TOKEN which I can later use in sockets.

A CURL request POSTs login and password and gets access token in JSON
  format and refresh token in cookie.

```<code>curl -kX POST https://site/login -b cookies.txt -c cookies.txt -D headers.txt -H 'Content-Type:application/json' -d '
{
    "username":"gruzua",
    "password":"qwerty09876",
}'
</code>```

Response

JSON part

```<code>{
    "access_token":"ACCESS_TOKEN",
    "expires_in":600,
}
</code>```

Cookie part (just in case):

```<code>HTTP/1.1 200 OK
Server: nginx/1.10.3
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: no-cache, private
Date: Wed, 17 May 2017 17:08:09 GMT
Set-Cookie: refreshToken=SOME_REFRESH_TOKEN; expires=Mon, 07-Jan-2019 17:08:09 GMT; Max-Age=51840000; path=/; HttpOnly
</code>```

On each sequent request CURL sends the ACCESS_TOKEN token to
  authenticate

curl -kX GET https://site/user  -H 'Authorization: Bearer ACCESS_TOKEN'

At this point I have an access token and want to open a socket connection.

According to http://socketo.me/docs/hello-world I can open a telnet connection and write there some JSON formatted data containing my ACCESS_TOKEN. At the server side in a Ratchet ComponentInterface implementation onOpen method I have to check user authorization. Maybe it's not possible onOpen, then the options is onMessage? Anyway

My question is how to use laravel authentication here?

```<code>namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later

/*
Here I have to get somehow the user ACCESS_TOKEN
and to check authorization the way it's checked
when using CURL passes ACCESS_TOKEN in header
Something like this
$user = Auth::user();
if (!emtpy($user))
{
// Check e.g. user permissions (authorization) and allow connection if it's ok
}
else
{
// Reject connection
}
*/
        $this->clients->attach($conn);

        echo "New connection! ({$conn->resourceId})\n";
    }
...
</code>```

As far as I understand a client can pass a JSON string to socket connection. The server I can query my oauth_access_tokens laravel database for the ACCESS_TOKEN and get my user model and load the corresponding user data. But I think it's not the correct way, as I want to use all the power of Laravel guard/middleware and other coll stuff which I'm not as familiar with as I'd like, but I feel it badly needed. So I want to check authentication not by hands, but to let laravel do the job.

I'm aware of this topic Laravel Ratchet socket Auth , but it speaks of Session and request cookies, which is not possible in my case.

答:
So here is how my solution looks like.

I need this approach to authorize in a browser-less socket connection (Ratchet), where JS code is not running. So I could not use Ratchet WebSocket, only simple socket Ratchet IoServer.

My API controller returns JSON so it's easy to work with the response further.

I need this approach mainly to authenticate the socket connection assuming the client knows the access token when one opens the socket (got by REST on login).

A user connects by telnet and posts a JSON string containing the token. Alas, I didn't manage

telnet 192.168.0.100 8080

{"token":"ACCESS_TOKEN"}

The the ratchet server class looks like this described here
Call Laravel controller from code and pass HTTP headers to it

So according to my API controller response (false or current user if autheticated) I can decide if the $conn is authenticated as well.

Here is another narrower question, helping with this question answer: Call Laravel controller from code and pass HTTP headers to it

Body:
I develop a Laravel REST API  for an iOS application (being developed by another guy). This means no web-part at all, the application communicates via CURL requests to API. Though cookies are used.

Now I need to check online/offline user status, where socket comes. And I cannot understand how I can authenticate a user on a socket connect.

At all examples I've managed to find a JS script handles authentication at Laravel via PHP sessions and cookies.

So in my scenario for REST API the iOS app gets ACCESS_TOKEN which I can later use in sockets.

A CURL request POSTs login and password and gets access token in JSON
  format and refresh token in cookie.

curl -kX POST https://site/login -b cookies.txt -c cookies.txt -D headers.txt -H 'Content-Type:application/json' -d '
{
    "username":"gruzua",
    "password":"qwerty09876",
}'

Response

JSON part

{
    "access_token":"ACCESS_TOKEN",
    "expires_in":600,
}

Cookie part (just in case):

HTTP/1.1 200 OK
Server: nginx/1.10.3
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: no-cache, private
Date: Wed, 17 May 2017 17:08:09 GMT
Set-Cookie: refreshToken=SOME_REFRESH_TOKEN; expires=Mon, 07-Jan-2019 17:08:09 GMT; Max-Age=51840000; path=/; HttpOnly

On each sequent request CURL sends the ACCESS_TOKEN token to
  authenticate

curl -kX GET https://site/user  -H 'Authorization: Bearer ACCESS_TOKEN'

At this point I have an access token and want to open a socket connection.

According to http://socketo.me/docs/hello-world I can open a telnet connection and write there some JSON formatted data containing my ACCESS_TOKEN. At the server side in a Ratchet ComponentInterface implementation onOpen method I have to check user authorization. Maybe it's not possible onOpen, then the options is onMessage? Anyway

My question is how to use laravel authentication here?

namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later

/*
Here I have to get somehow the user ACCESS_TOKEN
and to check authorization the way it's checked
when using CURL passes ACCESS_TOKEN in header
Something like this
$user = Auth::user();
if (!emtpy($user))
{
// Check e.g. user permissions (authorization) and allow connection if it's ok
}
else
{
// Reject connection
}
*/
        $this->clients->attach($conn);

        echo "New connection! ({$conn->resourceId})\n";
    }
...

As far as I understand a client can pass a JSON string to socket connection. The server I can query my oauth_access_tokens laravel database for the ACCESS_TOKEN and get my user model and load the corresponding user data. But I think it's not the correct way, as I want to use all the power of Laravel guard/middleware and other coll stuff which I'm not as familiar with as I'd like, but I feel it badly needed. So I want to check authentication not by hands, but to let laravel do the job.

I'm aware of this topic Laravel Ratchet socket Auth , but it speaks of Session and request cookies, which is not possible in my case.


问:
How to use onBackPress in android
In my application I am using navigation drawer menu. I need to close this menu and get back to previous activity, when user clicks on back button.

I wrote below code :

```<code>@Override
public void onBackPressed() {
    if (toNightSearchView.isSearchOpen()) {
        toNightSearchView.closeSearch();
    } else if (toNightDrawerLayout.isShown()) {
        toNightDrawerLayout.closeDrawer(Gravity.END);
    } else {
        super.onBackPressed();
    }
}
</code>```

The problem is when menu is closed app does not back to previous activity.

How can I fix this?

答:
```<code>// use `isOpen()` to check the drawer state
if (toNightSearchView.isSearchOpen() || toNightDrawerLayout.isOpen()) {

   //close if any of the views are open
    if (toNightSearchView.isSearchOpen())
       toNightSearchView.closeSearch();
    if (toNightDrawerLayout.isOpen())
       toNightDrawerLayout.closeDrawer(Gravity.END);

      // Gravity.END is used for closing right drawer and start for left one
} else{
     super.onBackPressed(); // go back to previous activity
}
</code>```

or better use isDrawerOpen

```<code>if (toNightSearchView.isSearchOpen() || toNightDrawerLayout.isDrawerOpen(Gravity.START)) {

    if (toNightSearchView.isSearchOpen())
       toNightSearchView.closeSearch();
    if (toNightDrawerLayout.isDrawerOpen(Gravity.START))
       toNightDrawerLayout.closeDrawer(Gravity.START);
} else{
     super.onBackPressed(); // go back to previous activity
}
</code>```

Title: How to use onBackPress in android

Body:
In my application I am using navigation drawer menu. I need to close this menu and get back to previous activity, when user clicks on back button.

I wrote below code :

@Override
public void onBackPressed() {
    if (toNightSearchView.isSearchOpen()) {
        toNightSearchView.closeSearch();
    } else if (toNightDrawerLayout.isShown()) {
        toNightDrawerLayout.closeDrawer(Gravity.END);
    } else {
        super.onBackPressed();
    }
}

The problem is when menu is closed app does not back to previous activity.

How can I fix this?

Body:
// use `isOpen()` to check the drawer state
if (toNightSearchView.isSearchOpen() || toNightDrawerLayout.isOpen()) {

   //close if any of the views are open
    if (toNightSearchView.isSearchOpen())
       toNightSearchView.closeSearch();
    if (toNightDrawerLayout.isOpen())
       toNightDrawerLayout.closeDrawer(Gravity.END);

      // Gravity.END is used for closing right drawer and start for left one
} else{
     super.onBackPressed(); // go back to previous activity
}

or better use isDrawerOpen

if (toNightSearchView.isSearchOpen() || toNightDrawerLayout.isDrawerOpen(Gravity.START)) {

    if (toNightSearchView.isSearchOpen())
       toNightSearchView.closeSearch();
    if (toNightDrawerLayout.isDrawerOpen(Gravity.START))
       toNightDrawerLayout.closeDrawer(Gravity.START);
} else{
     super.onBackPressed(); // go back to previous activity
}


问:
Optimal way to store follower and following MySQL
I have 2 tables one is user and another is company. Both have the following columns common while other columns are different.

```<code>id   email                name
1    first@email.com      First user
2    second@email.com     Second User
3    third@email.com      Third User
</code>```

Now a user can follow many companies but a company does not follow back user. Company should have data with users who follow them and a user should also store the companies they are following.

What is the simplest and optimal to make this happen on MySQL? Either should I create separate table for it or just add a column on existing tables with array of followers. Please answer assuming I have working level of knowledge on PHP and MySQL.

答:
The simplest solution is to have a MANY-TO-MANY join table to link these 2 tables. You can do this with either 2 MANY-TO-MANY tables or a single one.

For example 2 table:

user_follows_company

```<code>ID    CompanyID UserID
----  ------ ---------
1     1      5
1     1      6
1     1      8
1     2      5
</code>```

You can get the companies a user follows by using the following SQL:

SELECT * FROM company c JOIN user_follows_company ufc on ufc.companyID = c.ID WHERE user = $USER_ID

company_follows_user

```<code>ID    CompanyID UserID
----  --------- ---------
1     3         5
1     3         6
1     5         3
1     5         4
</code>```

You can get the users a company follows by using the following SQL:

SELECT * FROM user u JOIN company_follow_user cfu on cfu.userID = u.ID WHERE user = $USER_ID

or you can do this with a single table and have a column that designates which direction is being followed:

follows_table

```<code>ID    CompanyID UserID     Initiator
----  --------- ---------  ---------
1     3         5          Company
1     3         6          Company
1     5         3          Company
1     5         4          Company
1     5         1          User
1     6         1          User
1     8         1          User
1     5         2          User
</code>```

Note that storing the "initiator" as a string is not a good idea - it probably should be an int or an ENUM

To query on this table, do the following queries:

Companies a user follows:
SELECT * FROM company c JOIN follows_table ft on ft.userID = c.ID WHERE user = $USER_ID AND ft.initiator = 'user'

Users a company follows:
SELECT * FROM user u JOIN follows_table ft on ft.userID = u.ID WHERE companyID = $$COMPANY_ID AND ft.initiator = 'company'

Body:
I have 2 tables one is user and another is company. Both have the following columns common while other columns are different.

id   email                name
1    first@email.com      First user
2    second@email.com     Second User
3    third@email.com      Third User

Now a user can follow many companies but a company does not follow back user. Company should have data with users who follow them and a user should also store the companies they are following.

What is the simplest and optimal to make this happen on MySQL? Either should I create separate table for it or just add a column on existing tables with array of followers. Please answer assuming I have working level of knowledge on PHP and MySQL.

Body:
The simplest solution is to have a MANY-TO-MANY join table to link these 2 tables. You can do this with either 2 MANY-TO-MANY tables or a single one.

For example 2 table:

user_follows_company

ID    CompanyID UserID
----  ------ ---------
1     1      5
1     1      6
1     1      8
1     2      5

You can get the companies a user follows by using the following SQL:

SELECT * FROM company c JOIN user_follows_company ufc on ufc.companyID = c.ID WHERE user = $USER_ID

company_follows_user

ID    CompanyID UserID
----  --------- ---------
1     3         5
1     3         6
1     5         3
1     5         4

You can get the users a company follows by using the following SQL:

SELECT * FROM user u JOIN company_follow_user cfu on cfu.userID = u.ID WHERE user = $USER_ID

or you can do this with a single table and have a column that designates which direction is being followed:

follows_table

ID    CompanyID UserID     Initiator
----  --------- ---------  ---------
1     3         5          Company
1     3         6          Company
1     5         3          Company
1     5         4          Company
1     5         1          User
1     6         1          User
1     8         1          User
1     5         2          User

Note that storing the "initiator" as a string is not a good idea - it probably should be an int or an ENUM

To query on this table, do the following queries:

Companies a user follows:
SELECT * FROM company c JOIN follows_table ft on ft.userID = c.ID WHERE user = $USER_ID AND ft.initiator = 'user'

Users a company follows:
SELECT * FROM user u JOIN follows_table ft on ft.userID = u.ID WHERE companyID = $$COMPANY_ID AND ft.initiator = 'company'


问:
How to create make file for only object and header file?
I'm performing blackbox testing using a set.h interface where I have no access to set.c, I've been provided with the object file set.o and I'm required to write a bunch of tests in a main.c file for the set. How do I create a makefile that would include set.o, set.h and main.c?

**I already have the set.o file so I don't have to regenerate it using set.c

I'm confused because I only know how to do this using the complete files.

Here's my template

```<code>CC = clang
CFLAGS = -g -Wall

PROG = example
HDRS = set.h
SRCS = main.c

OBJDIR = object
OBJS = $(OBJDIR)/main.o $(OBJDIR)/set.o

# compiling rules

$(PROG): $(OBJS) $(OBJDIR)
    $(CC) $(CFLAGS) $(OBJS) -o $(PROG)

$(OBJDIR)/set.o: set.h $(HDRS) $(OBJDIR)
    $(CC) $(CFLAGS) -c set.h -o $(OBJDIR)/set.o

$(OBJDIR)/main.o: main.c $(HDRS) $(OBJDIR)
    $(CC) $(CFLAGS) -c main.c -o $(OBJDIR)/main.o

$(OBJDIR):
    mkdir $(OBJDIR)

clean:
    rm -f $(PROG) $(OBJS)
</code>```

答:
If you already have the set.o file there is no need to create a rule for it, just use it. Also note I got rid of the mkdir because if you already have a set.o, it should already be in objects/ right?

```<code>CC = clang
CFLAGS = -g -Wall

PROG = example
HDRS = set.h
SRCS = main.c

OBJDIR = object
OBJS = $(OBJDIR)/main.o

# compiling rules

$(PROG): $(OBJS)
    $(CC) $(CFLAGS) $(OBJS) $(OBJDIR)/set.o -o $(PROG)

$(OBJDIR)/main.o: main.c $(HDRS)
    $(CC) $(CFLAGS) -c main.c -o $(OBJDIR)/main.o

clean:
    rm -f $(PROG) $(OBJS)
</code>```

Body:
I'm performing blackbox testing using a set.h interface where I have no access to set.c, I've been provided with the object file set.o and I'm required to write a bunch of tests in a main.c file for the set. How do I create a makefile that would include set.o, set.h and main.c?

**I already have the set.o file so I don't have to regenerate it using set.c

I'm confused because I only know how to do this using the complete files.

Here's my template

CC = clang
CFLAGS = -g -Wall

PROG = example
HDRS = set.h
SRCS = main.c

OBJDIR = object
OBJS = $(OBJDIR)/main.o $(OBJDIR)/set.o

# compiling rules

$(PROG): $(OBJS) $(OBJDIR)
    $(CC) $(CFLAGS) $(OBJS) -o $(PROG)

$(OBJDIR)/set.o: set.h $(HDRS) $(OBJDIR)
    $(CC) $(CFLAGS) -c set.h -o $(OBJDIR)/set.o

$(OBJDIR)/main.o: main.c $(HDRS) $(OBJDIR)
    $(CC) $(CFLAGS) -c main.c -o $(OBJDIR)/main.o

$(OBJDIR):
    mkdir $(OBJDIR)

clean:
    rm -f $(PROG) $(OBJS)

Body:
If you already have the set.o file there is no need to create a rule for it, just use it. Also note I got rid of the mkdir because if you already have a set.o, it should already be in objects/ right?

CC = clang
CFLAGS = -g -Wall

PROG = example
HDRS = set.h
SRCS = main.c

OBJDIR = object
OBJS = $(OBJDIR)/main.o

# compiling rules

$(PROG): $(OBJS)
    $(CC) $(CFLAGS) $(OBJS) $(OBJDIR)/set.o -o $(PROG)

$(OBJDIR)/main.o: main.c $(HDRS)
    $(CC) $(CFLAGS) -c main.c -o $(OBJDIR)/main.o

clean:
    rm -f $(PROG) $(OBJS)


问:
.net core, n-layered app, should services layer have dependency on Microsoft.Extensions.Options.dll
Straightforward question is: are Microsoft.Extensions.Options.IOptions meant to be used only within the context of umbrella app (web app in this case) or in class libraries also?

Example:

In a n-layered, asp.net core app we have services layer that is dependant on some settings coming from appsettings.json file.

What we first started with is something along these lines in Startup.cs:

```<code>  services.Configure<Services.Options.XOptions>(options =>
  {
    options.OptionProperty1 = Configuration["OptionXSection:OptionXProperty"];
  });
</code>```

And then in service constructor:

```<code>ServiceConstructor(IOptions<XOptions> xOptions){}
</code>```

But that assumes that in our Service layer we have dependecy on Microsoft.Extensions.Options.

We're not sure if this is recomended way or is there some better practice?

It just feels a bit awkward our services class library should be aware of DI container implementation.

答:
You can register POCO settings for injection too, but you lose some functionalities related to when the appsettings.json gets edited.

services.AddTransient<XOptions>(
    provider => provider.GetRequiredService<IOptionsSnapshot<XOptions>>().Value);
```

<p>Now when you inject <code>XOptions</code> in constructor, you will get the class. But when your edit your <code>appsettings.json</code>, the value won't be updated until the next time it's resolved which for scoped services would be on next request and singleton services <strong>never</strong>. </p>

<p>On other side injecting <code>IOptionsSnapshot<T></code> <code>.Value</code> will always get you the current settings, even when <code>appsettings.json</code> is reloaded (assuming you registered it with <code>.AddJsonFile("appsettings.json", reloadOnSave: true)</code>).</p>

<p>The obvious reason to keep the functionality w/o pulling <code>Microsoft.Extensions.Options</code> package into your service/domain layer will be create your own interface and implementation. </p>

<pre class="lang-cs prettyprint-override"><code>// in your shared service/domain assembly
public interface ISettingsSnapshot<T> where T : class
{
    T Value { get; }
}
</code>```

and implement it on the application side (outside of your services/domain assemblies), i.e. MyProject.Web (where ASP.NET Core and the composition root is)

public class OptionsSnapshotWrapper<T> : ISettingsSnapshot<T>
{
    private readonly IOptionsSnapshot<T> snapshot;

    public OptionsSnapshotWrapper(IOptionsSnapshot<T> snapshot)
    {
        this.snapshot = snapshot ?? throw new ArgumentNullException(nameof(snapshot));
    }

    public T Value => snapshot.Value;
}
```

<p>and register it as</p>

<pre class="lang-cs prettyprint-override"><code>services.AddSingleton(typeof(ISettingsSnapshot<>), typeof(OptionsSnapshotWrapper<T>));
</code>```

Now you have removed your dependency on IOptions<T> and IOptionsSnapshot<T> from your services but retain all up advantages of it like updating options when appsettings.json is edited. When you change DI, just replace OptionsSnapshotWrapper<T> with your new implementation.

Body:
Straightforward question is: are Microsoft.Extensions.Options.IOptions meant to be used only within the context of umbrella app (web app in this case) or in class libraries also?

Example:

In a n-layered, asp.net core app we have services layer that is dependant on some settings coming from appsettings.json file.

What we first started with is something along these lines in Startup.cs:

  services.Configure<Services.Options.XOptions>(options =>
  {
    options.OptionProperty1 = Configuration["OptionXSection:OptionXProperty"];
  });

And then in service constructor:

ServiceConstructor(IOptions<XOptions> xOptions){}

But that assumes that in our Service layer we have dependecy on Microsoft.Extensions.Options.

We're not sure if this is recomended way or is there some better practice?

It just feels a bit awkward our services class library should be aware of DI container implementation.

Body:
You can register POCO settings for injection too, but you lose some functionalities related to when the appsettings.json gets edited.

services.AddTransient<XOptions>(
    provider => provider.GetRequiredService<IOptionsSnapshot<XOptions>>().Value);

Now when you inject XOptions in constructor, you will get the class. But when your edit your appsettings.json, the value won't be updated until the next time it's resolved which for scoped services would be on next request and singleton services never.

On other side injecting IOptionsSnapshot<T> .Value will always get you the current settings, even when appsettings.json is reloaded (assuming you registered it with .AddJsonFile("appsettings.json", reloadOnSave: true)).

The obvious reason to keep the functionality w/o pulling Microsoft.Extensions.Options package into your service/domain layer will be create your own interface and implementation.

// in your shared service/domain assembly
public interface ISettingsSnapshot<T> where T : class
{
    T Value { get; }
}

and implement it on the application side (outside of your services/domain assemblies), i.e. MyProject.Web (where ASP.NET Core and the composition root is)

public class OptionsSnapshotWrapper<T> : ISettingsSnapshot<T>
{
    private readonly IOptionsSnapshot<T> snapshot;

    public OptionsSnapshotWrapper(IOptionsSnapshot<T> snapshot)
    {
        this.snapshot = snapshot ?? throw new ArgumentNullException(nameof(snapshot));
    }

    public T Value => snapshot.Value;
}

and register it as

services.AddSingleton(typeof(ISettingsSnapshot<>), typeof(OptionsSnapshotWrapper<T>));

Now you have removed your dependency on IOptions<T> and IOptionsSnapshot<T> from your services but retain all up advantages of it like updating options when appsettings.json is edited. When you change DI, just replace OptionsSnapshotWrapper<T> with your new implementation.


问:
What's an easy way to read random line from a file?
What's an easy way to read random line from a file in a shell script?</p>

答:
Another alternative:</p>

```<code>head -$((${RANDOM} % `wc -l < file` + 1)) file | tail -1
</code>```

OwnerDisplayName: Newbie Prog

ContentLicense: CC BY-SA 4.0

Body:
Another alternative:

head -$((${RANDOM} % `wc -l < file` + 1)) file | tail -1

OwnerDisplayName: PolyThinker


问:
Convert HTML to Image on Azure
I have tried two HTML to Image conversion packages HiQPd and NReco.

Both libraries work beautifully when run from Visual Studio on my local PC.

When I deploy to an Azure-hosted website, both packages fail thusly:

HiQPdf throws Exceptions when invoking ConvertHtmlToImage(...).

NReco produces a black rectangle for each rendered character.

The HTML I'm converting is simple stuff, like
Hello

Is this a problem with Azure, hosting on servers in general, or not including some library which "everybody knows that!"?

答: Upgrading my Azure service plan to B1 Basic solved my problem.  Thank you Vitaliy!</p>

Title: Convert HTML to Image on Azure


问:
Array property in Javascript object is undefined
I'm using Node.js to loop through an array of Artist results I obtain from Mongoose:

```<code>User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
    for (var i=0; i < artists.length; i++){
        console.log(artists[i]);
    }
})
</code>```

The above code works find and prints out all three properties of Artists that I asked for.

EDIT: Here's an example of what I see in console:

```<code>{
    _id: 'T8fdSmf0e1ua',
    BIO: 'This is Susan's bio...\n',
    Firstname: 'Susan',
    list_artworks: [
        'ID ONE',
        'ID TWO',
        ...
    ]
}
</code>```

However, when I try to access a property that is an array of Artwork ids, everything is undefined using console.log():

```<code>for (var i=0; i < artists.length; i++){
    console.log(artists[i].list_artworks);
}
</code>```

When I access the other properties of my Artist, like BIO or Firstname, it prints successfully to my console:

```<code>for (var i=0; i < artists.length; i++){
    console.log(artists[i].BIO);
}
</code>```

Why is this the case? I don't think it has to do with async code in this case given that all objects are return in the then() chain. The list_artworks property is clearly there if I print the entire artist object, but why is it undefined when I attempt to access it?

Here's another example. I print out each property, and then the object itself:

```<code>console.log(artist.BIO);
console.log("---------------")
console.log(artist.Firstname);
console.log("---------------")
console.log(artist.list_artworks);
console.log("---------------")
console.log(artist)
</code>```

And here's what is printed on my console:

---------------
Mike
---------------
undefined // <--- when I access the property itself
---------------
{
  _id: '599asdsdasd232d23d2',
  Firstname: 'Mike',
  BIO: '',
  list_artworks: // <-- why does it show up here?
   [ '6cohpx7d23asu',
     'W4Fgs23X5aXds',...
```

<p>Here is my entire code base:</p>

```setTimeout(function(){

     User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
         console.log(artists.length);

        for (var i=0; i < artists.length; i++){
            artist = artists[i];
             console.log(artist.BIO);
             console.log("---------------")
             console.log(artist.Firstname);
             console.log("---------------")
            console.log(artist['list_artworks']);
             console.log("---------------")
             console.log(artist)
            }
        }

     ).catch((err)=>{console.log(err)});
}, constants.NLP_TRAINING_INTERVAL);
```

答:
Try this</p>

```<code>User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{

        for (var i=0; i < artists.length; i++){
            console.log(artists[i][‘list_artworks’]);
        }
         }
</code>```

Body:
I'm using Node.js to loop through an array of Artist results I obtain from Mongoose:

User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
    for (var i=0; i < artists.length; i++){
        console.log(artists[i]);
    }
})

The above code works find and prints out all three properties of Artists that I asked for.

EDIT: Here's an example of what I see in console:

{
    _id: 'T8fdSmf0e1ua',
    BIO: 'This is Susan's bio...\n',
    Firstname: 'Susan',
    list_artworks: [
        'ID ONE',
        'ID TWO',
        ...
    ]
}

However, when I try to access a property that is an array of Artwork ids, everything is undefined using console.log():

for (var i=0; i < artists.length; i++){
    console.log(artists[i].list_artworks);
}

When I access the other properties of my Artist, like BIO or Firstname, it prints successfully to my console:

for (var i=0; i < artists.length; i++){
    console.log(artists[i].BIO);
}

Why is this the case? I don't think it has to do with async code in this case given that all objects are return in the then() chain. The list_artworks property is clearly there if I print the entire artist object, but why is it undefined when I attempt to access it?

Here's another example. I print out each property, and then the object itself:

console.log(artist.BIO);
console.log("---------------")
console.log(artist.Firstname);
console.log("---------------")
console.log(artist.list_artworks);
console.log("---------------")
console.log(artist)

And here's what is printed on my console:

---------------
Mike
---------------
undefined // <--- when I access the property itself
---------------
{
  _id: '599asdsdasd232d23d2',
  Firstname: 'Mike',
  BIO: '',
  list_artworks: // <-- why does it show up here?
   [ '6cohpx7d23asu',
     'W4Fgs23X5aXds',...

Here is my entire code base:

setTimeout(function(){

     User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
         console.log(artists.length);

        for (var i=0; i < artists.length; i++){
            artist = artists[i];
             console.log(artist.BIO);
             console.log("---------------")
             console.log(artist.Firstname);
             console.log("---------------")
            console.log(artist['list_artworks']);
             console.log("---------------")
             console.log(artist)
            }
        }

     ).catch((err)=>{console.log(err)});
}, constants.NLP_TRAINING_INTERVAL);

Body:
Try this

User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{

        for (var i=0; i < artists.length; i++){
            console.log(artists[i][‘list_artworks’]);
        }
         }


问:
Storing Data From List To Another Form VS2008
I don't know exactly how to explain this but I'll try.

Is it possible to store or transfer data from a List to another form?
Like for example, I have 20 questions and the answers are being stored in a list. If the user clicks on "review answers" button, another form will pop up showing the questions and the user's answers to those questions.

Sorry I don't really have a code to post as I have no idea how to do this or if this can be done at all.

UPDATE 1

I am using List (Of String).. I need the values that are being stored in my List (Of String) to be passed to another form on button click

答:
You can use global variables to pass data from one from to another

maybe your list of QSN,ANS should look like

```<code>        Dim Question As New List(Of String)
        Question.Add("A")
        Question.Add("B")
        Dim Ans As New List(Of String)
        ans.Add("Ans A")
        ans.Add("Ans B")
</code>```

Here how you declare the global The class can be define anywhere in the application.

```<code>Public Class GlobalVariables
Public Shared Question As String
Public Shared Answer As String
End Class
</code>```

And how you use global variable to store the answer is here

```<code>GlobalVariables.Question=Question.Item(<Question list Index Number>)
GlobleVariables.Answer=Ans.Item(<Question list Index Number>)
</code>```

put this two lines in button click event and you can access the variable to any of your form that is in your WINDOWS application.

And how you print or store the value of this variable is

```<code>Dim A as String = GlobleVariables.Answer
</code>```

Body:
You can use global variables to pass data from one from to another

maybe your list of QSN,ANS should look like

        Dim Question As New List(Of String)
        Question.Add("A")
        Question.Add("B")
        Dim Ans As New List(Of String)
        ans.Add("Ans A")
        ans.Add("Ans B")

Here how you declare the global The class can be define anywhere in the application.

Public Class GlobalVariables
Public Shared Question As String
Public Shared Answer As String
End Class

And how you use global variable to store the answer is here

GlobalVariables.Question=Question.Item(<Question list Index Number>)
GlobleVariables.Answer=Ans.Item(<Question list Index Number>)

put this two lines in button click event and you can access the variable to any of your form that is in your WINDOWS application.

And how you print or store the value of this variable is

Dim A as String = GlobleVariables.Answer


问:
Unable to connect to the Remote Debugging - Web App Azure
I am trying to remote debug an Asp.Net Core Web Application (with Web API) project deployed as an Azure App Service with Visual Studio 2017 Professional.

Followed the instructions as documented here. Essentially, using the Server Explorer-->App Service-->Attach Debugger

Also, enabled the necessary firewall ports as mentioned. The ones I opened are TCP (4022, 4023) and UDP (3702). Also, ensure remote debugger application is in allowed list of apps in Windows Firewall. Documentation for the firewall steps.

Despite all the settings, I am getting following error

```<code>System.Runtime.InteropServices.COMException (0x89710023): Unable to connect to the Microsoft Visual Studio Remote Debugger named 'essamplepoc2.azurewebsites.net'.  The Visual Studio 2017 Remote Debugger (MSVSMON.EXE) does not appear to be running on the remote computer. This may be because a firewall is preventing communication to the remote computer. Please see Help for assistance on configuring remote debugging.
   at Microsoft.VisualStudio.Debugger.Interop.Internal.IDebuggerInternal120.ConnectToServer(String szServerName, VsDebugRemoteConnectOptions[] pConnectOptions, CONNECT_REASON ConnectReason, Int32 fIncrementUsageCount, IDebugCoreServer3& ppServer)
   at Microsoft.VisualStudio.Web.Azure.MicrosoftWeb.Operations.RemoteDiagnosticsSessionBase.ConnectToServer(String site, String user, String password)
</code>```

Any suggestion would be helpful.

答:
It seems remote debugging is not turned on for your App Service.

Open your App Service in the Azure portal and go to Application Settings. Then turn Remote Debugging to On and select Visual Studio Version to 2017.

It should look like this:

Screenshot source

I hope this helps.

Body:
I am trying to remote debug an Asp.Net Core Web Application (with Web API) project deployed as an Azure App Service with Visual Studio 2017 Professional.

Followed the instructions as documented here. Essentially, using the Server Explorer-->App Service-->Attach Debugger

Also, enabled the necessary firewall ports as mentioned. The ones I opened are TCP (4022, 4023) and UDP (3702). Also, ensure remote debugger application is in allowed list of apps in Windows Firewall. Documentation for the firewall steps.

Despite all the settings, I am getting following error

System.Runtime.InteropServices.COMException (0x89710023): Unable to connect to the Microsoft Visual Studio Remote Debugger named 'essamplepoc2.azurewebsites.net'.  The Visual Studio 2017 Remote Debugger (MSVSMON.EXE) does not appear to be running on the remote computer. This may be because a firewall is preventing communication to the remote computer. Please see Help for assistance on configuring remote debugging.
   at Microsoft.VisualStudio.Debugger.Interop.Internal.IDebuggerInternal120.ConnectToServer(String szServerName, VsDebugRemoteConnectOptions[] pConnectOptions, CONNECT_REASON ConnectReason, Int32 fIncrementUsageCount, IDebugCoreServer3& ppServer)
   at Microsoft.VisualStudio.Web.Azure.MicrosoftWeb.Operations.RemoteDiagnosticsSessionBase.ConnectToServer(String site, String user, String password)

Any suggestion would be helpful.


问:
Help with SQL Stored procedure
I need some help with an SQL stored procedure, I haven't got alot of experience with it.
I have a table "dbo.Lookup_Country". It contains 3 fields: ID, Name, Code.
Now I wrote a stored procedure that retrieves the country name by Code.

```<code>Select Name from Lookup_Country where Code = @Code
</code>```

I need to adjust the stored procedure so that if there are 0 results it has to see if there are results by searching with ID:

Select Name from Lookup_Country where Id = @Code

So basically I need some kind of 'IF' structure:

```<code>if (Select Name from Lookup_Country where Code = @Code) == 0 results
      Select Name from Lookup_Country where Id = @Code
</code>```

Is this possible?

thx

Thx for the help everyone, I used this:

```<code>DECLARE @Name nvarchar(50)

-- Insert statements for procedure here
SET @Name = (SELECT Name from dbo.Lookup_Country WHERE Code = @CODE)
IF @Name != ''
    SELECT Name from dbo.Lookup_Country WHERE Code = @CODE
ELSE
    SELECT Name from dbo.Lookup_Country WHERE ID = @CODE
</code>```

答:
There isn't a really elegant way for this...

```<code>SELECT Name
INTO #foo
from Lookup_Country where Code = @Code
IF @@ROWCOUNT <> 0
   SELECT Name  FROM #foo
ELSE
   Select Name from Lookup_Country where Id = @Code
</code>```

Whether you use a table variable or count, it doesn't matter

Or you have this construct, perhaps with an aggregate

```<code>SELECT TOP 1
    Name
FROM
    (
    Select Name, 0 AS Precedence from Lookup_Country where Code = @Code
    UNION ALL
    Select Name, 1 AS Precedence from Lookup_Country where Id = @Code
    ) foo
ORDER BY
    Precedence
</code>```

If you include Precedence in the output you have information on how it was found...

Title: Help with SQL Stored procedure

Body:
I need some help with an SQL stored procedure, I haven't got alot of experience with it.
I have a table "dbo.Lookup_Country". It contains 3 fields: ID, Name, Code.
Now I wrote a stored procedure that retrieves the country name by Code.

Select Name from Lookup_Country where Code = @Code

I need to adjust the stored procedure so that if there are 0 results it has to see if there are results by searching with ID:

Select Name from Lookup_Country where Id = @Code

So basically I need some kind of 'IF' structure:

if (Select Name from Lookup_Country where Code = @Code) == 0 results
      Select Name from Lookup_Country where Id = @Code

Is this possible?

thx

Thx for the help everyone, I used this:

DECLARE @Name nvarchar(50)

-- Insert statements for procedure here
SET @Name = (SELECT Name from dbo.Lookup_Country WHERE Code = @CODE)
IF @Name != ''
    SELECT Name from dbo.Lookup_Country WHERE Code = @CODE
ELSE
    SELECT Name from dbo.Lookup_Country WHERE ID = @CODE

Body:
There isn't a really elegant way for this...

SELECT Name
INTO #foo
from Lookup_Country where Code = @Code
IF @@ROWCOUNT <> 0
   SELECT Name  FROM #foo
ELSE
   Select Name from Lookup_Country where Id = @Code

Whether you use a table variable or count, it doesn't matter

Or you have this construct, perhaps with an aggregate

SELECT TOP 1
    Name
FROM
    (
    Select Name, 0 AS Precedence from Lookup_Country where Code = @Code
    UNION ALL
    Select Name, 1 AS Precedence from Lookup_Country where Id = @Code
    ) foo
ORDER BY
    Precedence

If you include Precedence in the output you have information on how it was found...


问:
Modulo division of large uint64_t from C to Java
So, here is a simple C program that I would like to be able to reproduce in Java:

```<code>#include<stdio.h>
#include<stdint.h>
int main() {
    uint64_t x = 0xB3E110C4CFF34548;

    printf("%16lX %20ld\n", x, x);
    printf("%16lX %20ld\n", x % 5, x % 5);
}
</code>```

Compile with: gcc -Wall -std=c11 main.c. My gcc --version is 7.1.1 20170621

So far, I have tried this:

```<code>public class Main {
    public static void main(String[] args) {
        long x = 0xB3E110C4CFF34548L;

        System.out.printf("%16X %20d\n", x, x);
        System.out.printf("%16X %20d\n", x % 5, x % 5);
        System.out.printf(
            "%16X %20d\n", Math.floorMod(x, 5), Math.floorMod(x, 5)
            );
    }
}
</code>```

Compile with: javac Main.c, my javac -version is 1.8.0_131 and I assume it produces Java 8.

However, as you can see for yourself, the results are different. C executable gives you 2 as modulo, while Java gives you -4 or 1 depending on the modulo you use. What am I doing wrong here?

答:
Alright, for me the answer turned out to be Long.remainderUnsigned which is a new feature since Java 8:

```<code>public class Main {
    public static void main(String[] args) {
        long x = 0xB3E110C4CFF34548L;

        System.out.printf("%16X %20d\n", x, x);
        System.out.printf("%16X %20d\n", x % 5, x % 5);
        System.out.printf(
            "%16X %20d\n", Math.floorMod(x, 5), Math.floorMod(x, 5)
            );
        System.out.printf("%16X %20d\n", Long.remainderUnsigned(x, 5), Long.remainderUnsigned(x, 5));
    }
}
</code>```

Body:
So, here is a simple C program that I would like to be able to reproduce in Java:

#include<stdio.h>
#include<stdint.h>
int main() {
    uint64_t x = 0xB3E110C4CFF34548;

    printf("%16lX %20ld\n", x, x);
    printf("%16lX %20ld\n", x % 5, x % 5);
}

Compile with: gcc -Wall -std=c11 main.c. My gcc --version is 7.1.1 20170621

So far, I have tried this:

public class Main {
    public static void main(String[] args) {
        long x = 0xB3E110C4CFF34548L;

        System.out.printf("%16X %20d\n", x, x);
        System.out.printf("%16X %20d\n", x % 5, x % 5);
        System.out.printf(
            "%16X %20d\n", Math.floorMod(x, 5), Math.floorMod(x, 5)
            );
    }
}

Compile with: javac Main.c, my javac -version is 1.8.0_131 and I assume it produces Java 8.

However, as you can see for yourself, the results are different. C executable gives you 2 as modulo, while Java gives you -4 or 1 depending on the modulo you use. What am I doing wrong here?

Body:
Alright, for me the answer turned out to be Long.remainderUnsigned which is a new feature since Java 8:

public class Main {
    public static void main(String[] args) {
        long x = 0xB3E110C4CFF34548L;

        System.out.printf("%16X %20d\n", x, x);
        System.out.printf("%16X %20d\n", x % 5, x % 5);
        System.out.printf(
            "%16X %20d\n", Math.floorMod(x, 5), Math.floorMod(x, 5)
            );
        System.out.printf("%16X %20d\n", Long.remainderUnsigned(x, 5), Long.remainderUnsigned(x, 5));
    }
}


问:
componentRecieveProps getting different props value than in render
I try to do infinite scroll by detecting the items are different in componentWillReceiveprops, like so

```<code>componentWillReceiveprops(nextProps) {

        //if infinite load triggered
        if(!isEqual(nextProps.items, this.props.items)){
            this.props.items.push(...nextProps.items)
            //this.forceUpdate()
            console.log(this.props.items) // newly items are merge with previous items array, worked.
        }

}

render() {
    const { items } = this.props

    console.log(items) // still old items, newly loaded items is not here?

    return(<div></div>)
}
</code>```

But items in my render method and the items in componentWillReceiveprops is not the same? I also tried forceUpdate still coulnd't make this infinite scroll work.

答:
props are supposed to be immutable. See this answer by Mike Driver. Quoting:

The React philosophy is that props should be immutable and top-down. This means that a parent can send whatever prop values it likes to a child, but the child cannot modify its own props. What you do is react to the incoming props and then, if you want to, modify your child's state based on incoming props.

So you don't ever update your own props, or a parent's props. Ever. You only ever update your own state, and react to prop values you are given by parent.

You are using this.props.items.push(...) which is altering the props being received. This is something React advises you not to do, and it's bound to cause all sorts of trouble. You will need to start thinking differently about how you change application state in your app.

As a suggestion, you can make the parent component send down a method as a prop to your child component which will be called back whenever you need to change the component's state.

Body:
I try to do infinite scroll by detecting the items are different in componentWillReceiveprops, like so

componentWillReceiveprops(nextProps) {

        //if infinite load triggered
        if(!isEqual(nextProps.items, this.props.items)){
            this.props.items.push(...nextProps.items)
            //this.forceUpdate()
            console.log(this.props.items) // newly items are merge with previous items array, worked.
        }

}

render() {
    const { items } = this.props

    console.log(items) // still old items, newly loaded items is not here?

    return(

)
}

But items in my render method and the items in componentWillReceiveprops is not the same? I also tried forceUpdate still coulnd't make this infinite scroll work.


问:
Javascript code doesn't work. Why?
The values of the buttons should change when you click on them

```<code><html>
<head>

</head>

<body>

<input type = "button" value ="1" onclick="click(this);">
<input type = "button" value ="0" onclick="click(this);">
<input type = "button" value ="1" onclick="click(this);">

<script>

function click(objekt) {

if(objekt.value == 1)
    objekt.value = 0;
    else
        objekt.value = 1;

}

</script>

</body>
</html>
</code>```

Please explain how to get the value on onclick event?

答:
Try removing the spaces on

```<code><input type = "button" value ="1" onclick="click(this);">
<input type = "button" value ="0" onclick="click(this);">
<input type = "button" value ="1" onclick="click(this);">
</code>```

to

```<code><input type="button" value="1" onclick="click(this);">
<input type="button" value="0" onclick="click(this);">
<input type="button" value="1" onclick="click(this);">
</code>```

Also, what are the values when you change them? Try printing them out. That might help you find what you're looking for. Does it actually change to 1 or 0? Also, I know you don't need curly brackets on if statements if there is only one statement but try with curly brackets.

Title: Javascript code doesn't work. Why?

Body:
The values of the buttons should change when you click on them

<input type = "button" value ="1" onclick="click(this);">
<input type = "button" value ="0" onclick="click(this);">
<input type = "button" value ="1" onclick="click(this);">

Please explain how to get the value on onclick event?

Body:
Try removing the spaces on

<input type = "button" value ="1" onclick="click(this);">
<input type = "button" value ="0" onclick="click(this);">
<input type = "button" value ="1" onclick="click(this);">

to

<input type="button" value="1" onclick="click(this);">
<input type="button" value="0" onclick="click(this);">
<input type="button" value="1" onclick="click(this);">

Also, what are the values when you change them? Try printing them out. That might help you find what you're looking for. Does it actually change to 1 or 0? Also, I know you don't need curly brackets on if statements if there is only one statement but try with curly brackets.


问:
ionic framework - unable to prevent ion-toggle from toggling
I am using ion-toggle in my app . when user clicks(checks) on the ion-toggle , i have written ionChange hook on the ion-toogle . In this hook ,due to application logic , i am giving prompt to the user saying ion-toggle can not be set .

 using event.preventDefault to prevent ion-toggle to toggle

 component html

```<code><ion-content padding>
     <ion-slides pager="true">
    <ion-slide *ngFor="let giftSlide of giftsAllMatrix" >
    <ion-row *ngFor="let giftRecord of giftSlide">
      <ion-col *ngFor="let giftCol of giftRecord" col-6>
        <img src="./assets/{{giftCol.giftImage}}" >
          <p> gift code :  {{ giftCol.giftCode }} </p>
          <ion-item>
         <ion-toggle   #giftSelect (ionChange)="onGiftSelect(giftCol.giftCode, giftCol.pointsRequired ,giftCol.giftImage,giftSelect.checked,giftSelect,$event)" checked="false"></ion-toggle>
          </ion-item>
        </ion-col>
    </ion-row>
    </ion-slide>
    </ion-slides>
</code>```

 component hook - onGiftSelect

```<code>onGiftSelect( giftSelCode : string ,
           pointsRequired : number ,
           giftImage : string ,
            selected : boolean
           ,giftSelect : any,
           event : Event)
      {
         console.log("inside onGiftSelect "+giftSelCode);
         console.log("inside onGiftSelect  points required "+pointsRequired);
         console.log(" selected "+selected );
         console.log(" this.giftSelectedFlg "+this.giftSelectedFlg );
         let navigate = true;
         // if ion-toggle is true then only navigate
         // when toggle is from 'selected' to 'deselected' do not
         if ( selected === true)
         {
            if ( this.giftSelectedFlg  === false )
            {
                this.giftSelectedFlg = true;
            }
            else
            {

                if(isProdSetup() === true)
                {
                    this.toast.show( "Select one gift at time ", '3000', 'center').subscribe
                    ( toast =>
                    {
                        console.log(toast);
                    });
                }
                else
                {
                     let alert = this.alertCtrl.create({
                     title: 'Gift selection',
                     subTitle: 'Multiple gift selection disallowed',
                     buttons: ['Dismiss']
                     });
                     alert.present();
                }
              navigate = false;
              event.preventDefault();
        }
         if ( navigate)
        {
           // Pass the control to giftSelect page
           this.navCtrl.push("Giftselect",
              {
                 giftCode : giftSelCode ,
                 pointsRequired : pointsRequired ,
                 giftImage : giftImage
              });
         }

    }
</code>```

 using viewchild

  using nativeElement

 this code also does not work . Can anybody help me to get right way to prevent ion-toggle component prevent toggling in ionChange event.

```<code> export class Giftfactory {
      giftsAllMatrix : GiftCatalogueEntry[][][];
      gifts : Array<any> ;
      totalPoints : number = 0;
      error : string;
      giftSelectedFlg : boolean = false;
      giftChoice : any;
      //giftSelect :  any; //template variable.
     @ViewChild ('giftSelect') gtSel ;

onGiftSelect( giftSelCode : string ,
           pointsRequired : number ,
           giftImage : string ,
            selected : boolean
           ,giftSelect : any,
           event : Event)
    {
    ...
        // trying to uncheck ion-toggle - does not work
        this.gtSel.nativeElement.checked = false;
    }
</code>```

答:
ion-toggle tag

```<code><ion-toggle  #giftSelect (ionChange)="onGiftSelect(giftCol.giftCode, giftCol.pointsRequired ,giftCol.giftImage,giftSelect.checked,giftSelect,$event)" checked="false"></ion-toggle>
</code>```

toggle event handler

 Use template reference variable giftSelect to access ion-toggle. giftSelect is passed to the event handler. use checked property to set toggle off.

```<code> onGiftSelect( giftSelCode : string ,
               pointsRequired : number ,
               giftImage : string ,
                selected : boolean
               ,giftSelect : any)
   {
      //make toggle off ,depending on the application logic.
      giftSelect.checked = false;

   }
</code>```

Body:
I am using ion-toggle in my app . when user clicks(checks) on the ion-toggle , i have written ionChange hook on the ion-toogle . In this hook ,due to application logic , i am giving prompt to the user saying ion-toggle can not be set .

 using event.preventDefault to prevent ion-toggle to toggle

 component html

<ion-content padding>
     <ion-slides pager="true">
    <ion-slide *ngFor="let giftSlide of giftsAllMatrix" >
    <ion-row *ngFor="let giftRecord of giftSlide">
      <ion-col *ngFor="let giftCol of giftRecord" col-6>

 gift code :  {{ giftCol.giftCode }}

          <ion-item>
         <ion-toggle   #giftSelect (ionChange)="onGiftSelect(giftCol.giftCode, giftCol.pointsRequired ,giftCol.giftImage,giftSelect.checked,giftSelect,$event)" checked="false"></ion-toggle>
          </ion-item>
        </ion-col>
    </ion-row>
    </ion-slide>
    </ion-slides>

 component hook - onGiftSelect

onGiftSelect( giftSelCode : string ,
           pointsRequired : number ,
           giftImage : string ,
            selected : boolean
           ,giftSelect : any,
           event : Event)
      {
         console.log("inside onGiftSelect "+giftSelCode);
         console.log("inside onGiftSelect  points required "+pointsRequired);
         console.log(" selected "+selected );
         console.log(" this.giftSelectedFlg "+this.giftSelectedFlg );
         let navigate = true;
         // if ion-toggle is true then only navigate
         // when toggle is from 'selected' to 'deselected' do not
         if ( selected === true)
         {
            if ( this.giftSelectedFlg  === false )
            {
                this.giftSelectedFlg = true;
            }
            else
            {

                if(isProdSetup() === true)
                {
                    this.toast.show( "Select one gift at time ", '3000', 'center').subscribe
                    ( toast =>
                    {
                        console.log(toast);
                    });
                }
                else
                {
                     let alert = this.alertCtrl.create({
                     title: 'Gift selection',
                     subTitle: 'Multiple gift selection disallowed',
                     buttons: ['Dismiss']
                     });
                     alert.present();
                }
              navigate = false;
              event.preventDefault();
        }
         if ( navigate)
        {
           // Pass the control to giftSelect page
           this.navCtrl.push("Giftselect",
              {
                 giftCode : giftSelCode ,
                 pointsRequired : pointsRequired ,
                 giftImage : giftImage
              });
         }

    }

 using viewchild

  using nativeElement

 this code also does not work . Can anybody help me to get right way to prevent ion-toggle component prevent toggling in ionChange event.

 export class Giftfactory {
      giftsAllMatrix : GiftCatalogueEntry[][][];
      gifts : Array<any> ;
      totalPoints : number = 0;
      error : string;
      giftSelectedFlg : boolean = false;
      giftChoice : any;
      //giftSelect :  any; //template variable.
     @ViewChild ('giftSelect') gtSel ;

onGiftSelect( giftSelCode : string ,
           pointsRequired : number ,
           giftImage : string ,
            selected : boolean
           ,giftSelect : any,
           event : Event)
    {
    ...
        // trying to uncheck ion-toggle - does not work
        this.gtSel.nativeElement.checked = false;
    }

Body:
ion-toggle tag

<ion-toggle  #giftSelect (ionChange)="onGiftSelect(giftCol.giftCode, giftCol.pointsRequired ,giftCol.giftImage,giftSelect.checked,giftSelect,$event)" checked="false"></ion-toggle>

toggle event handler

 Use template reference variable giftSelect to access ion-toggle. giftSelect is passed to the event handler. use checked property to set toggle off.

 onGiftSelect( giftSelCode : string ,
               pointsRequired : number ,
               giftImage : string ,
                selected : boolean
               ,giftSelect : any)
   {
      //make toggle off ,depending on the application logic.
      giftSelect.checked = false;

   }


问:
Localhost Service Discovery For a Custom XEP-0114 Component in Prosody or ejabberd
I have written a silly hello-world XEP-0114 component and got it connected to Prosody and ejabberd. Now I want to use service discovery to announce presence of the service and provide instructions about its usage.

So I seek a way to make it discoverable for anyone with a JID, remote or local, to provide more details about it.

For Prosody I do:

```<code>Component "foo.localhost"
  component_secret = "secret"

disco_items = {
  { "foo.localhost", "FOO BAR" };
}
</code>```

For ejabberd I do:

```<code>modules:
  mod_disco:
    extra_domains:
      - "foo.localhost"
      - "localhost"
    server_info:
      -
        modules: all
        name: "abuse-addresses"
        urls:
          - "foo.com"
listen:
  -
    port: 8888
    module: ejabberd_service
    access: all
    shaper_rule: fast
    ip: "127.0.0.1"
    hosts:
      "foo.localhost":
        password: "secret"
</code>```

Then in Gajim I start service discovery on localhost and get error:

There is no service at the address you entered, or it is not responding. Check the address and try again.

What do I miss?

答:
First thing to check when in trouble is a XML-console of a xmpp-client (Gajim), there I found this:

<iq xmlns="jabber:client" to="localhost" type="get" id="546">
<query xmlns="http://jabber.org/protocol/disco#info" />
</iq>

<iq xml:lang='en' to='mynickhere@jabb.im/Gajim' from='localhost' type='error' id='546'>
<query xmlns='http://jabber.org/protocol/disco#info'/>
<error code='504' type='wait'>
<remote-server-timeout xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
<text xml:lang='en' xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'>Stream closed by peer: host-unknown</text>
</error>
</iq>
```

It shows that discovery requests are sent to the server where currently used account is located (jabb.im). I don't know how things work, but this should prompt you to disconnect from remote server, create account on local server and login with it instead, then discovery will work as expected.

Body:
I have written a silly hello-world XEP-0114 component and got it connected to Prosody and ejabberd. Now I want to use service discovery to announce presence of the service and provide instructions about its usage.

So I seek a way to make it discoverable for anyone with a JID, remote or local, to provide more details about it.

For Prosody I do:

Component "foo.localhost"
  component_secret = "secret"

disco_items = {
  { "foo.localhost", "FOO BAR" };
}

For ejabberd I do:

modules:
  mod_disco:
    extra_domains:
      - "foo.localhost"
      - "localhost"
    server_info:
      -
        modules: all
        name: "abuse-addresses"
        urls:
          - "foo.com"
listen:
  -
    port: 8888
    module: ejabberd_service
    access: all
    shaper_rule: fast
    ip: "127.0.0.1"
    hosts:
      "foo.localhost":
        password: "secret"

Then in Gajim I start service discovery on localhost and get error:

There is no service at the address you entered, or it is not responding. Check the address and try again.

What do I miss?

Body:
First thing to check when in trouble is a XML-console of a xmpp-client (Gajim), there I found this:

<iq xmlns="jabber:client" to="localhost" type="get" id="546">
<query xmlns="http://jabber.org/protocol/disco#info" />
</iq>

<iq xml:lang='en' to='mynickhere@jabb.im/Gajim' from='localhost' type='error' id='546'>
<query xmlns='http://jabber.org/protocol/disco#info'/>
<error code='504' type='wait'>
<remote-server-timeout xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
<text xml:lang='en' xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'>Stream closed by peer: host-unknown</text>
</error>
</iq>

It shows that discovery requests are sent to the server where currently used account is located (jabb.im). I don't know how things work, but this should prompt you to disconnect from remote server, create account on local server and login with it instead, then discovery will work as expected.


问:
elm-test Expect print message on failure?
Most unit test frameworks support having a string in the assertion that gets printed out when the assertion fails. So far I don't see that ability in elm-test?(!)</p>

答:
The onFail function gives the ability to give a custom failure message for any of the other expectations. From the docs:

```<code>"something"
    |> Expect.equal "something else"
    |> Expect.onFail "thought those two strings would be the same"
</code>```

Body:
The onFail function gives the ability to give a custom failure message for any of the other expectations. From the docs:

"something"
    |> Expect.equal "something else"
    |> Expect.onFail "thought those two strings would be the same"


问:
Issue casting to string in google sheets script
I have the following function for a google sheets document:

```<code>function names(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
    var str = String(nameCells[i]);
    var splitted = str.split(", ");
    for (k = 0; splitted.length; i++) {
      roomieNames.push(splitted[i]);
    }
  }
  return roomieNames;
}
</code>```

The function is supposed take a list of cells with names that are comma separated and return and single list of all the names.

For example:

```<code>James
Reese, Peter
Ryan, Monica
Reba

Nick
</code>```

Should produce

```<code>James
Reese
Peter
Ryan
Monica
Nick
</code>```

However I seem to be having an issue casting the cell values to string values and it says "Internal error executing the custom function" without giving me any more specifics than that. The following more basic program does work as expected:

```<code>function namesSimple(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
      roomieNames.push(nameCells[i]);
  }
  return roomieNames;
}
</code>```

However the following produces the error seen in the comments in line 4:

```<code>function namesBroken(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
    var splitted = nameCells[i].split(", ");  //TypeError: Cannot find function split in object James. (line 4).
    for (k = 0; splitted.length; i++) {
      roomieNames.push(splitted[i]);
    }
  }
  return roomieNames;
}
</code>```

Which leads to me to believe I need to cast the object to a string but as stated above that doesn't seem to be working either.

I tried googling casting techniques and feel that this should work. I have also tried .toString(); with no luck. Can someone help me out please. Thanks :)

答:
The problem is with the nested for loop (I need to use any IDE to catch these mistakes)</p>

```<code>function names(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
    var str = String(nameCells[i]);
    var splitted = str.split(", ");
    for (k = 0; splitted.length; i++) {  //should be for (k = 0; splitted.length; k++)
      roomieNames.push(splitted[i]);  //should be roomieNames.push(splitted[k])
    }
  }
  return roomieNames;
}
</code>```

Body:
I have the following function for a google sheets document:

function names(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
    var str = String(nameCells[i]);
    var splitted = str.split(", ");
    for (k = 0; splitted.length; i++) {
      roomieNames.push(splitted[i]);
    }
  }
  return roomieNames;
}

The function is supposed take a list of cells with names that are comma separated and return and single list of all the names.

For example:

James
Reese, Peter
Ryan, Monica
Reba

Nick

Should produce

James
Reese
Peter
Ryan
Monica
Nick

However I seem to be having an issue casting the cell values to string values and it says "Internal error executing the custom function" without giving me any more specifics than that. The following more basic program does work as expected:

function namesSimple(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
      roomieNames.push(nameCells[i]);
  }
  return roomieNames;
}

However the following produces the error seen in the comments in line 4:

function namesBroken(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
    var splitted = nameCells[i].split(", ");  //TypeError: Cannot find function split in object James. (line 4).
    for (k = 0; splitted.length; i++) {
      roomieNames.push(splitted[i]);
    }
  }
  return roomieNames;
}

Which leads to me to believe I need to cast the object to a string but as stated above that doesn't seem to be working either.

I tried googling casting techniques and feel that this should work. I have also tried .toString(); with no luck. Can someone help me out please. Thanks :)

Body:
The problem is with the nested for loop (I need to use any IDE to catch these mistakes)

function names(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
    var str = String(nameCells[i]);
    var splitted = str.split(", ");
    for (k = 0; splitted.length; i++) {  //should be for (k = 0; splitted.length; k++)
      roomieNames.push(splitted[i]);  //should be roomieNames.push(splitted[k])
    }
  }
  return roomieNames;
}


问:
ReactJs - Redux State is not updating in a dropdown in the child component
I am trying to update the items in my dropdown as my state updates with players BUT I am failing. Please help.

In the child component I have dropdown in the Skylight dialog box.
I am using following code which prints the dropdown of the array of players from the state. State is updated from the json.php (remote server).

```<code><select name="bowlerId"  value={this.state.bowlerId} onChange={this.handleInputChange} className="form-control">
            <option value="">Select an existing bowler</option>
            {
                this.currState.teamBowling.players.map(function (player, index) {
                return <option value="{player}" key={index}>{player}</option>
                })
            }
    </select>
</code>```

I can clearly see in the console.log that the state is correctly updated and it prints 11 player names. But in the child component it does not update the dropdown.

Surprising enough, in the child component componentWillReceiveProps() does print new player names as they become availble but the dropdown is not updated still.

Please advise.

Console.log output as page loads

BowlingSummary render() Object {id: 0, name: "", runs: 0, overs: 0, balls: 0…}

PropStore Object {id: 0, name: "", runs: 0, overs: 0, balls: 0…}

BowlingAddBowler render() []

Console.log output after few seconds as data is fetched from php

BowlingSummary render() Object {id: 20, name: "Team Bowling", runs: 0, overs: 0, balls: 0…}

componentWillReceiveProps Object {id: 20, name: "Team Bowling", runs: 0, overs: 0, balls: 0…}

BowlingAddBowler render() []

Parent component named BowlingSummary

```<code>class BowlingSummary extends Component {

    render() {
    const { store }             = this.context;
    const currState             = store.getState();
    this.isBowlerBowling        = false;

    console.log('BowlingSummary render()', currState.teamBowling);

    return (
        <div>
        <div className="score-summary-bar">
            <div className="row">
            <div className="col-xs-4">Bowling</div>
            <div className="col-xs-1"></div>
            <div className="col-xs-1">Ovr</div>
            <div className="col-xs-1">Mdn</div>
            <div className="col-xs-1">Run</div>
            <div className="col-xs-1">Wkt</div>
            <div className="col-xs-1">Econ</div>
            <div className="col-xs-1">W</div>
            <div className="col-xs-1">N</div>
            </div>
        </div>

        <div className="score-summary-bowling">
            <div className="">
            {
            currState.teamBowling.players.map(function (player, index) {
                if ( player.isBowling === true ) {
                this.isBowlerBowling = true;
                return <BowlingBowler player={player} key={index}/>
                }
            })
            }
            </div>
            <div className="">
            {
                this.isBowlerBowling != true &&
                <BowlingAddBowler propStore={store} />

            }
            </div>
        </div>
        <div className="score-summary-bowling">
            <ScoreThisOver />
        </div>
        </div>
    );
    }
}

BowlingSummary.contextTypes = {
    store: PropTypes.object
}

export default BowlingSummary;
</code>```

Child component named BowlingAddBowler

```<code>class BowlingAddBowler extends Component {

    constructor(props, context) {
    super(props, context);

    // Setup current state
    this.currState      = this.props.propStore.getState();
    console.log('PropStore', this.currState.teamBowling);

    // This component state
    this.state      = {
        bowlerId:               0,
        bowlerName:             '',
        markPrevOverFinished:   false
    };

    // Setup variables
    this.players    = this.props.players;

    // Bind this (so that we write short code in the onChange like onChange=this.func)
    this.handleInputChange = this.handleInputChange.bind(this);
    }

    componentWillReceiveProps(nextProps, nextState){
    //this.props.something // old value
    //nextProps.something // new value
    console.log('componentWillReceiveProps', nextProps.propStore.getState().teamBowling);
    }

    render() {
    //console.log('BowlingBowler render()', this.props);
    var responsiveWidth = {
        width:      '90vw',
        transform:  'translate(-23%, 0%)'
    };
    console.log('BowlingAddBowler render()', this.currState.teamBowling.players);

    return (
        <div className="row">
        <div className="col-xs-12">
            <button className="btn" onClick={() => this.refs.dialogAddBowler.show()}>No Bowler Selected. Click To Select</button>
        </div>
        <SkyLight dialogStyles={responsiveWidth} hideOnOverlayClicked ref="dialogAddBowler" title="Select a new bowler">
            <div>
            <form onSubmit={this.handleSubmit.bind(this)}>
                <label className="bg-yellow">
                Total <span className="text-red">0</span> for the loss of <span className="text-red">0</span> wickets in <span className="text-red">0</span> overs
                </label>
                <div className="spacer-horizontal"></div>

                <label>Who will bowl the next over ?</label>
                <select name="bowlerId"  value={this.state.bowlerId} onChange={this.handleInputChange} className="form-control">
                <option value="">Select an existing bowler</option>
                {
                    this.currState.teamBowling.players.map(function (player, index) {
                    return <option value="{player}" key={index}>{player}</option>
                    })
                }
                </select>
                <div className="spacer-horizontal"></div>

                <b>- OR -</b>
                <input type="text" name="bowlerName" value={this.state.bowlerName} onChange={this.handleInputChange} className="form-control" />
                <div className="spacer-horizontal"></div>

                <input type="checkbox" name="markPrevOverFinished" checked={this.state.markPrevOverFinished} onChange={this.handleInputChange}/>
                <label> Mark previous over finished</label>
                <div className="spacer-horizontal"></div>

                <div className="HorizLine"></div>
                <div className="text-right">
                <button type="submit" className="btn btn-primary"> Save </button>
                </div>
            </form>
            </div>
        </SkyLight>
        </div>
    )

    }
}
</code>```

答:
This code:

```<code>this.currState      = this.props.propStore.getState();
</code>```

is in BowlingAddBowler's constructor and only runs first time when the class is instantiated. You can put it in componentWillReceiveProps of BowlingAddBowler too so that it runs when new data comes from server and parent component updates BowlingAddBowler.

Body:
I am trying to update the items in my dropdown as my state updates with players BUT I am failing. Please help.

In the child component I have dropdown in the Skylight dialog box.
I am using following code which prints the dropdown of the array of players from the state. State is updated from the json.php (remote server).

<select name="bowlerId"  value={this.state.bowlerId} onChange={this.handleInputChange} className="form-control">
            <option value="">Select an existing bowler</option>
            {
                this.currState.teamBowling.players.map(function (player, index) {
                return <option value="{player}" key={index}>{player}</option>
                })
            }
    </select>

I can clearly see in the console.log that the state is correctly updated and it prints 11 player names. But in the child component it does not update the dropdown.

Surprising enough, in the child component componentWillReceiveProps() does print new player names as they become availble but the dropdown is not updated still.

Please advise.

Console.log output as page loads

BowlingSummary render() Object {id: 0, name: "", runs: 0, overs: 0, balls: 0…}

PropStore Object {id: 0, name: "", runs: 0, overs: 0, balls: 0…}

BowlingAddBowler render() []

Console.log output after few seconds as data is fetched from php

BowlingSummary render() Object {id: 20, name: "Team Bowling", runs: 0, overs: 0, balls: 0…}

componentWillReceiveProps Object {id: 20, name: "Team Bowling", runs: 0, overs: 0, balls: 0…}

BowlingAddBowler render() []

Parent component named BowlingSummary

class BowlingSummary extends Component {

    render() {
    const { store }             = this.context;
    const currState             = store.getState();
    this.isBowlerBowling        = false;

    console.log('BowlingSummary render()', currState.teamBowling);

    return (

Bowling

Ovr

Mdn

Run

Wkt

Econ

W

N

            {
            currState.teamBowling.players.map(function (player, index) {
                if ( player.isBowling === true ) {
                this.isBowlerBowling = true;
                return <BowlingBowler player={player} key={index}/>
                }
            })
            }

            {
                this.isBowlerBowling != true &&
                <BowlingAddBowler propStore={store} />

            }

            <ScoreThisOver />

    );
    }
}

BowlingSummary.contextTypes = {
    store: PropTypes.object
}

export default BowlingSummary;

Child component named BowlingAddBowler

class BowlingAddBowler extends Component {

    constructor(props, context) {
    super(props, context);

    // Setup current state
    this.currState      = this.props.propStore.getState();
    console.log('PropStore', this.currState.teamBowling);

    // This component state
    this.state      = {
        bowlerId:               0,
        bowlerName:             '',
        markPrevOverFinished:   false
    };

    // Setup variables
    this.players    = this.props.players;

    // Bind this (so that we write short code in the onChange like onChange=this.func)
    this.handleInputChange = this.handleInputChange.bind(this);
    }

    componentWillReceiveProps(nextProps, nextState){
    //this.props.something // old value
    //nextProps.something // new value
    console.log('componentWillReceiveProps', nextProps.propStore.getState().teamBowling);
    }

    render() {
    //console.log('BowlingBowler render()', this.props);
    var responsiveWidth = {
        width:      '90vw',
        transform:  'translate(-23%, 0%)'
    };
    console.log('BowlingAddBowler render()', this.currState.teamBowling.players);

    return (

            <button className="btn" onClick={() => this.refs.dialogAddBowler.show()}>No Bowler Selected. Click To Select</button>

        <SkyLight dialogStyles={responsiveWidth} hideOnOverlayClicked ref="dialogAddBowler" title="Select a new bowler">

            <form onSubmit={this.handleSubmit.bind(this)}>

                Total 0 for the loss of 0 wickets in 0 overs

                Who will bowl the next over ?
                <select name="bowlerId"  value={this.state.bowlerId} onChange={this.handleInputChange} className="form-control">
                <option value="">Select an existing bowler</option>
                {
                    this.currState.teamBowling.players.map(function (player, index) {
                    return <option value="{player}" key={index}>{player}</option>
                    })
                }
                </select>

                - OR -
                <input type="text" name="bowlerName" value={this.state.bowlerName} onChange={this.handleInputChange} className="form-control" />

                <input type="checkbox" name="markPrevOverFinished" checked={this.state.markPrevOverFinished} onChange={this.handleInputChange}/>
                 Mark previous over finished

                <button type="submit" className="btn btn-primary"> Save </button>

            </form>

        </SkyLight>

    )

    }
}

Body:
This code:

this.currState      = this.props.propStore.getState();

is in BowlingAddBowler's constructor and only runs first time when the class is instantiated. You can put it in componentWillReceiveProps of BowlingAddBowler too so that it runs when new data comes from server and parent component updates BowlingAddBowler.


问:
Insert Blobs in MySql databases with php mysqli_escape_string not working
I have the same problem as this one Insert Blobs in MySql databases with php but my files are music files and somehow the answers are not working for me.

This is my database:

```<code>+---------+-----------+------+----+--------+--------------+
| Field   |    Type   | Null |Key |Default |Extra         |
+---------+-----------+------+----+--------+--------------+
|music_id |int(11)    |  NO  |PRI |NULL    |auto_increment|
|mp3      |longblob   |  YES |    |NULL    |              |
|mime     |varchar(30)|  NO  |    |NULL    |              |
+---------+-----------+------+----+--------+--------------+
</code>```

This is my form in html:

```<code><form method="post" action="uploadFile.php" enctype='multipart/form-data'>
    <label>Upload a file with blob datatype</label><br>
    <input type="file" name="Upfile" required="" accept= "audio/*">
    <input type="submit" name="submit_Upfile" value="Submit">
</form>
</code>```

This is my php file:

```<code><?php
$host = "localhost";
$user = "root";
$pword = "";
$db = "musics";
$con = mysqli_connect($host,$user,$pword,$db);

if($con)
{
if(isset($_POST["submit_Upfile"]))
{
    $audio_name= mysqli_escape_string($con,basename( $_FILES["Upfile"]["name"] ));

    $audio_content = mysqli_escape_string($con,file_get_contents($_FILES['Upfile']['tmp_name']));

    $audio_size = getimagesize($_FILES["Upfile"]["tmp_name"]);
    $audio_content = base64_encode($audio_content);
    echo "audio_size here => ".$audio_size["mime"]."<br>";
    echo "audio_name here => ".$audio_name."<br>";
    echo "audio_content here => ".$audio_content."<br>";

    $insert_audio_to_db = mysqli_query($con,"INSERT INTO `mp3s`( `mp3` ,`mime`) VALUES ('".$audio_content."','".$audio_size['mime']."')" );
    if($insert_audio_to_db)
    {
        echo "Insert successful.";
    }else
    echo "Insert failed.";
}
}
else
echo "Connection error.";

?>
</code>```

I tried to echo some things and this is what I got:

```<code>audio_size here =>
audio_name here => iMessage Send and Receive Sounds.mp3
audio_content here => [too long to display]
Insert failed.
</code>```

Did I miss something?

答:
Since I have found the answer of this question with the help of my colleague Diana Llona. We will share it to others who are experiencing the same problem.

Problem: The main problem here is that xampp has a default max size of upload files.

To change it follow these steps:

Open your Xampp Control Panel.  See image here.

On the row of your Apacheclick the config button. Find the PHP (php.ini) file.

It will open the php.ini file for you and there, find the upload_max_filesize and post_max_size.

Change it to your desired size then save and close the file. (I just changed the post_max_size this and upload_max_filesize that big because I just want to.)

Next is to change the innodb_log_file_size of the MySQL.

Click the config button for your MySQL on the Xampp Control Panel. See image here

Then find the innodb_log_file_size and change it to your desired size then save and close the file. See image here

After you've done these steps, restart your Apache and MySQL by clicking the Stop button and Start it again.

Body:
I have the same problem as this one Insert Blobs in MySql databases with php but my files are music files and somehow the answers are not working for me.

This is my database:

+---------+-----------+------+----+--------+--------------+
| Field   |    Type   | Null |Key |Default |Extra         |
+---------+-----------+------+----+--------+--------------+
|music_id |int(11)    |  NO  |PRI |NULL    |auto_increment|
|mp3      |longblob   |  YES |    |NULL    |              |
|mime     |varchar(30)|  NO  |    |NULL    |              |
+---------+-----------+------+----+--------+--------------+

This is my form in html:

<form method="post" action="uploadFile.php" enctype='multipart/form-data'>
    Upload a file with blob datatype

    <input type="file" name="Upfile" required="" accept= "audio/*">
    <input type="submit" name="submit_Upfile" value="Submit">
</form>

This is my php file:

<?php
$host = "localhost";
$user = "root";
$pword = "";
$db = "musics";
$con = mysqli_connect($host,$user,$pword,$db);

if($con)
{
if(isset($_POST["submit_Upfile"]))
{
    $audio_name= mysqli_escape_string($con,basename( $_FILES["Upfile"]["name"] ));

    $audio_content = mysqli_escape_string($con,file_get_contents($_FILES['Upfile']['tmp_name']));

    $audio_size = getimagesize($_FILES["Upfile"]["tmp_name"]);
    $audio_content = base64_encode($audio_content);
    echo "audio_size here => ".$audio_size["mime"]."
";
    echo "audio_name here => ".$audio_name."
";
    echo "audio_content here => ".$audio_content."
";

    $insert_audio_to_db = mysqli_query($con,"INSERT INTO `mp3s`( `mp3` ,`mime`) VALUES ('".$audio_content."','".$audio_size['mime']."')" );
    if($insert_audio_to_db)
    {
        echo "Insert successful.";
    }else
    echo "Insert failed.";
}
}
else
echo "Connection error.";

?>

I tried to echo some things and this is what I got:

audio_size here =>
audio_name here => iMessage Send and Receive Sounds.mp3
audio_content here => [too long to display]
Insert failed.

Did I miss something?


问:
insert a new element into array key in php
I have a array like this-

```<code>$array = array('o' => 'one', 't' => 'three', 'f' => 'four');
</code>```

I want to add a new element in the 't' key of the array. The result will be like the following:

```<code>$array = array('o' => 'one', 't' => 'three','six', 'f' => 'four');
</code>```

How can i do this?

答:
There is how i do it.

$array_for_t_key = ['three'];

$array = array('o' => 'one', 't' => $array_for_t_key, 'f' => 'four');

array_push($array_for_t_key,"six");

//Redeclare the array

$array = array('o' => 'one', 't' => $array_for_t_key, 'f' => 'four');

Body:
I have a array like this-

$array = array('o' => 'one', 't' => 'three', 'f' => 'four');

I want to add a new element in the 't' key of the array. The result will be like the following:

$array = array('o' => 'one', 't' => 'three','six', 'f' => 'four');

How can i do this?