问:
React js break when match happens
I am wanting to stop a loop that i have when it matches a condition but its just not breaking ive tried try catch loops with throw e and throw new typeerror but its just not breaking how do i get it to break here is the code i want to break

```<code>LoginAuth = (Res) => {
    try {
        if (Res.username === this.state.Username && Res.password === this.state.Password) {
            return (
                this.setState({
                    isLoggedIn: true,
                }, function () {

                }),
                this.hideModal()
            );
        } else {
            console.log("Gets to login auth and false");
        }
}
</code>```

I want to make it stop when the user input in state.username and state.password are equal to the one in the variable Res but i cant get it to stop looping how do i do this.

this is the function that calls this one

```<code>CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.forEach(function (Res) {
        return (
            console.log("ID=" + Res.id),
            console.log("Username=" + Res.username),
            console.log("Password=" + Res.password),
            self.LoginAuth(Res)
        );
    });
}
</code>```

edit

```<code>CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    this.props.AuthRes.some(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        if (Res.username === this.state.Username && Res.password === this.state.Password) {// the error is on this line saying it doesnt know what Username or Password are in the state
            return (
                this.setState({
                    isLoggedIn: true,
                }, function () {
                }),
                this.hideModal()
            );
        } else {
            console.log("Gets to login auth and false");
        }
    });
}
</code>```

error is Cannot read property 'state' of undefined

```<code>LoginAuth = (Res) => {
    if (Res.username === this.state.Username && Res.password === this.state.Password) {
        return (
            this.setState({
                isLoggedIn: true,
            }, function () {
            }),
            this.hideModal()
        );
    } else {
        console.log("Gets to login auth and false");
    }
}
CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.every(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        return (
            self.LoginAuth(Res)
        );
    });
}
</code>```

loops through but stops on the first one weather its true or false

答:
I have fixed it by making it break

my code was

```<code>LoginAuth = (Res) => {
if (Res.username === this.state.Username && Res.password === this.state.Password) {
    return (
        this.setState({
            isLoggedIn: true,
        }, function () {
        }),
        this.hideModal()
    );
} else {
    console.log("Gets to login auth and false");
}
}
CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.every(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        return (
            self.LoginAuth(Res)
        );
    });
}
</code>```

it is now

```<code>LoginAuth = (Res) => {
    if (Res.username === this.state.Username && Res.password === this.state.Password) {
            this.setState({
                isLoggedIn: true,
            })

            this.hideModal();
            return true;
    } else {
        console.log("Gets to login auth and false");
        return null;
    }
}
CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.some(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        return self.LoginAuth(Res);
    });
}
</code>```

i wasn't returning a truthy value or a falsy value

Title: React js break when match happens

Body:
I am wanting to stop a loop that i have when it matches a condition but its just not breaking ive tried try catch loops with throw e and throw new typeerror but its just not breaking how do i get it to break here is the code i want to break

LoginAuth = (Res) => {
    try {
        if (Res.username === this.state.Username && Res.password === this.state.Password) {
            return (
                this.setState({
                    isLoggedIn: true,
                }, function () {

                }),
                this.hideModal()
            );
        } else {
            console.log("Gets to login auth and false");
        }
}

I want to make it stop when the user input in state.username and state.password are equal to the one in the variable Res but i cant get it to stop looping how do i do this.

this is the function that calls this one

CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.forEach(function (Res) {
        return (
            console.log("ID=" + Res.id),
            console.log("Username=" + Res.username),
            console.log("Password=" + Res.password),
            self.LoginAuth(Res)
        );
    });
}

edit

CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    this.props.AuthRes.some(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        if (Res.username === this.state.Username && Res.password === this.state.Password) {// the error is on this line saying it doesnt know what Username or Password are in the state
            return (
                this.setState({
                    isLoggedIn: true,
                }, function () {
                }),
                this.hideModal()
            );
        } else {
            console.log("Gets to login auth and false");
        }
    });
}

error is Cannot read property 'state' of undefined

LoginAuth = (Res) => {
    if (Res.username === this.state.Username && Res.password === this.state.Password) {
        return (
            this.setState({
                isLoggedIn: true,
            }, function () {
            }),
            this.hideModal()
        );
    } else {
        console.log("Gets to login auth and false");
    }
}
CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.every(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        return (
            self.LoginAuth(Res)
        );
    });
}

loops through but stops on the first one weather its true or false

Body:
I have fixed it by making it break

my code was

LoginAuth = (Res) => {
if (Res.username === this.state.Username && Res.password === this.state.Password) {
    return (
        this.setState({
            isLoggedIn: true,
        }, function () {
        }),
        this.hideModal()
    );
} else {
    console.log("Gets to login auth and false");
}
}
CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.every(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        return (
            self.LoginAuth(Res)
        );
    });
}

it is now

LoginAuth = (Res) => {
    if (Res.username === this.state.Username && Res.password === this.state.Password) {
            this.setState({
                isLoggedIn: true,
            })

            this.hideModal();
            return true;
    } else {
        console.log("Gets to login auth and false");
        return null;
    }
}
CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.some(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        return self.LoginAuth(Res);
    });
}

i wasn't returning a truthy value or a falsy value


来源: stackexchange

问:
What is happening when you assign a pointer to another pointer?
Code:

```<code>int x = 2;
int* pointerone = &x;
int* pointertwo = pointerone;
</code>```

So the address of pointerone is assigned to pointertwo, but is the copy constructor being called and the object that holds the address is copied into the address object of the other pointer, like all the default copy constructors on other types performing a shallow copy. If it is as I expect, how does the copy constructor of a pointer look like?

答:
You could pretend, for symmetry, that the pointer's copy constructor is being invoked (and this would involve the copying of a single numerical "memory address").

In reality, pointers are of a built-in type and don't have constructors per se. The compiler has built-in logic that tells it what to make the program do.

ContentLicense: CC BY-SA 3.0

Body:
Code:

int x = 2;
int* pointerone = &x;
int* pointertwo = pointerone;

So the address of pointerone is assigned to pointertwo, but is the copy constructor being called and the object that holds the address is copied into the address object of the other pointer, like all the default copy constructors on other types performing a shallow copy. If it is as I expect, how does the copy constructor of a pointer look like?


问:
Thymeleaf - how to get value from input to "href" param in link
I have an input like this

```<code><input type="text" id="age" name="age">
</code>```

and link like this

```<code> <a th:href="person?age=????"> GET </a>
</code>```

My goal is get value from input and set it into param "age" in href, because  i have a spring controller whose catch a request param. Can I do it without JavaScript, use only Thymeleaf ?

答:
I'm not entirely sure I understand what you are trying to achieve. Thymeleaf is a server-side templating engine, so wouldn't be able to access local parameters until they are posted to the server.

If you are trying to populate a parameter from the model (or from a previous request) with Thymeleaf, then this is the syntax;

```<code><a th:href="@{person(age=${param.age)}">Link</a>
</code>```

Body:
I have an input like this

<input type="text" id="age" name="age">

and link like this

  GET

My goal is get value from input and set it into param "age" in href, because  i have a spring controller whose catch a request param. Can I do it without JavaScript, use only Thymeleaf ?

Body:
I'm not entirely sure I understand what you are trying to achieve. Thymeleaf is a server-side templating engine, so wouldn't be able to access local parameters until they are posted to the server.

If you are trying to populate a parameter from the model (or from a previous request) with Thymeleaf, then this is the syntax;

<a th:href="@{person(age=${param.age)}">Link</a>


问:
How do I migrate db.child() from Firebase 2?
I have several calls to db.child() in my app where I was using Firebase 2.4.2 as a signaling server.

