问:
Execute function on button press (unity3d/C#)
Basically, what I'm trying to do is when pressing Z - it executes function to spin, and X - it executes function to stop spinning. Before, I had UI buttons which worked perfectly fine, now I try doing it by button but nothing happens.

Also, if you can suggest on how to make it start spinning and stop spinning by only pressing "Space" button, that'd be great.

Heres my code so far:

```<code>using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class spin : MonoBehaviour
{
    public float speed = 500f;
    public Button starter;
    public Button stopper;
    bool isSpinning = false;

    IEnumerator spinnerCoroutine;

    void Start()
    {
        //The spin function
        spinnerCoroutine = spinCOR();

        //Button btn = starter.GetComponent<Button>();
        //Button butn = stopper.GetComponent<Button>();

        //butn.onClick.AddListener(FidgetSpinnerStop);
        //btn.onClick.AddListener(FidgetSpinnerStart);

        if (Input.GetKey(KeyCode.Z)) {

            FidgetSpinnerStart();
        }

        if (Input.GetKey(KeyCode.X)) {
            FidgetSpinnerStop();
        }
    }

    IEnumerator spinCOR()
    {
        //Spin forever untill FidgetSpinnerStop is called
        while (true)
        {
            transform.Rotate(Vector3.up, speed * Time.deltaTime);
            //Wait for the next frame
            yield return null;
        }
    }

    void FidgetSpinnerStart()
    {
        //Spin only if it is not spinning
        if (!isSpinning)
        {
            isSpinning = true;
            StartCoroutine(spinnerCoroutine);
        }
    }

    void FidgetSpinnerStop()
    {
        //Stop Spinning only if it is already spinning
        if (isSpinning)
        {
            StopCoroutine(spinnerCoroutine);
            isSpinning = false;
        }
    }
}
</code>```

Thanks.

答:
There are just two problems in your code:

1.Checking the keypress in the Start() function.

The Start() will be called once while the Update() function will be called every frame.

You need to use the Update() function to constantly poll the input every frame.

2.Using Input.GetKey() function to check for keypress.

The Input.GetKey() function can return true multiple times over several frames. While you may not see any problems now, that's because the isSpinning variable is preventing possible problems but you will run into problems if you want to add more code directly inside the if (Input.GetKey(KeyCode.Z)) code because those code will execute multiple times in a frame.

You need to use the Input.GetKeyDown() function.

```<code>public class spin : MonoBehaviour
{
    public float speed = 500f;
    public Button starter;
    public Button stopper;
    bool isSpinning = false;

    IEnumerator spinnerCoroutine;

    void Start()
    {
        spinnerCoroutine = spinCOR();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Z)) {

            FidgetSpinnerStart();
        }

        if (Input.GetKeyDown(KeyCode.X)) {
            FidgetSpinnerStop();
        }
    }

    IEnumerator spinCOR()
    {
        //Spin forever until FidgetSpinnerStop is called
        while (true)
        {
            transform.Rotate(Vector3.up, speed * Time.deltaTime);
            //Wait for the next frame
            yield return null;
        }
    }

    void FidgetSpinnerStart()
    {
        //Spin only if it is not spinning
        if (!isSpinning)
        {
            isSpinning = true;
            StartCoroutine(spinnerCoroutine);
        }
    }

    void FidgetSpinnerStop()
    {
        //Stop Spinning only if it is already spinning
        if (isSpinning)
        {
            StopCoroutine(spinnerCoroutine);
            isSpinning = false;
        }
    }
}
</code>```

Also, if you can suggest on how to make it start spinning and stop
  spinning by only pressing "Space" button, that'd be great

You can do that with  KeyCode.Space. Check if Space key is pressed then check the isSpinning variable before starting/stopping the coroutine.

Just replace the Update function above with the one below:

```<code>void Update()
{
    //Start if Space-key is pressed AND is not Spinning
    if (Input.GetKeyDown(KeyCode.Space) && !isSpinning)
    {
        FidgetSpinnerStart();
    }

    //Stop if Space-key is pressed AND is already Spinning
    else if (Input.GetKeyDown(KeyCode.Space) && isSpinning)
    {
        FidgetSpinnerStop();
    }
}
</code>```

Body:
Basically, what I'm trying to do is when pressing Z - it executes function to spin, and X - it executes function to stop spinning. Before, I had UI buttons which worked perfectly fine, now I try doing it by button but nothing happens.

Also, if you can suggest on how to make it start spinning and stop spinning by only pressing "Space" button, that'd be great.

Heres my code so far:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class spin : MonoBehaviour
{
    public float speed = 500f;
    public Button starter;
    public Button stopper;
    bool isSpinning = false;

    IEnumerator spinnerCoroutine;

    void Start()
    {
        //The spin function
        spinnerCoroutine = spinCOR();

        //Button btn = starter.GetComponent<Button>();
        //Button butn = stopper.GetComponent<Button>();

        //butn.onClick.AddListener(FidgetSpinnerStop);
        //btn.onClick.AddListener(FidgetSpinnerStart);

        if (Input.GetKey(KeyCode.Z)) {

            FidgetSpinnerStart();
        }

        if (Input.GetKey(KeyCode.X)) {
            FidgetSpinnerStop();
        }
    }

    IEnumerator spinCOR()
    {
        //Spin forever untill FidgetSpinnerStop is called
        while (true)
        {
            transform.Rotate(Vector3.up, speed * Time.deltaTime);
            //Wait for the next frame
            yield return null;
        }
    }

    void FidgetSpinnerStart()
    {
        //Spin only if it is not spinning
        if (!isSpinning)
        {
            isSpinning = true;
            StartCoroutine(spinnerCoroutine);
        }
    }

    void FidgetSpinnerStop()
    {
        //Stop Spinning only if it is already spinning
        if (isSpinning)
        {
            StopCoroutine(spinnerCoroutine);
            isSpinning = false;
        }
    }
}

Thanks.

Body:
There are just two problems in your code:

1.Checking the keypress in the Start() function.

The Start() will be called once while the Update() function will be called every frame.

You need to use the Update() function to constantly poll the input every frame.

2.Using Input.GetKey() function to check for keypress.

The Input.GetKey() function can return true multiple times over several frames. While you may not see any problems now, that's because the isSpinning variable is preventing possible problems but you will run into problems if you want to add more code directly inside the if (Input.GetKey(KeyCode.Z)) code because those code will execute multiple times in a frame.

You need to use the Input.GetKeyDown() function.

public class spin : MonoBehaviour
{
    public float speed = 500f;
    public Button starter;
    public Button stopper;
    bool isSpinning = false;

    IEnumerator spinnerCoroutine;

    void Start()
    {
        spinnerCoroutine = spinCOR();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Z)) {

            FidgetSpinnerStart();
        }

        if (Input.GetKeyDown(KeyCode.X)) {
            FidgetSpinnerStop();
        }
    }

    IEnumerator spinCOR()
    {
        //Spin forever until FidgetSpinnerStop is called
        while (true)
        {
            transform.Rotate(Vector3.up, speed * Time.deltaTime);
            //Wait for the next frame
            yield return null;
        }
    }

    void FidgetSpinnerStart()
    {
        //Spin only if it is not spinning
        if (!isSpinning)
        {
            isSpinning = true;
            StartCoroutine(spinnerCoroutine);
        }
    }

    void FidgetSpinnerStop()
    {
        //Stop Spinning only if it is already spinning
        if (isSpinning)
        {
            StopCoroutine(spinnerCoroutine);
            isSpinning = false;
        }
    }
}

Also, if you can suggest on how to make it start spinning and stop
  spinning by only pressing "Space" button, that'd be great

You can do that with  KeyCode.Space. Check if Space key is pressed then check the isSpinning variable before starting/stopping the coroutine.

Just replace the Update function above with the one below:

void Update()
{
    //Start if Space-key is pressed AND is not Spinning
    if (Input.GetKeyDown(KeyCode.Space) && !isSpinning)
    {
        FidgetSpinnerStart();
    }

    //Stop if Space-key is pressed AND is already Spinning
    else if (Input.GetKeyDown(KeyCode.Space) && isSpinning)
    {
        FidgetSpinnerStop();
    }
}


来源: stackexchange

问:
How would you go about making this if else if program much more simplistic and less code redundant (C++)?
Write a program that asks for the names of three runners and the time it took each
of them to finish a race. The program should display who came in first, second, and
third place.
Input Validation: Only accept positive numbers for the times.

My Code

```<code>#include <iostream>
#include <string>
using namespace std;

int main()
{
    string runner1, runner2, runner3;
    int time1, time2, time3;

    cout << "Please enter the names of three runners" << endl;
    cin >> runner1 >> runner2 >> runner3;
    cout << "How many minutes did it take " << runner1 << " to finish the race?" << endl;
    cin >> time1;
    cout << "How many minutes did it take " << runner2 << " to finish the race?" << endl;
    cin >> time2;
    cout << "How many minutes did it take " << runner3 << " to finish the race?" << endl;
    cin >> time3;

    if (time1 < time2 && time1 < time3)
    {
        cout << runner1 << " is 1st place!" << endl;

        if (time2 < time3)
        {
            cout << runner2 << " is 2nd place!" << endl;
            cout << runner3 << " is 3rd place!" << endl;
        }
        else if (time3 < time2)
        {
            cout << runner3 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else if (time2 < time1 && time2 < time3)
    {
        cout << runner2 << " is 1st place!" << endl;

        if (time1 < time3)
        {
            cout << runner1 << " is 2nd place!" << endl;
            cout << runner3 << " is 3rd place!" << endl;
        }
        else if (time3 < time1)
        {
            cout << runner3 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else if (time3 < time2 && time3 < time1)
    {
        cout << runner3 << " is 1st Place!" << endl;

        if (time2 < time1)
        {
            cout << runner2 << " is 2nd place!" << endl;
            cout << runner1 << " is 3rd place!" << endl;
        }
        else if (time1 < time2)
        {
            cout << runner1 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else
    {
        cout << "Error! Please restart the program and input a positive value" << endl;
    }
    return 0;
}
</code>```

答:
It looks like you're beginning your journey in c++ programming. Welcome.

I'd seek to break the problem down into its component parts, so that we can end up expressing the intent of the solution in an easy-to-understand form:

