问:
Trying to join three tables to get a specific result
I am trying to write an SQL query to return the name of the person who adopted the cat 'seashell'

I have a adopters table with people who will or have adopted an animal.

```<code>pets=# SELECT * FROM adopters;
 id | first_name | last_name |       address        | phone_number
----+------------+-----------+----------------------+--------------
  1 | jack       | smith     | 1 ave                | 123-123-1234
  2 | james      | dude      | 2 ave                | 221-234-4444
  3 | Forrest    | Stone     | 3 lane               | 234-667-6543
  4 | craig      | list      | 44 bulvard           | 555-444-3243
  5 | kap        | seven     | no team              | 999-000-0909
  6 | Miles      | Garrett   | First energy stadium | 123-555-2424
(6 rows)
</code>```

A cats table with the cats on file

```<code>pets=# SELECT * FROM cats;
 id |   name   | gender | age |     intake_date     |    adoption_date
----+----------+--------+-----+---------------------+---------------------
  1 | Mushi    | M      |   1 | 2016-01-09 00:00:00 | 2016-03-22 00:00:00
  2 | Seashell | F      |   7 | 2016-01-09 00:00:00 |
  3 | Azul     | M      |   3 | 2016-01-11 00:00:00 | 2016-04-17 00:00:00
  4 | Victoire | M      |   7 | 2016-01-11 00:00:00 | 2016-09-01 00:00:00
  5 | Nala     | F      |   1 | 2016-01-12 00:00:00 |
(5 rows)
</code>```

And an adoptions table with a record of all the adoptions that have taken place.

```<code>pets=# SELECT * FROM adoptions;
 id | adopters | cat |  dog  |  fee  |    date
----+----------+-----+-------+-------+------------
  1 |        1 |     | 10001 | 10.50 | 2017-11-22
  2 |        2 |     | 10007 | 10.50 | 2017-11-22
  3 |        3 |   5 |       | 10.50 | 2017-11-22
  4 |        5 |   2 |       | 10.50 | 2016-11-22
(4 rows)
</code>```

I am having trouble with the concept of joining three tables and even if you don't have a direct answer to the problem I would greatly appreciate being pointed in the direction of a resource that would help.

答:
This should work:</p>

```<code>SELECT p.first_name, p.last_name
FROM adoptions a
JOIN cats c on c.id = a.cat
JOIN adopters p on p.id = a.adopters
WHERE c.name = 'seashell'
</code>```

Body:
I am trying to write an SQL query to return the name of the person who adopted the cat 'seashell'

I have a adopters table with people who will or have adopted an animal.

pets=# SELECT * FROM adopters;
 id | first_name | last_name |       address        | phone_number
----+------------+-----------+----------------------+--------------
  1 | jack       | smith     | 1 ave                | 123-123-1234
  2 | james      | dude      | 2 ave                | 221-234-4444
  3 | Forrest    | Stone     | 3 lane               | 234-667-6543
  4 | craig      | list      | 44 bulvard           | 555-444-3243
  5 | kap        | seven     | no team              | 999-000-0909
  6 | Miles      | Garrett   | First energy stadium | 123-555-2424
(6 rows)

A cats table with the cats on file

pets=# SELECT * FROM cats;
 id |   name   | gender | age |     intake_date     |    adoption_date
----+----------+--------+-----+---------------------+---------------------
  1 | Mushi    | M      |   1 | 2016-01-09 00:00:00 | 2016-03-22 00:00:00
  2 | Seashell | F      |   7 | 2016-01-09 00:00:00 |
  3 | Azul     | M      |   3 | 2016-01-11 00:00:00 | 2016-04-17 00:00:00
  4 | Victoire | M      |   7 | 2016-01-11 00:00:00 | 2016-09-01 00:00:00
  5 | Nala     | F      |   1 | 2016-01-12 00:00:00 |
(5 rows)

And an adoptions table with a record of all the adoptions that have taken place.

pets=# SELECT * FROM adoptions;
 id | adopters | cat |  dog  |  fee  |    date
----+----------+-----+-------+-------+------------
  1 |        1 |     | 10001 | 10.50 | 2017-11-22
  2 |        2 |     | 10007 | 10.50 | 2017-11-22
  3 |        3 |   5 |       | 10.50 | 2017-11-22
  4 |        5 |   2 |       | 10.50 | 2016-11-22
(4 rows)

I am having trouble with the concept of joining three tables and even if you don't have a direct answer to the problem I would greatly appreciate being pointed in the direction of a resource that would help.

Body:
This should work:

SELECT p.first_name, p.last_name
FROM adoptions a
JOIN cats c on c.id = a.cat
JOIN adopters p on p.id = a.adopters
WHERE c.name = 'seashell'


来源: stackexchange

问:
Python: converting date string to UTC
I am parsing a 3rd party website HTML with dates and times which are always in UK time format, however they don't have any timezone info in the source. Converting the string to an object is easy enough using datetime.strptime(), but how do I add timezone info?

Ultimately, I need to convert these strings to a datetime object in UTC format. The code will always run on a PC which is timezone aware, i.e. datetime.now() will return UK time.

```<code>temp = '07/12/2017 13:30'
dt = datetime.strptime(temp, '%d/%m/%Y %H:%M')
</code>```

Is there a nicer way to do this?

```<code>offset = datetime.now() - datetime.utcnow()
dt -= offset</code>```

答:
Use pytz</p>

```<code>import datetime
import pytz

temp = '07/12/2017 13:30'
dt = datetime.strptime(temp, '%d/%m/%Y %H:%M')
timezone = pytz.timezone("Etc/Greenwich")
d_aware = timezone.localize(dt)
d_aware.tzinfo
> <DstTzInfo 'Etc/Greenwich' PST-1 day, 16:00:00 STD>
d_aware
datetime.datetime(2017, 12, 7, 13, 30, tzinfo=<StaticTzInfo 'Etc/Greenwich'>)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python: converting date string to UTC

Body:
I am parsing a 3rd party website HTML with dates and times which are always in UK time format, however they don't have any timezone info in the source. Converting the string to an object is easy enough using datetime.strptime(), but how do I add timezone info?

Ultimately, I need to convert these strings to a datetime object in UTC format. The code will always run on a PC which is timezone aware, i.e. datetime.now() will return UK time.

temp = '07/12/2017 13:30'
dt = datetime.strptime(temp, '%d/%m/%Y %H:%M')

Is there a nicer way to do this?

offset = datetime.now() - datetime.utcnow()
dt -= offset

Body:
Use pytz

import datetime
import pytz

temp = '07/12/2017 13:30'
dt = datetime.strptime(temp, '%d/%m/%Y %H:%M')
timezone = pytz.timezone("Etc/Greenwich")
d_aware = timezone.localize(dt)
d_aware.tzinfo
> <DstTzInfo 'Etc/Greenwich' PST-1 day, 16:00:00 STD>
d_aware
datetime.datetime(2017, 12, 7, 13, 30, tzinfo=<StaticTzInfo 'Etc/Greenwich'>)


问:
org.hibernate.PropertyAccessException: Null value was assigned to a property of boolean type
I'm working on java web app, which uses Spring Boot, Hibernate and thymeleaf. At the moment I'm trying to implement registration process for my application and I'm stuck on a problem with my entity class.

Part of User @Entity clas

```<code>@Column(name = "aktywny")
private boolean enabled;

@Column(name = "token")
private String confirmationToken;

public boolean getEnabled() {
    return enabled;
}

public void setEnabled(boolean value) {
    this.enabled = value;
}
</code>```

Request method

```<code>@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView processRegistrationForm(Model model, ModelAndView modelAndView, @Valid User user, BindingResult bindingResult, @RequestParam Map requestParams, RedirectAttributes redir, HttpServletRequest httpServletRequest){

    //Lookup user in db by email
    User userExist = userService.findByEmail(user.getEmail());

    System.out.println(userExist);

    if( userExist != null){
        model.addAttribute("alreadyRegisteredMessage", "Użytkownik o podanym adresie e-mail już istnieje");
        bindingResult.reject("email");
    }

    if(bindingResult.hasErrors()){
        modelAndView.setViewName("home");
    }else {

        //set disabled until confirmation link clicked
        user.setEnabled(false);

        //generate string token
        user.setConfirmationToken(UUID.randomUUID().toString());

        Zxcvbn passwordCheck = new Zxcvbn();

        Strength strength = passwordCheck.measure(requestParams.get("password").toString());

        if(strength.getScore() < 3) {
            bindingResult.reject("password");

            redir.addFlashAttribute("errorMessage", "Twoje hasło jest zbyt słabe, wybierz silniejsze");

            modelAndView.setViewName("redirect: confirm?token=" + requestParams.get("token"));
            System.out.println(requestParams.get("token"));

            // Set new password
            user.setPassword(bCryptPasswordEncoder.encode(requestParams.get("password").toString()));

        }

        userService.saveUser(user);

        String appUrl = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName();

        SimpleMailMessage registrationEmail = new SimpleMailMessage();
        registrationEmail.setTo(user.getEmail());
        registrationEmail.setSubject("Potwierdzenie rejestracji");
        registrationEmail.setText("Aby dokończyć rejestrację, kliknij w poniższy link: "
                    + appUrl + "/confirm?token=" + user.getConfirmationToken());
        registrationEmail.setFrom("hotelwaltertorun@gmail.com");
        emailService.sendEmail(registrationEmail);

        if (user == null) { // No token found in DB
            modelAndView.addObject("invalidToken", "Oops!  This is an invalid confirmation link.");
        } else { // Token found
            modelAndView.addObject("confirmationToken", user.getConfirmationToken());
        }

        model.addAttribute("confirmationMessage", "E-mail potwierdzający został wysłany na adres " + user.getEmail());
        modelAndView.setViewName("home");
    }

    return modelAndView;

}
</code>```

HTML form code

```<code><form th:autocomplete="on" id="register_form" class="form-horizontal"  action="#"
                              th:action="@{/register}" th:object="${user}" method="post" role="form"
                              data-toggle="validator">
                            <input type="hidden" name="token" th:value="${confirmationToken}">

                            <div class="col-md-6 form-group">
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                                    <input type="text" th:field="*{firstname}"
                                           placeholder="Imię" class="form-control" required/>
                                </div>
                            </div>

                            <div class="col-md-6 form-group">
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                                    <input type="text" th:field="*{lastname}"
                                           placeholder="Nazwisko" class="form-control" required/>                                    </div>
                            </div>

                            <div class="col-md-6 form-group">
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                                    <input type="text" th:field="*{username}"
                                           placeholder="Login" class="form-control" required/>
                                </div>
                            </div>

                            <div class="col-md-6 form-group">
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                                    <input name="password" type="password" id="password"
                                           placeholder="Hasło" class="form-control" required />
                                </div>
                            </div>

                            <div class="col-md-6 form-group">
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                                    <input type="password" class="form-control" id="signup-password-confirm" placeholder="Potwierdź hasło" name="ConfirmPassword" data-fv-notempty="true"
                                           data-fv-notempty-message="Please confirm password"
                                           data-fv-identical="true"
                                           data-fv-identical-field="password"
                                           data-fv-identical-message="Both passwords must be identical" />
                                </div>
                            </div>

                            <div class="col-md-6 form-group">
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
                                    <input type="email" th:field="*{email}"
                                           placeholder="Adres e-mail" class="form-control"
                                           data-error="This email address is invalid" required />
                                </div>
                            </div>

                            <div class="col-md-6 form-group">
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span>
                                    <input type="tel" th:field="*{phone}"
                                           placeholder="Telefon" class="form-control"
                                           data-error="This email address is invalid" required />
                                </div>
                            </div>

                            <div class="col-md-6 form-group">
                                <button id="register" class="btn btn-success" name="register" style="width:100%;">Zarejestruj   <span class="glyphicon glyphicon-send"></span></button>
                            </div>
                        </form>