```<code>this.channels = {
  announce: this.db.child('announce'),
  signal: this.db.child('messages').child(this.id)
};

this.channels.signal.on('child_added', this.onSignal.bind(self));
this.channels.announce.on('child_added', this.onAnnounce.bind(self));
</code>```

Once signaling is finished, I would send messages back and forth like so:

this.db.child('messages').child( id ).push(msg);

I have to migrate to the latest Firebase. I have access to the database in my app, but this.db.child is not a function. How do I migrate these calls to Firebase 4?

答:
Referrence.child() and Snapshot.child() are still existing methods in the 3.x and 4.x versions of the Firebase Database API.

Based on that, a very quick guess is that you need:

```<code>this.db.ref('messages').child( id )
</code>```

But it's impossible to be certain, because your code doesn't show how this.db gets initialized.

For the most direct help in porting your code from 2.x to 3.x, see this guide: https://firebase.google.com/support/guides/firebase-web

Body:
I have several calls to db.child() in my app where I was using Firebase 2.4.2 as a signaling server.

this.channels = {
  announce: this.db.child('announce'),
  signal: this.db.child('messages').child(this.id)
};

this.channels.signal.on('child_added', this.onSignal.bind(self));
this.channels.announce.on('child_added', this.onAnnounce.bind(self));

Once signaling is finished, I would send messages back and forth like so:

this.db.child('messages').child( id ).push(msg);

I have to migrate to the latest Firebase. I have access to the database in my app, but this.db.child is not a function. How do I migrate these calls to Firebase 4?

Body:
Referrence.child() and Snapshot.child() are still existing methods in the 3.x and 4.x versions of the Firebase Database API.

Based on that, a very quick guess is that you need:

this.db.ref('messages').child( id )

But it's impossible to be certain, because your code doesn't show how this.db gets initialized.

For the most direct help in porting your code from 2.x to 3.x, see this guide: https://firebase.google.com/support/guides/firebase-web


问:
Algorithmic help needed (N bags and items distributed randomly)
I have encountered an algorithmic problem but am not able to figure out anything better than brute force or reduce it to a better know problem. Any hints?

There are N bags of variable sizes and N types of items. Each type of items belongs to one bag. There are lots of items of each type and each item may be of a different size. Initially, these items are distributed across all the bags randomly. We have to place the items in their respective bags. However, we can only operate with a pair of bags at one time by exchanging items <s>(as much as possible)</s> and proceeding to the next pair. <s>The aim is to reduce the total number of pairs.</s> Edit: The aim is to find a sequence of transfers that minimizes the total number of bag pairs involved

Clarification:

The bags are not arbitrarily large (You can assume the bag and item sizes to be integers between 0 to 1000 if it helps). You'll frequently encounter scenarios where  the all the items between 2 bags cannot be swapped due to the limited capacity of one of the bags. This is where the algorithm needs to make an optimisation. Perhaps, if another pair of bags were swapped first, the current swap can be done in one go. To illustrate this, let's consider Bags A, B and C and their items 1, 2, 3 respectively. The number in the brackets is the size.

A(10) : 3(8)

B(10): 1(2), 1(3)

C(10): 1(4)

The swap orders can be AB, AC, AB or AC, AB. The latter is optimal as the number of swaps is lesser.

答:
Since I cannot come to an idea for an algorithm that will always find an optimal answer, and approximation of the fitness of the solution (amount of swaps) is also fine, I suggest a stochastic local search algorithm with pruning.

Given a random starting configuration, this algorithm considers all possible swaps, and makes a weighed decision based on chance: the better a swap is, the more likely it is chosen.

The value of a swap would be the sum of the value of the transaction of an item, which is zero if the item does not end up in it's belonging bag, and is positive if it does end up there. The value increases as the item's size increases (the idea behind this is that a larger block is hard to move many times in comparison to smaller blocks). This fitness function can be replaced by any other fitness function, it's efficiency is unknown until empirically shown.

Since any configuration can be the consequence of many preceding swaps, we keep track of which configurations we have seen before, along with a fitness (based on how many items are in their correct bag - this fitness is not related to the value of a swap) and the list of preceded swaps. If the fitness function for a configuration is the sum of the items that are in their correct bags, then the amount of items in the problem is the highest fitness (and therefor marks a configuration to be a solution).

A swap is not possible if:

Either of the affected bags is holding more than it's capacity after the potential swap.

The new swap brings you back to  the last configuration you were in before the last swap you did (i.e. reversed swap).

When we identify potential swaps, we look into our list of previously seen configurations (use a hash function for O(1) lookup). Then we either set its preceded swaps to our preceded swaps (if our list is shorter than it's), or we set our preceded swaps to its list (if it's list is shorter than ours). We can do this because it does not matter which swaps we did, as long as the amount of swaps is as small as possible.

If there are no more possible swaps left in a configuration, it means you're stuck. Local search tells you 'reset' which you can do in may ways, for instance:

Reset to a previously seen state (maybe the best one you've seen so far?)

Reset to a new valid random solution

Note

Since the algorithm only allows you to do valid swaps, all constraints will be met for each configuration.

The algorithm does not guarantee to 'stop' out of the box, you can implement a maximum number of iterations (swaps)

The algorithm does not guarantee to find a correct solution, as it does it's best to find a better configuration each iteration. However, since a perfect solution (set of swaps) should look closely to an almost perfect solution, a human might be able to finish what the local search algorithm was not after it results in a invalid configuration (where not every item is in its correct bag).

The used fitness functions and strategies are very likely not the most efficient out there. You could look around to find better ones. A more efficient fitness function / strategy should result in a good solution faster (less iterations).


问:
HashMap with multiple values under the same key
Is it possible to implement a HashMap with one key and two values?

Just as HashMap<userId, clientID,timeStamp>?

If not, is there any other way to implement the storage of multiple values e.g. one key and two values?

答:
The easiest way would be to use a google collection library:

```<code>import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class Test {

    public static void main(final String[] args) {

        // multimap can handle one key with a list of values
        final Multimap<String, String> cars = ArrayListMultimap.create();
        cars.put("Nissan", "Qashqai");
        cars.put("Nissan", "Juke");
        cars.put("Bmw", "M3");
        cars.put("Bmw", "330E");
        cars.put("Bmw", "X6");
        cars.put("Bmw", "X5");

        cars.get("Bmw").forEach(System.out::println);

        // It will print the:
        // M3
        // 330E
        // X6
        // X5
    }

}
</code>```

maven link: https://mvnrepository.com/artifact/com.google.collections/google-collections/1.0-rc2

more on this: http://tomjefferys.blogspot.be/2011/09/multimaps-google-guava.html

ContentLicense: CC BY-SA 4.0

Body:
The easiest way would be to use a google collection library:

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class Test {

    public static void main(final String[] args) {

        // multimap can handle one key with a list of values
        final Multimap<String, String> cars = ArrayListMultimap.create();
        cars.put("Nissan", "Qashqai");
        cars.put("Nissan", "Juke");
        cars.put("Bmw", "M3");
        cars.put("Bmw", "330E");
        cars.put("Bmw", "X6");
        cars.put("Bmw", "X5");

        cars.get("Bmw").forEach(System.out::println);

        // It will print the:
        // M3
        // 330E
        // X6
        // X5
    }

}

maven link: https://mvnrepository.com/artifact/com.google.collections/google-collections/1.0-rc2

more on this: http://tomjefferys.blogspot.be/2011/09/multimaps-google-guava.html


问:
How to do meta_query when the value of a meta_key is an array?
I am working on Wordpress website and hit an obstacle when I tried to do the following query:

```<code>    $args=array(
     'post_type' => 'post',
     'post_status' => 'publish',
     'meta_query'    =>  array(
        array(
       'key'     => 'ad_info',
        'value'  => // check again with weight between 50 and 100,
        'compare' => //compare operator,
        ),
       )
     );
</code>```

the value of the key  ad_info is: Array ( [weight] => 48 [height] => 160)    and I want to check if the value of weight in this array is between 50 and 100.
Can anybody help me on this problem?
Thanks

答:
In mysql array values saved as strings, and it make problem for WP_Query filtering.

So best solution in this problem - change saving method to 2 keys:

ad_info_width and ad_info_height.

In that way you can use meta_query between compare.

Body:
I am working on Wordpress website and hit an obstacle when I tried to do the following query:

    $args=array(
     'post_type' => 'post',
     'post_status' => 'publish',
     'meta_query'    =>  array(
        array(
       'key'     => 'ad_info',
        'value'  => // check again with weight between 50 and 100,
        'compare' => //compare operator,
        ),
       )
     );

the value of the key  ad_info is: Array ( [weight] => 48 [height] => 160)    and I want to check if the value of weight in this array is between 50 and 100.
Can anybody help me on this problem?
Thanks


问:
Failure in establishing connection with MSSQL Server using mssql package node.js
i am a new by to node.js and i am trying to connect with a test database on my local SQLExpress instance using mssql in node.js but i am stuck with the following error.

```<code>message: 'Port for SQLEXPRESS not found in ServerName;ComputerName;InstanceName;SQLEXPRESS;IsClustered;No;Version;12.0.2000.8;;'
    ,code: 'EINSTLOOKUP'
</code>```

I have installed tedious and enabled by TCP/IP protocol in SQL Server Configuration Manager as well but it won`t work.
Here is my connection configuration

```<code> var config = {
            user: 'sa',
            password: 'mypassword',
            server: 'ComupterName\\SQLEXPRESS',
            database: 'testdb',
            port: 1433
        };
</code>```

package.json file:

```<code>{
  "name": "app.js",
  "version": "1.0.0",
  "main": "app.js",
  "scripts": {
    "test": "npm install express --save",
    "start": "node server.js"
  },
  "author": "Aamir",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.15.2",
    "express": "^4.14.0",
    "mssql": "^3.3.0",
    "tedious": "^1.14.0"
  },
  "devDependencies": {},
  "description": ""
}
</code>```

Am i missing some configuration or is there any connection string related issue?

答:
I don't know if this is still a problem for you. Put SQL Server is being run as  service on your computer thus using localhost instead of your computer name would automatically resolve the request from the node process to your sql server service.

Let me know if this worked for you.

P.S Also I'm not sure if the node package mssql works for SQL Server Express since that is the free version. I know it works for SQL server since I use it at work.

Body:
i am a new by to node.js and i am trying to connect with a test database on my local SQLExpress instance using mssql in node.js but i am stuck with the following error.

message: 'Port for SQLEXPRESS not found in ServerName;ComputerName;InstanceName;SQLEXPRESS;IsClustered;No;Version;12.0.2000.8;;'
    ,code: 'EINSTLOOKUP'

I have installed tedious and enabled by TCP/IP protocol in SQL Server Configuration Manager as well but it won`t work.
Here is my connection configuration

 var config = {
            user: 'sa',
            password: 'mypassword',
            server: 'ComupterName\\SQLEXPRESS',
            database: 'testdb',
            port: 1433
        };

package.json file:

{
  "name": "app.js",
  "version": "1.0.0",
  "main": "app.js",
  "scripts": {
    "test": "npm install express --save",
    "start": "node server.js"
  },
  "author": "Aamir",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.15.2",
    "express": "^4.14.0",
    "mssql": "^3.3.0",
    "tedious": "^1.14.0"
  },
  "devDependencies": {},
  "description": ""
}

Am i missing some configuration or is there any connection string related issue?


问:
jQuery highlighting clicked list item
When I clicked on list item it is highlighting only one. If list item has sub list then the total sub list is also highlighting but only one list should be highlight.

CSS

```<code>.active {
  background: #f00;
}
</code>```

HTML

```<code><ul id="orgCat">
  <li class="list-group-item active">Cras justo odio</li>
  <li class="list-group-item">Dapibus ac facilisis in</li>
  <li class="list-group-item">Morbi leo risus
    <ul>
    <li>abc</li>
    <li>sdf</li>
    <li>oupu
      <ul>
      <li>progf</li>
      <li>ghfhg</li>
      </ul>
    </li>
    </ul>
  </li>
  <li class="list-group-item">Porta ac consectetur ac</li>
  <li class="list-group-item">Vestibulum at eros</li>
  <li class="list-group-item">Cras justo odio</li>
  <li class="list-group-item">Dapibus ac facilisis in</li>
  <li class="list-group-item">Morbi leo risus</li>
  <li class="list-group-item">Porta ac consectetur ac</li>
  <li class="list-group-item">Vestibulum at eros</li>
</ul>
</code>```

JQUERY

```<code>$('#orgCat li').click(function(e) {
    e.preventDefault()

    $that = $(this);

    $that.parent().find('li').removeClass('active');
    $that.addClass('active');
  });
</code>```

Demo

答:
Try adding return false like this:

```<code>$('#orgCat li').click(function(e) {
e.preventDefault();

$that=$(this);
$('#orgCat .active').removeClass('active');
$that.addClass('active');
return false;
});
</code>```