```<code>int solve(std::istream& is, std::ostream& os) {

    Runners runners;
    collect_runners(os, is, runners);
    sort_by_time(runners);
    print_first_3(os, runners);

    return 0;
}
</code>```

Note that I have not tied the solution to any particular input or output stream. That's so I can test it easily later.

Now that we have expressed the intent of the solution cleanly, we fill in the blanks (I have used various 'advanced' techniques that I hope you will find instructive and interesting).

I have used c++11.

Comments inline.

```<code>#include <string>
#include <vector>
#include <algorithm>
#include <type_traits>
#include <iostream>
#include <sstream>

/** The concept of coupling a runner's name with the time it took to run the race
 *
 */
struct Runner {
    std::string name;
    int time;
};

/** A collection of runners and their corresponding time.
 *
 */
using Runners = std::vector<Runner>;

/** Sort a container with a predicate. Return a reference to the container
 *
 * @tparam Container
 * @tparam Pred
 * @param c
 * @param pred
 * @return
 */
template<class Container, class Pred>
auto sort_container(Container &c, Pred &&pred) -> Container & {
    std::sort(std::begin(c), std::end(c), std::forward<Pred>(pred));
    return c;
}

/** Sort a Runners array by ascending time
 *
 * @param vec
 * @return
 * */
Runners &sort_by_time(Runners &vec) {
    auto by_increasing_time = [](Runner const& l, Runner const& r) {
        return l.time < r.time;
    };

    sort_container(vec, by_increasing_time);
    return vec;
}

/** Print the first 3 runnes in an array of runners to an ostream
 *
 * @param os
 * @param vec
 */
void print_first_3(std::ostream& os, Runners const &vec) {
    static const char *nth[] = {
            "first",
            "second",
            "third"
    };

    auto limit = std::extent<decltype(nth)>::value;
    limit = std::min(limit, vec.size());
    for (std::size_t i = 0; i < limit; ++i) {
        auto const &runner = vec[i];
        os << runner.name << " is in " << nth[i] << " place with a time of " << runner.time << "\n";
    }
}

/** Ask a question on the console if the answer is to come from stdin
 *
 * @param is
 * @param q
 */
template<class Target>
void question(std::istream& is, Target& target, std::string const& q)
{
    if (std::addressof(is) == static_cast<std::istream*>(std::addressof(std::cin)))
    {
        std::cout << q << std::endl;
    }
    is >> target;
}

/** Build a runner using the supplied input and output streams
 *
 * @param os
 * @param is
 * @return
 */
Runner collect_runner(std::ostream& os, std::istream& is)
{
    Runner runner {};
    question(is, runner.name, "runner's name?");
    question(is, runner.time, "runner's time?");
    return runner;
}

/** Populate a Runners array using input and output streams
 *
 * @param os
 * @param is
 * @param runners
 * @return
 */
Runners& collect_runners(std::ostream& os, std::istream& is, Runners& runners)
{
    int nrunners = 0;
    question(is, nrunners, "how many runners?");

    while (nrunners-- > 0) {
        runners.push_back(collect_runner(os, is));
    }
    return runners;
}

/** Solve the problem at hand
 *
 * @param is
 * @param os
 * @return
 */
int solve(std::istream& is, std::ostream& os) {

    Runners runners;
    collect_runners(os, is, runners);
    sort_by_time(runners);
    print_first_3(os, runners);

    return 0;
}

/** Solve the problem using either std input/output or test input
 *
 * @param argc
 * @param argv
 * @note If argc == 2 and argv[1] == "test" then run solve using test input.
 *       We do this so that we can test our code without playing around with external files or
 *       the console each time we want to test it
 * @return
 */
int main(int argc, char **argv) {
    if (argc == 2 && argv[1] == std::string("test")) {
        static const char test_data[] = R"__(
5
bob 40
bill 20
sue 30
peter 25
zool 29
)__";
        std::istringstream test_stream{test_data};

        return solve(test_stream, std::cout);

    } else {

        return solve(std::cin, std::cout);
    }
}
</code>```

test on the console with:

```<code>$ ./a.out test
</code>```

expected output:

```<code>bill is in first place with a time of 20
peter is in second place with a time of 25
zool is in third place with a time of 29
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Write a program that asks for the names of three runners and the time it took each
of them to finish a race. The program should display who came in first, second, and
third place.
Input Validation: Only accept positive numbers for the times.

My Code

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string runner1, runner2, runner3;
    int time1, time2, time3;

    cout << "Please enter the names of three runners" << endl;
    cin >> runner1 >> runner2 >> runner3;
    cout << "How many minutes did it take " << runner1 << " to finish the race?" << endl;
    cin >> time1;
    cout << "How many minutes did it take " << runner2 << " to finish the race?" << endl;
    cin >> time2;
    cout << "How many minutes did it take " << runner3 << " to finish the race?" << endl;
    cin >> time3;

    if (time1 < time2 && time1 < time3)
    {
        cout << runner1 << " is 1st place!" << endl;

        if (time2 < time3)
        {
            cout << runner2 << " is 2nd place!" << endl;
            cout << runner3 << " is 3rd place!" << endl;
        }
        else if (time3 < time2)
        {
            cout << runner3 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else if (time2 < time1 && time2 < time3)
    {
        cout << runner2 << " is 1st place!" << endl;

        if (time1 < time3)
        {
            cout << runner1 << " is 2nd place!" << endl;
            cout << runner3 << " is 3rd place!" << endl;
        }
        else if (time3 < time1)
        {
            cout << runner3 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else if (time3 < time2 && time3 < time1)
    {
        cout << runner3 << " is 1st Place!" << endl;

        if (time2 < time1)
        {
            cout << runner2 << " is 2nd place!" << endl;
            cout << runner1 << " is 3rd place!" << endl;
        }
        else if (time1 < time2)
        {
            cout << runner1 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else
    {
        cout << "Error! Please restart the program and input a positive value" << endl;
    }
    return 0;
}

Body:
It looks like you're beginning your journey in c++ programming. Welcome.

I'd seek to break the problem down into its component parts, so that we can end up expressing the intent of the solution in an easy-to-understand form:

int solve(std::istream& is, std::ostream& os) {

    Runners runners;
    collect_runners(os, is, runners);
    sort_by_time(runners);
    print_first_3(os, runners);

    return 0;
}

Note that I have not tied the solution to any particular input or output stream. That's so I can test it easily later.

Now that we have expressed the intent of the solution cleanly, we fill in the blanks (I have used various 'advanced' techniques that I hope you will find instructive and interesting).

I have used c++11.

Comments inline.

#include <string>
#include <vector>
#include <algorithm>
#include <type_traits>
#include <iostream>
#include <sstream>

/** The concept of coupling a runner's name with the time it took to run the race
 *
 */
struct Runner {
    std::string name;
    int time;
};

/** A collection of runners and their corresponding time.
 *
 */
using Runners = std::vector<Runner>;

/** Sort a container with a predicate. Return a reference to the container
 *
 * @tparam Container
 * @tparam Pred
 * @param c
 * @param pred
 * @return
 */
template<class Container, class Pred>
auto sort_container(Container &c, Pred &&pred) -> Container & {
    std::sort(std::begin(c), std::end(c), std::forward<Pred>(pred));
    return c;
}

/** Sort a Runners array by ascending time
 *
 * @param vec
 * @return
 * */
Runners &sort_by_time(Runners &vec) {
    auto by_increasing_time = [](Runner const& l, Runner const& r) {
        return l.time < r.time;
    };

    sort_container(vec, by_increasing_time);
    return vec;
}

/** Print the first 3 runnes in an array of runners to an ostream
 *
 * @param os
 * @param vec
 */
void print_first_3(std::ostream& os, Runners const &vec) {
    static const char *nth[] = {
            "first",
            "second",
            "third"
    };

    auto limit = std::extent<decltype(nth)>::value;
    limit = std::min(limit, vec.size());
    for (std::size_t i = 0; i < limit; ++i) {
        auto const &runner = vec[i];
        os << runner.name << " is in " << nth[i] << " place with a time of " << runner.time << "\n";
    }
}

/** Ask a question on the console if the answer is to come from stdin
 *
 * @param is
 * @param q
 */
template<class Target>
void question(std::istream& is, Target& target, std::string const& q)
{
    if (std::addressof(is) == static_cast<std::istream*>(std::addressof(std::cin)))
    {
        std::cout << q << std::endl;
    }
    is >> target;
}

/** Build a runner using the supplied input and output streams
 *
 * @param os
 * @param is
 * @return
 */
Runner collect_runner(std::ostream& os, std::istream& is)
{
    Runner runner {};
    question(is, runner.name, "runner's name?");
    question(is, runner.time, "runner's time?");
    return runner;
}

/** Populate a Runners array using input and output streams
 *
 * @param os
 * @param is
 * @param runners
 * @return
 */
Runners& collect_runners(std::ostream& os, std::istream& is, Runners& runners)
{
    int nrunners = 0;
    question(is, nrunners, "how many runners?");

    while (nrunners-- > 0) {
        runners.push_back(collect_runner(os, is));
    }
    return runners;
}

/** Solve the problem at hand
 *
 * @param is
 * @param os
 * @return
 */
int solve(std::istream& is, std::ostream& os) {

    Runners runners;
    collect_runners(os, is, runners);
    sort_by_time(runners);
    print_first_3(os, runners);

    return 0;
}

/** Solve the problem using either std input/output or test input
 *
 * @param argc
 * @param argv
 * @note If argc == 2 and argv[1] == "test" then run solve using test input.
 *       We do this so that we can test our code without playing around with external files or
 *       the console each time we want to test it
 * @return
 */
int main(int argc, char **argv) {
    if (argc == 2 && argv[1] == std::string("test")) {
        static const char test_data[] = R"__(
5
bob 40
bill 20
sue 30
peter 25
zool 29
)__";
        std::istringstream test_stream{test_data};

        return solve(test_stream, std::cout);

    } else {

        return solve(std::cin, std::cout);
    }
}

test on the console with:

$ ./a.out test

expected output:

bill is in first place with a time of 20
peter is in second place with a time of 25
zool is in third place with a time of 29


问:
Cannot delete slf4j dependencies
I have a problem with slf4j dependencies.

On POM.xml, i declared this:

```<code>     <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.12</version>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.12</version>
    </dependency>
