问:
Web method returns 401 without calling membership provider
I have a Web Api controller which (partially) looks like this:

```<code>public class VehicleController : ApiController
{
    [Authorize]
    public VehicleModel Get(VehicleRequest request)
    {
        return VehicleLogic.Get(request);
    }
}
</code>```

A custom membership provider has been configured as follows:

```<code><system.web>
    <membership defaultProvider="CustMembership">
        <providers>
            <clear/>
            <add name="CustMembership"
                type="blah.Auth.CustMembership"
                enablePasswordRetrieval="false"
                enablePasswordReset="false"
                requiresQuestionAndAnswer="false"
                requiresUniqueEmail="false"
                minRequiredPasswordLength="6"
                minRequiredNonalphanumericCharacters="0"
                passwordAttemptWindow="10"
                applicationName="/" />
        </providers>
    </membership>
    ...
</system.web>

public class CustMembership : MembershipProvider
{
    ...
    public override bool ValidateUser(string username, string password)
    {
        using (var context = new Entities())
        {
            var user = context.UserAccounts.SingleOrDefault(x => x.Username == username);
            if (user != null)
            {
                var hash = user.Hash;
                var salt = user.Salt;
                var saltedPassword = $"{salt}{password}{salt}";
                var check = getSha256(saltedPassword);
                if (check == hash)
                {
                    _Name = username;
                    return true;
                }
            }
        }
        return false;
    }
    ...
}
</code>```

However, when I make a call to the method from Postman, a 401 is returned and the provider code is never called. If I place a break-point at the start of the ValidateUser method, it is never hit.

If I remove the [Authorize] attribute, all works as I would expect.

It's as if a provider is being used, but not the one I am expecting.

The same code works fine in other projects.

What am I missing?

答:
The way I understand the Authorize attribute is that, if you call a method without authentication, you would get a 401 (which matches with the result you are getting)

https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

Using the [Authorize] Attribute

Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action.

From the way I understand this, you would need to have a way to "authenticate" the user first. Then, for the subsequent calls the Authorize attribute will allow the authorised request to proceed.

Body:
I have a Web Api controller which (partially) looks like this:

public class VehicleController : ApiController
{
    [Authorize]
    public VehicleModel Get(VehicleRequest request)
    {
        return VehicleLogic.Get(request);
    }
}

A custom membership provider has been configured as follows:

<system.web>
    <membership defaultProvider="CustMembership">
        <providers>
            <clear/>
            <add name="CustMembership"
                type="blah.Auth.CustMembership"
                enablePasswordRetrieval="false"
                enablePasswordReset="false"
                requiresQuestionAndAnswer="false"
                requiresUniqueEmail="false"
                minRequiredPasswordLength="6"
                minRequiredNonalphanumericCharacters="0"
                passwordAttemptWindow="10"
                applicationName="/" />
        </providers>
    </membership>
    ...
</system.web>

public class CustMembership : MembershipProvider
{
    ...
    public override bool ValidateUser(string username, string password)
    {
        using (var context = new Entities())
        {
            var user = context.UserAccounts.SingleOrDefault(x => x.Username == username);
            if (user != null)
            {
                var hash = user.Hash;
                var salt = user.Salt;
                var saltedPassword = $"{salt}{password}{salt}";
                var check = getSha256(saltedPassword);
                if (check == hash)
                {
                    _Name = username;
                    return true;
                }
            }
        }
        return false;
    }
    ...
}

However, when I make a call to the method from Postman, a 401 is returned and the provider code is never called. If I place a break-point at the start of the ValidateUser method, it is never hit.

If I remove the [Authorize] attribute, all works as I would expect.

It's as if a provider is being used, but not the one I am expecting.

The same code works fine in other projects.

What am I missing?


来源: stackexchange

问:
CakeDC/Users new role
I'm using the CakeDC/Users plugin and want add other user roles.

Right now I have the both superuser and user roles.

I'm doing the permissions control in the permissions.php.

I'm also overwriting the layout files. Tried initially force the role field in the form, but the plugin write the user role in the controllers.

答:
As steinkel posted in this issue: https://github.com/CakeDC/users/issues/513

You must add this line after the pathEntity in /vendor/cakedc/user/src/Controller/Traits/SimpleCrudTrait.php

```<code>$entity->role = $this->request->data('role');
</code>```

Then configure your form to pass the role field. In my case, I passed this information with a select box.

ContentLicense: CC BY-SA 3.0

Title: CakeDC/Users new role

Body:
As steinkel posted in this issue: https://github.com/CakeDC/users/issues/513

You must add this line after the pathEntity in /vendor/cakedc/user/src/Controller/Traits/SimpleCrudTrait.php

$entity->role = $this->request->data('role');

Then configure your form to pass the role field. In my case, I passed this information with a select box.


问:
React Router: Get location in container component
I need to access the active path in the parent component, so that I can vary some CSS depending on the location. Here is App - the parent:

```<code>class App extends React.Component {

  render(){
    return (
      <div className="wrapper" >
        <div className="content">
          <Router>
          <div className="container_b">
            <Menu />
            <div>
              <Route exact path="/" component={Home}/>
              <Route path="/confidence" component={ConfidenceInterval}/>
              <Route path="/proind" component={ProportionTestInd}/>
              <Route path="/prodep" component={ProportionTestDep}/>
            </div>
          </div>
          </Router>
          <div className="push"></div>
        </div>
        <footer className="footer"><Footer /></footer>
      </div>
    )
  }

}
</code>```

答:
I think for the App component, you have two options. First one is wrapping App with withRouter higher order component.
React-router provides a higher order component called withRouter, which passes match, history and location props to the component wrapped by it.
(for details please check withRouter)

In that case you can to the following

```<code>class App extends React.Component {

  render(){
    const {location: {pathname}} = this.props // pathname gives you the current path
    return (
      <div className="wrapper" >
        <div className="content">
          <Router>
          <div className="container_b">
            <Menu />
            <div>
              <Route exact path="/" component={Home}/>
              <Route path="/confidence" component={ConfidenceInterval}/>
              <Route path="/proind" component={ProportionTestInd}/>
              <Route path="/prodep" component={ProportionTestDep}/>
            </div>
          </div>
          </Router>
          <div className="push"></div>
        </div>
        <footer className="footer"><Footer /></footer>
      </div>
    )
  }

}

export const WrappedApp = withRouter(App)
</code>```

Second option is, (again for App component) you can use window.location (please check window.location). location.pathname should also give you the current path in that case.

For other components, like Home,ConfidenceInterval etc, Route passes match, history and location props by default so you can make use of them.

Body:
I need to access the active path in the parent component, so that I can vary some CSS depending on the location. Here is App - the parent:

class App extends React.Component {

  render(){
    return (

          <Router>

            <Menu />

              <Route exact path="/" component={Home}/>
              <Route path="/confidence" component={ConfidenceInterval}/>
              <Route path="/proind" component={ProportionTestInd}/>
              <Route path="/prodep" component={ProportionTestDep}/>

          </Router>

    )
  }

}

Body:
I think for the App component, you have two options. First one is wrapping App with withRouter higher order component.
React-router provides a higher order component called withRouter, which passes match, history and location props to the component wrapped by it.
(for details please check withRouter)

In that case you can to the following

class App extends React.Component {

  render(){
    const {location: {pathname}} = this.props // pathname gives you the current path
    return (
      <div className="wrapper" >
        <div className="content">
          <Router>
          <div className="container_b">
            <Menu />
            <div>
              <Route exact path="/" component={Home}/>
              <Route path="/confidence" component={ConfidenceInterval}/>
              <Route path="/proind" component={ProportionTestInd}/>
              <Route path="/prodep" component={ProportionTestDep}/>
            </div>
          </div>
          </Router>
          <div className="push"></div>
        </div>
        <footer className="footer"><Footer /></footer>
      </div>
    )
  }

}

export const WrappedApp = withRouter(App)

Second option is, (again for App component) you can use window.location (please check window.location). location.pathname should also give you the current path in that case.

For other components, like Home,ConfidenceInterval etc, Route passes match, history and location props by default so you can make use of them.


问:
Am trying to join three queries in an ACCESS but the result is duplicating
why the result is duplicating for this query, am trying to combine three queries together in ACCESS</p>

```<code>`SELECT qryNDI.tblNDI_First.Matric_no, qryNDI.tblNDI_First.TPoint,
qryNDI.tblNDI_Second.TPoint, qryNDII.tblNDII_First.TPoint,
qryNDII.tblNDII_Second.TPoint, qryNDIIYEARIII.tblNDIIYEARIII_First.TPoint,
qryNDIIYEARIII.tblNDIIYEARIII_Second.TPoint FROM ((qryNDI INNER JOIN qryNDII
ON qryNDI.tblNDI_First.Matric_no = qryNDII.Matric_no) INNER JOIN
qryNDIIYEARIII ON qryNDII.Matric_no = qryNDIIYEARIII.Matric_no);`
</code>```

答:
possible quick fix!  use 'distinct' right after 'select'.  Distinct Description

```<code>SELECT distinct qryNDI.tblNDI_First.Matric_no, qryNDI.tblNDI_First.TPoint,
qryNDI.tblNDI_Second.TPoint, qryNDII.tblNDII_First.TPoint,
qryNDII.tblNDII_Second.TPoint, qryNDIIYEARIII.tblNDIIYEARIII_First.TPoint,
qryNDIIYEARIII.tblNDIIYEARIII_Second.TPoint FROM ((qryNDI INNER JOIN qryNDII
ON qryNDI.tblNDI_First.Matric_no = qryNDII.Matric_no) INNER JOIN
qryNDIIYEARIII ON qryNDII.Matric_no = qryNDIIYEARIII.Matric_no);
</code>```

to help understand the relationship between the data.  example: you have one parent table row that matches three child table rows then your query will show three rows, only if those three child rows are unique in some way. if they differ only by the identifier using distinct may give you the results your looking for.

I cannot 'comment' because my rep points aren't high enough.

Body:
why the result is duplicating for this query, am trying to combine three queries together in ACCESS

`SELECT qryNDI.tblNDI_First.Matric_no, qryNDI.tblNDI_First.TPoint,
qryNDI.tblNDI_Second.TPoint, qryNDII.tblNDII_First.TPoint,
qryNDII.tblNDII_Second.TPoint, qryNDIIYEARIII.tblNDIIYEARIII_First.TPoint,
qryNDIIYEARIII.tblNDIIYEARIII_Second.TPoint FROM ((qryNDI INNER JOIN qryNDII
ON qryNDI.tblNDI_First.Matric_no = qryNDII.Matric_no) INNER JOIN
qryNDIIYEARIII ON qryNDII.Matric_no = qryNDIIYEARIII.Matric_no);`

Body:
possible quick fix!  use 'distinct' right after 'select'.  Distinct Description

SELECT distinct qryNDI.tblNDI_First.Matric_no, qryNDI.tblNDI_First.TPoint,
qryNDI.tblNDI_Second.TPoint, qryNDII.tblNDII_First.TPoint,
qryNDII.tblNDII_Second.TPoint, qryNDIIYEARIII.tblNDIIYEARIII_First.TPoint,
qryNDIIYEARIII.tblNDIIYEARIII_Second.TPoint FROM ((qryNDI INNER JOIN qryNDII
ON qryNDI.tblNDI_First.Matric_no = qryNDII.Matric_no) INNER JOIN
qryNDIIYEARIII ON qryNDII.Matric_no = qryNDIIYEARIII.Matric_no);