$('#orgCat li').click(function(e) {
    e.preventDefault();

   $that=$(this);
    $('#orgCat .active').removeClass('active');
    $that.addClass('active');
    return false;
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {
  background: #f00;
}</code>```

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

abc

sdf

oupu

progf

ghfhg

Porta ac consectetur ac

Vestibulum at eros

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

```

Title: jQuery highlighting clicked list item

Body:
When I clicked on list item it is highlighting only one. If list item has sub list then the total sub list is also highlighting but only one list should be highlight.

CSS

.active {
  background: #f00;
}

HTML

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

abc

sdf

oupu

progf

ghfhg

Porta ac consectetur ac

Vestibulum at eros

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

JQUERY

$('#orgCat li').click(function(e) {
    e.preventDefault()

    $that = $(this);

    $that.parent().find('li').removeClass('active');
    $that.addClass('active');
  });

Demo

Body:
Try adding return false like this:

$('#orgCat li').click(function(e) {
e.preventDefault();

$that=$(this);
$('#orgCat .active').removeClass('active');
$that.addClass('active');
return false;
});

$('#orgCat li').click(function(e) {
    e.preventDefault();

   $that=$(this);
    $('#orgCat .active').removeClass('active');
    $that.addClass('active');
    return false;
  });

.active {
  background: #f00;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<ul id="orgCat">
  <li class="list-group-item active">Cras justo odio</li>
  <li class="list-group-item">Dapibus ac facilisis in</li>
  <li class="list-group-item">Morbi leo risus
    <ul>
    <li>abc</li>
    <li>sdf</li>
    <li>oupu
      <ul>
      <li>progf</li>
      <li>ghfhg</li>
      </ul>
    </li>
    </ul>
  </li>
  <li class="list-group-item">Porta ac consectetur ac</li>
  <li class="list-group-item">Vestibulum at eros</li>
  <li class="list-group-item">Cras justo odio</li>
  <li class="list-group-item">Dapibus ac facilisis in</li>
  <li class="list-group-item">Morbi leo risus</li>
  <li class="list-group-item">Porta ac consectetur ac</li>
  <li class="list-group-item">Vestibulum at eros</li>
</ul>


问:
Add address book like letters in array of names
I'm trying to take an array of people (simplified with just a first name for now) and not only sort it, but also add the first letter in front of all people starting with this letter.

Basically this: ["Daniel", "Michael", "Lisa", "Lena"] should become this: ["D", "Daniel", "L", "Lena", "Lisa", "M", "Michael"]

I have something working in a playground, but to me this looks ugly as hell and no idea about performance if people get in the thousands or more.

```<code>//: Playground - noun: a place where people can play

import Cocoa

var previousName: String?

let people = ["Martin", "Michael", "Lisa", "Lena", "Dirk"]
var peopleWithLetters: [String] = []

people.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }.forEach {
    if $0.uppercased().characters.first! != previousName?.uppercased().characters.first! {
        peopleWithLetters.append("\($0.uppercased().characters.first!)")
    }
    previousName = $0
    peopleWithLetters.append($0)
}
</code>```

Any idea how to streamline or follow best practices would be highly appreciated.

答:
This is a perfect usecase where functional programming shines.

Map array of names to array of first letters

Use a set to remove duplicates

Combine letters with names

Sort the array

Here is the code:

```<code>//: Playground - noun: a place where people can play

func addSections(in words: [String]) -> [String] {
    let sections = Set(words.map { String($0[$0.startIndex]) })
    let wordsWithSections = words + sections
    return wordsWithSections.sorted { $0 < $1 }
}

let names = ["Daniel", "Michael", "Lisa", "Lena"]
addSections(in: names)
</code>```

Although if you plan on using this array to feed a tableView (sections/rows) you would be better off with a dictionary like you mentioned in your comment.

Body:
I'm trying to take an array of people (simplified with just a first name for now) and not only sort it, but also add the first letter in front of all people starting with this letter.

Basically this: ["Daniel", "Michael", "Lisa", "Lena"] should become this: ["D", "Daniel", "L", "Lena", "Lisa", "M", "Michael"]

I have something working in a playground, but to me this looks ugly as hell and no idea about performance if people get in the thousands or more.

//: Playground - noun: a place where people can play

import Cocoa

var previousName: String?

let people = ["Martin", "Michael", "Lisa", "Lena", "Dirk"]
var peopleWithLetters: [String] = []

people.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }.forEach {
    if $0.uppercased().characters.first! != previousName?.uppercased().characters.first! {
        peopleWithLetters.append("\($0.uppercased().characters.first!)")
    }
    previousName = $0
    peopleWithLetters.append($0)
}

Any idea how to streamline or follow best practices would be highly appreciated.

Body:
This is a perfect usecase where functional programming shines.

Map array of names to array of first letters

Use a set to remove duplicates

Combine letters with names

Sort the array

Here is the code:

//: Playground - noun: a place where people can play

func addSections(in words: [String]) -> [String] {
    let sections = Set(words.map { String($0[$0.startIndex]) })
    let wordsWithSections = words + sections
    return wordsWithSections.sorted { $0 < $1 }
}

let names = ["Daniel", "Michael", "Lisa", "Lena"]
addSections(in: names)

Although if you plan on using this array to feed a tableView (sections/rows) you would be better off with a dictionary like you mentioned in your comment.


问:
404 with spring 3
hi
I am going through my first lessons with spring 3.I created a dynamic web app in eclipse with the following structure.

```<code>spring3mvc \src\my.spring.HelloWorldController.java
                \WebContent
                   |
                   |-----WEB-INF\jsp\hello.jsp
                   |-----index.jsp
                   |-----WEB-INF\web.xml
                   |-----WEB-INF\spring-servlet.xml
                   |-----WEB-INF\lib\...*.jar files
</code>```

I created the spring-servlet.xml as below

```<code> <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:context="http://www.springframework.org/schema/context"
             xmlns:mvc="http://www.springframework.org/schema/mvc"
             xmlns:p="http://www.springframework.org/schema/p"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
               http://www.springframework.org/schema/mvc
               http://www.springframework.org/schema/context
                http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
                http://www.springframework.org/schema/context/spring-context-3.0.xsd">
                 <mvc:annotation-driven/>

        <context:component-scan base-package="my.spring" />
        <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
            p:prefix="/WEB-INF/jsp/"
        p:suffix=".jsp">

          <property name="contentType" value="text/html; charset=utf-8" />
        </bean>
      </beans>
</code>```

and coded the controller

```<code>package my.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {
 @RequestMapping("/hello")
 public ModelAndView helloWorld() {
  String message = "Hello World, Spring 3.0!";
  return new ModelAndView("hello", "message", message);
 }
}
</code>```

index.jsp has a link to hello view

```<code><html>
<body>
<a href="hello.html">Say Hello</a>

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

finally in hello.jsp I have put

```<code><html>
<body>
${message}
</body>
</html>
</code>```

My web.xml has

```<code><display-name>Spring3MVC</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</code>```

When I run the app on Tomcat6 server( thru eclipse),I can see the index page at
http://localhost:8080/Spring3MVC/ .It displays the link to hello page.When I click on it(http://localhost:8080/Spring3MVC/hello.html),I get a 404 error.

```<code>message /Spring3MVC/hello.html
description The requested resource (/Spring3MVC/hello.html) is not available.
</code>```

Any idea how I can solve this?

thanks

mark.

答:
You need to configure ViewResolver.

Here is sample configuration:

```<code><bean id="viewResolver"
    class=" org.springframework.web.servlet.view. InternalResourceViewResolver" >
  <property name="prefix">
    <value>/WEB-INF/jsp/</value>
  </property>
  <property name="suffix">
    <value>.jsp</value>
  </property>
</bean>
</code>```

When you do return new ModelAndView("hello", "message", message);
from above conf. it will try loading

```<code>prefix value + view name + suffix value
</code>```

which will be required jsp.

Also you need to map your servlet in web.xml following way

```<code><servlet-mapping>
  <servlet-name>dispatcher</servlet-name>
  <url-pattern>*.htm</url-pattern>
</servlet-mapping>
</code>```

ContentLicense: CC BY-SA 2.5

Title: 404 with spring 3

Body:
hi
I am going through my first lessons with spring 3.I created a dynamic web app in eclipse with the following structure.

spring3mvc \src\my.spring.HelloWorldController.java
                \WebContent
                   |
                   |-----WEB-INF\jsp\hello.jsp
                   |-----index.jsp
                   |-----WEB-INF\web.xml
                   |-----WEB-INF\spring-servlet.xml
                   |-----WEB-INF\lib\...*.jar files

I created the spring-servlet.xml as below

 <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:context="http://www.springframework.org/schema/context"
             xmlns:mvc="http://www.springframework.org/schema/mvc"
             xmlns:p="http://www.springframework.org/schema/p"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
               http://www.springframework.org/schema/mvc
               http://www.springframework.org/schema/context
                http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
                http://www.springframework.org/schema/context/spring-context-3.0.xsd">
                 <mvc:annotation-driven/>

        <context:component-scan base-package="my.spring" />
        <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
            p:prefix="/WEB-INF/jsp/"
        p:suffix=".jsp">

          <property name="contentType" value="text/html; charset=utf-8" />
        </bean>
      </beans>

and coded the controller

package my.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {
 @RequestMapping("/hello")
 public ModelAndView helloWorld() {
  String message = "Hello World, Spring 3.0!";
  return new ModelAndView("hello", "message", message);
 }
}

index.jsp has a link to hello view

Say Hello

finally in hello.jsp I have put

${message}

My web.xml has

<display-name>Spring3MVC</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

When I run the app on Tomcat6 server( thru eclipse),I can see the index page at
http://localhost:8080/Spring3MVC/ .It displays the link to hello page.When I click on it(http://localhost:8080/Spring3MVC/hello.html),I get a 404 error.

message /Spring3MVC/hello.html
description The requested resource (/Spring3MVC/hello.html) is not available.

Any idea how I can solve this?

thanks

mark.

Body:
You need to configure ViewResolver.

Here is sample configuration:

<bean id="viewResolver"
    class=" org.springframework.web.servlet.view. InternalResourceViewResolver" >
  <property name="prefix">
    <value>/WEB-INF/jsp/</value>
  </property>
  <property name="suffix">
    <value>.jsp</value>
  </property>
</bean>

When you do return new ModelAndView("hello", "message", message);
from above conf. it will try loading

prefix value + view name + suffix value

which will be required jsp.

Also you need to map your servlet in web.xml following way

<servlet-mapping>
  <servlet-name>dispatcher</servlet-name>
  <url-pattern>*.htm</url-pattern>
</servlet-mapping>


问:
laravel 5 redirect route to external url
I am in the process of moving a website to a new version of the site that has been created to Laravel 5,

However, I need to link to some old static content in a subdirectory on my old site, so I would like to create a route that automatically re-directs any querys to a specific sub-directory to to the old site.

For example:

user goes to:

```<code>www.site1.com/brochures/brochure1
</code>```

I want it to redirect to:

```<code>www.oldsite.com/brochures/brochure1
</code>```

And I want to have it do this for anything that comes in as

```<code>www.site1.com/brochures/whatever  ...
</code>```

I want it to duplicate the same path but redirected to the old site.  I don't want to have to put in each brochure, as every once in a while a new brochure gets added...

答:
Can you try this:</p>

```<code>return redirect()->to($path);
</code>```

Body:
I am in the process of moving a website to a new version of the site that has been created to Laravel 5,

However, I need to link to some old static content in a subdirectory on my old site, so I would like to create a route that automatically re-directs any querys to a specific sub-directory to to the old site.

For example:

user goes to:

www.site1.com/brochures/brochure1

I want it to redirect to:

www.oldsite.com/brochures/brochure1

And I want to have it do this for anything that comes in as

www.site1.com/brochures/whatever  ...

I want it to duplicate the same path but redirected to the old site.  I don't want to have to put in each brochure, as every once in a while a new brochure gets added...

Body:
Can you try this:

return redirect()->to($path);


问:
Ionic 2 "Can't resolve all parameters" when importing a component
My home component has functions to operate on my main array of list items.  I am trying to access these functions through another component called item-details.

However, when I import the HomePage component, and add it to the constructor for item-details.ts, I get the following error:

```<code>"Runtime Error Can't resolve all parameters for ItemDetailPage: ([object Object], [object Object], ?)".
</code>```

item-details.ts:

```<code>import { Component } from '@angular/core';
import { NavParams, NavController } from 'ionic-angular';
import { HomePage } from '../home/home';

@Component({
  selector: 'page-item-detail',
  templateUrl: 'item-detail.html'
})
export class ItemDetailPage {
  title;
  description;

  constructor(
    public navParams: NavParams,
    public navController: NavController,
    public home: HomePage
  ){

  }

  ionViewDidLoad() {
    this.title = this.navParams.get('item').title;
    this.description = this.navParams.get('item').description;
  }

  deleteItem(item){
    //call deleteItem in home.ts
  }
}
</code>```

home.ts:

```<code>import { Component } from '@angular/core';
import { ModalController, NavController, ViewController } from 'ionic-angular';
import { AddItemPage } from '../add-item/add-item'
import { ItemDetailPage } from '../item-detail/item-detail';
import { Data } from '../../providers/data/data';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  public items = [];

  constructor(
    public navCtrl: NavController,
    public modalCtrl: ModalController,
    public dataService: Data
   ) {
    this.dataService.getData().then((todos) => {
      if(todos){
        this.items = JSON.parse(todos);
      }
    });
  }

  ionViewDidLoad(){

  }

  addItem(){
    let addModal = this.modalCtrl.create(AddItemPage);

    addModal.onDidDismiss((item) => {
          if(item){
            this.saveItem(item);
          }
    });
    addModal.present();
  }

  saveItem(item){
    this.items.push(item);
    this.dataService.save(this.items);
  }

  viewItem(item){
    this.navCtrl.push(ItemDetailPage, {
      item: item
    });
  }

  deleteItem(item){
    //code to delete an item from items array
  }
}
</code>```

And here is a picture of my file structure in case it is relevant.  file structure

What's wrong and how can I fix it?

答:
In your ItemDetailPage component, you're asking the container to resolve a HomePage component when you should really be asking for a service instead.

As shown above, in your ItemDetailPage, you are trying to get a reference to a HomePage component (the creating, and also a ItemDetailPage referencing component), and that makes for a circular reference. That will not work.

There's really no need to resolve a component when you have a service that will do what you need. That is what services are for, to share functionality. Move your item management code (saveItem, addItem, deleteItem) out into a service that the Home, and ItemDetail pages can each reference and use.

Body:
My home component has functions to operate on my main array of list items.  I am trying to access these functions through another component called item-details.

However, when I import the HomePage component, and add it to the constructor for item-details.ts, I get the following error:

"Runtime Error Can't resolve all parameters for ItemDetailPage: ([object Object], [object Object], ?)".

item-details.ts:

import { Component } from '@angular/core';
import { NavParams, NavController } from 'ionic-angular';
import { HomePage } from '../home/home';

@Component({
  selector: 'page-item-detail',
  templateUrl: 'item-detail.html'
})
export class ItemDetailPage {
  title;
  description;

  constructor(
    public navParams: NavParams,
    public navController: NavController,
    public home: HomePage
  ){

  }

  ionViewDidLoad() {
    this.title = this.navParams.get('item').title;
    this.description = this.navParams.get('item').description;
  }

  deleteItem(item){
    //call deleteItem in home.ts
  }
}

home.ts:

import { Component } from '@angular/core';
import { ModalController, NavController, ViewController } from 'ionic-angular';
import { AddItemPage } from '../add-item/add-item'
import { ItemDetailPage } from '../item-detail/item-detail';
import { Data } from '../../providers/data/data';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  public items = [];

  constructor(
    public navCtrl: NavController,
    public modalCtrl: ModalController,
    public dataService: Data
   ) {
    this.dataService.getData().then((todos) => {
      if(todos){
        this.items = JSON.parse(todos);
      }
    });
  }

  ionViewDidLoad(){

  }

  addItem(){
    let addModal = this.modalCtrl.create(AddItemPage);

    addModal.onDidDismiss((item) => {
          if(item){
            this.saveItem(item);
          }
    });
    addModal.present();
  }

  saveItem(item){
    this.items.push(item);
    this.dataService.save(this.items);
  }

  viewItem(item){
    this.navCtrl.push(ItemDetailPage, {
      item: item
    });
  }

  deleteItem(item){
    //code to delete an item from items array
  }
}

And here is a picture of my file structure in case it is relevant.  file structure

What's wrong and how can I fix it?


问:
Need help in groovy scripting in SOAP UI Pro
Thanks in advance for any help. I tried searching the answers and I could not find a clear answer. Hence, creating a new thread.

Outline: I am trying to create an test suite in SOAP UI aiming to test all the api's involved in our application.

Scenario:

first step is to create a REST request, GET method. It gives me back response which contains 12 nodes.

I would need to run a REST request,'POST' method for each of the nodes.

Issue: I am stuck in the second step. I could think of the logic needed but I am not very sure with the code.

Logic I thought:

Create an array and get each node's values as an item

Create a loop with the number of items in the array as upper limit

Assign each node's values as input properties to the post method

It would be of much help if anyone could help me out with groovy script for this.

答:
You are missing a little detail on what the nodes contain but I've done very similar things.

You actually may not even need a groovy script if the node is just a parameter for the post request.

Your step structure would be something like

GET Request Data Source

GET request

POST Request Data Source (JSON/XML option)

POST request

Any additional stuff

Loop back to POST request data source

Loop back to GET request data source

This is assuming your structure is something like

```<code><GETResponse>
  <node>
    <nodeValue1>1</nodeValue1>
    <nodeValue2>2</nodeValue2>
  </node>
  <node>
    <nodeValue1>3</nodeValue1>
    <nodeValue2>4</nodeValue2>
  </node>
</GETResponse>
</code>```

Step 3 you just need to set up with the row being each node. And the column being whatever values you need from the nodes.

Please comment if this does not fit your use case

Body:
You are missing a little detail on what the nodes contain but I've done very similar things.

You actually may not even need a groovy script if the node is just a parameter for the post request.

Your step structure would be something like

GET Request Data Source

GET request

POST Request Data Source (JSON/XML option)

POST request

Any additional stuff

Loop back to POST request data source

Loop back to GET request data source

This is assuming your structure is something like

<GETResponse>
  <node>
    <nodeValue1>1</nodeValue1>
    <nodeValue2>2</nodeValue2>
  </node>
  <node>
    <nodeValue1>3</nodeValue1>
    <nodeValue2>4</nodeValue2>
  </node>
</GETResponse>

Step 3 you just need to set up with the row being each node. And the column being whatever values you need from the nodes.

Please comment if this does not fit your use case


问:
angular 4 http.post not sending or working
I am quite new to the latest version of Angular. http.post does not seem to work in anywhere in my application. I have tried things like:

```<code>this.http
    .post(this.bikesUrl, data, { headers: this.headers })
    .toPromise()
    .then(res => res.json().data)
    .catch(this.handleError);
</code>```

...or...

```<code>this.http.post(this.config.apiEndpoint+'/authenticate', JSON.stringify({ username: username, password: password }))
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let token = response.json() && response.json().token;
            if (token) {
                // set token property
                this.token = token;

                // store username and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));

                // return true to indicate successful login
                return true;
            } else {
                // return false to indicate failed login
                return false;
            }
        }).subscribe(result => {
      if (result === true) {
        // login successful
        this.router.navigate(['/']);
      } else {
        // login failed
        this.error = 'Username or password is incorrect';
        this.loading = false;
      }
    })