</code>```

But i meet this error message:

```<code>   SLF4J: Class path contains multiple SLF4J bindings.
   SLF4J: Found binding in
   [jar:file:/C:/Users/r.rossi/.m2/repository/org/slf4j/slf4j-
   nop/1.5.3/slf4j-nop-1.5.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
   SLF4J: Found binding in
   [jar:file:/C:/Users/r.rossi/.m2/repository/org/slf4j/slf4j-
    jdk14/1.5.6/slf4j-jdk14-
    1.5.6.jar!/org/slf4j/impl/StaticLoggerBinder.class]
    SLF4J: Found binding in
    [jar:file:/C:/Users/r.rossi/.m2/repository/org/slf4j/slf4j-
    log4j12/1.7.12/slf4j-log4j12-
    1.7.12.jar!/org/slf4j/impl/StaticLoggerBinder.class]
     SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an
    explanation.
    SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding.
    SLF4J: Your binding is version 1.5.5 or earlier.
    SLF4J: Upgrade your binding to version 1.6.x.
</code>```

On those directorties and on maven dependencies i have  1.5 versions but i don't have them on POM.xml file (as you can see), so i don't know how delete them. If i delete the directories, it works but the next esecution the project download again the 1.5 versions. How can i delete those damned 1.5 versions?

答:
As the error stack suggest check the link Multiple Binding.

Also, check Dependency Tree to check which external dependency is trying to include (1.5.5 or earlier version).
Basically, your exclusion code

```<code><exclusions>
   <exclusion>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
   </exclusion>
</exclusions>
</code>```

should be inserted inside that dependency which depends on an earlier version 1.5.5.

Title: Cannot delete slf4j dependencies

Body:
I have a problem with slf4j dependencies.

On POM.xml, i declared this:

     <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.12</version>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.12</version>
    </dependency>

But i meet this error message:

   SLF4J: Class path contains multiple SLF4J bindings.
   SLF4J: Found binding in
   [jar:file:/C:/Users/r.rossi/.m2/repository/org/slf4j/slf4j-
   nop/1.5.3/slf4j-nop-1.5.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
   SLF4J: Found binding in
   [jar:file:/C:/Users/r.rossi/.m2/repository/org/slf4j/slf4j-
    jdk14/1.5.6/slf4j-jdk14-
    1.5.6.jar!/org/slf4j/impl/StaticLoggerBinder.class]
    SLF4J: Found binding in
    [jar:file:/C:/Users/r.rossi/.m2/repository/org/slf4j/slf4j-
    log4j12/1.7.12/slf4j-log4j12-
    1.7.12.jar!/org/slf4j/impl/StaticLoggerBinder.class]
     SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an
    explanation.
    SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding.
    SLF4J: Your binding is version 1.5.5 or earlier.
    SLF4J: Upgrade your binding to version 1.6.x.

On those directorties and on maven dependencies i have  1.5 versions but i don't have them on POM.xml file (as you can see), so i don't know how delete them. If i delete the directories, it works but the next esecution the project download again the 1.5 versions. How can i delete those damned 1.5 versions?

Body:
As the error stack suggest check the link Multiple Binding.

Also, check Dependency Tree to check which external dependency is trying to include (1.5.5 or earlier version).
Basically, your exclusion code

<exclusions>
   <exclusion>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
   </exclusion>
</exclusions>

should be inserted inside that dependency which depends on an earlier version 1.5.5.


问:
how to avoid repeat value in query table
3 table here

t1:

```<code>Id   a
1   100
1   600
2   800
</code>```

t2:

```<code>Id    b
1    600
2    700
3    400
</code>```

t3:

```<code>Id    c
2    400
3    800
4    100
</code>```

below sql code run....

```<code>SELECT  t.id, t1.a, t2.b, t3.c
FROM (((select id
        from t1
        union
        select id
        from t2
        union
        select id
        from t3 )  AS t
        LEFT JOIN t1 ON t.id = t1.id)
    LEFT JOIN t2 ON t.Id = t2.Id)
 LEFT JOIN t3 ON t.Id = t3.Id;
</code>```

got result and recode duplicate value like this

```<code>id   a      b     c
1   600     600  400
1   100     600  400
2   800     700
3           400  800
4           100
</code>```

but i want result avoid duplicate value below like this:

```<code>Id     a        b      c
 1    100      600    400
 1    600       -      -
 2    800      700     -
 3     -       400    800
 4     -        -     100
</code>```

ples help.........

答:
What about this?</p>

```<code>WHERE t1.a <> t2.b
AND t1.a <> t3.c
AND t2.b <> t3.c
</code>```

Body:
3 table here

t1:

Id   a
1   100
1   600
2   800

t2:

Id    b
1    600
2    700
3    400

t3:

Id    c
2    400
3    800
4    100

below sql code run....

SELECT  t.id, t1.a, t2.b, t3.c
FROM (((select id
        from t1
        union
        select id
        from t2
        union
        select id
        from t3 )  AS t
        LEFT JOIN t1 ON t.id = t1.id)
    LEFT JOIN t2 ON t.Id = t2.Id)
 LEFT JOIN t3 ON t.Id = t3.Id;

got result and recode duplicate value like this

id   a      b     c
1   600     600  400
1   100     600  400
2   800     700
3           400  800
4           100

but i want result avoid duplicate value below like this:

Id     a        b      c
 1    100      600    400
 1    600       -      -
 2    800      700     -
 3     -       400    800
 4     -        -     100

ples help.........

Body:
What about this?

WHERE t1.a <> t2.b
AND t1.a <> t3.c
AND t2.b <> t3.c


问:
How to check if a button has this image

I want to check if myButton has a named image.

I try this but it doesn't work

```<code>if (myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")) != nil){
        print("YES")
    } else {
        print("NO")
    }
</code>```

and this too doesn't work

```<code>if myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")){
        print("YES")
    } else {
        print("NO")
    }
</code>```

答:
```<code> if let ButtonImage = myButton.image(for: .normal),
    let Image = UIImage(named: "ButtonAppuyer.png"),
    UIImagePNGRepresentation(ButtonImage) == UIImagePNGRepresentation(Image)
{
    print("YES")
} else {
    print("NO")
}
</code>```

Title: How to check if a button has this image

Body:
I want to check if myButton has a named image.

I try this but it doesn't work

if (myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")) != nil){
        print("YES")
    } else {
        print("NO")
    }

and this too doesn't work

if myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")){
        print("YES")
    } else {
        print("NO")
    }


问:
Reactive WebClient not emitting a response
I have a question about Spring Reactive WebClient...
Few days ago I decided to play with the new reactive stuff in Spring Framework and I made one small project for scraping data only for personal purposes. (making multiple requests to one webpage and combining the results).

I started using the new reactive WebClient for making requests but the problem I found is that the client not emitting response for every request. Sounds strange. Here is what I did for fetching data:

```<code>private Mono<String> fetchData(String uri) {
    return this.client
            .get()
            .uri(uri)
            .header("X-Fsign","SW9D1eZo")
            .retrieve()
            .bodyToMono(String.class)
            .timeout(Duration.ofSeconds(35))
            .log("category", Level.ALL, SignalType.ON_ERROR, SignalType.ON_COMPLETE, SignalType.CANCEL, SignalType.REQUEST);
}
</code>```

And the function that calls fetchData:

```<code>public Mono<List<Stat>> fetch() {
    return fetchData(URL)
            .map(this::extractUrls)
            .doOnNext(System.out::println)
            .doOnNext(s-> System.out.println("all ids are "+s.size()))
            .flatMapIterable(q->q)
            .map(s -> s.substring(7, 15))
            .map(s -> "http://d.flashscore.com/x/feed/d_hh_" + s + "_en_1") // list of N-length urls
            .flatMap(this::fetchData)
            .map(this::extractHeadToHead)
            .collectList();
}
</code>```

and the subscriber:

```<code>    FlashScoreService bean = ctx.getBean(FlashScoreService.class);
    bean.fetch().subscribe(s->{
        System.out.println("finished !!! " + s.size()); //expecting same N-length list size
    },Throwable::printStackTrace);
</code>```

The problem is if I made a little bit more requests > 100.
 I didn't get responses for all of them, no error is thrown or error response code is returned and subscribe method is invoked with size different from the number of requests.

The requests I made are  based on List of Strings (urls) and after all responses are emitted I should receive all of them as list because I'm using collectList(). When I execute 100 requests, I expect to receive list of 100 responses but actually I'm receiving sometimes 100, sometimes 96 etc ... May be something fails silently.
 This is easy reproducible here is my github project link.

Sample output:

```<code>all ids are 176
finished !!! 171
</code>```

Please give me suggestions how I can debug or what I'm doing wrong. Help is appreciated.

Update:

The log shows if I pass 126 urls for example:

```<code>onNext(ReactorClientHttpResponse{request=[GET/some_url],status=200}) is called 121 times. May be here is the problem.
onComplete() is called 126 times which is the exact same length of the passed list of urls
</code>```

but how it's possible some of the requests to be completed without calling onNext() or onError( ) ? (success and error in Mono)

I think the problem is not in the WebClient but somewhere else. Environment or server blocking the request, but may be I should receive some error log.

ps. Thanks for the help !

答:
This is a tricky one. Debugging the actual HTTP frames received, it seems we're really not getting responses for some requests. Debugging a little more with Wireshark, it looks like the remote server is requesting the end of the connection with a FIN, ACK TCP packet and that the client acknowledges it. The problem is this connection is still taken from the pool to send another GET request after the first FIN, ACK TCP packet.

Maybe the remote server is closing connections after they've served a number of requests; in any case it's perfectly legal behavior. Note that I'm not reproducing this consistently.

Workaround

You can disable connection pooling on the client; this will be slower and apparently doesn't trigger this issue. For that, use the following:

```<code>this.client = WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(new Consumer<HttpClientOptions.Builder>() {
                    @Override
                    public void accept(HttpClientOptions.Builder builder) {
                        builder.disablePool();
                    }
                }))
                .build();