</code>```

and error description from browser

There was an unexpected error (type=Internal Server Error, status=500).
  org.hibernate.PropertyAccessException: Null value was assigned to a property [class com.kaceper.model.User.enabled] of primitive type setter of com.kaceper.model.User.enabled

Thanks for help

答:
Thymeleaf is trying to execute something like this:

```<code>user.setEnabled(null)
</code>```

Which causes a NullPointerException since enabled is a primitive type and can only be true or false.

Change the enabled field to Boolean instead of boolean and update the getter and setter accordingly.

Body:
I'm working on java web app, which uses Spring Boot, Hibernate and thymeleaf. At the moment I'm trying to implement registration process for my application and I'm stuck on a problem with my entity class.

Part of User @Entity clas

@Column(name = "aktywny")
private boolean enabled;

@Column(name = "token")
private String confirmationToken;

public boolean getEnabled() {
    return enabled;
}

public void setEnabled(boolean value) {
    this.enabled = value;
}

Request method

@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView processRegistrationForm(Model model, ModelAndView modelAndView, @Valid User user, BindingResult bindingResult, @RequestParam Map requestParams, RedirectAttributes redir, HttpServletRequest httpServletRequest){

    //Lookup user in db by email
    User userExist = userService.findByEmail(user.getEmail());

    System.out.println(userExist);

    if( userExist != null){
        model.addAttribute("alreadyRegisteredMessage", "Użytkownik o podanym adresie e-mail już istnieje");
        bindingResult.reject("email");
    }

    if(bindingResult.hasErrors()){
        modelAndView.setViewName("home");
    }else {

        //set disabled until confirmation link clicked
        user.setEnabled(false);

        //generate string token
        user.setConfirmationToken(UUID.randomUUID().toString());

        Zxcvbn passwordCheck = new Zxcvbn();

        Strength strength = passwordCheck.measure(requestParams.get("password").toString());

        if(strength.getScore() < 3) {
            bindingResult.reject("password");

            redir.addFlashAttribute("errorMessage", "Twoje hasło jest zbyt słabe, wybierz silniejsze");

            modelAndView.setViewName("redirect: confirm?token=" + requestParams.get("token"));
            System.out.println(requestParams.get("token"));

            // Set new password
            user.setPassword(bCryptPasswordEncoder.encode(requestParams.get("password").toString()));

        }

        userService.saveUser(user);

        String appUrl = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName();

        SimpleMailMessage registrationEmail = new SimpleMailMessage();
        registrationEmail.setTo(user.getEmail());
        registrationEmail.setSubject("Potwierdzenie rejestracji");
        registrationEmail.setText("Aby dokończyć rejestrację, kliknij w poniższy link: "
                    + appUrl + "/confirm?token=" + user.getConfirmationToken());
        registrationEmail.setFrom("hotelwaltertorun@gmail.com");
        emailService.sendEmail(registrationEmail);

        if (user == null) { // No token found in DB
            modelAndView.addObject("invalidToken", "Oops!  This is an invalid confirmation link.");
        } else { // Token found
            modelAndView.addObject("confirmationToken", user.getConfirmationToken());
        }

        model.addAttribute("confirmationMessage", "E-mail potwierdzający został wysłany na adres " + user.getEmail());
        modelAndView.setViewName("home");
    }

    return modelAndView;

}

HTML form code

<form th:autocomplete="on" id="register_form" class="form-horizontal"  action="#"
                              th:action="@{/register}" th:object="${user}" method="post" role="form"
                              data-toggle="validator">
                            <input type="hidden" name="token" th:value="${confirmationToken}">

                                    <input type="text" th:field="*{firstname}"
                                           placeholder="Imię" class="form-control" required/>

                                    <input type="text" th:field="*{lastname}"
                                           placeholder="Nazwisko" class="form-control" required/>

                                    <input type="text" th:field="*{username}"
                                           placeholder="Login" class="form-control" required/>

                                    <input name="password" type="password" id="password"
                                           placeholder="Hasło" class="form-control" required />

                                    <input type="password" class="form-control" id="signup-password-confirm" placeholder="Potwierdź hasło" name="ConfirmPassword" data-fv-notempty="true"
                                           data-fv-notempty-message="Please confirm password"
                                           data-fv-identical="true"
                                           data-fv-identical-field="password"
                                           data-fv-identical-message="Both passwords must be identical" />

                                    <input type="email" th:field="*{email}"
                                           placeholder="Adres e-mail" class="form-control"
                                           data-error="This email address is invalid" required />

                                    <input type="tel" th:field="*{phone}"
                                           placeholder="Telefon" class="form-control"
                                           data-error="This email address is invalid" required />

                                <button id="register" class="btn btn-success" name="register" style="width:100%;">Zarejestruj   </button>

                        </form>

and error description from browser

There was an unexpected error (type=Internal Server Error, status=500).
  org.hibernate.PropertyAccessException: Null value was assigned to a property [class com.kaceper.model.User.enabled] of primitive type setter of com.kaceper.model.User.enabled

Thanks for help

Body:
Thymeleaf is trying to execute something like this:

user.setEnabled(null)

Which causes a NullPointerException since enabled is a primitive type and can only be true or false.

Change the enabled field to Boolean instead of boolean and update the getter and setter accordingly.

ContentLicense: CC BY-SA 4.0


问:
Make first letter of a string upper case (with maximum performance)
I have a DetailsView with a TextBox
and I want the input data be saved always with the first letter in capital.

Example:

```<code>"red" --> "Red"
"red house" --> " Red house"
</code>```

How can I achieve this maximizing performance?

Note:

Based on the answers and the comments under the answers, many people think this is asking about capitalizing all words in the string. E.g. => Red House It isn't, but if that is what you seek, look for one of the answers that uses TextInfo's ToTitleCase method. (Note: Those answers are incorrect for the question actually asked.)
See TextInfo.ToTitleCase documentation for caveats (doesn't touch all-caps words - they are considered acronyms; may lowercase letters in middle of words that "shouldn't" be lowered, e.g., "McDonald" → "Mcdonald"; not guaranteed to handle all culture-specific subtleties re capitalization rules.)

Note:

The question is ambiguous as to whether letters after the first should be forced to lower case.  The accepted answer assumes that only the first letter should be altered. If you want to force all letters in the string except the first to be lower case, look for an answer containing ToLower, and not containing ToTitleCase.

答:
I wanted to provide a "maximum performance" answer.  In my mind, a "maximum performance" answer catches all scenarios and provides the answer to the question accounting for those scenarios.  So, here is my answer.  With these reasons:

IsNullOrWhiteSpace accounts for strings that are just spaces or null/empty.

.Trim() removes white space from the front and back of the string.

.First() takes the first element of an IEnumerable<TSource> (or string).

We should check to see if it is a letter that can/should be uppercase.

We then add the rest of the string, only if the length indicates we should.

By .NET best practice, we should provide a culture under System.Globalization.CultureInfo.

Providing them as optional parameters makes this method totally reusable, without having to type the chosen culture every time.

I also noticed that my and most of these answers did not maintain the whitespace at the beginning of the string. This will also show how to maintain that whitespace.

```<code>//Capitalize the first letter disregard all chars using regex.
public static string RegCapString(this string instring, string culture = "en-US", bool useSystem = false)
{
    if (string.IsNullOrWhiteSpace(instring))
    {
        return instring;
    }
    var m = Regex.Match(instring, "[A-Za-z]").Index;
    return instring.Substring(0, m) + instring[m].ToString().ToUpper(new CultureInfo(culture, useSystem)) + instring.Substring(m + 1);
}
//Capitalize first char if it is a letter disregard white space.
public static string CapString(this string instring, string culture = "en-US", bool useSystem = false)
{
    if (string.IsNullOrWhiteSpace(instring) ||
       !char.IsLetter(instring.Trim().First()))
    {
        return instring;
    }
    var whiteSpaces = instring.Length - instring.TrimStart().Length;
    return (new string(' ', whiteSpaces)) +
        instring.Trim().First().ToString().ToUpper(new CultureInfo(culture, useSystem)) +
        ((instring.TrimStart().Length > 1) ? instring.Substring(whiteSpaces + 1) : "");
}
</code>```

OwnerDisplayName: anon

Body:
I have a DetailsView with a TextBox
and I want the input data be saved always with the first letter in capital.

Example:

"red" --> "Red"
"red house" --> " Red house"

How can I achieve this maximizing performance?

Note:

Based on the answers and the comments under the answers, many people think this is asking about capitalizing all words in the string. E.g. => Red House It isn't, but if that is what you seek, look for one of the answers that uses TextInfo's ToTitleCase method. (Note: Those answers are incorrect for the question actually asked.)
See TextInfo.ToTitleCase documentation for caveats (doesn't touch all-caps words - they are considered acronyms; may lowercase letters in middle of words that "shouldn't" be lowered, e.g., "McDonald" → "Mcdonald"; not guaranteed to handle all culture-specific subtleties re capitalization rules.)

Note:

The question is ambiguous as to whether letters after the first should be forced to lower case.  The accepted answer assumes that only the first letter should be altered. If you want to force all letters in the string except the first to be lower case, look for an answer containing ToLower, and not containing ToTitleCase.

Body:
I wanted to provide a "maximum performance" answer.  In my mind, a "maximum performance" answer catches all scenarios and provides the answer to the question accounting for those scenarios.  So, here is my answer.  With these reasons:

IsNullOrWhiteSpace accounts for strings that are just spaces or null/empty.

.Trim() removes white space from the front and back of the string.

.First() takes the first element of an IEnumerable<TSource> (or string).

We should check to see if it is a letter that can/should be uppercase.

We then add the rest of the string, only if the length indicates we should.

By .NET best practice, we should provide a culture under System.Globalization.CultureInfo.

Providing them as optional parameters makes this method totally reusable, without having to type the chosen culture every time.

I also noticed that my and most of these answers did not maintain the whitespace at the beginning of the string. This will also show how to maintain that whitespace.

//Capitalize the first letter disregard all chars using regex.
public static string RegCapString(this string instring, string culture = "en-US", bool useSystem = false)
{
    if (string.IsNullOrWhiteSpace(instring))
    {
        return instring;
    }
    var m = Regex.Match(instring, "[A-Za-z]").Index;
    return instring.Substring(0, m) + instring[m].ToString().ToUpper(new CultureInfo(culture, useSystem)) + instring.Substring(m + 1);
}
//Capitalize first char if it is a letter disregard white space.
public static string CapString(this string instring, string culture = "en-US", bool useSystem = false)
{
    if (string.IsNullOrWhiteSpace(instring) ||
       !char.IsLetter(instring.Trim().First()))
    {
        return instring;
    }
    var whiteSpaces = instring.Length - instring.TrimStart().Length;
    return (new string(' ', whiteSpaces)) +
        instring.Trim().First().ToString().ToUpper(new CultureInfo(culture, useSystem)) +
        ((instring.TrimStart().Length > 1) ? instring.Substring(whiteSpaces + 1) : "");
}


问:
clickable div javascript programming
I have 5 divs and I want each of them to be clickable and change the background and content in the div "new"

  <button id="btn">Przeczytaj Artykułt</button>

⟩

⟨

```