</code>```

...or...

```<code> var json = {var1: 'test'};
var params = 'json='+json;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
http.post("http://example.com/infoarray.php", params, headers ).subscribe (re => {
  console.log(re)
})
</code>```

When I run this in the browser it is almost like the script is not there. I see no requests in the inspector. I am using Angular CLI

答:
This is how I am doing in my Ionic 3 App.</p>

```<code>//in my ApiProvider

let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

http.post("http://localhost/login", params, options)
  .map(this.onLoginSuccess)
  .catch(this.onError);

onLoginSuccess(res: Response): Observable<LoginUserResponse> {
 return res.json();
}

private onError(error: Response | any) {
  console.error(error.message || error);
  return Observable.throw(error.message || error);
}
</code>```

Body:
I am quite new to the latest version of Angular. http.post does not seem to work in anywhere in my application. I have tried things like:

this.http
    .post(this.bikesUrl, data, { headers: this.headers })
    .toPromise()
    .then(res => res.json().data)
    .catch(this.handleError);

...or...

this.http.post(this.config.apiEndpoint+'/authenticate', JSON.stringify({ username: username, password: password }))
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let token = response.json() && response.json().token;
            if (token) {
                // set token property
                this.token = token;

                // store username and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));

                // return true to indicate successful login
                return true;
            } else {
                // return false to indicate failed login
                return false;
            }
        }).subscribe(result => {
      if (result === true) {
        // login successful
        this.router.navigate(['/']);
      } else {
        // login failed
        this.error = 'Username or password is incorrect';
        this.loading = false;
      }
    })

...or...

 var json = {var1: 'test'};
var params = 'json='+json;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
http.post("http://example.com/infoarray.php", params, headers ).subscribe (re => {
  console.log(re)
})

When I run this in the browser it is almost like the script is not there. I see no requests in the inspector. I am using Angular CLI

Body:
This is how I am doing in my Ionic 3 App.

//in my ApiProvider

let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

http.post("http://localhost/login", params, options)
  .map(this.onLoginSuccess)
  .catch(this.onError);

onLoginSuccess(res: Response): Observable<LoginUserResponse> {
 return res.json();
}

private onError(error: Response | any) {
  console.error(error.message || error);
  return Observable.throw(error.message || error);
}


问:
Vuejs - Get value of semantic calendar in vuejs
I used semantic ui calendar combine with Vuejs to get value. After pick a date with datepicker, this calendar did not set the value. So i cannot save a date via Vuejs. This is my html:

```<code><div class="ui calendar" id="date">
    <div class="ui input left icon">
         <i class="calendar icon"></i>
         <input type="text" v-model="input.date">
    </div>