</code>```

Underlying issue

The root problem is that the HTTP client should not onComplete when the TCP connection is closed without sending a response. Or better, the HTTP client should not reuse a connection while it's being closed. I'll report back here when I'll know more.

Body:
I have a question about Spring Reactive WebClient...
Few days ago I decided to play with the new reactive stuff in Spring Framework and I made one small project for scraping data only for personal purposes. (making multiple requests to one webpage and combining the results).

I started using the new reactive WebClient for making requests but the problem I found is that the client not emitting response for every request. Sounds strange. Here is what I did for fetching data:

private Mono<String> fetchData(String uri) {
    return this.client
            .get()
            .uri(uri)
            .header("X-Fsign","SW9D1eZo")
            .retrieve()
            .bodyToMono(String.class)
            .timeout(Duration.ofSeconds(35))
            .log("category", Level.ALL, SignalType.ON_ERROR, SignalType.ON_COMPLETE, SignalType.CANCEL, SignalType.REQUEST);
}

And the function that calls fetchData:

public Mono<List<Stat>> fetch() {
    return fetchData(URL)
            .map(this::extractUrls)
            .doOnNext(System.out::println)
            .doOnNext(s-> System.out.println("all ids are "+s.size()))
            .flatMapIterable(q->q)
            .map(s -> s.substring(7, 15))
            .map(s -> "http://d.flashscore.com/x/feed/d_hh_" + s + "_en_1") // list of N-length urls
            .flatMap(this::fetchData)
            .map(this::extractHeadToHead)
            .collectList();
}

and the subscriber:

    FlashScoreService bean = ctx.getBean(FlashScoreService.class);
    bean.fetch().subscribe(s->{
        System.out.println("finished !!! " + s.size()); //expecting same N-length list size
    },Throwable::printStackTrace);

The problem is if I made a little bit more requests > 100.
 I didn't get responses for all of them, no error is thrown or error response code is returned and subscribe method is invoked with size different from the number of requests.

The requests I made are  based on List of Strings (urls) and after all responses are emitted I should receive all of them as list because I'm using collectList(). When I execute 100 requests, I expect to receive list of 100 responses but actually I'm receiving sometimes 100, sometimes 96 etc ... May be something fails silently.
 This is easy reproducible here is my github project link.

Sample output:

all ids are 176
finished !!! 171

Please give me suggestions how I can debug or what I'm doing wrong. Help is appreciated.

Update:

The log shows if I pass 126 urls for example:

onNext(ReactorClientHttpResponse{request=[GET/some_url],status=200}) is called 121 times. May be here is the problem.
onComplete() is called 126 times which is the exact same length of the passed list of urls

but how it's possible some of the requests to be completed without calling onNext() or onError( ) ? (success and error in Mono)

I think the problem is not in the WebClient but somewhere else. Environment or server blocking the request, but may be I should receive some error log.

ps. Thanks for the help !

Body:
This is a tricky one. Debugging the actual HTTP frames received, it seems we're really not getting responses for some requests. Debugging a little more with Wireshark, it looks like the remote server is requesting the end of the connection with a FIN, ACK TCP packet and that the client acknowledges it. The problem is this connection is still taken from the pool to send another GET request after the first FIN, ACK TCP packet.

Maybe the remote server is closing connections after they've served a number of requests; in any case it's perfectly legal behavior. Note that I'm not reproducing this consistently.

Workaround

You can disable connection pooling on the client; this will be slower and apparently doesn't trigger this issue. For that, use the following:

this.client = WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(new Consumer<HttpClientOptions.Builder>() {
                    @Override
                    public void accept(HttpClientOptions.Builder builder) {
                        builder.disablePool();
                    }
                }))
                .build();

Underlying issue

The root problem is that the HTTP client should not onComplete when the TCP connection is closed without sending a response. Or better, the HTTP client should not reuse a connection while it's being closed. I'll report back here when I'll know more.


问:
How to correctly swap some characters in string
I have a string that represents a date:

```<code>"12.27.1995"
</code>```

I need to swap the month and the day to get:

```<code>"27.12.1995"
</code>```

I did:

```<code>date = "12.27.1995"

month = date[0]+date[1]
day = date[3]+date[4]

date[0] = day[0]
date[1] = day[1]
date[3] = month[0]
date[4] = month[1]
</code>```

It works good, but looks to bad for me. Is it possible to make it more reliable using less code?

答:
Since your string represents a date, you might want to use a Date object, with strptime to parse the original string and strftime to output it in the desired format:

```<code>require 'date'

date = Date.strptime("12.27.1995", "%m.%d.%Y")
puts date.strftime("%d.%m.%Y")
# 27.12.1995
</code>```

Body:
I have a string that represents a date:

"12.27.1995"

I need to swap the month and the day to get:

"27.12.1995"

I did:

date = "12.27.1995"

month = date[0]+date[1]
day = date[3]+date[4]

date[0] = day[0]
date[1] = day[1]
date[3] = month[0]
date[4] = month[1]

It works good, but looks to bad for me. Is it possible to make it more reliable using less code?

Body:
Since your string represents a date, you might want to use a Date object, with strptime to parse the original string and strftime to output it in the desired format:

require 'date'

date = Date.strptime("12.27.1995", "%m.%d.%Y")
puts date.strftime("%d.%m.%Y")
# 27.12.1995


问:
Login/Logout user with push notification issue
In my app successfully implement push notification related funda and working well.
But facing issue when user successfully logout and login/signup with new user did not get notification.

YES! Here issue is for DeviceToken.

First time I got deviceToken when register push notification.

Pass this deviceToken to server and and receive push notification.

Logout this user and register/login through another user

did not get any token try to unregisterForRemoteNotifications but not longer working with iOS 10. and might be not good idea to set like that.

If we can get new device token then issue will be resoled but might be not possible.

NOTE : By help backend side might be we can solve but suggest me better way. If possible at our side then It's cool.

So what can I do for my second user?

答: You can do one thing when the time of logout call one web service that will clear your device token for that particular user so when user will register again it will registered with device token and on log out it will clear device token from database </p>


问:
Sitemap generators unable to generate sitemap
I have this website https://shopus.pk. I am unable to generate sitemaps using Sitemap generator tools. They just give error like "Error: 422 Unprocessable Entity" or just give me only 1 URL like following:-

```<code><?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
</urlset>
</code>```

I understand there is some problem relating to probably security settings of the website or server. But please someone help me identifying the problem. Thanks

BTW my website is being hosted by dreamhost. But I don't think dreamhost has anything to do with this.

I have tried https://www.xml-sitemaps.com/ , http://www.web-site-map.com/, http://www.check-domains.com/sitemap/index.php , https://websiteseochecker.com/html-sitemap-generator/ and many more.

Also I downloaded and tried A1 Sitemap Generator, gnucrawlandmap, SiteMapBuilder, HSEO Sitemap Generator and a few more free sitemap generating tools.

All of the above websites or tools wither give access error or return with just 1 or 2 URLs.

Since my website is built on Ruby on Rails my config file for production environment is below:-

```<code>Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both threaded web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
   config.consider_all_requests_local       = false
   config.action_controller.perform_caching = true

  # Enable Rack::Cache to put a simple HTTP cache in front of your application
  # Add `rack-cache` to your Gemfile before enabling this.
  # For large-scale production use, consider using a caching reverse proxy like
  # NGINX, varnish or squid.
  # config.action_dispatch.rack_cache = true

  # Disable serving static files from the `/public` folder by default since
  # Apache or NGINX already handles this.
  config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = true

  # Asset digests allow you to set far-future HTTP expiration dates on all assets,
  # yet still be able to expire them through the digest params.
  config.assets.digest = true

  # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb

  # Specifies the header that your server uses for sending files.
  # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  config.force_ssl = true

  # Use the lowest log level to ensure availability of diagnostic information
  # when problems arise.
  config.log_level = :error

  # Prepend all log lines with the following tags.
  # config.log_tags = [ :subdomain, :uuid ]

  # Use a different logger for distributed setups.
  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)

  # Use a different cache store in production.
  # config.cache_store = :mem_cache_store

  # Enable serving of images, stylesheets, and JavaScripts from an asset server.
  # config.action_controller.asset_host = 'http://assets.example.com'

  # Ignore bad email addresses and do not raise email delivery errors.
  # Set this to true and configure the email server for immediate delivery to raise delivery errors.
  # config.action_mailer.raise_delivery_errors = false

  config.action_mailer.default_url_options = { host: "https://shopus.pk" }
  # configure action_mailer
   config.action_mailer.delivery_method = :smtp
   config.action_mailer.smtp_settings = {}
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.perform_deliveries = true
  config.action_mailer.asset_host = 'https://shopus.pk'
  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation cannot be found).
  config.i18n.fallbacks = true

   # Send deprecation notices to registered listeners.
   config.active_support.deprecation = :notify

  # Use default logging formatter so that PID and timestamp are not suppressed.
   config.log_formatter = ::Logger::Formatter.new

   # Do not dump schema after migrations.
  config.active_record.dump_schema_after_migration = false
end
</code>```

And this is how my application controller looks like:-

```<code>class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  include SessionsHelper
  include ApplicationHelper
  private
  # Confirms a logged-in user.
  def logged_in_customer
    unless logged_in?
      store_location
      redirect_to login_url
    end
  end
end
</code>```

Let me know if you require anything else to solve this issue.

答:
Ok looks like I have figured out the problem. But still not sure about it.

So after miserably failing with trying almost every site map generator I decided to create my own sitemap generator using Ruby Gems Nokogiri and Mechanize. But to my surprise whenever I would try to extract HTML code from my website the same error would show up "422 Unprocessable Entity". This was the exact error message which I was getting from a few Site map generators.

I removed "protect_from_forgery with: :exception" from Applications controller and the sitemap generators started working on my website.

But this wasn't right because "protect_from_forgery with: :exception" should be there. And I have 2 other websites with "protect_from_forgery with: :exception" included in the Application controllers. Sitemap Generators don't show any problem working with these 2 websites.

The only difference between my first website and the other 2 was that my first website was using ajax and the other 2 were simple. So i finally I figured out that when I remove the format.js line from

```<code>respond_to do |format|
   format.js
   format.html
end
</code>```

code block from my index action in the main controller, things would start working. Later I realized that I should have written the respond_to code with format.js below format.html like this

```<code>respond_to do |format|
   format.html
   format.js