to help understand the relationship between the data.  example: you have one parent table row that matches three child table rows then your query will show three rows, only if those three child rows are unique in some way. if they differ only by the identifier using distinct may give you the results your looking for.

I cannot 'comment' because my rep points aren't high enough.


问:
Receiving UDP packets at high frequency : packet loss?
I have a C++ application which uses a UDP Server (using Boost.Asio) that receives packets from a gigabit local network device at a high frequency (3500 packets per second). Some users report a few packet losses. So in the end I chose to run in parallel WireShark and my application to check if there are any packets that WireShark is able to receive but not my application.

What I found is that WireShark does not receive every packet, it seems that it misses some. My application misses also a few more frames that Wireshark received correctly.

My questions : Is it possible WireShark gets packets that my application does not ? I thought maybe WireShark has low-level access to the IP stack and packets are discarded by the OS even if they are shown in WireShark ?
Is it possible that the operation in (1) takes too much time such that the next async_receive_from is called too late?
I would like to have opinions on this subject. Thanks.

Here is the code I use (quite basic). udp_server.h :

```<code>#pragma once

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <fstream>

const int MAX_BUFFER_SIZE = 65537;

using boost::asio::ip::udp;

class UDPServer
{
public:
    UDPServer(boost::asio::io_service& ios, udp::endpoint endpoint)
        :m_io_service(ios),
        m_udp_socket(m_io_service, endpoint)
    {
        // Resize the buffer to max size in the component property
        m_recv_buffer.resize(MAX_BUFFER_SIZE);

        m_output_file.open("out.bin", std::ios::out | std::ios::binary);

        StartReceive();
    }

public:
    void StartReceive()
    {
        m_udp_socket.async_receive_from(
            boost::asio::buffer(m_recv_buffer), m_remote_endpoint,
            boost::bind(&UDPServer::HandleReceive, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    }

private:
    void HandleReceive(const boost::system::error_code& error, std::size_t bytes_transferred)
    {
        if (!error || error == boost::asio::error::message_size)
        {
            // Write to output -- (1)
            m_output_file.sputn(&m_recv_buffer[0], bytes_transferred);

            // Start to receive again
            StartReceive();
        }
    }

    boost::asio::io_service&    m_io_service;
    udp::socket                 m_udp_socket;
    udp::endpoint               m_remote_endpoint;
    std::vector<char>           m_recv_buffer;
    std::filebuf                m_output_file;
};
</code>```

main.cpp:

```<code>include <boost/asio.hpp>
#include "udp_server.h"

const unsigned short PORT_NUMBER = 44444;

int main()
{
    boost::asio::io_service ios;
    boost::asio::ip::udp::endpoint endpoint(udp::endpoint(udp::v4(), PORT_NUMBER));
    UDPServer server(ios, endpoint);
    ios.run();

    return 0;
}
</code>```

答:
In a word, yes.

If you want to fix or improve this, rather than just ask about it, use a much bigger socket receive buffer than the default, as big as the platform will allow, and make sure your writes to the file are also buffered, with as large a buffer as you can afford given whatever your requirements are about data loss on crash.

Body:
I have a C++ application which uses a UDP Server (using Boost.Asio) that receives packets from a gigabit local network device at a high frequency (3500 packets per second). Some users report a few packet losses. So in the end I chose to run in parallel WireShark and my application to check if there are any packets that WireShark is able to receive but not my application.

What I found is that WireShark does not receive every packet, it seems that it misses some. My application misses also a few more frames that Wireshark received correctly.

My questions : Is it possible WireShark gets packets that my application does not ? I thought maybe WireShark has low-level access to the IP stack and packets are discarded by the OS even if they are shown in WireShark ?
Is it possible that the operation in (1) takes too much time such that the next async_receive_from is called too late?
I would like to have opinions on this subject. Thanks.

Here is the code I use (quite basic). udp_server.h :

#pragma once

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <fstream>

const int MAX_BUFFER_SIZE = 65537;

using boost::asio::ip::udp;