答:
This can do it

function ChangeBackground(incomingDiv)
      {
       incomingDiv.style.background = "green";
    incomingDiv.innerHTML = "the original text wasn't good enough";
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <html lang="en">
     <head>
      <title>Document</title>
     </head>
     <body>
      <div id="div1" onclick="ChangeBackground(this);">blah blah blah</div>
      <div id="div2" onclick="ChangeBackground(this);">bleh bleh bleh</div>
      <div id="div3" onclick="ChangeBackground(this);">blue blue blue</div>
     </body>
    </html></code>```

This method works too, and it shows how to discriminate between elements

function ChangeBackground(incomingDivId) {
    var theclickeddiv = document.getElementById(incomingDivId);
    switch (incomingDivId) {
        case "div1":
            theclickeddiv.style.background = "green";
            theclickeddiv.innerHTML = "new text for div1"
            break;
        case "div2":
            theclickeddiv.style.background = "orange";
            theclickeddiv.innerHTML = "new text for div2"
            break;
        case "div3":
            theclickeddiv.style.background = "purple";
            theclickeddiv.innerHTML = "new text for div3"
            break;
        default:
            break;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="div1" onclick="ChangeBackground(this.id);">blah blah blah</div>
<div id="div2" onclick="ChangeBackground(this.id);">bleh bleh bleh</div>
<div id="div3" onclick="ChangeBackground(this.id);">blue blue blue</div></code>```

Title: clickable div javascript programming

Body:
This can do it

function ChangeBackground(incomingDiv)
      {
       incomingDiv.style.background = "green";
    incomingDiv.innerHTML = "the original text wasn't good enough";
      }

    <html lang="en">
     <head>
      <title>Document</title>
     </head>
     <body>
      <div id="div1" onclick="ChangeBackground(this);">blah blah blah</div>
      <div id="div2" onclick="ChangeBackground(this);">bleh bleh bleh</div>
      <div id="div3" onclick="ChangeBackground(this);">blue blue blue</div>
     </body>
    </html>

This method works too, and it shows how to discriminate between elements

function ChangeBackground(incomingDivId) {
    var theclickeddiv = document.getElementById(incomingDivId);
    switch (incomingDivId) {
        case "div1":
            theclickeddiv.style.background = "green";
            theclickeddiv.innerHTML = "new text for div1"
            break;
        case "div2":
            theclickeddiv.style.background = "orange";
            theclickeddiv.innerHTML = "new text for div2"
            break;
        case "div3":
            theclickeddiv.style.background = "purple";
            theclickeddiv.innerHTML = "new text for div3"
            break;
        default:
            break;
    }
}

<div id="div1" onclick="ChangeBackground(this.id);">blah blah blah</div>
<div id="div2" onclick="ChangeBackground(this.id);">bleh bleh bleh</div>
<div id="div3" onclick="ChangeBackground(this.id);">blue blue blue</div>


问:
C# - Declaration of class variables
How can I create a new instance of Boeing737 and use it later in the program. For example I want to be able to create 5 Boeings, do I have to define them like

```<code>Boeing737 boeing1 =  new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);

Boeing737 boeing2 =  new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);
</code>```

and so on...
Or is there easier way?
Other question, to WHAT can I assign all the properties of boeing1 for example?

Here is my current code:

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Insert the type of boeing that u are using");
        Boeing737 boeing = new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);
        Console.WriteLine("{0} has {1} tons of fuel and weights {2}", boeing.Name, boeing.Fuel, boeing.Tons);
        Console.ReadKey();

    }
}

public class Planes
{
    public Planes(string name, int fuel, int tons)
    {
        Name = name;
        Fuel = fuel;
        Tons = tons;
    }
    public int Tons;
    public int Fuel;
    public string Name { private set; get; }
}
class Boeing737 : Planes
{
    public Boeing737(string name, int fuel, int tons) : base(name, fuel, tons)
    {
        Tons = 700;
    }
}
</code>```

}

答:
Well, let's start by improving your code a little bit:

```<code>// the class represents a single object, give it a
// singular name
public class Plane
{
    // get before set, it's not mandatory but give yourself
    // some basic coding rules to improve code maintainability
    // and readability
    // avoid public members, implementing properties is always
    // a good choice for future extensions and manipulations
    public int Fuel { get; private set; }
    public int Tons { get; private set; }
    public string Name { get; private set; }

    public Plane(string name, int fuel, int tons)
    {
        Name = name;
        Fuel = fuel;
        Tons = tons;
    }
}

// if your inheritance stops here, you could set a
// sealed attribute
public sealed class Boeing737 : Plane
{
    // no need to set the property twice, you are already
    // calling the base constructor, pass him the fixed
    // tons value of 700...
    public Boeing737(string name, int fuel) : base(name, fuel, 700)
    {
    }
}
</code>```

Now, concerning instantiation, go for a the generic List<T> type, which is very easy to manage and will expand itself when you add more objects:

```<code>List<Boeing737> boeings = new List<Boeing737>
{
    new Boeing737("A", 5),
    new Boeing737("B", 5),
    new Boeing737("C", 5),
    new Boeing737("D", 5)
};
</code>```

If you want to create a List that can contain different type of planes, stick to the upper level type:

```<code>List<Plane> planes = new List<Plane>
{
    new Boeing737("A", 5),
    new Boeing737("B", 5),
    new Boeing737("C", 5),
    new Boeing737("D", 5),
    new AirplaneX("D", 10, 350)
};
</code>```

List can also be used together with LINQ to facilitate its manipulation and filtering (more info here). For example, sort by weight:

```<code>var planesSortedTons = planes.OrderBy(x => x.Tons).ToList();
</code>```

Select only the planes with Fuel > 10:

```<code>var planesFuel10 = planes.Where(x => x.Fuel > 10).ToList();
</code>```

On a side note, if you want to fill a huge list of data through console input, you need to build an infinite loop (for example a while (true)) and populate list by addition:

```<code>static void Main(string[] args)
{
    List<Boeing737> boeings = new List<Boeing737>();

    String input;

    while (true)
    {
        Consol.WriteLine("Enter name:");
        input = Console.ReadLine();

        if (input.ToLowerInvariant() == "stop")
            break;

        String name = input.Trim();

        Consol.WriteLine("Enter fuel:");
        input = Console.ReadLine();

        if (input.ToLowerInvariant() == "stop")
            break;

        Int32 fuel;

        try
        {
            fuel = Int32.Parse(input.Trim());
        }
        catch
        {
            Console.WriteLine("Wrong input, stopping!");
            break;
        }

        boeings.Add(new Boeing737(name, fuel));
    }
}
</code>```

Title: C# - Declaration of class variables

Body:
How can I create a new instance of Boeing737 and use it later in the program. For example I want to be able to create 5 Boeings, do I have to define them like

Boeing737 boeing1 =  new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);

Boeing737 boeing2 =  new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);

and so on...
Or is there easier way?
Other question, to WHAT can I assign all the properties of boeing1 for example?

Here is my current code:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Insert the type of boeing that u are using");
        Boeing737 boeing = new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);
        Console.WriteLine("{0} has {1} tons of fuel and weights {2}", boeing.Name, boeing.Fuel, boeing.Tons);
        Console.ReadKey();

    }
}

public class Planes
{
    public Planes(string name, int fuel, int tons)
    {
        Name = name;
        Fuel = fuel;
        Tons = tons;
    }
    public int Tons;
    public int Fuel;
    public string Name { private set; get; }
}
class Boeing737 : Planes
{
    public Boeing737(string name, int fuel, int tons) : base(name, fuel, tons)
    {
        Tons = 700;
    }
}

}

Body:
Well, let's start by improving your code a little bit:

// the class represents a single object, give it a
// singular name
public class Plane
{
    // get before set, it's not mandatory but give yourself
    // some basic coding rules to improve code maintainability
    // and readability
    // avoid public members, implementing properties is always
    // a good choice for future extensions and manipulations
    public int Fuel { get; private set; }
    public int Tons { get; private set; }
    public string Name { get; private set; }

    public Plane(string name, int fuel, int tons)
    {
        Name = name;
        Fuel = fuel;
        Tons = tons;
    }
}

// if your inheritance stops here, you could set a
// sealed attribute
public sealed class Boeing737 : Plane
{
    // no need to set the property twice, you are already
    // calling the base constructor, pass him the fixed
    // tons value of 700...
    public Boeing737(string name, int fuel) : base(name, fuel, 700)
    {
    }
}

Now, concerning instantiation, go for a the generic List<T> type, which is very easy to manage and will expand itself when you add more objects:

List<Boeing737> boeings = new List<Boeing737>
{
    new Boeing737("A", 5),
    new Boeing737("B", 5),
    new Boeing737("C", 5),
    new Boeing737("D", 5)
};

If you want to create a List that can contain different type of planes, stick to the upper level type:

List<Plane> planes = new List<Plane>
{
    new Boeing737("A", 5),
    new Boeing737("B", 5),
    new Boeing737("C", 5),
    new Boeing737("D", 5),
    new AirplaneX("D", 10, 350)
};

List can also be used together with LINQ to facilitate its manipulation and filtering (more info here). For example, sort by weight:

var planesSortedTons = planes.OrderBy(x => x.Tons).ToList();

Select only the planes with Fuel > 10:

var planesFuel10 = planes.Where(x => x.Fuel > 10).ToList();

On a side note, if you want to fill a huge list of data through console input, you need to build an infinite loop (for example a while (true)) and populate list by addition:

static void Main(string[] args)
{
    List<Boeing737> boeings = new List<Boeing737>();

    String input;

    while (true)
    {
        Consol.WriteLine("Enter name:");
        input = Console.ReadLine();

        if (input.ToLowerInvariant() == "stop")
            break;

        String name = input.Trim();

        Consol.WriteLine("Enter fuel:");
        input = Console.ReadLine();

        if (input.ToLowerInvariant() == "stop")
            break;

        Int32 fuel;

        try
        {
            fuel = Int32.Parse(input.Trim());
        }
        catch
        {
            Console.WriteLine("Wrong input, stopping!");
            break;
        }

        boeings.Add(new Boeing737(name, fuel));
    }
}


问:
React JS : Warning: Each child in an array or iterator should have a unique "key" prop
I'm having some trouble while learning ReactJs. I keep having this warning :

Warning: Each child in an array or iterator should have a unique "key" prop.

What loses me is that I did gave a unique key to each of my elements, in that piece of code :

```<code>let tab = props.todos.map((t) => {return <TodoListItem key={t.id} todo={t} onRemove={props.onRemove} /> })
</code>```

My TodoListItems are
 elements, I also tried to give them a key then I tested the existence and the value of {t.id} before giving it as a key and it's ok. I also cleared the cache before every execution.

I'm out of solutions, that's why I'm asking for your help.

Thank you in advance.

答:
The Safest way to enforce a unique key is to use the index parameter of your map function.

```<code>let tab = props.todos.map((t, index) => {return <TodoListItem key={index} todo={t} onRemove={props.onRemove} /> })
</code>```

If you truly want to use your t.id as the key, I would suggest temporarily changing your code to use the index (per above snippet), but dumping out your t.id in your rendered markup to validate that your id's are, in fact, unique.

Body:
I'm having some trouble while learning ReactJs. I keep having this warning :

Warning: Each child in an array or iterator should have a unique "key" prop.

What loses me is that I did gave a unique key to each of my elements, in that piece of code :

let tab = props.todos.map((t) => {return <TodoListItem key={t.id} todo={t} onRemove={props.onRemove} /> })

My TodoListItems are
 elements, I also tried to give them a key then I tested the existence and the value of {t.id} before giving it as a key and it's ok. I also cleared the cache before every execution.

I'm out of solutions, that's why I'm asking for your help.

Thank you in advance.

Body:
The Safest way to enforce a unique key is to use the index parameter of your map function.

let tab = props.todos.map((t, index) => {return <TodoListItem key={index} todo={t} onRemove={props.onRemove} /> })

If you truly want to use your t.id as the key, I would suggest temporarily changing your code to use the index (per above snippet), but dumping out your t.id in your rendered markup to validate that your id's are, in fact, unique.


问:
How to effectively check if a string contains one of a few sub strings?
How can I effectively check if a string contains one of a few sub strings?
Suppose I have a string:

```<code>`Hi there, <B>my</B> name is Joe <DIV>.</DIV> Hello world.  `
</code>```

How can I check if the string contains either  OR
 OR  ?

I could do a simple:

```<code>Result := (Pos('<B>', S) > 0) or
          (Pos('<DIV>', S) > 0) or
          (Pos(' ', S) > 0);