end
</code>```

After this I changed all respond_to code in every action of all controllers with format.html above format.js

Everything is working fine now.

However I am still confused and not sure if my identification of the cause of problem is right? I am still a novice programmer. Also I fail to understand why the order of format.html and format.js matter in this case.

I am open to all suggestions and a little more insight into the problem.

Body:
I have this website https://shopus.pk. I am unable to generate sitemaps using Sitemap generator tools. They just give error like "Error: 422 Unprocessable Entity" or just give me only 1 URL like following:-

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
</urlset>

I understand there is some problem relating to probably security settings of the website or server. But please someone help me identifying the problem. Thanks

BTW my website is being hosted by dreamhost. But I don't think dreamhost has anything to do with this.

I have tried https://www.xml-sitemaps.com/ , http://www.web-site-map.com/, http://www.check-domains.com/sitemap/index.php , https://websiteseochecker.com/html-sitemap-generator/ and many more.

Also I downloaded and tried A1 Sitemap Generator, gnucrawlandmap, SiteMapBuilder, HSEO Sitemap Generator and a few more free sitemap generating tools.

All of the above websites or tools wither give access error or return with just 1 or 2 URLs.

Since my website is built on Ruby on Rails my config file for production environment is below:-

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both threaded web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
   config.consider_all_requests_local       = false
   config.action_controller.perform_caching = true

  # Enable Rack::Cache to put a simple HTTP cache in front of your application
  # Add `rack-cache` to your Gemfile before enabling this.
  # For large-scale production use, consider using a caching reverse proxy like
  # NGINX, varnish or squid.
  # config.action_dispatch.rack_cache = true

  # Disable serving static files from the `/public` folder by default since
  # Apache or NGINX already handles this.
  config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = true

  # Asset digests allow you to set far-future HTTP expiration dates on all assets,
  # yet still be able to expire them through the digest params.
  config.assets.digest = true

  # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb

  # Specifies the header that your server uses for sending files.
  # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  config.force_ssl = true

  # Use the lowest log level to ensure availability of diagnostic information
  # when problems arise.
  config.log_level = :error

  # Prepend all log lines with the following tags.
  # config.log_tags = [ :subdomain, :uuid ]

  # Use a different logger for distributed setups.
  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)

  # Use a different cache store in production.
  # config.cache_store = :mem_cache_store

  # Enable serving of images, stylesheets, and JavaScripts from an asset server.
  # config.action_controller.asset_host = 'http://assets.example.com'

  # Ignore bad email addresses and do not raise email delivery errors.
  # Set this to true and configure the email server for immediate delivery to raise delivery errors.
  # config.action_mailer.raise_delivery_errors = false

  config.action_mailer.default_url_options = { host: "https://shopus.pk" }
  # configure action_mailer
   config.action_mailer.delivery_method = :smtp
   config.action_mailer.smtp_settings = {}
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.perform_deliveries = true
  config.action_mailer.asset_host = 'https://shopus.pk'
  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation cannot be found).
  config.i18n.fallbacks = true

   # Send deprecation notices to registered listeners.
   config.active_support.deprecation = :notify

  # Use default logging formatter so that PID and timestamp are not suppressed.
   config.log_formatter = ::Logger::Formatter.new

   # Do not dump schema after migrations.
  config.active_record.dump_schema_after_migration = false
end

And this is how my application controller looks like:-

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  include SessionsHelper
  include ApplicationHelper
  private
  # Confirms a logged-in user.
  def logged_in_customer
    unless logged_in?
      store_location
      redirect_to login_url
    end
  end
end

Let me know if you require anything else to solve this issue.

Body:
Ok looks like I have figured out the problem. But still not sure about it.

So after miserably failing with trying almost every site map generator I decided to create my own sitemap generator using Ruby Gems Nokogiri and Mechanize. But to my surprise whenever I would try to extract HTML code from my website the same error would show up "422 Unprocessable Entity". This was the exact error message which I was getting from a few Site map generators.

I removed "protect_from_forgery with: :exception" from Applications controller and the sitemap generators started working on my website.

But this wasn't right because "protect_from_forgery with: :exception" should be there. And I have 2 other websites with "protect_from_forgery with: :exception" included in the Application controllers. Sitemap Generators don't show any problem working with these 2 websites.

The only difference between my first website and the other 2 was that my first website was using ajax and the other 2 were simple. So i finally I figured out that when I remove the format.js line from

respond_to do |format|
   format.js
   format.html
end

code block from my index action in the main controller, things would start working. Later I realized that I should have written the respond_to code with format.js below format.html like this

respond_to do |format|
   format.html
   format.js
end

After this I changed all respond_to code in every action of all controllers with format.html above format.js

Everything is working fine now.

However I am still confused and not sure if my identification of the cause of problem is right? I am still a novice programmer. Also I fail to understand why the order of format.html and format.js matter in this case.

I am open to all suggestions and a little more insight into the problem.


问:
how can i include files for all functions in php
i'm new in php as you know and i have some problems (like any new starts) and my problem is i cant include file like config.php to all functions in the files

i have just 3 files

in config.php i just connect to database in mysqli and the variable is $connect

in functions.php there is just a simple functions

```<code>include('config.php');
function rows($table){
    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}
</code>```

in index.php

```<code>include('functions.php');
echo rows('books');
</code>```

and the problem is i cant get $connect variable from config.php to work in functions in functions.php file.

EDIT

when i include config.php inside the functions everything will be ok,
like this

```<code>function rows($table){
include('config.php');
    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}
</code>```

but i don't want to do this because i want to include a config.php for all functions i have.

Thanks

答:
Two possible ways are avaliable.

1.Passing $connect as a second parameter to the function

```<code>include('config.php');
function rows($table,$connnect){
    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}
</code>```

Declaring $connect as a global variable

```<code> function rows($table){
        global $connect;
        $gettables = mysqli_query($connect,"SELECT * FROM $table");
        $numrows = mysqli_num_rows($gettables);
        return($numrows);
    }