</div>
</code>```

My Vuejs :

```<code>var app = new Vue({
    el: "#app",
    data: {
        input: {
            unique_number:"",
            date: "",
            description: ""
        },
            inputErrors: []
    }
});
</code>```

Any idea ?

答:
I don't see a datepicker in there. Try changing:

```<code><input type="text" v-model="input.date">
</code>```

to

```<code><input type="date" v-model="input.date">
</code>```

Body:
I used semantic ui calendar combine with Vuejs to get value. After pick a date with datepicker, this calendar did not set the value. So i cannot save a date via Vuejs. This is my html:

         <input type="text" v-model="input.date">

My Vuejs :

var app = new Vue({
    el: "#app",
    data: {
        input: {
            unique_number:"",
            date: "",
            description: ""
        },
            inputErrors: []
    }
});

Any idea ?

Body:
I don't see a datepicker in there. Try changing:

<input type="text" v-model="input.date">

to

<input type="date" v-model="input.date">


问:
Using multiple speech to text APIs to improve accuracy
Has anyone ever tried to transcribe audio using two or more speech to text APIs? You could match up the words using time stamps, and pick the word with the highest confidence. If anyone has done this, did it significantly improve the accuracy of the transcription? Is it worth it?</p>

答:
This approach could be problematic for a number of different reasons.  Not all vendors return confidence scores on a word-by-word basis, and even if they did, a confidence of 60% from one vendor does not mean the same thing as a confidence score of 60% from a different vendor's API.  The confidence scores are only valid within the context of the API that is issuing them.

Most speech-to-text vendors have pretty good models at this point.  Some (like IBM Watson) actually allow you to customize the model by adding vocabulary words.  If you look at the industry benchmarks against the SWITCHBOARD corpus, you'll notice that the vendors keep improving and leapfrogging each other.  On 09/13/2016 Microsoft announced it had the lowest error rate (https://blogs.microsoft.com/next/2016/09/13/microsoft-researchers-achieve-speech-recognition-milestone/).  On 01/11/2017 Google claimed to have beaten this, and then IBM claimed superiority on 03/07/2017 (https://www.ibm.com/blogs/watson/2017/03/reaching-new-records-in-speech-recognition/).  The differences have all been a percent or fraction of a percent improvement.  I would expect that this leapfrogging of improvements will continue for the short term.

So to sum it up - By using two different API's you effectively double the cost of your speech to text implementation - which is going to be hard to justify, based on the minimal improvement in accuracy that you would achieve.


问:
picture element responsive images not working with angular 4
The picture element as

```<code> <picture>
     <source  media="(max-width: 768px)" srcset="../assets/image1.png">
     <source  media="(min-width: 769px)" srcset="../assets/image2.png">
     <source  src="../assets/image3.png">
 </picture>