</code>```

But this seems to be very inefficient since it make N (at worst) passes and my strings are considerably large.

答:
Here is my solution, thanks to David Heffernan comment:

```<code>function StringContainsAny(const S: string; const AnyOf: array of string): Boolean;
var
  CurrChr, C: PChar;
  I, L, H: Integer;
begin
  Result := False;
  CurrChr := PChar(S);
  while CurrChr^ <> #0 do
  begin
    H := High(AnyOf);
    for I := 0 to H do
    begin
      L := 0;
      C := PChar(AnyOf[I]);
      while C^ <> #0 do
      begin
        if C^ = CurrChr^ then
          Inc(L)
        else
          Break;
        Inc(C);
        Inc(CurrChr);
        if CurrChr^ = #0 then // end of S string
        begin
          Result := (C^ = #0);
          if Result or (not Result and (I = H)) then // match or last AnyOf
            Exit;
        end;
      end;
      if C^ = #0 then // match
      begin
        Result := True;
        Exit;
      end
      else
        Dec(CurrChr, L);
    end;
    Inc(CurrChr);
  end;
end;
</code>```

I'm not sure it is perfect.

EDIT:
What can I say? You know what they say about assumptions...

after actually testing, it seems like  using Pos():

```<code>function StringContainsAny(const S: string; const AnyOf: array of string): Boolean;
var
  I: Integer;
begin
  for I := 0 to High(AnyOf) do
  begin
    if Pos(AnyOf[I], S) <> 0 then
    begin
      Result := True;
      Exit;
    end;
  end;
  Result := False;
end;
</code>```

Is faster than my solution and @Green_Wizard solution! they did a good job with the Pos function!

Body:
How can I effectively check if a string contains one of a few sub strings?
Suppose I have a string:

`Hi there, <B>my</B> name is Joe <DIV>.</DIV> Hello world.  `

How can I check if the string contains either  OR
 OR  ?

I could do a simple:

Result := (Pos('', S) > 0) or
          (Pos('
', S) > 0) or
          (Pos(' ', S) > 0);

But this seems to be very inefficient since it make N (at worst) passes and my strings are considerably large.

Body:
Here is my solution, thanks to David Heffernan comment:

function StringContainsAny(const S: string; const AnyOf: array of string): Boolean;
var
  CurrChr, C: PChar;
  I, L, H: Integer;
begin
  Result := False;
  CurrChr := PChar(S);
  while CurrChr^ <> #0 do
  begin
    H := High(AnyOf);
    for I := 0 to H do
    begin
      L := 0;
      C := PChar(AnyOf[I]);
      while C^ <> #0 do
      begin
        if C^ = CurrChr^ then
          Inc(L)
        else
          Break;
        Inc(C);
        Inc(CurrChr);
        if CurrChr^ = #0 then // end of S string
        begin
          Result := (C^ = #0);
          if Result or (not Result and (I = H)) then // match or last AnyOf
            Exit;
        end;
      end;
      if C^ = #0 then // match
      begin
        Result := True;
        Exit;
      end
      else
        Dec(CurrChr, L);
    end;
    Inc(CurrChr);
  end;
end;

I'm not sure it is perfect.

EDIT:
What can I say? You know what they say about assumptions...

after actually testing, it seems like  using Pos():

function StringContainsAny(const S: string; const AnyOf: array of string): Boolean;
var
  I: Integer;
begin
  for I := 0 to High(AnyOf) do
  begin
    if Pos(AnyOf[I], S) <> 0 then
    begin
      Result := True;
      Exit;
    end;
  end;
  Result := False;
end;

Is faster than my solution and @Green_Wizard solution! they did a good job with the Pos function!


问:
Does lazy loading require an almost empty component containing router outlet?
I am looking to implement lazy loading, but the user component currently contains a grid displaying all users, and no < router-outlet > .

Consider an app folder such as this:

```<code>src
-- app
----user
------user.component.html
------user.component.ts
------userdetail
--------userdetail.component.html
--------userdetail.component.ts
</code>```

and here are the routes:

```<code>{ path: 'user', component: UserComponent },
{ path: 'user/:id', component: UserDetailComponent },
</code>```

When I switch the structure to the following:

```<code>src
-- app
----user
------user-routing.module.ts (new)
------user.component.html
------user.component.ts
------user.module.ts (new)
------userdetail
--------userdetail.component.html
--------userdetail.component.ts
</code>```

new route:

```<code>{ path: 'user', loadChildren: 'app/user/user.module#UserModule'},
</code>```

the user component lazy loads, but I can't navigate to userdetail, so I plan to move my user grid into a new component 'userlist' and have only < router-outlet >  in the 'user' component.

Is it really necessary to have an almost empty component 'user' just for this router outlet? My goal is to lazy load not only the user grid component but user detail component as well.

Here is a plunk I began, but haven't finished yet - https://plnkr.co/edit/m5gYG40wySngiiNpIY7W?p=preview

答:
I believe it is about the route you defined. You can define your UserDetailComponent as one of children like:

```<code>export const ROUTES: Routes = [
  {
    path: '',
    component: UserComponent,
    children: [
      {
        path: ':id',
        component: UserDetailComponent,
      }
    ]
  }
];
</code>```

As you defined { path: 'user', loadChildren: 'app/user/user.module#UserModule'},
, therefore you can use '' for your UserComponent

Body:
I am looking to implement lazy loading, but the user component currently contains a grid displaying all users, and no < router-outlet > .

Consider an app folder such as this:

src
-- app
----user
------user.component.html
------user.component.ts
------userdetail
--------userdetail.component.html
--------userdetail.component.ts

and here are the routes:

{ path: 'user', component: UserComponent },
{ path: 'user/:id', component: UserDetailComponent },

When I switch the structure to the following:

src
-- app
----user
------user-routing.module.ts (new)
------user.component.html
------user.component.ts
------user.module.ts (new)
------userdetail
--------userdetail.component.html
--------userdetail.component.ts

new route:

{ path: 'user', loadChildren: 'app/user/user.module#UserModule'},

the user component lazy loads, but I can't navigate to userdetail, so I plan to move my user grid into a new component 'userlist' and have only < router-outlet >  in the 'user' component.

Is it really necessary to have an almost empty component 'user' just for this router outlet? My goal is to lazy load not only the user grid component but user detail component as well.

Here is a plunk I began, but haven't finished yet - https://plnkr.co/edit/m5gYG40wySngiiNpIY7W?p=preview

Body:
I believe it is about the route you defined. You can define your UserDetailComponent as one of children like:

export const ROUTES: Routes = [
  {
    path: '',
    component: UserComponent,
    children: [
      {
        path: ':id',
        component: UserDetailComponent,
      }
    ]
  }
];

As you defined { path: 'user', loadChildren: 'app/user/user.module#UserModule'},
, therefore you can use '' for your UserComponent


问:
which IVR framework is suitable in UAE region?
We want to build IVR based application for a client in UAE.

The user can ask a query and a voice enabled bot can resolve the query on the other end.

If anyone knows suitable framework for this could be a big help.

Thank you

答: If you want to build an IVR you can use any SIP framework with media capabilities. You can check Adhearsion framework for reference.</p>


问:
Scheduling Logic App to run Quarterly
I want to schedule a logic app to run on 10th day following the end of each quarter(10th January, 10th April, 10th July and 10th October).

I thought the configuring for recurrence trigger should be with following settings:

Interval: 4

Frequency: Month

Time zone: Easter Time

Start time: 2018-01-10T10:00:00Z

I tried with start time close to the current local time for testing but its not getting triggered. Need help.

答:
Notice that you are specifying start time in UTC (the 'Z' format identifier); you want to specify it in local time instead.

```<code>{
   "startTime": "2018-01-10T10:00:00",
   "timeZone": "Eastern Standard Time"
}
</code>```

Full documentation for complex schedules is available here:
https://learn.microsoft.com/en-us/azure/connectors/connectors-native-recurrence

Here is the documentation for complex schedules: learn.microsoft.com/en-us/azure/connectors/…

Title: Scheduling Logic App to run Quarterly

Body:
Notice that you are specifying start time in UTC (the 'Z' format identifier); you want to specify it in local time instead.

{
   "startTime": "2018-01-10T10:00:00",
   "timeZone": "Eastern Standard Time"
}

Full documentation for complex schedules is available here:
https://learn.microsoft.com/en-us/azure/connectors/connectors-native-recurrence

Here is the documentation for complex schedules: learn.microsoft.com/en-us/azure/connectors/…


问:
java.lang.NullPointerException + reading from file and write to structure
the old problem searched many times but i still do not understand what i am doing wrong xD, this is my code:
`

```<code>package dev.codenmore.tilegame.worlds;

import dev.codenmore.tilegame.Utils;
import dev.codenmore.tilegame.objects.Objects;

import java.awt.*;

public class World {

public class Object {

    private int id = 0,
                x = 0,
                y = 0;
    public Object(){

    }

    public void setId(int id) {
        this.id = id;
    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }
}

private int width, height;
private int spawnX, spawnY;
private int x, y, id, nr = 0;
private Object[] objects;

public World(String path){
    loadWorld(path);
}

public void tick(){

}

public void render(Graphics g){
    int i = 0;
    for(; i <(width*height)/3; i++){
        getObject(i).render(g, objects[i].x, objects[i].y);

    }
}

public Objects getObject(int i){
    Objects o = Objects.objects[objects[i].id];
    if(o == null)
        return Objects.alpha;
    return o;
}

private void loadWorld(String path){
    String file = Utils.loadFileAsString(path);
    String[] tokens = file.split("\\s+");
    width = Utils.parseInt(tokens[0]);
    height = Utils.parseInt(tokens[1]);
    spawnX = Utils.parseInt(tokens[2]);
    spawnY = Utils.parseInt(tokens[3]);
    objects = new Object[width*height/3];

    for(int i = 4; i < width*height+3; i += 3){
        id = Utils.parseInt(tokens[i]);
        x = Utils.parseInt(tokens[i+1]);
        y = Utils.parseInt(tokens[i+2]);

        objects[nr].setId(id);
        objects[nr].setX(x);
        objects[nr].setY(y);
        nr++;
    }

}

}
</code>```

`
the error occurs on line 64 when im trying to write data to my structure, which is telling me that am trying to write to empty memory but i dont know how to handle this on my own. Additional to that i have second question, is this the best way to do this ? i mean reading file and writing data to structure here is my file:

```<code>6 3
960 540
0 0 0 255 0 0
2 0 500 2 1620 500
1 0 790 255 0 0
</code>```

答:
well, isn't it because id, x, y in Object are private, and you do not have setters in this class? therefore you don't have access to those fields.
I'd try to add setters in Object class and then instead of objects[nr].id = id; use objects[nr].setId(id);

Body:
the old problem searched many times but i still do not understand what i am doing wrong xD, this is my code:
`

package dev.codenmore.tilegame.worlds;

import dev.codenmore.tilegame.Utils;
import dev.codenmore.tilegame.objects.Objects;

import java.awt.*;

public class World {

public class Object {

    private int id = 0,
                x = 0,
                y = 0;
    public Object(){

    }

    public void setId(int id) {
        this.id = id;
    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }
}

private int width, height;
private int spawnX, spawnY;
private int x, y, id, nr = 0;
private Object[] objects;

public World(String path){
    loadWorld(path);
}

public void tick(){

}

public void render(Graphics g){
    int i = 0;
    for(; i <(width*height)/3; i++){
        getObject(i).render(g, objects[i].x, objects[i].y);

    }
}

public Objects getObject(int i){
    Objects o = Objects.objects[objects[i].id];
    if(o == null)
        return Objects.alpha;
    return o;
}

private void loadWorld(String path){
    String file = Utils.loadFileAsString(path);
    String[] tokens = file.split("\\s+");
    width = Utils.parseInt(tokens[0]);
    height = Utils.parseInt(tokens[1]);
    spawnX = Utils.parseInt(tokens[2]);
    spawnY = Utils.parseInt(tokens[3]);
    objects = new Object[width*height/3];

    for(int i = 4; i < width*height+3; i += 3){
        id = Utils.parseInt(tokens[i]);
        x = Utils.parseInt(tokens[i+1]);
        y = Utils.parseInt(tokens[i+2]);

        objects[nr].setId(id);
        objects[nr].setX(x);
        objects[nr].setY(y);
        nr++;
    }

}

}

`
the error occurs on line 64 when im trying to write data to my structure, which is telling me that am trying to write to empty memory but i dont know how to handle this on my own. Additional to that i have second question, is this the best way to do this ? i mean reading file and writing data to structure here is my file:

6 3
960 540
0 0 0 255 0 0
2 0 500 2 1620 500
1 0 790 255 0 0


问:
ajax post data is not read yii2
I'm trying to read $_POST array posted through AJAX in a controller action using Yii::$app->request->post(), but something strange happens.

jQuery:
`

```<code>    function renderGridView() {
    var formId = $('#input-field :input[value!=""]');
    // extract values. Make sure to send _csrf token

   $.ajax({
       url: "?r=value-search%2Fsearch", //this one works
       method: 'POST',
       data: {
           searchData: formId.serializeArray(),
       },
       success: function(response) { //JSON array is returned.
           /*$('#resultGrid').DataTable( {
               data: [
                   response['provider']
                ],
               columns: [
                   response['columns']
                ]
           }); */
           console.log(response);

       }

   })

}
</code>```

`

PHP Controller action:

```<code>public function actionSearch() {
       $data = \Yii::$app->request->post('searchData');
       $tt; $svalue;
       if(count($data) === 0) {throw new UserException('data is emptry');}

       echo var_dump($data);
    }
</code>```

And here's the issue, the code above works just fine. But when I'm trying to echo $data my custom UserException 'data is empty' is thrown, instead of PHP's 'trying to pass array as a string', which I'd normally expect. What is causing this? Why does post() behave like this? Is there a technical reason to it?

答:
just change

```<code> data: {
           searchData: formId.serializeArray(),
       },
</code>```

to

```<code> data:formId.serialize(),
</code>```

you should use ActiveForm to create your form using your model and the names will be automatically assigned to inputs which include the convention ModelName[field_name] apart from this you haven't shown your form but in your action you are getting the searchData in the post() array so I assume you have the data being posted as

```<code>[
  searchData=>[
    field_1=>value,
    field_1=>value,
    field_1=>value,
    field_1=>value,
  ]
]
</code>```

Title: ajax post data is not read yii2

Body:
I'm trying to read $_POST array posted through AJAX in a controller action using Yii::$app->request->post(), but something strange happens.

jQuery:
`

    function renderGridView() {
    var formId = $('#input-field :input[value!=""]');
    // extract values. Make sure to send _csrf token

   $.ajax({
       url: "?r=value-search%2Fsearch", //this one works
       method: 'POST',
       data: {
           searchData: formId.serializeArray(),
       },
       success: function(response) { //JSON array is returned.
           /*$('#resultGrid').DataTable( {
               data: [
                   response['provider']
                ],
               columns: [
                   response['columns']
                ]
           }); */
           console.log(response);

       }

   })

}

`

PHP Controller action:

public function actionSearch() {
       $data = \Yii::$app->request->post('searchData');
       $tt; $svalue;
       if(count($data) === 0) {throw new UserException('data is emptry');}

       echo var_dump($data);
    }

And here's the issue, the code above works just fine. But when I'm trying to echo $data my custom UserException 'data is empty' is thrown, instead of PHP's 'trying to pass array as a string', which I'd normally expect. What is causing this? Why does post() behave like this? Is there a technical reason to it?

Body:
just change

 data: {
           searchData: formId.serializeArray(),
       },

to

 data:formId.serialize(),

you should use ActiveForm to create your form using your model and the names will be automatically assigned to inputs which include the convention ModelName[field_name] apart from this you haven't shown your form but in your action you are getting the searchData in the post() array so I assume you have the data being posted as

[
  searchData=>[
    field_1=>value,
    field_1=>value,
    field_1=>value,
    field_1=>value,
  ]
]


问:
Looking for an in-memory database with same SQL syntax as Oracle
I'm looking for a in-memory database that can be used for automatic testing of legacy ADO.NET code against Oracle. So the in-memory database should have the same SQL syntax as Oracle.

Any suggestions?

答: try Oracle TimesTen  I haven't played with it myself but believe it has the same syntax as Oracle RDBMS.</p>

ContentLicense: CC BY-SA 2.5


问:
Is it OK to use a function declaration for Javascript namespacing?
Every time I see JS namespacing referenced it is implemented with an object expression. If I want to be sure that my namespace exists before it is assigned any properties, can I instantiate it by way of function declaration?

e.g.;

```<code>function namespace() {}
</code>```

vs

```<code>let namespace = {};
</code>```

The former being hoisted, and guaranteeing that properties I append to my namespace won't encounter an "undefined" error.

I know it works at least for my basic tests, but are there pros/cons to this?

Edit: Another example: https://jsbin.com/nuquxuxinu/edit?js,console

Edit: Bergi provided some good clarification, but I still need to be convinced as to why using a function as a namespace is a bad idea.

ANSWER: Since my question was marked as "opinion based" I can only deduce that there is no technical reason why you shouldn't use a function for a namespace.

答:
No, you should not make your namespace object a function object unless you need it to be callable. If the function does nothing (like in your example), don't use a function.

Hoisting does not have any benefits for you. The variable declaration let namespace is hoisted just as well. What is actually important is that the members of your namespace are created before you use them, and they are created by assignment. Just put them in the right order in your file - first the namespace object instantiation, then the properties of that object (if they were not already created as part of it in an object literal), last the code that uses the namespace.

Body:
Every time I see JS namespacing referenced it is implemented with an object expression. If I want to be sure that my namespace exists before it is assigned any properties, can I instantiate it by way of function declaration?

e.g.;

function namespace() {}

vs

let namespace = {};

The former being hoisted, and guaranteeing that properties I append to my namespace won't encounter an "undefined" error.

I know it works at least for my basic tests, but are there pros/cons to this?

Edit: Another example: https://jsbin.com/nuquxuxinu/edit?js,console

Edit: Bergi provided some good clarification, but I still need to be convinced as to why using a function as a namespace is a bad idea.

ANSWER: Since my question was marked as "opinion based" I can only deduce that there is no technical reason why you shouldn't use a function for a namespace.


问:
Share button on twitter not working properly
I want to add twitter button on my website.
The code I am using is:

```<code>echo"<iframe src='https://www.facebook.com/plugins/share_button.php?href=http%3A%2F%2Fconnecting-youth.org%2Fsingle_news.php%3Fsubmit%3D".$lastnum."&layout=button_count&size=small&mobile_iframe=true&width=69&height=20&appId' width='69' height='20' style='border:none;overflow:hidden' scrolling='no' frameborder='0' allowTransparency='true'></iframe>
    <a style='margin-left:10px;' class='twitter-share-button'  href='https://twitter.com/share?url=http%3A%2F%2Fconnecting-youth.org%2Fsingle_news.php%3Fsubmit%3D".$lastnum."'  data-size='large'>Tweet</a>
    ";
</code>```

The problem is that on twitter it appears as text not as a post.
For example

The way I want it to appear is:

It works fine when I add another URL.

答: Try shortening it useing for example https://bitly.com</p>

Body:
I want to add twitter button on my website.
The code I am using is:

echo"
    Tweet
    ";

The problem is that on twitter it appears as text not as a post.
For example

The way I want it to appear is:

It works fine when I add another URL.


问:
Find Stored Procedure that Inserts Into a Specific Table teradata
How do I find out the stored procedures(using SQl query) that is used to load a specific table in teradata?</p>

答:
This is not going to yield exact results, but it may help point you in the right direction. You could query dbc.dbqlogtbl for INSERT's into the table, grab the sessionid and look for dbc.dbqlogtbl entry's for CALL statementTypes.

Again... grain of salt here, but it might yield something of interest:

```<code>SELECT *
FROM dbc.dbqlogtbl
WHERE sessionid IN (
        SELECT sessionId
        FROM dbc.dbqlogtbl
        WHERE statementtype = 'INSERT'
            AND username = '<usrname>' /*username that executes the procedure if available*/
            AND querytext LIKE '%yourdatabase.yourtable%'
        )
    AND statementtype = 'Call'
</code>```

Alternatively you could just dump all of the SPL's for your procs and Ctrl+F until you get a hit.

Body:
This is not going to yield exact results, but it may help point you in the right direction. You could query dbc.dbqlogtbl for INSERT's into the table, grab the sessionid and look for dbc.dbqlogtbl entry's for CALL statementTypes.

Again... grain of salt here, but it might yield something of interest:

SELECT *
FROM dbc.dbqlogtbl
WHERE sessionid IN (
        SELECT sessionId
        FROM dbc.dbqlogtbl
        WHERE statementtype = 'INSERT'
            AND username = '<usrname>' /*username that executes the procedure if available*/
            AND querytext LIKE '%yourdatabase.yourtable%'
        )
    AND statementtype = 'Call'

Alternatively you could just dump all of the SPL's for your procs and Ctrl+F until you get a hit.


问:
No Application Permissions for Intune on Microsoft Graph?
As per (&today) https://developer.microsoft.com/en-us/graph/docs/concepts/permissions_reference#intune-device-management-permissions it says "Applications Permissions - None".

Is this going to remain that way or is it planned that at some point we will be able to access Intune as an application (running without a signed-in user present)?

答:
We are considering adding this functionality, yes.  However, we don't have a committed timeline as of now.  But, we understand the customer and partner interest here, and thanks for helping keep this top of mind for us.</p>

<p>-Dave [MSFT] </p>

Body:
We are considering adding this functionality, yes.  However, we don't have a committed timeline as of now.  But, we understand the customer and partner interest here, and thanks for helping keep this top of mind for us.

-Dave [MSFT]


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答:
You can in fact write provably correct programs. Microsoft, for example, has created an extension of the C# language called Spec# which includes an automated theorem prover. For java, there is ESC/java. I'm sure there are many more examples out there.

(edit: apparently spec# is no longer being developed, but the contract tools will become part of .NET 4.0)

I see some posters hand-waving about the halting problem or incompleteness theorems which supposedly prevent the automatic verification of programs. This is of course not true; these issues merely tell us that it is possible to write programs which cannot be proven to be correct or incorrect. That does not prevent us from constructing  programs which are provably correct.

Title: Why can't programs be proven?

OwnerDisplayName: wcoenen

LastEditorDisplayName: wcoenen


问:
How (and where) to register a custom query method in Laravel
In my application I needed to retrieve the users who were registered in last 7 days. Later I realized I also need to check for 30 days and 365 days and so on. So I wrote a query scope in my User.php:

```<code>public function scopeCreatedWithinDays($query,$day){
    $str = $day.' days ago';
    $carbon = new Carbon($str);
    $query->where('created_at', '>=', $carbon);
}
</code>```

And I suddenly realized that this method is a good candidate for repeated use across all models. So I need to define this method in a common place so that I can easily get the rows created within last x days by simply calling $anyModel->createdWithinDays(30). But I don't know where to put it and how...

答:
For reusable code you have 2 options:

create base model and make all other models extend from this base model (this model should extend from Eloquent model)

create trait and use this trait in all models that really need it.

There is no big difference, but it's better to create multiple traits with similar set of functionalities instead of creating one big class having multiple reusable methods.

Of course you can also mix this, so you can put the method in trait and use this trait in base model and make all models extend from this base model

Body:
In my application I needed to retrieve the users who were registered in last 7 days. Later I realized I also need to check for 30 days and 365 days and so on. So I wrote a query scope in my User.php:

public function scopeCreatedWithinDays($query,$day){
    $str = $day.' days ago';
    $carbon = new Carbon($str);
    $query->where('created_at', '>=', $carbon);
}

And I suddenly realized that this method is a good candidate for repeated use across all models. So I need to define this method in a common place so that I can easily get the rows created within last x days by simply calling $anyModel->createdWithinDays(30). But I don't know where to put it and how...


问:
Smarty 3.1.30, php 7.0.26 Compatibility issues?
I have used smarty with php5.x for years. I recently upgraded my dev box to php7.2 and smarty to php 3.1.30. Works great.

Our production server was just upgraded to php 7.0.26. My code on my local machine and the production server is nearly identical (config file differences, for example.) Unfortunately, on that server $smarty->fetch(<filename>); returns an empty string.

Does anyone know if there is compatibility issues between smarty 3.1.30 and php 7.0.26? Have you ever encountered fetch() returning an empty string?

答: The issue was that the server did not allocate enough memory to PHP processes. Not sure why, but it would die silently during Smarty fetch processing and return an empty string - no errors in log files, etc. Once I increased allowable memory allocation it was fine. Wanted to post an answer to how I fixed in case anyone out there is looking.</p>


问:
Formatting the output from a text file - Java
How can I change the code so that it prints out like the way I want it to be printed out? I want the userNameGenerator to be printed out first, with an arrow (->) in front of it, and the personName to be displayed with open and close square brackets ([]) beside it. I also want to remove the commas at the end. I've done a bit of it already as you can see below:

Code that needs changing:

```<code>Set<String> newStrSet = new HashSet<>();
for(int i = 0; i < personFile.size(); i++) {
    String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
    for(int j = 0; j < regionSplit.length; j++) {
    newStrSet.add(regionSplit[j]);
    }
}

for (String p: newStrSet) {
    System.out.printf("%s -> [", p);
    for (Codes2 s: personFile) {
        if (s.getUserNameGenerator().contains(p)) {
            System.out.printf("%s, ", s.getPersonName());
        }
    }
    System.out.println("]");
}
</code>```

Full code:

```<code>import java.util.*;
import java.io.*;

public class Codes {
    public static void main(String[] args) {
        List<Codes2> personFile = new ArrayList<>();

        try {
            BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
            String fileRead = br.readLine();
            while (fileRead != null) {
                String[] personData = fileRead.split(":");
                String personName = personData[0];
                String userNameGenerator = personData[1];
                Codes2 personObj = new Codes2(personName, userNameGenerator);
                personFile.add(personObj);
                fileRead = br.readLine();
            }
            br.close();
        }

        catch (FileNotFoundException ex) {
            System.out.println("File not found!");
        }

        Set<String> newStrSet = new HashSet<>();
        for(int i = 0; i < personFile.size(); i++) {
            String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
            for(int j = 0; j < regionSplit.length; j++) {
                newStrSet.add(regionSplit[j]);
            }
        }

        for (String p: newStrSet) {
            System.out.printf("%s -> [", p);
            for (Codes2 s: personFile) {
            if (s.getUserNameGenerator().contains(p)) {
                System.out.printf("%s, ", s.getPersonName());
            }
        }
        System.out.println("]");
    }
}
</code>```

Java Class:

```<code>public class Codes2 implements Comparable<Codes2> {

    private String personName;
    private String userNameGenerator;

    public Codes2(String personName, String userNameGenerator) {
        this.personName = personName;
        this.userNameGenerator = userNameGenerator;
    }

    public String getPersonName() {
        return personName;
    }

    public String getUserNameGenerator() {
        return userNameGenerator;
    }

    @Override
    public int compareTo(Codes2 o) {
        return getUserNameGenerator().compareTo(o.getUserNameGenerator());
    }

    public int compare(Object lOCR1, Object lOCR2) {
        return ((Codes2)lOCR1).userNameGenerator
                .compareTo(((Codes2)lOCR2).userNameGenerator);
    }
}
</code>```

Output:

```<code>Dompteuse -> [Imran Sullivan, ]
Deservedness -> [Eadie Jefferson, ]
Ostracize -> [Eadie Jefferson, ]
Abattoir -> [Angel Whitehouse, ]
Choreography -> [Imran Sullivan, Taylor Vargas, Priya Oliver, ]
</code>```

How I want the output to look like:

```<code>Dompteuse -> [Imran Sullivan]
Deservedness -> [Eadie Jefferson]
Ostracize -> [Eadie Jefferson]
Abattoir -> [Angel Whitehouse]
Choreography -> [Imran Sullivan, Taylor Vargas, Priya Oliver]
</code>```

答:
I am looking through the double for each loop and I believe I have narrowed down your issue.  In the second for each loop, you print out the name of the person followed by the comma.  But you do this for every element, including the last one. Include a conditional in there that once it reaches the length of the row, only print out the name not the comma.

```<code>for (Codes2 s: personFile) {
        if (s.getUserNameGenerator().contains(p)) {
           //Try including conditional for the last element here
            System.out.printf("%s, ", s.getPersonName());
        }
}
</code>```

Hope this helps!

Body:
How can I change the code so that it prints out like the way I want it to be printed out? I want the userNameGenerator to be printed out first, with an arrow (->) in front of it, and the personName to be displayed with open and close square brackets ([]) beside it. I also want to remove the commas at the end. I've done a bit of it already as you can see below:

Code that needs changing:

Set<String> newStrSet = new HashSet<>();
for(int i = 0; i < personFile.size(); i++) {
    String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
    for(int j = 0; j < regionSplit.length; j++) {
    newStrSet.add(regionSplit[j]);
    }
}

for (String p: newStrSet) {
    System.out.printf("%s -> [", p);
    for (Codes2 s: personFile) {
        if (s.getUserNameGenerator().contains(p)) {
            System.out.printf("%s, ", s.getPersonName());
        }
    }
    System.out.println("]");
}

Full code:

import java.util.*;
import java.io.*;

public class Codes {
    public static void main(String[] args) {
        List<Codes2> personFile = new ArrayList<>();

        try {
            BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
            String fileRead = br.readLine();
            while (fileRead != null) {
                String[] personData = fileRead.split(":");
                String personName = personData[0];
                String userNameGenerator = personData[1];
                Codes2 personObj = new Codes2(personName, userNameGenerator);
                personFile.add(personObj);
                fileRead = br.readLine();
            }
            br.close();
        }

        catch (FileNotFoundException ex) {
            System.out.println("File not found!");
        }

        Set<String> newStrSet = new HashSet<>();
        for(int i = 0; i < personFile.size(); i++) {
            String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
            for(int j = 0; j < regionSplit.length; j++) {
                newStrSet.add(regionSplit[j]);
            }
        }

        for (String p: newStrSet) {
            System.out.printf("%s -> [", p);
            for (Codes2 s: personFile) {
            if (s.getUserNameGenerator().contains(p)) {
                System.out.printf("%s, ", s.getPersonName());
            }
        }
        System.out.println("]");
    }
}

Java Class:

public class Codes2 implements Comparable<Codes2> {

    private String personName;
    private String userNameGenerator;

    public Codes2(String personName, String userNameGenerator) {
        this.personName = personName;
        this.userNameGenerator = userNameGenerator;
    }

    public String getPersonName() {
        return personName;
    }

    public String getUserNameGenerator() {
        return userNameGenerator;
    }

    @Override
    public int compareTo(Codes2 o) {
        return getUserNameGenerator().compareTo(o.getUserNameGenerator());
    }

    public int compare(Object lOCR1, Object lOCR2) {
        return ((Codes2)lOCR1).userNameGenerator
                .compareTo(((Codes2)lOCR2).userNameGenerator);
    }
}

Output:

Dompteuse -> [Imran Sullivan, ]
Deservedness -> [Eadie Jefferson, ]
Ostracize -> [Eadie Jefferson, ]
Abattoir -> [Angel Whitehouse, ]
Choreography -> [Imran Sullivan, Taylor Vargas, Priya Oliver, ]

How I want the output to look like:

Dompteuse -> [Imran Sullivan]
Deservedness -> [Eadie Jefferson]
Ostracize -> [Eadie Jefferson]
Abattoir -> [Angel Whitehouse]
Choreography -> [Imran Sullivan, Taylor Vargas, Priya Oliver]

Body:
I am looking through the double for each loop and I believe I have narrowed down your issue.  In the second for each loop, you print out the name of the person followed by the comma.  But you do this for every element, including the last one. Include a conditional in there that once it reaches the length of the row, only print out the name not the comma.

for (Codes2 s: personFile) {
        if (s.getUserNameGenerator().contains(p)) {
           //Try including conditional for the last element here
            System.out.printf("%s, ", s.getPersonName());
        }
}

Hope this helps!


问:
strtok - moving one place forward
I have the function of myPrint that I am trying to use but I think that I am using the strtok function wrong

```<code>int myPrint( const  char* format , ...)
{
    char str[BUFFER];
    char cpy[BUFFER] = {0};
    char convert[BUFFER];
    char *check;
    char tempFormat[BUFFER];
    int len = 0;
    char *tempCheck;

    va_list args;
    va_start( args , format);
    strcpy(tempFormat , format );

    check = strtok ( tempFormat , "%");

    int flag = 0;
    while( check != NULL)
    {
        strcat( cpy , check  );
        len = strlen( cpy );

        switch(  tempFormat[len + 1]  )
        {
            case 'd':
                    sprintf( convert , "%d" , va_arg( args , int) );
                    strcat( cpy , convert);
                    break;
            case 'f':
                    sprintf( convert , "%f" , va_arg( args, double ));
                    strcat( cpy , convert);
                    break;
            case '%':
                    strcat( cpy ,"%" );
                    break;
            case 's':
                    strcat( cpy ,va_arg( args , char* ) );
                    break;
            default:
                break;
        }
        check = strtok ( NULL  , "%");
    }

    printf("%s" , cpy);
    va_end( args);
}

void main()
{
    int x = 7;
    float y = 11;
    char str[] ="HELLo";
    char str2[]="MY NAME";

    myPrint ( "ss %d is %d %s  " , 7 , 6 , str);
}
</code>```

The problem is if I send to the function to print what I want, I get after each % also the d

Is there a way to move the result of the strtok call one place forward?

答:
You'd need to feed strtok a new pointer if you want to move it beyond the last match. I tried your code with the changes below:

Edit:
I updated with the whole code which might be easier for you to see now!

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

#define BUFFER 500
int myPrint( const  char* format , ...)
{
    char str[BUFFER];
    char cpy[BUFFER] = {0};
    char convert[BUFFER];
    char *check;
    char *last_check;
    char tempFormat[BUFFER];
    int len = 0;
    char *tempCheck;

    va_list args;
    va_start( args , format);
    strcpy(tempFormat , format );

    check = strtok (tempFormat , "%");

    int flag = 0;
    while( check != NULL)
    {
        strcat( cpy , check  );
        len = strlen(cpy);

        switch(  tempFormat[len + 1]  )
        {
            case 'd':
                    sprintf( convert , "%d" , va_arg( args , int) );
                    strcat( cpy , convert);
                    break;
            case 'f':
                    sprintf( convert , "%f" , va_arg( args, double ));
                    strcat( cpy , convert);
                    break;
            case '%':
                    strcat( cpy ,"%" );
                    break;
            case 's':
                    strcat( cpy ,va_arg( args , char* ) );
                    break;
            default:
                break;
        }
        int len = strlen(check);
        last_check = check;
        check = strtok (check+len+2 , "%");
    }

    strcat( cpy , last_check);
    printf("%s" , cpy);
    va_end( args);
}

void main()
{
    int x = 7;
    float y = 11;
    char str[] ="HELLo";
    char str2[]="MY NAME";

    myPrint ("ss %d is %d %s  " , 7 , 6 , str);
}
</code>```

Title: strtok - moving one place forward

Body:
I have the function of myPrint that I am trying to use but I think that I am using the strtok function wrong

int myPrint( const  char* format , ...)
{
    char str[BUFFER];
    char cpy[BUFFER] = {0};
    char convert[BUFFER];
    char *check;
    char tempFormat[BUFFER];
    int len = 0;
    char *tempCheck;

    va_list args;
    va_start( args , format);
    strcpy(tempFormat , format );

    check = strtok ( tempFormat , "%");

    int flag = 0;
    while( check != NULL)
    {
        strcat( cpy , check  );
        len = strlen( cpy );

        switch(  tempFormat[len + 1]  )
        {
            case 'd':
                    sprintf( convert , "%d" , va_arg( args , int) );
                    strcat( cpy , convert);
                    break;
            case 'f':
                    sprintf( convert , "%f" , va_arg( args, double ));
                    strcat( cpy , convert);
                    break;
            case '%':
                    strcat( cpy ,"%" );
                    break;
            case 's':
                    strcat( cpy ,va_arg( args , char* ) );
                    break;
            default:
                break;
        }
        check = strtok ( NULL  , "%");
    }

    printf("%s" , cpy);
    va_end( args);
}

void main()
{
    int x = 7;
    float y = 11;
    char str[] ="HELLo";
    char str2[]="MY NAME";

    myPrint ( "ss %d is %d %s  " , 7 , 6 , str);
}

The problem is if I send to the function to print what I want, I get after each % also the d

Is there a way to move the result of the strtok call one place forward?

Body:
You'd need to feed strtok a new pointer if you want to move it beyond the last match. I tried your code with the changes below:

Edit:
I updated with the whole code which might be easier for you to see now!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

#define BUFFER 500
int myPrint( const  char* format , ...)
{
    char str[BUFFER];
    char cpy[BUFFER] = {0};
    char convert[BUFFER];
    char *check;
    char *last_check;
    char tempFormat[BUFFER];
    int len = 0;
    char *tempCheck;

    va_list args;
    va_start( args , format);
    strcpy(tempFormat , format );

    check = strtok (tempFormat , "%");

    int flag = 0;
    while( check != NULL)
    {
        strcat( cpy , check  );
        len = strlen(cpy);

        switch(  tempFormat[len + 1]  )
        {
            case 'd':
                    sprintf( convert , "%d" , va_arg( args , int) );
                    strcat( cpy , convert);
                    break;
            case 'f':
                    sprintf( convert , "%f" , va_arg( args, double ));
                    strcat( cpy , convert);
                    break;
            case '%':
                    strcat( cpy ,"%" );
                    break;
            case 's':
                    strcat( cpy ,va_arg( args , char* ) );
                    break;
            default:
                break;
        }
        int len = strlen(check);
        last_check = check;
        check = strtok (check+len+2 , "%");
    }

    strcat( cpy , last_check);
    printf("%s" , cpy);
    va_end( args);
}

void main()
{
    int x = 7;
    float y = 11;
    char str[] ="HELLo";
    char str2[]="MY NAME";

    myPrint ("ss %d is %d %s  " , 7 , 6 , str);
}


问:
pandas taking entries in column order
I have this df1:

```<code>ID  Name    Alias   Nickname
101 Robert  Rob Bob
201 Tom
315     Megan   Meg
405 Teddy       Ted
510         Bill
602
</code>```

But I want to add in a Result column that take the entries in an order (Name, Alias (if Name is empty), Nickname (if Alias and Name both empty))

```<code>ID  Name    Alias   Nickname    Result
101 Robert  Rob Bob Robert
201 Tom         Tom
315     Megan   Meg Megan
405 Teddy       Ted Teddy
510         Bill    Bill
602             NA
</code>```

答:
Try this.</p>

```<code>df1['Result'] = df1[['Name', 'Alias', 'Nickname']].bfill(axis=1).iloc[:, 0]

Out [142]:

    ID      Name    Alias   Nickname    Result
0   101     Robert  Rob     Bob         Robert
1   201     Tom     NaN     NaN         Tom
2   315     Megan   Meg     NaN         Megan
3   405     Teddy   Ted     NaN         Teddy
4   510     Bill    NaN     NaN         Bill
5   602     NaN     NaN     NaN         NaN
</code>```

Title: pandas taking entries in column order

Body:
I have this df1:

ID  Name    Alias   Nickname
101 Robert  Rob Bob
201 Tom
315     Megan   Meg
405 Teddy       Ted
510         Bill
602

But I want to add in a Result column that take the entries in an order (Name, Alias (if Name is empty), Nickname (if Alias and Name both empty))

ID  Name    Alias   Nickname    Result
101 Robert  Rob Bob Robert
201 Tom         Tom
315     Megan   Meg Megan
405 Teddy       Ted Teddy
510         Bill    Bill
602             NA

Body:
Try this.

df1['Result'] = df1[['Name', 'Alias', 'Nickname']].bfill(axis=1).iloc[:, 0]

Out [142]:

    ID      Name    Alias   Nickname    Result
0   101     Robert  Rob     Bob         Robert
1   201     Tom     NaN     NaN         Tom
2   315     Megan   Meg     NaN         Megan
3   405     Teddy   Ted     NaN         Teddy
4   510     Bill    NaN     NaN         Bill
5   602     NaN     NaN     NaN         NaN


问:
RuntimeError: module compiled against API version a but this version of numpy is 9
Code:

```<code>import numpy as np
import cv
</code>```

Console:

```<code>>>> runfile('/Users/isaiahnields/.spyder2/temp.py', wdir='/Users/isaiahnields/.spyder2')
RuntimeError: module compiled against API version a but this version of numpy is 9
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
File "/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py", line 78, in execfile
builtins.execfile(filename, *where)
File "/Users/isaiahnields/.spyder2/temp.py", line 9, in <module>
import cv
File "/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/cv.py", line 1, in <module>
from cv2.cv import *
ImportError: numpy.core.multiarray failed to import
>>>
</code>```

System Info: OS X El Capitan, Macbook Air, 1.3 GHz Intel Core i5, 8 GB 1600 HMz DDR3

I have already attempted updating numpy. I had to add cv.py to the python2.7 folder in Spyder-Py2 is there something else I need to add?

答:
You may also want to check your $PYTHONPATH. I had changed mine in ~/.bashrc in order to get another package to work.

To check your path:

```<code>    echo $PYTHONPATH
</code>```

To change your path (I use nano but you could edit another way)

```<code>    nano ~/.bashrc
</code>```

Look for the line with export PYTHONPATH ...

After making changes, don't forget to

```<code>   source ~/.bashrc
</code>```

Body:
Code:

import numpy as np
import cv

Console:

>>> runfile('/Users/isaiahnields/.spyder2/temp.py', wdir='/Users/isaiahnields/.spyder2')
RuntimeError: module compiled against API version a but this version of numpy is 9
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
File "/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py", line 78, in execfile
builtins.execfile(filename, *where)
File "/Users/isaiahnields/.spyder2/temp.py", line 9, in <module>
import cv
File "/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/cv.py", line 1, in <module>
from cv2.cv import *
ImportError: numpy.core.multiarray failed to import
>>>

System Info: OS X El Capitan, Macbook Air, 1.3 GHz Intel Core i5, 8 GB 1600 HMz DDR3

I have already attempted updating numpy. I had to add cv.py to the python2.7 folder in Spyder-Py2 is there something else I need to add?

Body:
You may also want to check your $PYTHONPATH. I had changed mine in ~/.bashrc in order to get another package to work.

To check your path:

    echo $PYTHONPATH

To change your path (I use nano but you could edit another way)

    nano ~/.bashrc

Look for the line with export PYTHONPATH ...

After making changes, don't forget to

   source ~/.bashrc


问:
Is there a packet sniffer that can be limited to one single program?
I've been using Wireshark for a while now to analyze a few programs. Is there a way that I can limit Wireshark to sniff only one program? Or is there another program that does something like this?</p>

答: Using Wireshark you can filter by destination port number or IP address. For example, Mail clients usually use ports 25 and 110 for sending and receiving emails.</p>


问:
Pandas read csv infer only bool
I would like to use pandas.read_csv to infer only boolean types in the data.

If I use dtypes=str, I do not have a simple way to convert my data back to boolean type as the following does not work well.

```<code>df['bool_column'].astype(bool).eq(False)
</code>```

I do not want to infer all dtypes as I do not want to lose any integer types in the data.

Is there a simple solution to this problem?

答:
If you have not standard values - true and false instead of True and False you can do the following:

```<code>df['bool_column'] = df['bool_column'].eq('true')
</code>```

Title: Pandas read csv infer only bool

Body:
I would like to use pandas.read_csv to infer only boolean types in the data.

If I use dtypes=str, I do not have a simple way to convert my data back to boolean type as the following does not work well.

df['bool_column'].astype(bool).eq(False)

I do not want to infer all dtypes as I do not want to lose any integer types in the data.

Is there a simple solution to this problem?

Body:
If you have not standard values - true and false instead of True and False you can do the following:

df['bool_column'] = df['bool_column'].eq('true')


问:
Error:Execution failed for task ':app:prepareComGoogleAndroidGmsPlayServicesAds980Library' > Failed to create parent directory when creating directory
I am using Android Studio 2.2.3. My app has always been compiling and working properly but suddenly today I received this error:

```<code>Error:Execution failed for task ':app:prepareComGoogleAndroidGmsPlayServicesAds980Library'.
> Failed to create parent directory 'C:\Users\[My path]\androidapp\build\app\build\intermediates\exploded-aar\com.google.android.gms\play-services-ads' when creating directory 'C:\Users\[My path]\androidapp\build\app\build\intermediates\exploded-aar\com.google.android.gms\play-services-ads\9.8.0'
</code>```

I tried restarting Android Studio, using "File > Invalidate Caches / Restart...", and running Android Studio as an administrator, but the error persists. Any ideas about what may be the cause of this issue?

答:
The solution was upgrading from Android 2.2.3 to Android 3.0.1. But then I was getting this error:

```<code>Warning:The specified Android SDK Build Tools version (23.0.1) is ignored, as it is below the minimum supported version (26.0.2) for Android Gradle Plugin 3.0.1. Android SDK Build Tools 26.0.2 will be used. To suppress this warning, remove "buildToolsVersion '23.0.1'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools. <a href="fix.build.tools.version">Update Build Tools version and sync project</a><br><a href="openFile:C:/Users/[My path]/androidapp/build/app/build.gradle">Open File</a>
</code>```

The solution was commenting out buildToolsVersion "23.0.1".

Body:
I am using Android Studio 2.2.3. My app has always been compiling and working properly but suddenly today I received this error:

Error:Execution failed for task ':app:prepareComGoogleAndroidGmsPlayServicesAds980Library'.
> Failed to create parent directory 'C:\Users\[My path]\androidapp\build\app\build\intermediates\exploded-aar\com.google.android.gms\play-services-ads' when creating directory 'C:\Users\[My path]\androidapp\build\app\build\intermediates\exploded-aar\com.google.android.gms\play-services-ads\9.8.0'

I tried restarting Android Studio, using "File > Invalidate Caches / Restart...", and running Android Studio as an administrator, but the error persists. Any ideas about what may be the cause of this issue?

Body:
The solution was upgrading from Android 2.2.3 to Android 3.0.1. But then I was getting this error:

Warning:The specified Android SDK Build Tools version (23.0.1) is ignored, as it is below the minimum supported version (26.0.2) for Android Gradle Plugin 3.0.1. Android SDK Build Tools 26.0.2 will be used. To suppress this warning, remove "buildToolsVersion '23.0.1'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools. <a href="fix.build.tools.version">Update Build Tools version and sync project</a><br><a href="openFile:C:/Users/[My path]/androidapp/build/app/build.gradle">Open File</a>

The solution was commenting out buildToolsVersion "23.0.1".


问:
Unable to import opencv in Jupyter notebook but able to import in command line on Anaconda
I created a new environment in anaconda for python 3.5 and installed all the required pip libraries including opencv.

If I execute the following in command line

```<code>$ python
Python 3.5.2 |Continuum Analytics, Inc.| (default, Jul  2 2016, 17:52:12)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>>
</code>```

As you can see above there is no issues importing cv2.

However when I open Jupyter notebook and execute the following

```<code>#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
</code>```

I get the following error

```<code>---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)

<ipython-input-5-69f36577ffd4> in <module>()
      3 import matplotlib.image as mpimg
      4 import numpy as np
----> 5 import cv2
      6 get_ipython().magic('matplotlib inline')

ImportError: No module named 'cv2'
</code>```

I also tried cycling through all the available kernals in Kernal->Change Kernal settings. That didnt help either

答:
I also had this problem.
I installed opencv-contrib-python package using pip in my conda env and getting the same error </p>

```<code>$ source activate env
$ pip install opencv-contrib-python
</code>```

<p>uninstalled opencv from my env and installed when I was not inside env  i.e </p>

```<code>$ source deactivate (if you are in the env )
$ pip install opencv-contrib-python
</code>```

Body:
I created a new environment in anaconda for python 3.5 and installed all the required pip libraries including opencv.

If I execute the following in command line

$ python
Python 3.5.2 |Continuum Analytics, Inc.| (default, Jul  2 2016, 17:52:12)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>>

As you can see above there is no issues importing cv2.

However when I open Jupyter notebook and execute the following

#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline

I get the following error

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)

<ipython-input-5-69f36577ffd4> in <module>()
      3 import matplotlib.image as mpimg
      4 import numpy as np
----> 5 import cv2
      6 get_ipython().magic('matplotlib inline')

ImportError: No module named 'cv2'

I also tried cycling through all the available kernals in Kernal->Change Kernal settings. That didnt help either

Body:
I also had this problem.
I installed opencv-contrib-python package using pip in my conda env and getting the same error

$ source activate env
$ pip install opencv-contrib-python

uninstalled opencv from my env and installed when I was not inside env  i.e

$ source deactivate (if you are in the env )
$ pip install opencv-contrib-python


问:
Get everything before dot or comma c#
how can I get a substring of everything before dot or comma?

For example:

```<code>    string input = "2.1";
int charLocation = text.IndexOf(".", StringComparison.Ordinal);
    string test = input.Substring(0, charLocation );
</code>```

but what if I have an input = "2,1" ?

I would like to do it in one method, not using twice a substring (once for dot and once for comma)?

答:
```<code>string test = input.Split(new Char[] { ',', '.' })[0];
</code>```

Title: Get everything before dot or comma c#

Body:
how can I get a substring of everything before dot or comma?

For example:

    string input = "2.1";
int charLocation = text.IndexOf(".", StringComparison.Ordinal);
    string test = input.Substring(0, charLocation );

but what if I have an input = "2,1" ?

I would like to do it in one method, not using twice a substring (once for dot and once for comma)?