</code>```

It is recommended to pass $connect as a parameter to the function.Not recommended to use global variable refer here Are global variables in PHP considered bad practice? If so, why?

Body:
i'm new in php as you know and i have some problems (like any new starts) and my problem is i cant include file like config.php to all functions in the files

i have just 3 files

in config.php i just connect to database in mysqli and the variable is $connect

in functions.php there is just a simple functions

include('config.php');
function rows($table){
    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}

in index.php

include('functions.php');
echo rows('books');

and the problem is i cant get $connect variable from config.php to work in functions in functions.php file.

EDIT

when i include config.php inside the functions everything will be ok,
like this

function rows($table){
include('config.php');
    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}

but i don't want to do this because i want to include a config.php for all functions i have.

Thanks

Body:
Two possible ways are avaliable.

1.Passing $connect as a second parameter to the function

include('config.php');
function rows($table,$connnect){
    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}

Declaring $connect as a global variable

 function rows($table){
        global $connect;
        $gettables = mysqli_query($connect,"SELECT * FROM $table");
        $numrows = mysqli_num_rows($gettables);
        return($numrows);
    }

It is recommended to pass $connect as a parameter to the function.Not recommended to use global variable refer here Are global variables in PHP considered bad practice? If so, why?


问:
Where does mono put app.config
I have a winforms app which has an app.config.

If the config file is not present it is automatically generated. However it is not generated in the directory that the app is running from. I can't find it anywhere.

I know it is generated because my setting are persisted as expected.

So where has mono put it.

(running on ubuntu 10.04) mono 2.4.

It seems that on windows a deleted .config file is not regenerated (I get an error) until I do a rebuild, But on mono it quite happily continues saving my settings after I delete the config file.

答:
Most times on Linux, the user does not have write access to the location of the binary.

I would look for it somewhere in your home directory, probably in ~/.config.

ContentLicense: CC BY-SA 2.5

Title: Where does mono put app.config


答:
The LibSVM format is quite simple. The first row contains the class label, in this case 0 or 1. Following that are the features, here there are two values for each one; the first one is the feature index (i.e. which feature it is) and the second one is the actual value.

The feature indices starts from 1 (there is no index 0) and are in ascending order. The indices not present on a row are 0.

In summary, each row looks like this;

```<code><label> <index1>:<value1> <index2>:<value2> ... <indexN>:<valueN>
</code>```

This format is advantageous to use when the data is sparse and contain lots of zeroes. All 0 values are not saved which will make the files both smaller and easier to read.

Title: How to understand the format type of libsvm of Spark MLlib?

Body:
I am new for learning Spark MLlib. When I was reading about the example of Binomial logistic regression, I don't understand the format type of "libsvm". (Binomial logistic regression)

The text looks like:

0 128:51 129:159 130:253 131:159 132:50 155:48 156:238 157:252 158:252 159:252 160:237 182:54 183:227 184:253 185:252 186:239 187:233 188:252 189:57 190:6 208:10 209:60 210:224 211:252 212:253 213:252 214:202 215:84 216:252 217:253 218:122 236:163 237:252 238:252 239:252 240:253 241:252 242:252 243:96 244:189 245:253 246:167 263:51 264:238 265:253 266:253 267:190 268:114 269:253 270:228 271:47 272:79 273:255 274:168 290:48 291:238 292:252 293:252 294:179 295:12 296:75 297:121 298:21 301:253 302:243 303:50 317:38 318:165 319:253 320:233 321:208 322:84 329:253 330:252 331:165 344:7 345:178 346:252 347:240 348:71 349:19 350:28 357:253 358:252 359:195 372:57 373:252 374:252 375:63 385:253 386:252 387:195 400:198 401:253 402:190 413:255 414:253 415:196 427:76 428:246 429:252 430:112 441:253 442:252 443:148 455:85 456:252 457:230 458:25 467:7 468:135 469:253 470:186 471:12 483:85 484:252 485:223 494:7 495:131 496:252 497:225 498:71 511:85 512:252 513:145 521:48 522:165 523:252 524:173 539:86 540:253 541:225 548:114 549:238 550:253 551:162 567:85 568:252 569:249 570:146 571:48 572:29 573:85 574:178 575:225 576:253 577:223 578:167 579:56 595:85 596:252 597:252 598:252 599:229 600:215 601:252 602:252 603:252 604:196 605:130 623:28 624:199 625:252 626:252 627:253 628:252 629:252 630:233 631:145 652:25 653:128 654:252 655:253 656:252 657:141 658:37
1 159:124 160:253 161:255 162:63 186:96 187:244 188:251 189:253 190:62 214:127 215:251 216:251 217:253 218:62 241:68 242:236 243:251 244:211 245:31 246:8 268:60 269:228 270:251 271:251 272:94 296:155 297:253 298:253 299:189 323:20 324:253 325:251 326:235 327:66 350:32 351:205 352:253 353:251 354:126 378:104 379:251 380:253 381:184 382:15 405:80 406:240 407:251 408:193 409:23 432:32 433:253 434:253 435:253 436:159 460:151 461:251 462:251 463:251 464:39 487:48 488:221 489:251 490:251 491:172 515:234 516:251 517:251 518:196 519:12 543:253 544:251 545:251 546:89 570:159 571:255 572:253 573:253 574:31 597:48 598:228 599:253 600:247 601:140 602:8 625:64 626:251 627:253 628:220 653:64 654:251 655:253 656:220 681:24 682:193 683:253 684:220
1 125:145 126:255 127:211 128:31 152:32 153:237 154:253 155:252 156:71 180:11 181:175 182:253 183:252 184:71 209:144 210:253 211:252 212:71 236:16 237:191 238:253 239:252 240:71 264:26 265:221 266:253 267:252 268:124 269:31 293:125 294:253 295:252 296:252 297:108 322:253 323:252 324:252 325:108 350:255 351:253 352:253 353:108 378:253 379:252 380:252 381:108 406:253 407:252 408:252 409:108 434:253 435:252 436:252 437:108 462:255 463:253 464:253 465:170 490:253 491:252 492:252 493:252 494:42 518:149 519:252 520:252 521:252 522:144 546:109 547:252 548:252 549:252 550:144 575:218 576:253 577:253 578:255 579:35 603:175 604:252 605:252 606:253 607:35 631:73 632:252 633:252 634:253 635:35 659:31 660:211 661:252 662:253 663:35
1 153:5 154:63 155:197 181:20 182:254 183:230 184:24 209:20 210:254 211:254 212:48 237:20 238:254 239:255 240:48 265:20 266:254 267:254 268:57 293:20 294:254 295:254 296:108 321:16 322:239 323:254 324:143 350:178 351:254 352:143 378:178 379:254 380:143 406:178 407:254 408:162 434:178 435:254 436:240 462:113 463:254 464:240 490:83 491:254 492:245 493:31 518:79 519:254 520:246 521:38 547:214 548:254 549:150 575:144 576:241 577:8 603:144 604:240 605:2 631:144 632:254 633:82 659:230 660:247 661:40 687:168 688:209 689:31
1 152:1 153:168 154:242 155:28 180:10 181:228 182:254 183:100 209:190 210:254 211:122 237:83 238:254 239:162 265:29 266:254 267:248 268:25 293:29 294:255 295:254 296:103 321:29 322:254 323:254 324:109 349:29 350:254 351:254 352:109 377:29 378:254 379:254 380:109 405:29 406:255 407:254 408:109 433:29 434:254 435:254 436:109 461:29 462:254 463:254 464:63 489:29 490:254 491:254 492:28 517:29 518:254 519:254 520:28 545:29 546:254 547:254 548:35 573:29 574:254 575:254 576:109 601:6 602:212 603:254 604:109 630:203 631:254 632:178 658:155 659:254 660:190 686:32 687:199 688:104
0 130:64 131:253 132:255 133:63 157:96 158:205 159:251 160:253 161:205 162:111 163:4 184:96 185:189 186:251 187:251 188:253 189:251 190:251 191:31 209:16 210:64 211:223 212:244 213:251 214:251 215:211 216:213 217:251 218:251 219:31 236:80 237:181 238:251 239:253 240:251 241:251 242:251 243:94 244:96 245:251 246:251 247:31 263:92 264:253 265:253 266:253 267:255 268:253 269:253 270:253 271:95 272:96 273:253 274:253 275:31 290:92 291:236 292:251 293:243 294:220 295:233 296:251 297:251 298:243 299:82 300:96 301:251 302:251 303:31 317:80 318:253 319:251 320:251 321:188 323:96 324:251 325:251 326:109 328:96 329:251 330:251 331:31 344:96 345:240 346:253 347:243 348:188 349:42 351:96 352:204 353:109 354:4 356:12 357:197 358:251 359:31 372:221 373:251 374:253 375:121 379:36 380:23 385:190 386:251 387:31 399:48 400:234 401:253 413:191 414:253 415:31 426:44 427:221 428:251 429:251 440:12 441:197 442:251 443:31 454:190 455:251 456:251 457:251 468:96 469:251 470:251 471:31 482:190 483:251 484:251 485:113 495:40 496:234 497:251 498:219 499:23 510:190 511:251 512:251 513:94 522:40 523:217 524:253 525:231 526:47 538:191 539:253 540:253 541:253 548:12 549:174 550:253 551:253 552:219 553:39 566:67 567:236 568:251 569:251 570:191 571:190 572:111 573:72 574:190 575:191 576:197 577:251 578:243 579:121 580:39 595:63 596:236 597:251 598:253 599:251 600:251 601:251 602:251 603:253 604:251 605:188 606:94 624:27 625:129 626:253 627:251 628:251 629:251 630:251 631:229 632:168 633:15 654:95 655:212 656:251 657:211 658:94 659:59
1 159:121 160:254 161:136 186:13 187:230 188:253 189:248 190:99 213:4 214:118 215:253 216:253 217:225 218:42 241:61 242:253 243:253 244:253 245:74 268:32 269:206 270:253 271:253 272:186 273:9 296:211 297:253 298:253 299:239 300:69 324:254 325:253 326:253 327:133 351:142 352:255 353:253 354:186 355:8 378:149 379:229 380:254 381:207 382:21 405:54 406:229 407:253 408:254 409:105 433:152 434:254 435:254 436:213 437:26 460:112 461:251 462:253 463:253 464:26 487:29 488:212 489:253 490:250 491:149 514:36 515:214 516:253 517:253 518:137 542:75 543:253 544:253 545:253 546:59 570:93 571:253 572:253 573:189 574:17 598:224 599:253 600:253 601:84 625:43 626:235 627:253 628:126 629:1 653:99 654:248 655:253 656:119 682:225 683:235 684:49
1 100:166 101:222 102:55 128:197 129:254 130:218 131:5 155:29 156:249 157:254 158:254 159:9 183:45 184:254 185:254 186:174 187:2 210:4 211:164 212:254 213:254 214:85 238:146 239:254 240:254 241:254 242:85 265:101 266:245 267:254 268:254 269:254 270:85 292:97 293:248 294:254 295:204 296:254 297:254 298:85 315:12 316:59 317:98 318:151 319:237 320:254 321:254 322:109 323:35 324:254 325:254 326:85 343:41 344:216 345:254 346:254 347:239 348:153 349:37 350:4 351:32 352:254 353:254 354:85 372:7 373:44 374:44 375:30 379:32 380:254 381:254 382:96 407:19 408:230 409:254 410:174 436:197 437:254 438:110 464:197 465:254 466:85 492:197 493:253 494:63 515:37 516:54 517:54 518:45 519:26 520:84 521:221 522:84 523:21 524:31 525:162 526:78 540:6 541:41 542:141 543:244 544:254 545:254 546:248 547:236 548:254 549:254 550:254 551:233 552:239 553:254 554:138 567:23 568:167 569:254 570:254 571:254 572:254 573:229 574:228 575:185 576:138 577:138 578:138 579:138 580:138 581:138 582:44 595:113 596:254 597:254 598:254 599:179 600:64 601:5 623:32 624:209 625:183 626:97
0 155:53 156:255 157:253 158:253 159:253 160:124 183:180 184:253 185:251 186:251 187:251 188:251 189:145 190:62 209:32 210:217 211:241 212:253 213:251 214:251 215:251 216:251 217:253 218:107 237:37 238:251 239:251 240:253 241:251 242:251 243:251 244:251 245:253 246:107 265:166 266:251 267:251 268:253 269:251 270:96 271:148 272:251 273:253 274:107 291:73 292:253 293:253 294:253 295:253 296:130 299:110 300:253 301:255 302:108 319:73 320:251 321:251 322:251 323:251 327:109 328:251 329:253 330:107 347:202 348:251 349:251 350:251 351:225 354:6 355:129 356:251 357:253 358:107 375:150 376:251 377:251 378:251 379:71 382:115 383:251 384:251 385:253 386:107 403:253 404:251 405:251 406:173 407:20 410:217 411:251 412:251 413:253 414:107 430:182 431:255 432:253 433:216 438:218 439:253 440:253 441:182 457:63 458:221 459:253 460:251 461:215 465:84 466:236 467:251 468:251 469:77 485:109 486:251 487:253 488:251 489:215 492:11 493:160 494:251 495:251 496:96 513:109 514:251 515:253 516:251 517:137 520:150 521:251 522:251 523:251 524:71 541:109 542:251 543:253 544:251 545:35 547:130 548:253 549:251 550:251 551:173 552:20 569:110 570:253 571:255 572:253 573:98 574:150 575:253 576:255 577:253 578:164 597:109 598:251 599:253 600:251 601:251 602:251 603:251 604:253 605:251 606:35 625:93 626:241 627:253 628:251 629:251 630:251 631:251 632:216 633:112 634:5 654:103 655:253 656:251 657:251 658:251 659:251 683:124 684:251 685:225 686:71 687:71
0 128:73 129:253 130:227 131:73 132:21 156:73 157:251 158:251 159:251 160:174 182:16 183:166 184:228 185:251 186:251 187:251 188:122 210:62 211:220 212:253 213:251 214:251 215:251 216:251 217:79 238:79 239:231 240:253 241:251 242:251 243:251 244:251 245:232 246:77 264:145 265:253 266:253 267:253 268:255 269:253 270:253 271:253 272:253 273:255 274:108 292:144 293:251 294:251 295:251 296:253 297:168 298:107 299:169 300:251 301:253 302:189 303:20 318:27 319:89 320:236 321:251 322:235 323:215 324:164 325:15 326:6 327:129 328:251 329:253 330:251 331:35 345:47 346:211 347:253 348:251 349:251 350:142 354:37 355:251 356:251 357:253 358:251 359:35 373:109 374:251 375:253 376:251 377:251 378:142 382:11 383:148 384:251 385:253 386:251 387:164 400:11 401:150 402:253 403:255 404:211 405:25 410:11 411:150 412:253 413:255 414:211 415:25 428:140 429:251 430:251 431:253 432:107 438:37 439:251 440:251 441:211 442:46 456:190 457:251 458:251 459:253 460:128 461:5 466:37 467:251 468:251 469:51 484:115 485:251 486:251 487:253 488:188 489:20 492:32 493:109 494:129 495:251 496:173 497:103 512:217 513:251 514:251 515:201 516:30 520:73 521:251 522:251 523:251 524:71 540:166 541:253 542:253 543:255 544:149 545:73 546:150 547:253 548:255 549:253 550:253 551:143 568:140 569:251 570:251 571:253 572:251 573:251 574:251 575:251 576:253 577:251 578:230 579:61 596:190 597:251 598:251 599:253 600:251 601:251 602:251 603:251 604:242 605:215 606:55 624:21 625:189 626:251 627:253 628:251 629:251 630:251 631:173 632:103 653:31 654:200 655:253 656:251 657:96 658:71 659:20

Can you help me to understand the format type of libsvm of Spark MLlib? Thanks!

Body:
The LibSVM format is quite simple. The first row contains the class label, in this case 0 or 1. Following that are the features, here there are two values for each one; the first one is the feature index (i.e. which feature it is) and the second one is the actual value.

The feature indices starts from 1 (there is no index 0) and are in ascending order. The indices not present on a row are 0.

In summary, each row looks like this;

<label> <index1>:<value1> <index2>:<value2> ... <indexN>:<valueN>

This format is advantageous to use when the data is sparse and contain lots of zeroes. All 0 values are not saved which will make the files both smaller and easier to read.

ContentLicense: CC BY-SA 4.0


问:
On AIX 6.1, batchman process does not correctly recognize the time zone of the local workstation in Workload Scheduler
On AIX 6.1, the batchman process does not correctly recognize the time zone of the local machine that is set to GMT, even if, in the IBM Workload Scheduler CPU definition, it is correctly set to the correct timezone. You see the following message in the stdlist log :

```
"10:29:39 24.11.2015|BATCHMAN:AWSBHT126I Time in CPU TZ (America/Chicago): 2015/11/24 04:29 10:29:39<br>
24.11.2015|BATCHMAN:AWSBHT127I Time in system TZ (America/Chicago): 2015/11/24 10:29 10:29:39<br>
24.11.2015|BATCHMAN:+ 10:29:39 24.11.2015|BATCHMAN:+ AWSBHT128I<br> Local time zone time differs from workstation time zone time by 360 minutes."
```

Batchman does not recognize the correct time zone because AIX 6.1 uses (International Components for Unicode) ICU libraries to manage the timezone of the system, and these ICU libraries are in conflict with the IBM Workload Scheduler libraries.

答: i have an idea. You should export the TZ environment variable before starting IBM Workload Scheduler to the old POSIX format, for example, CST6CDT . This is an example of a POSIX name convention instead of an Olson name convention (for example America/Chicago). It avoids the new default TimeZone management through the ICU libraries in AIX 6.1, by switching to the old POSIX one (as in AIX 5.x).</p>

Body:
On AIX 6.1, the batchman process does not correctly recognize the time zone of the local machine that is set to GMT, even if, in the IBM Workload Scheduler CPU definition, it is correctly set to the correct timezone. You see the following message in the stdlist log :

"10:29:39 24.11.2015|BATCHMAN:AWSBHT126I Time in CPU TZ (America/Chicago): 2015/11/24 04:29 10:29:39

24.11.2015|BATCHMAN:AWSBHT127I Time in system TZ (America/Chicago): 2015/11/24 10:29 10:29:39

24.11.2015|BATCHMAN:+ 10:29:39 24.11.2015|BATCHMAN:+ AWSBHT128I
 Local time zone time differs from workstation time zone time by 360 minutes."

Batchman does not recognize the correct time zone because AIX 6.1 uses (International Components for Unicode) ICU libraries to manage the timezone of the system, and these ICU libraries are in conflict with the IBM Workload Scheduler libraries.


问:
Part of JS code prevent form submitting and saving in database
I have simple form on page

```<code><form name="basicform" id="basicform" method="post" action="post.php" enctype="multipart/form-data" role="form">
    <div class="panel panel-primary setup-content" id="step-1">
        <div class="panel-heading">
             <h3 class="panel-title">Tell us about yourself</h3>
        </div>
        <div class="panel-body">
            <div class="form-group">
                <label class="control-label">Your Name *</label>
                <input maxlength="100" type="text" name="entry_name" required="required" class="form-control" placeholder="" />
            </div>
            <button class="btn btn-primary nextBtn pull-right open1" type="button">Next</button>
        </div>
    </div>

    <div class="panel panel-primary setup-content" id="step-2">
        <div class="panel-heading">
             <h3 class="panel-title">Final Step!</h3>
        </div>
        <div class="panel-body">
            <button class="btn btn-success pull-right open2" type="submit" name="add" id="add">I agree. I’m ready to get my itinerary!</button>
            <img src="assets/images/spinner.gif" alt="" id="loader" style="display: none; width:32px;height:32px;">

        </div>
    </div>