</code>```

does not work in Angular 4
It selects the first source for all viewport widths, which in the above example is image1.png

Any solutions on this?

答:
Angular has nothing to do with this. The browser interprets the <picture> code alone.

Anyway, the main issue with your code is that it lacks the mandatory  element.

Also, the third <source> is useless, the viewport will be either max-width: 768px or min-width: 769px, it can't be another value.

Body:
The picture element as

 <picture>
     <source  media="(max-width: 768px)" srcset="../assets/image1.png">
     <source  media="(min-width: 769px)" srcset="../assets/image2.png">
     <source  src="../assets/image3.png">
 </picture>

does not work in Angular 4
It selects the first source for all viewport widths, which in the above example is image1.png

Any solutions on this?

Body:
Angular has nothing to do with this. The browser interprets the <picture> code alone.

Anyway, the main issue with your code is that it lacks the mandatory <img> element.

Also, the third <source> is useless, the viewport will be either max-width: 768px or min-width: 769px, it can't be another value.


问:
Use a Class to set parameters in another class - Python
I am working on a Tkinter GUI and I want to add window sizing and positioning control in its separate class.
My structure is like so:

```<code>class MainApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.winsize= WinSize(container, 700, 500, 650, 450, True, True)
</code>```

I want WinSize to set the geometry of the main application as well as handle
the minsize, resizeable in the WinSize class.

```<code>class WinSize:

    def __init__(self, container, width, height, minx, miny, sizeablex, sizeabley):
        self.container = container
        self.width = width
        self.height = height
        self.minx = minx
        self.miny = miny
        self.sizeablex = sizeablex
        self.sizeabley = sizeabley
        self.ws = self.container.winfo_screenwidth()
        self.hs = self.container.winfo_screenheight()
        self.xpos = (self.ws / 2) - (self.width / 2)
        self.ypos = (self.hs / 2) - (self.height / 2)
</code>```

I have been searching extensively and found no solution/guidance on how to get those implemented in the WinSize class for that particular instance and/or Frame.
I want to use the same class to be able to set size and other attributes to pop-up messages/Frames that will display other information.
The main GUI class is taken from @Bryan Oakley's famous example: https://stackoverflow.com/a/7557028/7703610

How do I call the geometry, minsize and resizeable from Tk without having to inherit Tk again in my WinSize class and then apply it to that particular instance?

答:
There are two solutions. You can pass the window to WinSize() instead of the container, or you can use the winfo_toplevel method to get the window for a particular widget.

The first solution would look like this:

```<code>class MainApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        ...
        self.winsize= WinSize(self, 700, 500, 650, 450, True, True)

class WinSize:

    def __init__(self, window, width, height, minx, miny, sizeablex, sizeabley):
        self.window = window
        ...
        self.window.geometry("%d%d+%d+%d" % (width, height, minx, miny))
        ...
</code>```

The second solution requires no changes to the main app. Just add the following to WinSize:

```<code>class WinSize:
    def __init__(...):
        ...
        window = self.container.winfo_toplevel()
        self.window.geometry("%d%d+%d+%d" % (width, height, minx, miny))
</code>```

Body:
I am working on a Tkinter GUI and I want to add window sizing and positioning control in its separate class.
My structure is like so:

class MainApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.winsize= WinSize(container, 700, 500, 650, 450, True, True)

I want WinSize to set the geometry of the main application as well as handle
the minsize, resizeable in the WinSize class.

class WinSize:

    def __init__(self, container, width, height, minx, miny, sizeablex, sizeabley):
        self.container = container
        self.width = width
        self.height = height
        self.minx = minx
        self.miny = miny
        self.sizeablex = sizeablex
        self.sizeabley = sizeabley
        self.ws = self.container.winfo_screenwidth()
        self.hs = self.container.winfo_screenheight()
        self.xpos = (self.ws / 2) - (self.width / 2)
        self.ypos = (self.hs / 2) - (self.height / 2)

I have been searching extensively and found no solution/guidance on how to get those implemented in the WinSize class for that particular instance and/or Frame.
I want to use the same class to be able to set size and other attributes to pop-up messages/Frames that will display other information.
The main GUI class is taken from @Bryan Oakley's famous example: https://stackoverflow.com/a/7557028/7703610

How do I call the geometry, minsize and resizeable from Tk without having to inherit Tk again in my WinSize class and then apply it to that particular instance?

Body:
There are two solutions. You can pass the window to WinSize() instead of the container, or you can use the winfo_toplevel method to get the window for a particular widget.

The first solution would look like this:

class MainApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        ...
        self.winsize= WinSize(self, 700, 500, 650, 450, True, True)

class WinSize:

    def __init__(self, window, width, height, minx, miny, sizeablex, sizeabley):
        self.window = window
        ...
        self.window.geometry("%d%d+%d+%d" % (width, height, minx, miny))
        ...

The second solution requires no changes to the main app. Just add the following to WinSize:

class WinSize:
    def __init__(...):
        ...
        window = self.container.winfo_toplevel()
        self.window.geometry("%d%d+%d+%d" % (width, height, minx, miny))


问:
Parsing a JSON array of values as POJOs
I need to process responses from an external SAP service which returns data as an array of arrays like this:

```<code>{
    "INFO":"",
    "SERVICE_NAME":[["PARAM1","PARAM2","PARAM3","PARAM4"]],
    "RESULTS":[
        ["object1fieldValue1","object1fieldValue2"],
        ["object2fieldValue1","object2fieldValue2"]
    ]
}
</code>```

I would like to process the RESULTS further as a list of DTOs like this:

```<code>public class ResultItemDto {
    private String field1;
    private String field2;
}
</code>```

instead of working with every object as a list of Strings and possibly mapping it manually to DTOs.

What would be the right, concise "Jackson way" of mapping such JSON directly to POJOs?

答:
The "right" way is very subjective, but since you were curious about a concise way, your options are limited given that the fields you want access to are contained within arrays of arrays.  Given this structure, mapping directly via annotations and without using custom deserializers is going to be out of the question.  Your two options for custom parsing are the databind api and the streaming api.  The databind API tends to be a bit easier to read and write, so we'll use that to fulfill your requirements of conciseness

Below is some code that uses an ObjectReader to parse the json tree and then safely uses JsonNode's path, isArrayNode, and asText methods to pluck out the values of those inner arrays if they are where expected, and will not result in an exception if the json you receive is in a different structure.  This assumes you want to throw away the rest of the JSON body, as your question only discusses mapping specifically to the ResultItemDto.

```<code>package foo.bar;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.node.ArrayNode;

import java.util.ArrayList;
import java.util.List;

public class Test {

    static final String JSON = "{\n" +
                                       "    \"INFO\":\"\",\n" +
                                       "    \"SERVICE_NAME\":[[\"PARAM1\",\"PARAM2\",\"PARAM3\",\"PARAM4\"]],\n" +
                                       "    \"RESULTS\":[\n" +
                                       "        [\"object1fieldValue1\",\"object1fieldValue2\"],\n" +
                                       "        [\"object2fieldValue1\",\"object2fieldValue2\"]\n" +
                                       "    ]\n" +
                                       "}";

    static class ResultItemDto {
        private String field1;
        private String field2;
    }