class UDPServer
{
public:
    UDPServer(boost::asio::io_service& ios, udp::endpoint endpoint)
        :m_io_service(ios),
        m_udp_socket(m_io_service, endpoint)
    {
        // Resize the buffer to max size in the component property
        m_recv_buffer.resize(MAX_BUFFER_SIZE);

        m_output_file.open("out.bin", std::ios::out | std::ios::binary);

        StartReceive();
    }

public:
    void StartReceive()
    {
        m_udp_socket.async_receive_from(
            boost::asio::buffer(m_recv_buffer), m_remote_endpoint,
            boost::bind(&UDPServer::HandleReceive, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    }

private:
    void HandleReceive(const boost::system::error_code& error, std::size_t bytes_transferred)
    {
        if (!error || error == boost::asio::error::message_size)
        {
            // Write to output -- (1)
            m_output_file.sputn(&m_recv_buffer[0], bytes_transferred);

            // Start to receive again
            StartReceive();
        }
    }

    boost::asio::io_service&    m_io_service;
    udp::socket                 m_udp_socket;
    udp::endpoint               m_remote_endpoint;
    std::vector<char>           m_recv_buffer;
    std::filebuf                m_output_file;
};

main.cpp:

include <boost/asio.hpp>
#include "udp_server.h"

const unsigned short PORT_NUMBER = 44444;

int main()
{
    boost::asio::io_service ios;
    boost::asio::ip::udp::endpoint endpoint(udp::endpoint(udp::v4(), PORT_NUMBER));
    UDPServer server(ios, endpoint);
    ios.run();

    return 0;
}


问:
Optional for Post request jackson
I'm building a rest client in java. I have the following object Mode.

```<code> public class Mode {

 @JsonProperty("Replicated")
 private Optional<Replicated> replicated = Optional.empty();

 @JsonProperty("Global")
 private Optional<Global> global = Optional.empty();

 public Optional<Global> getGlobal() {
    return global;
 }

 public Optional<Replicated> getReplicated() {
    return replicated;
 }

 public void setGlobal(Global global) {
    this.global = Optional.ofNullable(global);
 }

 public void setReplicated(Replicated replicated) {
    this.replicated = Optional.ofNullable(replicated);
 }
}
</code>```

The 2 fields are Optionals.

This approach works for the GET request. But my issue happens for the POST request. In fact my object sent is the following :

```<code> { Mode : {Replicated : {present : true} ...
</code>```

So my workaround is the following :

```<code>@JsonProperty("Global")
public Global getGlobalForPost() {
    if (global.isPresent()) {
        return global.get();
    }
    return null;
}

@JsonProperty("Replicated")
public Replicated getReplicatedForPost() {
    if (replicated.isPresent()) {
        return replicated.get();
    }
    return null;
}
</code>```

Do you know a better solution, Maybe something in jackson which do the trick?

答: Jackson you cannot make the difference between optional and non-optional fields. Just declare any field in your POJO. If a field is not present in your JSON structure then Jackson will not call the setter. You may keep track of wether a setter has been called with a flag in the POJO.</p>

Title: Optional for Post request jackson

Body:
I'm building a rest client in java. I have the following object Mode.

 public class Mode {

 @JsonProperty("Replicated")
 private Optional<Replicated> replicated = Optional.empty();

 @JsonProperty("Global")
 private Optional<Global> global = Optional.empty();

 public Optional<Global> getGlobal() {
    return global;
 }

 public Optional<Replicated> getReplicated() {
    return replicated;
 }

 public void setGlobal(Global global) {
    this.global = Optional.ofNullable(global);
 }

 public void setReplicated(Replicated replicated) {
    this.replicated = Optional.ofNullable(replicated);
 }
}

The 2 fields are Optionals.

This approach works for the GET request. But my issue happens for the POST request. In fact my object sent is the following :

 { Mode : {Replicated : {present : true} ...

So my workaround is the following :

@JsonProperty("Global")
public Global getGlobalForPost() {
    if (global.isPresent()) {
        return global.get();
    }
    return null;
}

@JsonProperty("Replicated")
public Replicated getReplicatedForPost() {
    if (replicated.isPresent()) {
        return replicated.get();
    }
    return null;
}

Do you know a better solution, Maybe something in jackson which do the trick?


问:
Error when restoring model (Multiple OpKernel registrations match NodeDef)
I'm getting an error when attempting to restore a model from a checkpoint.

This is with the nightly Windows GPU build for python 3.5 on 2017-06-13.

```<code>InvalidArgumentError (see above for traceback):
Multiple OpKernel registrations match NodeDef 'Decoder/decoder/GatherTree = GatherTree[T=DT_INT32, _device="/device:CPU:0"](Decoder/decoder/TensorArrayStack_1/TensorArrayGatherV3, Decoder/decoder/TensorArrayStack
_2/TensorArrayGatherV3, Decoder/decoder/while/Exit_18)': 'op: "GatherTree" device_type: "GPU" constraint { name: "T" allowed_values { list { type: DT_INT32 } } }' and 'op: "GatherTree" device_type: "GPU" constraint { name: "T" allowed_values { list { type: DT_
INT32 } } }'[[Node: Decoder/decoder/GatherTree = GatherTree[T=DT_INT32, _device="/device:CPU:0"](Decoder/decoder/TensorArrayStack_1/TensorArrayGatherV3, Decoder/decoder/TensorArrayStack_2/TensorArrayGatherV3, Decoder/decoder/while/Exit_18)]]
</code>```

The model is using dynamic_decode with beam search, which otherwise works fine in training mode when not using beam search for decoding.

Any ideas on what this means or how to debug it?

答: I also faced the same issue a day ago. Turns out it was a bug in tensorflow. It's resolved now and BeamSearchDecoder should work with the latest build of tensorflow. </p>

Body:
I'm getting an error when attempting to restore a model from a checkpoint.

This is with the nightly Windows GPU build for python 3.5 on 2017-06-13.

InvalidArgumentError (see above for traceback):
Multiple OpKernel registrations match NodeDef 'Decoder/decoder/GatherTree = GatherTree[T=DT_INT32, _device="/device:CPU:0"](Decoder/decoder/TensorArrayStack_1/TensorArrayGatherV3, Decoder/decoder/TensorArrayStack
_2/TensorArrayGatherV3, Decoder/decoder/while/Exit_18)': 'op: "GatherTree" device_type: "GPU" constraint { name: "T" allowed_values { list { type: DT_INT32 } } }' and 'op: "GatherTree" device_type: "GPU" constraint { name: "T" allowed_values { list { type: DT_
INT32 } } }'[[Node: Decoder/decoder/GatherTree = GatherTree[T=DT_INT32, _device="/device:CPU:0"](Decoder/decoder/TensorArrayStack_1/TensorArrayGatherV3, Decoder/decoder/TensorArrayStack_2/TensorArrayGatherV3, Decoder/decoder/while/Exit_18)]]

The model is using dynamic_decode with beam search, which otherwise works fine in training mode when not using beam search for decoding.

Any ideas on what this means or how to debug it?


问:
UIButton inside of multiple UICollectionViewCells not working
I have created a UICollectionView with cells called baseCell. Inside of those cells is another UICollectionView with cells called subCell. Inside of each subCell is a UIButton. The button has

Here is the code that sets up the button and its action:

```<code>let openOptionsButton: UIButton = {
    let button = UIButton()
    button.setImage(#imageLiteral(resourceName: "CircleAdd"), for: .normal)
    button.addTarget(self, action: #selector(slideOverToOptions), for: .touchUpInside)
    button.contentMode = .scaleAspectFit
    return button
}()

func slideOverToOptions() {
    print("This is working")
}

func setupViews(){
    addSubview(openOptionsButton)

            _ = openOptionsButton.anchor(topAnchor, left: nil, bottom: nil, right: rightAnchor, topConstant: 8, leftConstant: 0, bottomConstant: 0, rightConstant: 12, widthConstant: 48, heightConstant: 48)
}
</code>```

When I press the button, it does not print. How can I fix this issue?

答: I figured out the issue. My problem was that I was accessing self inside of my button (in the button.addTarget line) with using a let declaration for the button. In order to access self inside my button, I needed to change let to lazy var. That fixed my issue.

Body:
I have created a UICollectionView with cells called baseCell. Inside of those cells is another UICollectionView with cells called subCell. Inside of each subCell is a UIButton. The button has

Here is the code that sets up the button and its action:

let openOptionsButton: UIButton = {
    let button = UIButton()
    button.setImage(#imageLiteral(resourceName: "CircleAdd"), for: .normal)
    button.addTarget(self, action: #selector(slideOverToOptions), for: .touchUpInside)
    button.contentMode = .scaleAspectFit
    return button
}()

func slideOverToOptions() {
    print("This is working")
}

func setupViews(){
    addSubview(openOptionsButton)

            _ = openOptionsButton.anchor(topAnchor, left: nil, bottom: nil, right: rightAnchor, topConstant: 8, leftConstant: 0, bottomConstant: 0, rightConstant: 12, widthConstant: 48, heightConstant: 48)
}

When I press the button, it does not print. How can I fix this issue?


问:
How to sort Solr Multivalued Result Or Store data without multivalued
I want to sort solr result by sku,

Here is my query to sort result

```<code>http://localhost:8983/solr/test_core/select?sort=skucode+asc&q=*skucode*&wt=xml
</code>```

skucode tag stored data in numeric field.

```<code><str name="id">39902395</str>
<arr name="skucode"><long>5076501</long></arr>
</code>```

I have stored data in solr using xml file.

It gives error that can not sort on multivalued field: skucode

Or Store data without multivalued

Please let me know how to store data without multivalued or how to change from backend.

答:
Your query will work only if the field on which you are performing sorting is single valued not multi-valued. You can use function query to perform sort on multi-valued field.

```<code>http://localhost:8983/solr/test_core/select?sort=field(skucode,max)+ASC&q=*skucode*&wt=xml
</code>```

For more Information on function query :- https://cwiki.apache.org/confluence/display/solr/Function+Queries

The second approach in which the query that are you using will also work is that you can change the data type for skucode and make it single value. To make it single value change data-type for skucode from longs to long in schema.xml.

```<code><field name="skucode" type="long"/>
</code>```

P.S :- After changing its data-type you need to re-index to reflect your changes

Body:
I want to sort solr result by sku,

Here is my query to sort result

http://localhost:8983/solr/test_core/select?sort=skucode+asc&q=*skucode*&wt=xml

skucode tag stored data in numeric field.

<str name="id">39902395</str>
<arr name="skucode"><long>5076501</long></arr>

I have stored data in solr using xml file.

It gives error that can not sort on multivalued field: skucode

Or Store data without multivalued

Please let me know how to store data without multivalued or how to change from backend.

Body:
Your query will work only if the field on which you are performing sorting is single valued not multi-valued. You can use function query to perform sort on multi-valued field.

http://localhost:8983/solr/test_core/select?sort=field(skucode,max)+ASC&q=*skucode*&wt=xml

For more Information on function query :- https://cwiki.apache.org/confluence/display/solr/Function+Queries

The second approach in which the query that are you using will also work is that you can change the data type for skucode and make it single value. To make it single value change data-type for skucode from longs to long in schema.xml.

<field name="skucode" type="long"/>

P.S :- After changing its data-type you need to re-index to reflect your changes


问:
gSOAP C union to xml encoding
I am generating the C to XML encoders using the soapcpp2 tool from gSoap 2.8.44
My input to soapcpp2 is an h file with:

```<code>union U_u
{
        int i;
        int j;
        int k;
};

struct A_t {
        int choice_type;
        int __union_choice_type;
        union U_u choice;
};
</code>```

After running the soapcpp2 -c and after linking with my test code, I get the encoded xml as

```<code><A-t>
   <choice-type>1</choice-type>
   <i>0</i>
</A-t>
</code>```

Why is the union element name missing from the xml?
I was expecting this:

```<code><A-t>
    <choice-type>1</choice-type>
    <choice>
      <i>0</i>
    </choice>
</A-t>
</code>```

Is there an option to include the union name also in the xml?

答:
A union provides a choice of elements, so one of , <j>, or <k> will show up in XML.

If you want these to be subelements of <choice> then use:

```<code>struct A_t {
    int choice_type;
    struct A_t_choice {
        int __union_choice_type;
        union U_u choice;
    } choice;
};
</code>```

Title: gSOAP C union to xml encoding

Body:
I am generating the C to XML encoders using the soapcpp2 tool from gSoap 2.8.44
My input to soapcpp2 is an h file with:

union U_u
{
        int i;
        int j;
        int k;
};

struct A_t {
        int choice_type;
        int __union_choice_type;
        union U_u choice;
};

After running the soapcpp2 -c and after linking with my test code, I get the encoded xml as

   <choice-type>1</choice-type>
   0

Why is the union element name missing from the xml?
I was expecting this:

    <choice-type>1</choice-type>
    <choice>
      0
    </choice>

Is there an option to include the union name also in the xml?

Body:
A union provides a choice of elements, so one of <i>, <j>, or <k> will show up in XML.

If you want these to be subelements of <choice> then use:

struct A_t {
    int choice_type;
    struct A_t_choice {
        int __union_choice_type;
        union U_u choice;
    } choice;
};


问:
TensorFlow image reading queue empty
I'm trying to use the pipeline for reading images to the CNN. I used string_input_producer() to obtain the queue of file names, but it seems to hang there without doing anything. Below is my code, please give me some advise of how to make it work.

```<code>def read_image_file(filename_queue, labels):
    reader = tf.WholeFileReader()
    key, value = reader.read(filename_queue)
    image = tf.image.decode_png(value, channels=3)
    image = tf.cast(image, tf.float32)
    resized_image = tf.image.resize_images(image, [224, 112])
    with tf.Session() as sess:
        label = getLabel(labels, key.eval())
    return resized_image, label

def input_pipeline(filename_queue, queue_names, batch_size, num_epochs, labels):
    image, label = read_image_file(filename_queue, labels)
    min_after_dequeue = 10 * batch_size
    capacity = 20 * batch_size
    image_batch, label_batch = tf.train.shuffle_batch(
        [image, label], batch_size=batch_size, num_threads=1, capacity=capacity,
        min_after_dequeue=min_after_dequeue)
    return image_batch, label_batch

train_queue = tf.train.string_input_producer(trainnames, shuffle=True, num_epochs=epochs)

train_batch, train_label = input_pipeline(train_queue, trainnames, batch_size, epochs, labels)

prediction = AlexNet(x)

#Training
with tf.name_scope("cost_function") as scope:
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=train_label, logits=prediction(train_batch)))
    tf.summary.scalar("cost_function", cost)

    train_step = tf.train.MomentumOptimizer(learning_rate, 0.9).minimize(cost)

#Accuracy
with tf.name_scope("accuracy") as scope:
    correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(y_,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    tf.summary.scalar("accuracy", accuracy)

    merged = tf.summary.merge_all()

#Session
with tf.Session() as sess:
    print('started')
    sess.run(tf.global_variables_initializer())
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord, start=True)
    sess.run(threads)

    try:
        for step in range(steps_per_epch * epochs):
            print('step: %d' %step)
            sess.run(train_step)
    except tf.errors.OutOfRangeError as ex:
        pass

    coord.request_stop()
    coord.join(threads)
</code>```

答:
Your code is not completely self-contained as the get_label method is not defined.

But it is very likely that the issue you have comes from these lines in the read_image_file method:

```<code>with tf.Session() as sess:
    label = getLabel(labels, key.eval())
</code>```

The key.eval part tries to dequeue an element of a queue which has not started yet.
You shouldn't create any session before your input pipeline is defined (nor try to eval key (and possibly labels)). The get_label method should only perform tensor operations on labels and key and return a label tensor..

For example, you can use these tensor string operations so they will be part of the graph.

Title: TensorFlow image reading queue empty

Body:
I'm trying to use the pipeline for reading images to the CNN. I used string_input_producer() to obtain the queue of file names, but it seems to hang there without doing anything. Below is my code, please give me some advise of how to make it work.

def read_image_file(filename_queue, labels):
    reader = tf.WholeFileReader()
    key, value = reader.read(filename_queue)
    image = tf.image.decode_png(value, channels=3)
    image = tf.cast(image, tf.float32)
    resized_image = tf.image.resize_images(image, [224, 112])
    with tf.Session() as sess:
        label = getLabel(labels, key.eval())
    return resized_image, label

def input_pipeline(filename_queue, queue_names, batch_size, num_epochs, labels):
    image, label = read_image_file(filename_queue, labels)
    min_after_dequeue = 10 * batch_size
    capacity = 20 * batch_size
    image_batch, label_batch = tf.train.shuffle_batch(
        [image, label], batch_size=batch_size, num_threads=1, capacity=capacity,
        min_after_dequeue=min_after_dequeue)
    return image_batch, label_batch

train_queue = tf.train.string_input_producer(trainnames, shuffle=True, num_epochs=epochs)

train_batch, train_label = input_pipeline(train_queue, trainnames, batch_size, epochs, labels)

prediction = AlexNet(x)

#Training
with tf.name_scope("cost_function") as scope:
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=train_label, logits=prediction(train_batch)))
    tf.summary.scalar("cost_function", cost)

    train_step = tf.train.MomentumOptimizer(learning_rate, 0.9).minimize(cost)

#Accuracy
with tf.name_scope("accuracy") as scope:
    correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(y_,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    tf.summary.scalar("accuracy", accuracy)

    merged = tf.summary.merge_all()

#Session
with tf.Session() as sess:
    print('started')
    sess.run(tf.global_variables_initializer())
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord, start=True)
    sess.run(threads)

    try:
        for step in range(steps_per_epch * epochs):
            print('step: %d' %step)
            sess.run(train_step)
    except tf.errors.OutOfRangeError as ex:
        pass

    coord.request_stop()
    coord.join(threads)

Body:
Your code is not completely self-contained as the get_label method is not defined.

But it is very likely that the issue you have comes from these lines in the read_image_file method:

with tf.Session() as sess:
    label = getLabel(labels, key.eval())

The key.eval part tries to dequeue an element of a queue which has not started yet.
You shouldn't create any session before your input pipeline is defined (nor try to eval key (and possibly labels)). The get_label method should only perform tensor operations on labels and key and return a label tensor..

For example, you can use these tensor string operations so they will be part of the graph.


问:
Django Inline for ManyToMany generate duplicate queries
I'm experiencing some major performing issue with my django admin. Lots of duplicate queries based on how many inlines that I have.

models.py

```<code>class Setting(models.Model):
    name = models.CharField(max_length=50, unique=True)

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

class DisplayedGroup(models.Model):
    name = models.CharField(max_length=30, unique=True)
    position = models.PositiveSmallIntegerField(default=100)

    class Meta:
        ordering = ('priority',)

    def __str__(self):
        return self.name

class Machine(models.Model):
    name = models.CharField(max_length=20, unique=True)
    settings = models.ManyToManyField(
        Setting, through='Arrangement', blank=True
    )

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

class Arrangement(models.Model):
    machine = models.ForeignKey(Machine, on_delete=models.CASCADE)
    setting = models.ForeignKey(Setting, on_delete=models.CASCADE)
    displayed_group = models.ForeignKey(
        DisplayedGroup, on_delete=models.PROTECT,
        default=1)
    priority = models.PositiveSmallIntegerField(
        default=100,
        help_text='Smallest number will be displayed first'
    )

    class Meta:
        ordering = ('priority',)
        unique_together = (("machine", "setting"),)
</code>```

admin.py

```<code>class ArrangementInline(admin.TabularInline):
    model = Arrangement
    extra = 1

class MachineAdmin(admin.ModelAdmin):
    inlines = (ArrangementInline,)
</code>```

If I have 3 settings added on inline form and 1 extra, I have about 10 duplicate queries

```<code>SELECT "corps_setting"."id", "corps_setting"."name", "corps_setting"."user_id", "corps_setting"."tagged", "corps_setting"."created", "corps_setting"."modified" FROM "corps_setting" ORDER BY "corps_setting"."name" ASC
- Duplicated 5 times

SELECT "corps_displayedgroup"."id", "corps_displayedgroup"."name", "corps_displayedgroup"."color", "corps_displayedgroup"."priority", "corps_displayedgroup"."created", "corps_displayedgroup"."modified" FROM "corps_displayedgroup" ORDER BY "corps_displayedgroup"."priority" ASC
- Duplicated 5 times.
</code>```

Could someone please tell me what I'm doing wrong right here? I've spent 3 days trying to figure the problem out myself without luck.

The issue gets worse when I have about 50 settings inlines of a Machine, I will have ~100 queries.

Here is the screenshot

答:
I've assembled a generic solution based on @makaveli's answer that doesn't seem to have problem mentioned in the comments:

```<code>class CachingModelChoicesFormSet(forms.BaseInlineFormSet):
    """
    Used to avoid duplicate DB queries by caching choices and passing them all the forms.
    To be used in conjunction with `CachingModelChoicesForm`.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        sample_form = self._construct_form(0)
        self.cached_choices = {}
        try:
            model_choice_fields = sample_form.model_choice_fields
        except AttributeError:
            pass
        else:
            for field_name in model_choice_fields:
                if field_name in sample_form.fields and not isinstance(
                    sample_form.fields[field_name].widget, forms.HiddenInput):
                    self.cached_choices[field_name] = [c for c in sample_form.fields[field_name].choices]

    def get_form_kwargs(self, index):
        kwargs = super().get_form_kwargs(index)
        kwargs['cached_choices'] = self.cached_choices
        return kwargs

class CachingModelChoicesForm(forms.ModelForm):
    """
    Gets cached choices from `CachingModelChoicesFormSet` and uses them in model choice fields in order to reduce
    number of DB queries when used in admin inlines.
    """

    @property
    def model_choice_fields(self):
        return [fn for fn, f in self.fields.items()
            if isinstance(f, (forms.ModelChoiceField, forms.ModelMultipleChoiceField,))]

    def __init__(self, *args, **kwargs):
        cached_choices = kwargs.pop('cached_choices', {})
        super().__init__(*args, **kwargs)
        for field_name, choices in cached_choices.items():
            if choices is not None and field_name in self.fields:
                self.fields[field_name].choices = choices
</code>```

All you'll need to do is subclass your model from CachingModelChoicesForm and use CachingModelChoicesFormSet in your inline class:

```<code>class ArrangementInlineForm(CachingModelChoicesForm):
    class Meta:
        model = Arrangement
        exclude = ()

class ArrangementInline(admin.TabularInline):
    model = Arrangement
    extra = 50
    form = ArrangementInlineForm
    formset = CachingModelChoicesFormSet
</code>```

Body:
I'm experiencing some major performing issue with my django admin. Lots of duplicate queries based on how many inlines that I have.

models.py

class Setting(models.Model):
    name = models.CharField(max_length=50, unique=True)

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

class DisplayedGroup(models.Model):
    name = models.CharField(max_length=30, unique=True)
    position = models.PositiveSmallIntegerField(default=100)

    class Meta:
        ordering = ('priority',)

    def __str__(self):
        return self.name

class Machine(models.Model):
    name = models.CharField(max_length=20, unique=True)
    settings = models.ManyToManyField(
        Setting, through='Arrangement', blank=True
    )

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

class Arrangement(models.Model):
    machine = models.ForeignKey(Machine, on_delete=models.CASCADE)
    setting = models.ForeignKey(Setting, on_delete=models.CASCADE)
    displayed_group = models.ForeignKey(
        DisplayedGroup, on_delete=models.PROTECT,
        default=1)
    priority = models.PositiveSmallIntegerField(
        default=100,
        help_text='Smallest number will be displayed first'
    )

    class Meta:
        ordering = ('priority',)
        unique_together = (("machine", "setting"),)

admin.py

class ArrangementInline(admin.TabularInline):
    model = Arrangement
    extra = 1

class MachineAdmin(admin.ModelAdmin):
    inlines = (ArrangementInline,)

If I have 3 settings added on inline form and 1 extra, I have about 10 duplicate queries

SELECT "corps_setting"."id", "corps_setting"."name", "corps_setting"."user_id", "corps_setting"."tagged", "corps_setting"."created", "corps_setting"."modified" FROM "corps_setting" ORDER BY "corps_setting"."name" ASC
- Duplicated 5 times

SELECT "corps_displayedgroup"."id", "corps_displayedgroup"."name", "corps_displayedgroup"."color", "corps_displayedgroup"."priority", "corps_displayedgroup"."created", "corps_displayedgroup"."modified" FROM "corps_displayedgroup" ORDER BY "corps_displayedgroup"."priority" ASC
- Duplicated 5 times.

Could someone please tell me what I'm doing wrong right here? I've spent 3 days trying to figure the problem out myself without luck.

The issue gets worse when I have about 50 settings inlines of a Machine, I will have ~100 queries.

Here is the screenshot

Body:
I've assembled a generic solution based on @makaveli's answer that doesn't seem to have problem mentioned in the comments:

class CachingModelChoicesFormSet(forms.BaseInlineFormSet):
    """
    Used to avoid duplicate DB queries by caching choices and passing them all the forms.
    To be used in conjunction with `CachingModelChoicesForm`.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        sample_form = self._construct_form(0)
        self.cached_choices = {}
        try:
            model_choice_fields = sample_form.model_choice_fields
        except AttributeError:
            pass
        else:
            for field_name in model_choice_fields:
                if field_name in sample_form.fields and not isinstance(
                    sample_form.fields[field_name].widget, forms.HiddenInput):
                    self.cached_choices[field_name] = [c for c in sample_form.fields[field_name].choices]

    def get_form_kwargs(self, index):
        kwargs = super().get_form_kwargs(index)
        kwargs['cached_choices'] = self.cached_choices
        return kwargs

class CachingModelChoicesForm(forms.ModelForm):
    """
    Gets cached choices from `CachingModelChoicesFormSet` and uses them in model choice fields in order to reduce
    number of DB queries when used in admin inlines.
    """

    @property
    def model_choice_fields(self):
        return [fn for fn, f in self.fields.items()
            if isinstance(f, (forms.ModelChoiceField, forms.ModelMultipleChoiceField,))]

    def __init__(self, *args, **kwargs):
        cached_choices = kwargs.pop('cached_choices', {})
        super().__init__(*args, **kwargs)
        for field_name, choices in cached_choices.items():
            if choices is not None and field_name in self.fields:
                self.fields[field_name].choices = choices

All you'll need to do is subclass your model from CachingModelChoicesForm and use CachingModelChoicesFormSet in your inline class:

class ArrangementInlineForm(CachingModelChoicesForm):
    class Meta:
        model = Arrangement
        exclude = ()

class ArrangementInline(admin.TabularInline):
    model = Arrangement
    extra = 50
    form = ArrangementInlineForm
    formset = CachingModelChoicesFormSet


问:
How do I write this AND/OR statement in SQL?
I have 2 fields: qty_released and qty_complete. I need to exclude rows where the qty_released = 1 and qty_complete = 0 at the same time. I can't do this:

```<code>--rest of code

and j.qty_released != 1
and j.qty_complete != 0

--rest of code
</code>```

...because there might be valid times when j.qty_complete = 0 while j.qty_released > 1. Similar situation for j.qty_released = 1. How should I write this? I need the query to consider both of these at the same time when filtering through a particular row.

答:
```<code>WHERE/AND (j.qty_released <> 1 OR j.qty_complete > 0)
</code>```

In English: Include rows where qty_released is not 1 OR, if it is 1, then qty_complete must be greater than 0. So rows filtered out will be rows that meet the condition qty_released = 1 AND qty_complete = 0.

Body:
I have 2 fields: qty_released and qty_complete. I need to exclude rows where the qty_released = 1 and qty_complete = 0 at the same time. I can't do this:

--rest of code

and j.qty_released != 1
and j.qty_complete != 0

--rest of code

...because there might be valid times when j.qty_complete = 0 while j.qty_released > 1. Similar situation for j.qty_released = 1. How should I write this? I need the query to consider both of these at the same time when filtering through a particular row.

Body:
WHERE/AND (j.qty_released <> 1 OR j.qty_complete > 0)

In English: Include rows where qty_released is not 1 OR, if it is 1, then qty_complete must be greater than 0. So rows filtered out will be rows that meet the condition qty_released = 1 AND qty_complete = 0.


问:
jQuery - Given a DIV with a bunch of
 tags, how to find the first
 that isn't empty
Given a DIV with a lot of paragraph tags:

```<code><div>
 <p></p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
</div>
</code>```

How to magically find the first
 which isn't empty using just jQUery? ideas?

答:
http://www.jsfiddle.net/bradchristie/8k3VW/1/</p>

```<code>$(document).ready(function(){
    $('div p:not(p:empty):first').text('First not empty');
});
</code>```

ContentLicense: CC BY-SA 2.5

Title: jQuery - Given a DIV with a bunch of <P> tags, how to find the first <P> that isn't empty

Body:
Given a DIV with a lot of paragraph tags:

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

How to magically find the first
 which isn't empty using just jQUery? ideas?

Body:
http://www.jsfiddle.net/bradchristie/8k3VW/1/

$(document).ready(function(){
    $('div p:not(p:empty):first').text('First not empty');
});


问:
counting records in a query
I'm querying data from SQL SERVER, and using a lot of CASE statement to get the appropriate results. After the data is queries, I dump it to excel. Here's what I'm trying to achieve...

Query looks something like...

```<code>Select ClientName, ClientNo,
   Case when AAA=0 then 'N' Else 'Y' End As AAA,
   Case when BBB=0 then 'N' Else 'Y' End as BBB,
   Case when CCC=0 then 'N' Else 'Y' End as CCC
From tblClientInformation
</code>```

So this is a much shortened version of the query, I actually have about 17 Case statements. Once I dump this data to Excel spreadsheet, I do a COUNTIF function to take a count of all Y values for each clientName/ClientNO, so the data looks something like...

```<code>ClientName    ClientNo     AAA        BBB       CCC       TotalY
Bob Smith     1775         Y          N         Y         2
</code>```

So in TotalY I basically use CountIF function in excel to count all the Y values starting in AAA - ZZZ (example). However, since my query yields around 12000 records, it seems to be quite time consuming.

Is there any way that I can count the Y's in the query so that by the time my data is queried in SQL SERVER, all I have to do is simply dump it in excel, rather than adding on the Column TotalY with CountIF function?

答:
You can compose a new query over your own with CTE:</p>

```<code>;WITH table_without_count as
( Select ClientName, ClientNo,
   Case when AAA=0 then 'N' Else 'Y' End As AAA,
   Case when BBB=0 then 'N' Else 'Y' End as BBB,
   Case when CCC=0 then 'N' Else 'Y' End as CCC
  From tblClientInformation
)
select *, LEN(REPLACE(AAA+BBB+..., 'N', '')) as TotalY
from table_without_count
</code>```

Title: counting records in a query

Body:
I'm querying data from SQL SERVER, and using a lot of CASE statement to get the appropriate results. After the data is queries, I dump it to excel. Here's what I'm trying to achieve...

Query looks something like...

Select ClientName, ClientNo,
   Case when AAA=0 then 'N' Else 'Y' End As AAA,
   Case when BBB=0 then 'N' Else 'Y' End as BBB,
   Case when CCC=0 then 'N' Else 'Y' End as CCC
From tblClientInformation

So this is a much shortened version of the query, I actually have about 17 Case statements. Once I dump this data to Excel spreadsheet, I do a COUNTIF function to take a count of all Y values for each clientName/ClientNO, so the data looks something like...

ClientName    ClientNo     AAA        BBB       CCC       TotalY
Bob Smith     1775         Y          N         Y         2

So in TotalY I basically use CountIF function in excel to count all the Y values starting in AAA - ZZZ (example). However, since my query yields around 12000 records, it seems to be quite time consuming.

Is there any way that I can count the Y's in the query so that by the time my data is queried in SQL SERVER, all I have to do is simply dump it in excel, rather than adding on the Column TotalY with CountIF function?

Body:
You can compose a new query over your own with CTE:

;WITH table_without_count as
( Select ClientName, ClientNo,
   Case when AAA=0 then 'N' Else 'Y' End As AAA,
   Case when BBB=0 then 'N' Else 'Y' End as BBB,
   Case when CCC=0 then 'N' Else 'Y' End as CCC
  From tblClientInformation
)
select *, LEN(REPLACE(AAA+BBB+..., 'N', '')) as TotalY
from table_without_count


问:
Efficient ExpandableListView implementation for Flutter
I'm trying to implement an ExpandableListView similar to this on Android https://developer.android.com/reference/android/widget/ExpandableListView.html

I was able to implement something similar using the Catalog Flutter example https://flutter.io/catalog/samples/ where I add and remove an entire Column on tap. However, for a size bigger than 50, it starts being inefficient and takes quite a lot of time to load. Can you suggest a better and more efficient approach in implementing something similar?

答:
ExpansionTile can be used to produce two-level or multi-level lists. If they are used as they are in the expansion tile sample, they should efficient. The important thing is to use ListView.builder since the default ListView constructor is not optimized for large amounts of content.

If you're still not getting the performance you want after trying this, please post a code sample in your question and we can suggest how to improve it.


问:
Differentiating between password and other kind of keyboard inputs in a keylogger
I am writing a keylogger for windows. I am planning to get the pressed key with GetAsyncKeyState(KEY) and a hidden console. After a key press has been identified I will get the current focused windows with GetForegroundWindow and indentify which program was on top when the key was pressed. I also want to be able to Differentiate between key presses for passwords and other kind of inputs. Is there a way to do it? How?

I am not writing a malicious software. This is for an assignment in Advanced Programming course.

答:
If the foreground app is using standard Win32 UI controls, then try this:

use GetForegroundWindow() to get the HWND of the foreground window.

then use GetWindowThreadProcessId() and GetGUIThreadInfo() to get the foreground window's currently focused child control.

then use GetClassName() to check if it is a standard EDIT control (this check might fail in some UI frameworks! You might have to use the UI Automation API to detect the control type)

then use GetWindowLong/Ptr() to check if it has the ES_PASSWORD style applied.

However, if the foreground app is not using standard Win32 UI controls, and/or is custom-drawing them, or the like, then all bets are off.


问:
Python: Assigning grouped mean to 1-D array
Suppose that I have 2 arrays:

```<code>x    = [2, 4, 1, 7, 3, 9, 2, 5, 5, 1]
flag = [0, 1, 0, 2, 1, 1, 2, 0, 0, 2]
</code>```

The flag array indicates which "group" each element of x belongs to. How can I replace each element of x (with, say, flag value k) by the mean of all elements of x whose corresponding flag value is also k?

After such a transformation, x would look like:

```<code>x    = [3.25, 5.33, 3.25, 3.33, 5.33, 5.33, 3.33, 3.25, 3.25, 3.33]
</code>```

(I could use loops to achieve this, but that would be quite inefficient.)

答:
You could use np.bincount to compute grouped means:

```<code>import numpy as np
x    = np.array([2, 4, 1, 7, 3, 9, 2, 5, 5, 1])
flag = np.array([0, 1, 0, 2, 1, 1, 2, 0, 0, 2])
total = np.bincount(flag, weights=x)
count = np.bincount(flag)
means = (total/count)[flag]
</code>```

yields

```<code>array([ 3.25      ,  5.33333333,  3.25      ,  3.33333333,  5.33333333,
        5.33333333,  3.33333333,  3.25      ,  3.25      ,  3.33333333])
</code>```

For more generalized grouped statistics there is also the scipy.stats.binned_statistic  function. It can compute grouped mean, median, count, sum, min, max statistics. It can also accept user-defined functions for the statistic, but the performance will (of course) be slower than for the built-in statistics.

Body:
Suppose that I have 2 arrays:

x    = [2, 4, 1, 7, 3, 9, 2, 5, 5, 1]
flag = [0, 1, 0, 2, 1, 1, 2, 0, 0, 2]

The flag array indicates which "group" each element of x belongs to. How can I replace each element of x (with, say, flag value k) by the mean of all elements of x whose corresponding flag value is also k?

After such a transformation, x would look like:

x    = [3.25, 5.33, 3.25, 3.33, 5.33, 5.33, 3.33, 3.25, 3.25, 3.33]

(I could use loops to achieve this, but that would be quite inefficient.)

Body:
You could use np.bincount to compute grouped means:

import numpy as np
x    = np.array([2, 4, 1, 7, 3, 9, 2, 5, 5, 1])
flag = np.array([0, 1, 0, 2, 1, 1, 2, 0, 0, 2])
total = np.bincount(flag, weights=x)
count = np.bincount(flag)
means = (total/count)[flag]

yields

array([ 3.25      ,  5.33333333,  3.25      ,  3.33333333,  5.33333333,
        5.33333333,  3.33333333,  3.25      ,  3.25      ,  3.33333333])

For more generalized grouped statistics there is also the scipy.stats.binned_statistic  function. It can compute grouped mean, median, count, sum, min, max statistics. It can also accept user-defined functions for the statistic, but the performance will (of course) be slower than for the built-in statistics.


问:
Onclick JS function call, returns "Can't find variable" only in Safari Console
So I have a very simple JS function written that works like the following.

There is a button that has the following code:

```<code><button type="submit" class="large button" onclick="addCart(76,95,73,96);">
    <i class="icon-shopping-cart"></i> Add to Cart
</button>
</code>```

Now when that is clicked there is a very simple function added to the page below that looks like the following:

```<code><script type="text/javascript">
    function addCart(pid, pattr, pval, pscent = 0) {
    ...
    }
</script>
</code>```

This works perfectly in Chrome, Firefox, Chrome for Mobile, Safari for Mobile.

But this does not seem to work on Safari on Mac. Instead I get the following error:

ReferenceError: Can't find variable: addCart

I cannot figure out why. It's hard for me to add a listener because there are 7 buttons and a wide arrange of variables that are being sent, and I'd rather send that like I'm currently doing.

答:
if you are using jquery try to use document ready function

```<code>$(document).ready(function() {
// code here
});
</code>```

or use plain javascript self executing function here

```<code>(function() {
   // your page initialization code here
   // the DOM will be available here

})();
</code>```

the possible reason is your function is not available at the time of click

Here is a sample (using jquery) https://jsfiddle.net/baphmoLt/

Body:
So I have a very simple JS function written that works like the following.

There is a button that has the following code:

<button type="submit" class="large button" onclick="addCart(76,95,73,96);">
     Add to Cart
</button>

Now when that is clicked there is a very simple function added to the page below that looks like the following:

This works perfectly in Chrome, Firefox, Chrome for Mobile, Safari for Mobile.

But this does not seem to work on Safari on Mac. Instead I get the following error:

ReferenceError: Can't find variable: addCart

I cannot figure out why. It's hard for me to add a listener because there are 7 buttons and a wide arrange of variables that are being sent, and I'd rather send that like I'm currently doing.

Body:
if you are using jquery try to use document ready function

$(document).ready(function() {
// code here
});

or use plain javascript self executing function here

(function() {
   // your page initialization code here
   // the DOM will be available here

})();

the possible reason is your function is not available at the time of click

Here is a sample (using jquery) https://jsfiddle.net/baphmoLt/


问:
HTML Signature Images not showing in Gmail Mobile app (IOS)
Working on an HTML Email signature and I've got everything working for most necessary clients, mobile and desktop. The only issue I'm running into is with the Gmail App for mobile (I'm using it on iOS 10). The images will not load on the Gmail app and I'm unsure as to why.

Image as it appears on Gmail Mobile app

The code for my images are all the same (There are 5 total, 1 logo, and 4 social media icons).

```<code><img src="image-source" height="133" width="275" style="border: none; width: 275px; max-width: 275px !important; height: 133px; max-height: 133px !important; color: #33424d; font-size: 20px; font-family: Arial, Helvetica, sans-serif; font-weight: bold;" alt="Alt Text" title="logo">
</code>```

I've looked everywhere and can't seem to figure out why this is only happening on the mobile app itself. Any idea what could be causing this and how I can fix it?

答:
I've found that this issue is due to Gmail's spam filter. My email account from my own domain is fairly new so Gmail sends all mail from this account to spam, even though I labelled it not spam it still blocked the images.

When I tested the signature by sending from a more established email it appears to display the images properly.

Body:
Working on an HTML Email signature and I've got everything working for most necessary clients, mobile and desktop. The only issue I'm running into is with the Gmail App for mobile (I'm using it on iOS 10). The images will not load on the Gmail app and I'm unsure as to why.

Image as it appears on Gmail Mobile app

The code for my images are all the same (There are 5 total, 1 logo, and 4 social media icons).

I've looked everywhere and can't seem to figure out why this is only happening on the mobile app itself. Any idea what could be causing this and how I can fix it?


问:
Demosaicing algorithm that contains downsampling

Introduction: What I am working on.

Hello everyone! I am working on a Demosaicing algorithm which I use to transform images that have Bayer pattern into images that represent red, green and blue channels. I wish that the algorithm would have the following properties:

It preserves as much raw information as possible.

It does not obscure details in the image, even if that means absence of denoising.

It produces as little artifacts as possible.

If the size of mosaic image is N x N, the three color images should each have size N/2 x N/2.

Algorithm should be fast. To put "fast" into a context, let me say this: I will settle for something that is at least twice as fast as OpenCV's algorithm which uses bilinear interpolation.

What I have achieved so far.

So far, I've come up with the algorithm that uses bilinear interpolation and produces three images that have half size of the mosaic image. The algorithm is approximately 3-4 times faster than OpenCV's cvtColor algorithm that performs CV_BayerBG2BGR conversion (bilinear interpolation).

See the sketch of the Bayer pattern below to get an idea about how it works. I perform the interpolation at points marked by circles. The numbers represent the coefficients by which I multiply the underlying pixels in order to get interpolated value in the point marked by black circle.

You can observe the results of my algorithm below. I've also added the results of both demosaicing algorithms that are available in OpenCV (bilinear interpolation and variable number of gradients). Please note that while results of my algorithm look really poor in comparison, the OpenCV's bilinear interpolation results look almost exactly the same if I downsample them. This is of course expected as the underlying algorithm is the same.

... so finally: the question.

My current solution gives acceptable results for my project and it is also acceptably fast. However, I would be willing to use a up to twice slower algorithm if that would bring improvements to any of the 5 criteria listed above. The question then is: how to improve my algorithm without significantly hindering the performance?

I have enough programming experience for this task so I am not specifically asking for code snippets - the answers of any kind (code, links, suggestions - especially the ones based on past experiences) are welcome.

Some additional information:

I am working in C++.

The algorithm is highly optimized, it uses SSE instructions and it is non-parallel.

I work with large images (few MB in size); cache-awareness and avoiding multiple passes through image are very important.

I am not looking for general programming advice (such as optimization in general, etc.), but on the other hand some task-specific answers are more than welcome. Thank you in advance.

答:
I'm a bit puzzled by your algorithm and won't comment on it... but to put some things into perspective...

OpenCV is a library which contains a lot of generic stuff to get the job done, and sometimes is deliberately not performance-over-optimized, there is a cost-maintainability tradeoff and “good enough is better than better”.
There is a trove of people selling performance-optimized libraries implementing some of OpenCV's features, sometimes with the exact same API.
I have not used it, but OpenCV has a cv::gpu::cvtColor() which could be achieving your goals, out of the box, assuming it's implemented for demosaicing, and that you have a suitable GPU.

Considering the bilinear demosaicing, a less-maintainable but more-optimized  CPU implementation can run much faster than the one from OpenCV, I'd estimate above 250 Mpx/s on one mainstream CPU core.

Now to elaborate on the optimization path...

First, because demosaicing is a local operation, cache awareness is really not a significant problem.

An performance-optimized implementation will have different code paths depending on the image dimensions, Bayer pattern type, instruction sets supported by the CPU (and their speed/latency), for such a simple algorithm it's going to become a lot of code.

There are SIMD instructions to perform shuffling, arithmetic including averaging, streaming memory writes, which you'd find useful. Intel's summary is not so bad to navigate, and Agner Fog's site is also valuable for any kind of implementation optimization. AVX & AVX2 provide several interesting instructions for pixel processing.

If you are more the 80/20 kind of person (good for you!), you'll appreciate working with a tool like Halide which can generate optimized stencil code like a breeze (modulo the learning curve, which is already setting you back a few days from a 1-hour naive implementation or the 10 minutes using OpenCV) and especially handles the boundary conditions (image borders).

You can get a little further (or take an alternative road) by using compiler intrinsics to access specific CPU instructions, at this point your code is now 4x costlier (in terms of development cost), and will probably get you 99% as far as hand-crafted assembly ($$$ x4 again).

If you want to squeeze the last drop (not generally advisable), you will definitely have to perform days of implementation benchmarks, to see which sequence of instructions can get you the best performance.

But also, GPUs... you can use your integrated GPU to perform demosaicing, it may be a little faster than the CPU and has access to the main memory... of course you'd have to care about pre-allocating shared buffers. A discrete GPU would have a more significant transfer overhead, at these fill rates.


问:
jquery .on not work
In my DOM this is generated dynamically:

```<code><li>333107 (<span id="pos_3488">1</span>)
<span><a id="del_3488" href="#" id_mod="3488"> - </a></span></li>
</code>```

My jQuery code:

```<code>$("a[id^='del_']").on("click", function(e){
    var id_modelo   = $(this).attr("id_mod");
    var id_bloque   = $(this).parent().attr("id");
});
</code>```

But when you click on the HTML element, there is no call to the "click event".

答:
Are you making sure the html has generated before you add your listeners? The code below seems to be working. It's probably a race condition issue. Maybe set a timeout. Before you add the listeners.

$(function(){
  setTimeout(function(){
    $("a[id^='del_']").on("click", function(e){
        var id_modelo   = $(this).attr("id_mod");
        var id_bloque   = $(this).parent().attr("id");
        console.log("hit:", id_modelo);
    });
  }, 2000); //Wait 2 seconds before setting the event listener
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li>333107 (<span id="pos_3488">1</span>)
  <span> - </span></li>
</ul></code>```

Title: jquery .on not work

Body:
In my DOM this is generated dynamically:

333107 (1)
 -

My jQuery code:

$("a[id^='del_']").on("click", function(e){
    var id_modelo   = $(this).attr("id_mod");
    var id_bloque   = $(this).parent().attr("id");
});

But when you click on the HTML element, there is no call to the "click event".

Body:
Are you making sure the html has generated before you add your listeners? The code below seems to be working. It's probably a race condition issue. Maybe set a timeout. Before you add the listeners.

$(function(){
  setTimeout(function(){
    $("a[id^='del_']").on("click", function(e){
        var id_modelo   = $(this).attr("id_mod");
        var id_bloque   = $(this).parent().attr("id");
        console.log("hit:", id_modelo);
    });
  }, 2000); //Wait 2 seconds before setting the event listener
});

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

<ul>
  <li>333107 (<span id="pos_3488">1</span>)
  <span><a id="del_3488" href="#" id_mod="3488"> - </a></span></li>
</ul>


问:
Generic type argument
I have the following trait:

```<code>trait F{
   type T
}
</code>```

and

```<code>trait C[T]{
   def getF: F{ type T = //I want the outer T}
}
</code>```

Is there a way to refer to the generic type argument without introducing helper type variable and renaming the type parameter?

答:
If you weren't so inclined to call all types T, you could just do

```<code>trait C[Foo] {
  def getF: F { type T = Foo }
}
</code>```

Title: Generic type argument

Body:
I have the following trait:

trait F{
   type T
}

and

trait C[T]{
   def getF: F{ type T = //I want the outer T}
}

Is there a way to refer to the generic type argument without introducing helper type variable and renaming the type parameter?

Body:
If you weren't so inclined to call all types T, you could just do

trait C[Foo] {
  def getF: F { type T = Foo }
}


问:
Vuejs component wait for facebook sdk to load
I have a component that show a login button or username of the user from facebook.
depends if he is logged in or not.

Now in this component I use the

```<code>created
</code>```

event so I'll check the login immidiatly.
code in created in a brief:

```<code>FB.getLoginStatus(function(response) {
    //more things.....
</code>```

the error is that it says that FB is not defined,
and sure he is right, FB is not loaded yet.

I load facebook like this

```

答:
This problem can be solve by creating a vuejs plugin.

Please check the related answer in nuxt.js.

create a plugin plugins/fb-sdk.js

```<code>const vue_fb = {}
vue_fb.install = function install(Vue, options) {
    (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0]
        if (d.getElementById(id)) {return}
        js = d.createElement(s)
        js.id = id
        js.src = "//connect.facebook.net/en_US/sdk.js"
        fjs.parentNode.insertBefore(js, fjs)
        console.log('setting fb sdk')
    }(document, 'script', 'facebook-jssdk'))

    window.fbAsyncInit = function onSDKInit() {
        FB.init(options)
        FB.AppEvents.logPageView()
        Vue.FB = FB
        window.dispatchEvent(new Event('fb-sdk-ready'))
    }
    Vue.FB = undefined
}

import Vue from 'vue'

Vue.use(vue_fb, {
    appId: 'your-app-id',
    autoLogAppEvents: true,
    xfbml: true,
    version: 'v2.9'
})
</code>```

Body:
I have a component that show a login button or username of the user from facebook.
depends if he is logged in or not.

Now in this component I use the

created

event so I'll check the login immidiatly.
code in created in a brief:

FB.getLoginStatus(function(response) {
    //more things.....

the error is that it says that FB is not defined,
and sure he is right, FB is not loaded yet.

I load facebook like this

Body:
This problem can be solve by creating a vuejs plugin.

Please check the related answer in nuxt.js.

create a plugin plugins/fb-sdk.js

const vue_fb = {}
vue_fb.install = function install(Vue, options) {
    (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0]
        if (d.getElementById(id)) {return}
        js = d.createElement(s)
        js.id = id
        js.src = "//connect.facebook.net/en_US/sdk.js"
        fjs.parentNode.insertBefore(js, fjs)
        console.log('setting fb sdk')
    }(document, 'script', 'facebook-jssdk'))

    window.fbAsyncInit = function onSDKInit() {
        FB.init(options)
        FB.AppEvents.logPageView()
        Vue.FB = FB
        window.dispatchEvent(new Event('fb-sdk-ready'))
    }
    Vue.FB = undefined
}

import Vue from 'vue'

Vue.use(vue_fb, {
    appId: 'your-app-id',
    autoLogAppEvents: true,
    xfbml: true,
    version: 'v2.9'
})

ContentLicense: CC BY-SA 4.0


问:
Kendo Grid edit command not reaching controller
Can someone please help with my question:
The edit command in kendo grid isn't reaching my controller.
Am I missing something?

```<code>@(Html.Kendo().Grid<WEEKLY_ORDERS_LINES>()
        .Name("orderDetails_edit" + Model.OrderID)
        .Columns(columns =>
        {
            columns.Bound(e => e.ID).Hidden(true);
            columns.Bound(e => e.INGRED_NAME).Title("Ingredient Name").Width(120).HeaderHtmlAttributes(new { style = "text-align: center;" }).HtmlAttributes(new { style = "text-align: center;" });
            columns.Command(command => { command.Edit(); }).Width(60);
        })
        .Editable(e => e.Mode(GridEditMode.InLine))
        .DataSource(dataSource => dataSource
        .Ajax()
        .Sort(sort => sort.Add("INGRED_NAME").Ascending())
        .Model(model =>
        {
            model.Id(p => p.ID);
            model.Field(p => p.ID).DefaultValue(new Guid());
            model.Field(f => f.INGRED_NAME).Editable(true);
        })
        .Update(update => update.Action("Update", "Food"))
        .Read(read => read.Action("Read", "Food").Data("additionalInfo"))
        )
        .Events(events => events.Cancel("refreshView"))
)
</code>```

And my controller is like this:

```<code>public ActionResult Update([DataSourceRequest] DataSourceRequest request, WEEKLY_ORDERS_LINES model)
    {
        if (model != null && ModelState.IsValid)
        {
            WEEKLY_FOOD dbFood = _db.WEEKLY_FOOD.Find(model.ID);
            dbFood.INGRED_NAME = model.INGRED_NAME;
            _db.SaveChanges();
        }

        ActionResult a = Json(new[] { model }.ToDataSourceResult(request, ModelState));
        return a;
    }
</code>```

答:
I'm a colleague of Rute.

The problem that was ocurring was that the kendo Update was calling other controller and not the right one. This was happening because all the results of the data that were being rendered didn't have an unique identifier.

This unique identifier is now assign to the model.Id and the problem is solved. I understood this after seeing this link http://www.telerik.com/forums/wrong-methods-are-fired.

Thanks for the help.

Body:
Can someone please help with my question:
The edit command in kendo grid isn't reaching my controller.
Am I missing something?

@(Html.Kendo().Grid<WEEKLY_ORDERS_LINES>()
        .Name("orderDetails_edit" + Model.OrderID)
        .Columns(columns =>
        {
            columns.Bound(e => e.ID).Hidden(true);
            columns.Bound(e => e.INGRED_NAME).Title("Ingredient Name").Width(120).HeaderHtmlAttributes(new { style = "text-align: center;" }).HtmlAttributes(new { style = "text-align: center;" });
            columns.Command(command => { command.Edit(); }).Width(60);
        })
        .Editable(e => e.Mode(GridEditMode.InLine))
        .DataSource(dataSource => dataSource
        .Ajax()
        .Sort(sort => sort.Add("INGRED_NAME").Ascending())
        .Model(model =>
        {
            model.Id(p => p.ID);
            model.Field(p => p.ID).DefaultValue(new Guid());
            model.Field(f => f.INGRED_NAME).Editable(true);
        })
        .Update(update => update.Action("Update", "Food"))
        .Read(read => read.Action("Read", "Food").Data("additionalInfo"))
        )
        .Events(events => events.Cancel("refreshView"))
)

And my controller is like this:

public ActionResult Update([DataSourceRequest] DataSourceRequest request, WEEKLY_ORDERS_LINES model)
    {
        if (model != null && ModelState.IsValid)
        {
            WEEKLY_FOOD dbFood = _db.WEEKLY_FOOD.Find(model.ID);
            dbFood.INGRED_NAME = model.INGRED_NAME;
            _db.SaveChanges();
        }

        ActionResult a = Json(new[] { model }.ToDataSourceResult(request, ModelState));
        return a;
    }


问:
Weird scanf behaviour
I was working on a C program and I found a weird behaviour with scanf:

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

int main() {
    int *a, i;
    printf("Hello, World!\n");
    for (i = 0; i < 10; i++) {
        scanf("%u", &a[i]);
    }
    for (i = 0; i < 10; i++) {
        printf("%d\n", a[i]);
    }
    return 0;
}
</code>```

For 10 input I sent + and the output was like:

```<code>1
0
239646720
32767
0
0
239646727
32767
239646771
32767
</code>```

I expected a memory leak, could any one please explain me this behaviour ?

答:
If you simply wanted to store 10 integers to an array and later printing them, this would do:-</p>

```<code>#include<stdio.h>
int main()
{
    int a[9],i ;
    printf("Hello, World!\n");
    for(i = 0;i<10;i++)`
    {
      scanf("%u",&a[i]);
    }

    for(i = 0;i<10;i++)
    {
      printf("%d\n",a[i]) ;
    }
    return 0;
}
</code>```

Title: Weird scanf behaviour

Body:
I was working on a C program and I found a weird behaviour with scanf:

#include <stdio.h>

int main() {
    int *a, i;
    printf("Hello, World!\n");
    for (i = 0; i < 10; i++) {
        scanf("%u", &a[i]);
    }
    for (i = 0; i < 10; i++) {
        printf("%d\n", a[i]);
    }
    return 0;
}

For 10 input I sent + and the output was like:

1
0
239646720
32767
0
0
239646727
32767
239646771
32767

I expected a memory leak, could any one please explain me this behaviour ?

Body:
If you simply wanted to store 10 integers to an array and later printing them, this would do:-

#include<stdio.h>
int main()
{
    int a[9],i ;
    printf("Hello, World!\n");
    for(i = 0;i<10;i++)`
    {
      scanf("%u",&a[i]);
    }

    for(i = 0;i<10;i++)
    {
      printf("%d\n",a[i]) ;
    }
    return 0;
}


问:
CSV parsing for embedded double quotes
I've written a simple CSV file parser. But after looking at the wiki page on CSV formats I noticed some "extensions" to the basic format. Specifically embedded comma via double quotes. I've managed to parse those, however there is a second issue: embedded double quotes.

Example:

12345,"ABC, ""IJK"" XYZ"  -> [1234] and [ABC, "IJK" XYZ]

I can't seem to find the correct way to distinguish between an enclosed double quote and none. So my question is what is the correct way/algorithm to parse CVS formats such as the one above?

答:
I suggest reading: Stop Rolling Your Own CSV Parser and this CSV RFC. The first is really just someone who wants you to use their C# CSV parser, but still explains many issues.

Your parser should be examining a character at a time. I used a double bool strategy for my parser in D. Each quote toggles weather the string is quoted or not. When in a quoted Cell you flag when hit a quote, and turn off quoting. If the next character is a quote, quoting is turned on, a quote is added to the result and the flag is turned off. If the next character isn't a quote then the flag is turned off and so is quoting.

OwnerDisplayName: Matthieu N.

Title: CSV parsing for embedded double quotes


问:
OnLocationChanged() is not automatically called. The location is not stored in the database
I have a gpsTracker java class which contains the onLocationChanged() method. I want to link my MainActivity's OnCreate function with this onLocationChanged() method.

```<code>public void onLocationChanged(Location newlocation) {

    Log.d("latitude", "old" + Double.toString(this.location.getLatitude()));
    Log.d("Longitude", "old " +
     Double.toString(this.location.getLatitude()));
    Log.i("info","LOCATION CHANGED");
    Log.d("latitude", "NEW: CHANGED TO KOLKATA" +
    Double.toString(newlocation.getLatitude()));
    Log.d("Longitude", "NEW: CHANGED TO KOLKATA " +
     Double.toString(newlocation.getLatitude()));
    this.location = newlocation;
    JSONObject locationChange = new JSONObject();
    getLocationName(location.getLatitude(), location.getLongitude());
    try {
        locationChange.put("userid",
       PreferenceManager.getInstance().getUserId());
        locationChange.put("location", addressString);
        locationChange.put("connection",
        PreferenceManager.getInstance().getConnectAllow() ? "1" : "0");
        locationChange.put("connection", "0");
        locationChange.put("notification",
    PreferenceManager.getInstance().getPushNotiAllow() ? "0" : "1");

        Log.d(TAG, "LOCATION CHANGED BY GPS FUNCTION: " + locationChange);

        RequestHandler.getInstance().postWithHeader(null,
      getString(R.string.baseurl) + getString(R.string.settings),
      locationChange, this,
    AppConstants.ApiRequestCodeKey.SAVE_APP_SETTINGS);
     }catch (JSONException e) {
                      e.printStackTrace();
         }
  }
public void getLocationName(double latitude, double longitude) {
    Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
    try {
        addresses = geocoder.getFromLocation(latitude, longitude, 1);
        addressString = addresses.get(0).getAddressLine(0)
                + addresses.get(0).getAddressLine(1) + " ";
    } catch (IOException e) {
        e.printStackTrace();
    }
}>
</code>```

The onCreate function in the MainActivity() contains this.

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_home_frame);

utils.mixpanelTrack(this, "Reached Home Page");
 homeFragObj = this;
    initViews();
    initSetup();
    initListeners();
    loadData();
>
</code>```

答:
To receive every location change in your Activiy, it´s the best option to use Broadcasts. Create a instance variable of BroadcastReceiver:

```<code>BroadcastReceiver mReceiver;
</code>```

In onCreate() add this receiver:

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_frame);

  IntentFilter filter = new IntentFilter();
  filter.addAction("LOCATION_CHANGE");

  mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

      String latitude = intent.getExtras().getString("LATITUDE");
      String longitude= intent.getExtras().getString("LONGITUDE");
    }
  };
    LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filter);
}
</code>```

Don´t forget to unregister the receiver if Activity closes:

```<code> @Override
 protected void onDestroy() {
  if (mReceiver != null) {
   LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
   mReceiver = null;
  }
  super.onDestroy();
 }
</code>```

And on OnLocationChange in your Utils class, send the Broadcast after you have the coordinates like this:

```<code>Intent intent=new Intent(context,YourActivity.class);
intent.setAction("LOCATION_CHANGE");
intent.putExtra("LATITUDE",Double.toString(latitude));
intent.putExtra("LONGITUDE",Double.toString(longitude));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
</code>```

What you need is the context that you can pass via your constructor of your Utils class, for example, if you create an instance in your Activity:

```<code>MyUtils utils = new MyUtils(this);
</code>```

This is just a basic answer, there are some things you have to be aware of.

Body:
I have a gpsTracker java class which contains the onLocationChanged() method. I want to link my MainActivity's OnCreate function with this onLocationChanged() method.

public void onLocationChanged(Location newlocation) {

    Log.d("latitude", "old" + Double.toString(this.location.getLatitude()));
    Log.d("Longitude", "old " +
     Double.toString(this.location.getLatitude()));
    Log.i("info","LOCATION CHANGED");
    Log.d("latitude", "NEW: CHANGED TO KOLKATA" +
    Double.toString(newlocation.getLatitude()));
    Log.d("Longitude", "NEW: CHANGED TO KOLKATA " +
     Double.toString(newlocation.getLatitude()));
    this.location = newlocation;
    JSONObject locationChange = new JSONObject();
    getLocationName(location.getLatitude(), location.getLongitude());
    try {
        locationChange.put("userid",
       PreferenceManager.getInstance().getUserId());
        locationChange.put("location", addressString);
        locationChange.put("connection",
        PreferenceManager.getInstance().getConnectAllow() ? "1" : "0");
        locationChange.put("connection", "0");
        locationChange.put("notification",
    PreferenceManager.getInstance().getPushNotiAllow() ? "0" : "1");

        Log.d(TAG, "LOCATION CHANGED BY GPS FUNCTION: " + locationChange);

        RequestHandler.getInstance().postWithHeader(null,
      getString(R.string.baseurl) + getString(R.string.settings),
      locationChange, this,
    AppConstants.ApiRequestCodeKey.SAVE_APP_SETTINGS);
     }catch (JSONException e) {
                      e.printStackTrace();
         }
  }
public void getLocationName(double latitude, double longitude) {
    Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
    try {
        addresses = geocoder.getFromLocation(latitude, longitude, 1);
        addressString = addresses.get(0).getAddressLine(0)
                + addresses.get(0).getAddressLine(1) + " ";
    } catch (IOException e) {
        e.printStackTrace();
    }
}>

The onCreate function in the MainActivity() contains this.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_home_frame);

utils.mixpanelTrack(this, "Reached Home Page");
 homeFragObj = this;
    initViews();
    initSetup();
    initListeners();
    loadData();
>

Body:
To receive every location change in your Activiy, it´s the best option to use Broadcasts. Create a instance variable of BroadcastReceiver:

BroadcastReceiver mReceiver;

In onCreate() add this receiver:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_frame);

  IntentFilter filter = new IntentFilter();
  filter.addAction("LOCATION_CHANGE");

  mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

      String latitude = intent.getExtras().getString("LATITUDE");
      String longitude= intent.getExtras().getString("LONGITUDE");
    }
  };
    LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filter);
}

Don´t forget to unregister the receiver if Activity closes:

 @Override
 protected void onDestroy() {
  if (mReceiver != null) {
   LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
   mReceiver = null;
  }
  super.onDestroy();
 }

And on OnLocationChange in your Utils class, send the Broadcast after you have the coordinates like this:

Intent intent=new Intent(context,YourActivity.class);
intent.setAction("LOCATION_CHANGE");
intent.putExtra("LATITUDE",Double.toString(latitude));
intent.putExtra("LONGITUDE",Double.toString(longitude));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

What you need is the context that you can pass via your constructor of your Utils class, for example, if you create an instance in your Activity:

MyUtils utils = new MyUtils(this);

This is just a basic answer, there are some things you have to be aware of.


问:
Generating SpecFlow Reports with the CakeBuild Specflow plugin possible?
Is it possible to generate SpecFlow Reports with the CakeBuild Specflow plugin (CakeBuild SpecFlow) ?

答:
This is a SpecFlow+Runner report (http://specflow.org/plus/runner/).
For CakeBuild I suggest you execute the tests via VSTest and the SpecFlow+Runner test adapter.

So use the VSTest functionality (http://cakebuild.net/dsl/vstest/) and configure the TestAdapterPath to the local NuGet package folder.

So you get this report generated.


问:
Angular 2 dependencies
Please consider this dependencies in package.json:

```<code>"dependencies": {
                  "@angular/common": "2.2.1",
                  "@angular/compiler": "2.2.1",
                  "@angular/core": "2.2.1",
                  "@angular/forms": "2.2.1",
                  "@angular/http": "2.2.1",
                  "@angular/platform-browser": "2.2.1",
                  "@angular/platform-browser-dynamic": "2.2.1",
                  "@angular/router": "3.2.1",
                  "@angular/upgrade": "2.2.1"
                }
</code>```

I want to use the bundle version of Angulajs and when I run this command:

npm install angular

It installs angular.min.js I want to know what is the difference between Those? Is there any way to bundle dependencies using npm and create a single file?

Another question is I know that Angular 4 has been released and when I run this command:

npm install angular

It installs angular.min.js with version v1.6.4 so what is this file? And why it outdated?

答:
When you run npm install angular, AngularJS (v1.x) is installed.

Which is why, when you run the command, the latest stable version of AngularJS i.e v1.6.4 is installed.

Note: Angular v1 (AngularJS) is still supported. Last stable release was 3 months ago.

Angular 2 and above versions are simply called Angular.

Note: Angular(v2 or v4) is an incompatible rewrite of AngularJS(v1)

Now the question is you should choose either of the above according to requirements. The steps you have followed is to get AngularJS(v1).

You can have a look at Angular Quickstart to get started with Angular2+ which is now updated to v4.4.5 (as of 5th July 2017).

You can have a look at Package.json and you would notice,

```<code>"dependencies": {
  "@angular/common": "~4.0.0",
  "@angular/compiler": "~4.0.0",
  "@angular/core": "~4.0.0",
  "@angular/forms": "~4.0.0",
  "@angular/http": "~4.0.0",
  "@angular/platform-browser": "~4.0.0",
  "@angular/platform-browser-dynamic": "~4.0.0",
  "@angular/router": "~4.0.0",

  "angular-in-memory-web-api": "~0.3.0",
  "systemjs": "0.19.40",
  "core-js": "^2.4.1",
  "rxjs": "5.0.1",
  "zone.js": "^0.8.4"
</code>```

},

which should install current stable version of Angular

angular-cli (command-line tool by Angular)

Title: Angular 2 dependencies

Body:
Please consider this dependencies in package.json:

"dependencies": {
                  "@angular/common": "2.2.1",
                  "@angular/compiler": "2.2.1",
                  "@angular/core": "2.2.1",
                  "@angular/forms": "2.2.1",
                  "@angular/http": "2.2.1",
                  "@angular/platform-browser": "2.2.1",
                  "@angular/platform-browser-dynamic": "2.2.1",
                  "@angular/router": "3.2.1",
                  "@angular/upgrade": "2.2.1"
                }

I want to use the bundle version of Angulajs and when I run this command:

npm install angular

It installs angular.min.js I want to know what is the difference between Those? Is there any way to bundle dependencies using npm and create a single file?

Another question is I know that Angular 4 has been released and when I run this command:

npm install angular

It installs angular.min.js with version v1.6.4 so what is this file? And why it outdated?

Body:
When you run npm install angular, AngularJS (v1.x) is installed.

Which is why, when you run the command, the latest stable version of AngularJS i.e v1.6.4 is installed.

Note: Angular v1 (AngularJS) is still supported. Last stable release was 3 months ago.

Angular 2 and above versions are simply called Angular.

Note: Angular(v2 or v4) is an incompatible rewrite of AngularJS(v1)

Now the question is you should choose either of the above according to requirements. The steps you have followed is to get AngularJS(v1).

You can have a look at Angular Quickstart to get started with Angular2+ which is now updated to v4.4.5 (as of 5th July 2017).

You can have a look at Package.json and you would notice,

"dependencies": {
  "@angular/common": "~4.0.0",
  "@angular/compiler": "~4.0.0",
  "@angular/core": "~4.0.0",
  "@angular/forms": "~4.0.0",
  "@angular/http": "~4.0.0",
  "@angular/platform-browser": "~4.0.0",
  "@angular/platform-browser-dynamic": "~4.0.0",
  "@angular/router": "~4.0.0",

  "angular-in-memory-web-api": "~0.3.0",
  "systemjs": "0.19.40",
  "core-js": "^2.4.1",
  "rxjs": "5.0.1",
  "zone.js": "^0.8.4"

},

which should install current stable version of Angular

angular-cli (command-line tool by Angular)


答:
This code will helps you.

If you load data dynamically than you have use

$(document).on("click",...)

also you made mistake in this line too. it was 'a [id^=del_]'.

$(document).on("click",'a[id^=del_]', function(e){
    e.preventDefault();
    var id_modelo   = $(this).attr("id_mod");
    var id_bloque   = $(this).parent().siblings("span").attr("id");
    console.log(id_modelo);
    console.log(id_bloque);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>333107 (<span id="pos_3488">1</span>)
<span> - </span></li></code>```

Title: jquery .on not work

Body:
This code will helps you.

If you load data dynamically than you have use

$(document).on("click",...)

also you made mistake in this line too. it was 'a [id^=del_]'.

$(document).on("click",'a[id^=del_]', function(e){
    e.preventDefault();
    var id_modelo   = $(this).attr("id_mod");
    var id_bloque   = $(this).parent().siblings("span").attr("id");
    console.log(id_modelo);
    console.log(id_bloque);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>333107 (<span id="pos_3488">1</span>)
<span><a id="del_3488" href="#" id_mod="3488"> - </a></span></li>


问:
jQuery - Given a DIV with a bunch of
 tags, how to find the first
 that isn't empty
Given a DIV with a lot of paragraph tags:

```<code><div>
 <p></p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
</div>
</code>```

How to magically find the first
 which isn't empty using just jQUery? ideas?

答:
You can try this:</p>

```<code>$('div p:not(:empty)').eq(0);
</code>```

Body:
Given a DIV with a lot of paragraph tags:

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

How to magically find the first
 which isn't empty using just jQUery? ideas?

Body:
You can try this:

$('div p:not(:empty)').eq(0);


问:
Is a For Loop always executed at least once?
According to my teacher, a for-loop always executes at least once, even if the condition is not met.

Example (like I know it from C++):

```<code>for (int i=6; i <=5; i++) {
    //irrelevant for this question
}
</code>```

According to her, this loop would execute at least once, yet it does not, or am I missing something?
Is there any case, no matter what language, where this would execute once?
To eliminate the thought in advance: yes, it was about for loops, not do-while-loops.

Edit:

Thanks for all those quick answers, I guess this case is already closed. Have a nice day/night.

答:
You could say a for-loop is always evaluated at least once.

But if a for-loop's condition is not met, its block will never execute.

Because you didn't ask about other loops, I won't address those.

Body:
According to my teacher, a for-loop always executes at least once, even if the condition is not met.

Example (like I know it from C++):

for (int i=6; i <=5; i++) {
    //irrelevant for this question
}

According to her, this loop would execute at least once, yet it does not, or am I missing something?
Is there any case, no matter what language, where this would execute once?
To eliminate the thought in advance: yes, it was about for loops, not do-while-loops.

Edit:

Thanks for all those quick answers, I guess this case is already closed. Have a nice day/night.


问:
Use data in angular directive link?
How i can use data , which passed from controller to directive from tag attribute ?? Its show undefined in console .

```<code>App.directive('applist', ['$rootScope', function($rootScope) {
'use strict';
    return {
       restrict: 'E',
       scope: {
           gamesList: '=',
       }.
       link: function(scope,attrs){
           console.log(scope.gamesList); //undefined
       }
    }
}])
</code>```

And html:

```<code><applist games-List="games">
    <div ng-repeat="(key, value) in gamesList | groupBy: 'game.id'"> ... </div>
</applist>
</code>```

答:
You must change your tag to:

```<code><applist games-list="games">...</applist>
</code>```

Also, in angular, the camelCase in your attributes is used with a '-' in the html tag. And you forgot the 's' to the 'game'

Edit: As stated, the dot before link is making the directive break. Try:

```<code>return {
   restrict: 'E',
   scope: {
       gamesList: '='
   }, //change dot to coma
   link: function(scope,attrs){
       console.log(scope.gamesList); //undefined
   }
}
</code>```

Title: Use data in angular directive link?

Body:
How i can use data , which passed from controller to directive from tag attribute ?? Its show undefined in console .

App.directive('applist', ['$rootScope', function($rootScope) {
'use strict';
    return {
       restrict: 'E',
       scope: {
           gamesList: '=',
       }.
       link: function(scope,attrs){
           console.log(scope.gamesList); //undefined
       }
    }
}])

And html:

<applist games-List="games">

 ...

</applist>

Body:
You must change your tag to:

<applist games-list="games">...</applist>

Also, in angular, the camelCase in your attributes is used with a '-' in the html tag. And you forgot the 's' to the 'game'

Edit: As stated, the dot before link is making the directive break. Try:

return {
   restrict: 'E',
   scope: {
       gamesList: '='
   }, //change dot to coma
   link: function(scope,attrs){
       console.log(scope.gamesList); //undefined
   }
}