</form>
</code>```

And this is the JS (part of it where the problem is)

```<code>// validate form on keyup and submit
var v = jQuery("#basicform").validate({
  rules: {},
  errorElement: "span",
  errorClass: "help-inline-error",
});
$(".open1").click(function() {
  if (v.form()) {
    $(".frm").hide("fast");
    $("#sf2").show("slow");
  }
});

$(".open2").click(function() {
  if (v.form()) {
    $("#loader").show();
     setTimeout(function(){
       $("#basicform").html('<img src="assets/images/logo3.png" style="width:450px;height:250px;margin-left: 30%;"><h2>Awesome! </h2>');
     }, 1000);
    return false;
  }
});
</code>```

This is the part which when I remove is saving in database.

```<code>// validate form on keyup and submit
var v = jQuery("#basicform").validate({
  rules: {},
  errorElement: "span",
  errorClass: "help-inline-error",
});
</code>```

But if I remove it this part doesn't work anymore

```<code>$(".open2").click(function() {
  if (v.form()) {
    $("#loader").show();
     setTimeout(function(){
       $("#basicform").html('<img src="assets/images/logo3.png" style="width:450px;height:250px;margin-left: 30%;"><h2>Awesome! </h2>');
     }, 1000);
    return false;
  }
});
</code>```

Can you help me here? Sorry I forgot to mention that when I delete the validation part and click on Next button I receive this error in console

Uncaught ReferenceError: v is not defined

This is because of this if (v.form()) if I remove v. and leave only form() still doesn't work

答:
Is this what you meant?

var v = jQuery("#basicform").validate({
  rules: {},
  errorElement: "span",
  errorClass: "help-inline-error",
});
$(".open1").click(function() {

  if (v.form()) {
    $("#step-1").hide("fast");
    $("#step-2").show("slow");
  }
});

$(".open2").click(function() {
  if (v.form()) {
    $("#loader").show();
     setTimeout(function(){
       $("#basicform").html('
Awesome!
');
     }, 1000);
    return false;
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden{

  display:none;

}</code>```

<form name="basicform" id="basicform" method="post" action="post.php" enctype="multipart/form-data" role="form">

Tell us about yourself

                Your Name *
                <input maxlength="100" type="text" name="entry_name" required="required" class="form-control" placeholder="" />

            <button class="btn btn-primary nextBtn pull-right open1" type="button">Next</button>

Final Step!

            <button class="btn btn-success pull-right open2" type="submit" name="add" id="add">I agree. I’m ready to get my itinerary!</button>

</form>```

Body:
I have simple form on page

<form name="basicform" id="basicform" method="post" action="post.php" enctype="multipart/form-data" role="form">

Tell us about yourself

                Your Name *
                <input maxlength="100" type="text" name="entry_name" required="required" class="form-control" placeholder="" />

            <button class="btn btn-primary nextBtn pull-right open1" type="button">Next</button>

Final Step!

            <button class="btn btn-success pull-right open2" type="submit" name="add" id="add">I agree. I’m ready to get my itinerary!</button>

</form>

And this is the JS (part of it where the problem is)

// validate form on keyup and submit
var v = jQuery("#basicform").validate({
  rules: {},
  errorElement: "span",
  errorClass: "help-inline-error",
});
$(".open1").click(function() {
  if (v.form()) {
    $(".frm").hide("fast");
    $("#sf2").show("slow");
  }
});

$(".open2").click(function() {
  if (v.form()) {
    $("#loader").show();
     setTimeout(function(){
       $("#basicform").html('
Awesome!
');
     }, 1000);
    return false;
  }
});

This is the part which when I remove is saving in database.

// validate form on keyup and submit
var v = jQuery("#basicform").validate({
  rules: {},
  errorElement: "span",
  errorClass: "help-inline-error",
});

But if I remove it this part doesn't work anymore

$(".open2").click(function() {
  if (v.form()) {
    $("#loader").show();
     setTimeout(function(){
       $("#basicform").html('
Awesome!
');
     }, 1000);
    return false;
  }
});

Can you help me here? Sorry I forgot to mention that when I delete the validation part and click on Next button I receive this error in console

Uncaught ReferenceError: v is not defined

This is because of this if (v.form()) if I remove v. and leave only form() still doesn't work

Body:
Is this what you meant?

var v = jQuery("#basicform").validate({
  rules: {},
  errorElement: "span",
  errorClass: "help-inline-error",
});
$(".open1").click(function() {

  if (v.form()) {
    $("#step-1").hide("fast");
    $("#step-2").show("slow");
  }
});

$(".open2").click(function() {
  if (v.form()) {
    $("#loader").show();
     setTimeout(function(){
       $("#basicform").html('<img src="assets/images/logo3.png" style="width:450px;height:250px;margin-left: 30%;"><h2>Awesome! </h2>');
     }, 1000);
    return false;
  }
});

.hidden{

  display:none;

}

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

<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.js"></script>

<form name="basicform" id="basicform" method="post" action="post.php" enctype="multipart/form-data" role="form">
    <div class="panel panel-primary setup-content" id="step-1">
        <div class="panel-heading">
             <h3 class="panel-title">Tell us about yourself</h3>
        </div>
        <div class="panel-body">
            <div class="form-group">
                <label class="control-label">Your Name *</label>
                <input maxlength="100" type="text" name="entry_name" required="required" class="form-control" placeholder="" />
            </div>
            <button class="btn btn-primary nextBtn pull-right open1" type="button">Next</button>
        </div>
    </div>

    <div class="panel panel-primary setup-content hidden" id="step-2">
        <div class="panel-heading">
             <h3 class="panel-title">Final Step!</h3>
        </div>
        <div class="panel-body">
            <button class="btn btn-success pull-right open2" type="submit" name="add" id="add">I agree. I’m ready to get my itinerary!</button>
            <img src="assets/images/spinner.gif" alt="" id="loader" style="display: none; width:32px;height:32px;">

        </div>
    </div>
</form>


问:
Large text is going back of Imageview

```<code> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:src="@android:drawable/ic_menu_gallery"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:id="@+id/Chartimg"
        android:layout_margin="5dp"
        android:padding="5dp" />
     <TextView
        android:text="Medium Textcbvvvccgcvcvcbcvbvvbcvbvcbvcb"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/InfoView_ItemName"
        android:layout_centerVertical="true"
        android:ellipsize="end"
        android:maxLines="1" />        <TextView
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/IvItemID"
        android:layout_below="@id/InfoView_ItemName" />
    <ImageView
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_action_next_item"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:scaleType="centerInside" />
</RelativeLayout>
 </FrameLayout>