    public static void main(String[] args) throws Exception {
        List<ResultItemDto> list = new ArrayList<ResultItemDto>();

        ObjectReader reader = new ObjectMapper().reader();
        JsonNode resultsNode = reader.readTree(JSON).path("RESULTS");
        if (resultsNode.isArray()) {
            ArrayNode arrNode = (ArrayNode) resultsNode;
            arrNode.elements().forEachRemaining(elem -> {
                ResultItemDto dto = new ResultItemDto()
                dto.field1 = elem.path(0).asText();
                dto.field2 = elem.path(1).asText();
                list.add(dto);
            });
        }
    }
}
</code>```

If you wanted to annotate your DTO class, the above code could be used inside of a custom deserializer once you've annotated the dto with @JsonDeserialize and can call the readTree method on the JsonParser you must use when deserializing.

Title: Parsing a JSON array of values as POJOs

Body:
I need to process responses from an external SAP service which returns data as an array of arrays like this:

{
    "INFO":"",
    "SERVICE_NAME":[["PARAM1","PARAM2","PARAM3","PARAM4"]],
    "RESULTS":[
        ["object1fieldValue1","object1fieldValue2"],
        ["object2fieldValue1","object2fieldValue2"]
    ]
}

I would like to process the RESULTS further as a list of DTOs like this:

public class ResultItemDto {
    private String field1;
    private String field2;
}

instead of working with every object as a list of Strings and possibly mapping it manually to DTOs.

What would be the right, concise "Jackson way" of mapping such JSON directly to POJOs?

Body:
The "right" way is very subjective, but since you were curious about a concise way, your options are limited given that the fields you want access to are contained within arrays of arrays.  Given this structure, mapping directly via annotations and without using custom deserializers is going to be out of the question.  Your two options for custom parsing are the databind api and the streaming api.  The databind API tends to be a bit easier to read and write, so we'll use that to fulfill your requirements of conciseness

Below is some code that uses an ObjectReader to parse the json tree and then safely uses JsonNode's path, isArrayNode, and asText methods to pluck out the values of those inner arrays if they are where expected, and will not result in an exception if the json you receive is in a different structure.  This assumes you want to throw away the rest of the JSON body, as your question only discusses mapping specifically to the ResultItemDto.

package foo.bar;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.node.ArrayNode;

import java.util.ArrayList;
import java.util.List;

public class Test {

    static final String JSON = "{\n" +
                                       "    \"INFO\":\"\",\n" +
                                       "    \"SERVICE_NAME\":[[\"PARAM1\",\"PARAM2\",\"PARAM3\",\"PARAM4\"]],\n" +
                                       "    \"RESULTS\":[\n" +
                                       "        [\"object1fieldValue1\",\"object1fieldValue2\"],\n" +
                                       "        [\"object2fieldValue1\",\"object2fieldValue2\"]\n" +
                                       "    ]\n" +
                                       "}";

    static class ResultItemDto {
        private String field1;
        private String field2;
    }

    public static void main(String[] args) throws Exception {
        List<ResultItemDto> list = new ArrayList<ResultItemDto>();

        ObjectReader reader = new ObjectMapper().reader();
        JsonNode resultsNode = reader.readTree(JSON).path("RESULTS");
        if (resultsNode.isArray()) {
            ArrayNode arrNode = (ArrayNode) resultsNode;
            arrNode.elements().forEachRemaining(elem -> {
                ResultItemDto dto = new ResultItemDto()
                dto.field1 = elem.path(0).asText();
                dto.field2 = elem.path(1).asText();
                list.add(dto);
            });
        }
    }
}

If you wanted to annotate your DTO class, the above code could be used inside of a custom deserializer once you've annotated the dto with @JsonDeserialize and can call the readTree method on the JsonParser you must use when deserializing.


问:
iOS - Push viewController from code and storyboard
I have this code

```<code> PlaceViewController *newView = [self.storyboard instantiateViewControllerWithIdentifier:@"PlaceView"];
 [self presentViewController:newView animated:YES completion:nil];
</code>```

And I can change view, but I would push this view for when I return at this page, the state persists.

I try to put this code:

```<code>[self.navigationController pushViewController:newView animated:YES];
</code>```

but doesn't do anything.

Thanks

答:
Use:

```<code>UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"STORYBOARD_NAME" bundle:nil];
PlaceViewController *newView = [storyboard instantiateViewControllerWithIdentifier:@"PlaceView"];
[self presentViewController:newView animated:YES completion:nil];
</code>```

Or:

```<code>UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"STORYBOARD_NAME" bundle:nil];
PlaceViewController *newView = [storyboard instantiateViewControllerWithIdentifier:@"PlaceView"];
[self.navigationController pushViewController:newView animated:YES];
</code>```

Body:
I have this code

 PlaceViewController *newView = [self.storyboard instantiateViewControllerWithIdentifier:@"PlaceView"];
 [self presentViewController:newView animated:YES completion:nil];

And I can change view, but I would push this view for when I return at this page, the state persists.

I try to put this code:

[self.navigationController pushViewController:newView animated:YES];

but doesn't do anything.

Thanks

Body:
Use:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"STORYBOARD_NAME" bundle:nil];
PlaceViewController *newView = [storyboard instantiateViewControllerWithIdentifier:@"PlaceView"];
[self presentViewController:newView animated:YES completion:nil];

Or:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"STORYBOARD_NAME" bundle:nil];
PlaceViewController *newView = [storyboard instantiateViewControllerWithIdentifier:@"PlaceView"];
[self.navigationController pushViewController:newView animated:YES];


问:
Selecting another HTML element from an ng-click attribute
I am attempting to pass a file into a function, where the file is originated from an input type of file.  My code looks something like this.

```<code><input type="file" id="scvFileUploadId"/>

<button id="uploadFilesubmit" ng-click"ctrl.uploadFile()">Upload</button>
</code>```

In short, I would like to take the file that has been added to the input and pass it into the parameter of the function of the ng-click attribute that is fired when the button is clicked.  I think this may be simple, but I cannot wrap my head around it at the moment.

I'm trying to do something like this.

```<code><input type="file" id="scvFileUploadId"/>

<button id="uploadFilesubmit" ng-click"ctrl.uploadFile(#scvFileUploadId.file)">Upload</button>
</code>```

答:
I highly recommend using existing directives created by the community;

https://github.com/nervgh/angular-file-upload

https://github.com/danialfarid/ng-file-upload

But if you are restricted and want to avoid 3rd parties you can see this implementation:

ng-model for <input type="file"/>

```<code><input type="file" fileread="vm.uploadme" />
<button id="uploadFilesubmit" ng-click"ctrl.uploadFile(vm.uploadme)">Upload</button>
</code>```

Body:
I am attempting to pass a file into a function, where the file is originated from an input type of file.  My code looks something like this.

<input type="file" id="scvFileUploadId"/>

<button id="uploadFilesubmit" ng-click"ctrl.uploadFile()">Upload</button>

In short, I would like to take the file that has been added to the input and pass it into the parameter of the function of the ng-click attribute that is fired when the button is clicked.  I think this may be simple, but I cannot wrap my head around it at the moment.

I'm trying to do something like this.

<input type="file" id="scvFileUploadId"/>

<button id="uploadFilesubmit" ng-click"ctrl.uploadFile(#scvFileUploadId.file)">Upload</button>

Body:
I highly recommend using existing directives created by the community;

https://github.com/nervgh/angular-file-upload

https://github.com/danialfarid/ng-file-upload

But if you are restricted and want to avoid 3rd parties you can see this implementation:

ng-model for <input type="file"/>

<input type="file" fileread="vm.uploadme" />
<button id="uploadFilesubmit" ng-click"ctrl.uploadFile(vm.uploadme)">Upload</button>