</code>```

I am creating litview when the listview item have large text it is going back to the image view here I am posting my code. please give me any solution but

答:
Try this, Give some id to imageview like this android:id="@+id/right_icon" and layout_toLeftOf in textview it will work fine

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/Chartimg"
            android:layout_width="50dip"
            android:layout_height="50dip"
            android:layout_margin="5dp"
            android:padding="5dp"
            android:src="@android:drawable/ic_menu_gallery"/>

        <TextView
            android:id="@+id/InfoView_ItemName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/Chartimg"
            android:layout_toLeftOf="@+id/right_icon"
            android:ellipsize="end"
            android:maxLines="1"
            android:text="Medium Textcbvvvccgcvcvcbcvbvvbcvbvcbvcb"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

        <TextView
            android:id="@+id/IvItemID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/InfoView_ItemName"
            android:layout_toRightOf="@id/Chartimg"
            android:paddingRight="5dp"
            android:textAppearance="?android:attr/textAppearanceSmall"/>

        <ImageView
            android:id="@+id/right_icon"
            android:layout_width="30dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:scaleType="centerInside"
            android:src="@drawable/ic_android_black_24dp"/>
    </RelativeLayout>
</FrameLayout>
</code>```

Title: Large text is going back of Imageview

Body:
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:src="@android:drawable/ic_menu_gallery"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:id="@+id/Chartimg"
        android:layout_margin="5dp"
        android:padding="5dp" />
     <TextView
        android:text="Medium Textcbvvvccgcvcvcbcvbvvbcvbvcbvcb"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/InfoView_ItemName"
        android:layout_centerVertical="true"
        android:ellipsize="end"
        android:maxLines="1" />        <TextView
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/IvItemID"
        android:layout_below="@id/InfoView_ItemName" />
    <ImageView
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_action_next_item"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:scaleType="centerInside" />
</RelativeLayout>
 </FrameLayout>

I am creating litview when the listview item have large text it is going back to the image view here I am posting my code. please give me any solution but

Body:
Try this, Give some id to imageview like this android:id="@+id/right_icon" and layout_toLeftOf in textview it will work fine

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/Chartimg"
            android:layout_width="50dip"
            android:layout_height="50dip"
            android:layout_margin="5dp"
            android:padding="5dp"
            android:src="@android:drawable/ic_menu_gallery"/>

        <TextView
            android:id="@+id/InfoView_ItemName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/Chartimg"
            android:layout_toLeftOf="@+id/right_icon"
            android:ellipsize="end"
            android:maxLines="1"
            android:text="Medium Textcbvvvccgcvcvcbcvbvvbcvbvcbvcb"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

        <TextView
            android:id="@+id/IvItemID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/InfoView_ItemName"
            android:layout_toRightOf="@id/Chartimg"
            android:paddingRight="5dp"
            android:textAppearance="?android:attr/textAppearanceSmall"/>

        <ImageView
            android:id="@+id/right_icon"
            android:layout_width="30dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:scaleType="centerInside"
            android:src="@drawable/ic_android_black_24dp"/>
    </RelativeLayout>
</FrameLayout>


问:
Receiving Mockito UnfinishedStubbingException for doNothing.when clause in Android Unit Test
Firstly, my setup is RXJava 1, Retrofit 2 and I'm using Java 7.

I have a method that, when it is called, will set an atomic boolean to true.

That method then calls a retrofit API.

Upon completion, timeout etc... the atomic boolean is reset to false.

So, I would therefore like to uni test that when I call my method, the Atomic Boolean is set to true.

So, I do the following:

```<code>    assertFalse(orderUseCase.isOrderInProcess());

    orderUseCase.execute(id, orderWrapper, ts);

    assertTrue(orderUseCase.isOrderInProcess());
</code>```

Test that the boolean is false.
Execute my use case
Test that the boolean is true.

Now, in order to perform the last test I need to ensure the API does nothing when it is called (the execute method will call the retrofit API.

To try and doNothing I am using the following line at the start of my test case.

```<code>doNothing().when(orderAPI.orderComplete(anyString(), any(OrderWrapper.class)));
</code>```

I am however receiving the following error:

```<code>org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.tfds.xms.unit_test.SingleTest.TestAtomicBooleanLocked(SingleTest.java:90)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
</code>```

From reading where other people had a similar issue, the answers were suggesting that their 'when' line was calling another Mock (which I don't believe I am doing) or that they hadn't done the 'PrepareForTest' step which I have done. I am however wondering if what is in my prepareForTest section is correct or not...

Incidentally I understand that the error is pointing me to add a 'thenReturn' but that would mean that the API 'does' something and would consequently cause the Atomic Boolean to unlock again, which is not what I want..

Any help is very much appreciated.

My full test case is:

```<code>@RunWith(TestRunner.class)
@PrepareForTest({OrderApiService.class, OrderUseCase.class})
public class SingleTest {

    @Rule
    public RxJavaResetRule pluginsReset = new RxJavaResetRule();

    private OrderApiService orderAPI;
    private OrderUseCase orderUseCase;
    private OrderRepository orderRepository;

    @Mock App app;

    @Before
    public void setUp() {

        orderAPI = mock(OrderApiService.class);

        orderRepository = new OrderRepository(app, orderAPI);

        orderUseCase = new OrderUseCase(orderRepository);

    }

    @Test
    public void TestAtomicBooleanLocked() throws Exception {

        doNothing().when(orderAPI.orderComplete(anyString(), any(OrderWrapper.class)));

        String id = "5";

        Order order = new Order();

        OrderWrapper orderWrapper = new orderWrapper(order);

        TestSubscriber<GenericResponse> ts = new TestSubscriber<GenericResponse>();

        assertFalse(orderUseCase.isOrderInProcess());

        orderUseCase.execute(id, orderWrapper, ts);

        assertTrue(orderUseCase.isOrderInProcess());

    }
}
</code>```

答:
The doNothing() method from Mockito works a bit different then the standalone when() method. You should be fine by just pushing the method call out of the .doNothing() like this:

```<code>doNothing().when(orderAPI)
    .orderComplete(anyString(), any(OrderWrapper.class));
</code>```

Happy testing!

Body:
Firstly, my setup is RXJava 1, Retrofit 2 and I'm using Java 7.

I have a method that, when it is called, will set an atomic boolean to true.

That method then calls a retrofit API.

Upon completion, timeout etc... the atomic boolean is reset to false.

So, I would therefore like to uni test that when I call my method, the Atomic Boolean is set to true.

So, I do the following:

    assertFalse(orderUseCase.isOrderInProcess());

    orderUseCase.execute(id, orderWrapper, ts);

    assertTrue(orderUseCase.isOrderInProcess());

Test that the boolean is false.
Execute my use case
Test that the boolean is true.

Now, in order to perform the last test I need to ensure the API does nothing when it is called (the execute method will call the retrofit API.

To try and doNothing I am using the following line at the start of my test case.

doNothing().when(orderAPI.orderComplete(anyString(), any(OrderWrapper.class)));

I am however receiving the following error:

org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.tfds.xms.unit_test.SingleTest.TestAtomicBooleanLocked(SingleTest.java:90)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

From reading where other people had a similar issue, the answers were suggesting that their 'when' line was calling another Mock (which I don't believe I am doing) or that they hadn't done the 'PrepareForTest' step which I have done. I am however wondering if what is in my prepareForTest section is correct or not...

Incidentally I understand that the error is pointing me to add a 'thenReturn' but that would mean that the API 'does' something and would consequently cause the Atomic Boolean to unlock again, which is not what I want..

Any help is very much appreciated.

My full test case is:

@RunWith(TestRunner.class)
@PrepareForTest({OrderApiService.class, OrderUseCase.class})
public class SingleTest {

    @Rule
    public RxJavaResetRule pluginsReset = new RxJavaResetRule();

    private OrderApiService orderAPI;
    private OrderUseCase orderUseCase;
    private OrderRepository orderRepository;

    @Mock App app;

    @Before
    public void setUp() {

        orderAPI = mock(OrderApiService.class);

        orderRepository = new OrderRepository(app, orderAPI);

        orderUseCase = new OrderUseCase(orderRepository);

    }

    @Test
    public void TestAtomicBooleanLocked() throws Exception {

        doNothing().when(orderAPI.orderComplete(anyString(), any(OrderWrapper.class)));

        String id = "5";

        Order order = new Order();

        OrderWrapper orderWrapper = new orderWrapper(order);

        TestSubscriber<GenericResponse> ts = new TestSubscriber<GenericResponse>();

        assertFalse(orderUseCase.isOrderInProcess());

        orderUseCase.execute(id, orderWrapper, ts);

        assertTrue(orderUseCase.isOrderInProcess());

    }
}

Body:
The doNothing() method from Mockito works a bit different then the standalone when() method. You should be fine by just pushing the method call out of the .doNothing() like this:

doNothing().when(orderAPI)
    .orderComplete(anyString(), any(OrderWrapper.class));

Happy testing!


问:
Displaying data from an array into labels and text areas (SQLite, iPhone)
I was reading tutorials for SQLite data reading and they all appear to use tables for displaying the data and I was wondering if anyone had an example of getting data into an array and displaying one database column in a label and another in a text area.

Any help would be great,

Thanks!

答:
You still need to use a tableView. But you'll need to customize it so that it appears to the user that there is one column solely for labels, and another column solely for text areas.

Besides, I don't think your question has much to do with SQLite. It appears to be more about UI pattern things.