答:
Your problem is this:

```<code>$user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');
</code>```

Is lacking a call to get the result set back from the query. Add ->first().

What it' saying is:

You gave me an instance of the query Builder

But

I wanted a model that extends the authenticatable class

If you open App\User, you'll see that it does indeed extend this class:

```<code>class User extends Authenticatable {
</code>```

Title: Auth::login($user) in laravel not able to login the user

Body:
Your problem is this:

$user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');

Is lacking a call to get the result set back from the query. Add ->first().

What it' saying is:

You gave me an instance of the query Builder

But

I wanted a model that extends the authenticatable class

If you open App\User, you'll see that it does indeed extend this class:

class User extends Authenticatable {


来源: stackexchange

问:
Error in installing opencv3 with homebrew and python3
I'm using homebrew installing opencv3 on OSX(EI Captain),

```<code>brew install opencv3 --with-contrib --with-python3 --HEAD
</code>```

and an error occurred:

```<code>Updating Homebrew...
==> Installing opencv3 from homebrew/science
==> Cloning https://github.com/opencv/opencv.git
Updating /Users/ksun/Library/Caches/Homebrew/opencv3--git
==> Checking out branch master
==> Cloning https://github.com/opencv/opencv_contrib.git
Updating /Users/ksun/Library/Caches/Homebrew/opencv3--contrib--git
> ==> Checking out branch master
Error: No such file or directory - /private/tmp/opencv3-20170330-14255-bxsn05/3rdparty/ippicv/downloader.cmake
</code>```

Can u guys help me find out how to fix it?

答:
I experienced the same problem. I solved it by running brew install opencv3 --with-contrib --with-python3

I think what happened is that people updated the ../3rdparty/ippicv folder in the repo such that the downloader.cmake file is no longer there, but they have not yet updated the brew formula.

brew install without --HEAD will build opencv3.2.0 which is good enough for me.

ContentLicense: CC BY-SA 3.0

Body:
I'm using homebrew installing opencv3 on OSX(EI Captain),

brew install opencv3 --with-contrib --with-python3 --HEAD

and an error occurred:

Updating Homebrew...
==> Installing opencv3 from homebrew/science
==> Cloning https://github.com/opencv/opencv.git
Updating /Users/ksun/Library/Caches/Homebrew/opencv3--git
==> Checking out branch master
==> Cloning https://github.com/opencv/opencv_contrib.git
Updating /Users/ksun/Library/Caches/Homebrew/opencv3--contrib--git
> ==> Checking out branch master
Error: No such file or directory - /private/tmp/opencv3-20170330-14255-bxsn05/3rdparty/ippicv/downloader.cmake

Can u guys help me find out how to fix it?


问:
Sip Calling in Android
I am using native sip android when I am calling from my Android application to application I have found errors
SipAudioCall﹕ sip session error: TRANSACTION_TERMINTED: transaction terminated
SipAudioCall﹕ onCallEstablished(): java.lang.NullPointerException
but call is established but on end call it does not giving call back

```<code>public void initiateCall(final String sipAddress,final IResponse m_listener) {
    this.m_listener = m_listener;

    //m_listener.connectionStatus(sipAddress);

    try {
        SipAudioCall.Listener listener = new SipAudioCall.Listener() {
            @Override
            public void onCallEstablished(SipAudioCall call) {
                //super.onCallEstablished(call);

                call.startAudio();
                call.setSpeakerMode(false);

                if (call.isMuted()) {
                    call.toggleMute();
                }
                //call.toggleMute();
                m_listener.callIsEtsablished(true);

                String useName = call.getPeerProfile().getDisplayName();

                if(useName == null) {
                    Log.d("hamid","useName is null");
                    useName = call.getPeerProfile().getUserName();
                }

            }

            // Much of the client's interaction with the SIP Stack will
            // happen via listeners.  Even making an outgoing m_audioCall, don't
            // forget to set up a listener to set things up once the m_audioCall is established.
           /* @Override
            public void onCallEstablished(SipAudioCall call) {
                //super.onCallEstablished(call);

            }*/
            @Override
            public void onCallEnded(SipAudioCall call) {
                //rejectIncomingCall();
                //m_listener.onCallEndedStatus("Call Ended");
                //m_listener.connectionStatus("Call Ended");
                m_listener.connectionStatus("Ready.");
                m_listener.callIsEtsablished(false);

            }

        };

        m_audioCall = m_manager.makeAudioCall(m_profile.getUriString(), sipAddress, listener, 30);

    }
    catch (Exception e) {
        Log.d("hamid", "Calling exception: "+e);

        Log.i("DialCallActivity/InitiateCall", "Error when trying to close manager.", e);

        if (m_profile != null) {

            try {
                m_manager.close(m_profile.getUriString());

            } catch (Exception ee) {
                Log.i("DialCallActivity/InitiateCall",
                        "Error when trying to close manager.", ee);
                ee.printStackTrace();
            }
        }
        if (m_audioCall != null) {
            m_audioCall.close();
        }
    }
}
</code>```

答:
Can you try to add

```<code>call.answerCall(-1);
</code>```

in front of start audio.

Title: Sip Calling in Android

Body:
I am using native sip android when I am calling from my Android application to application I have found errors
SipAudioCall﹕ sip session error: TRANSACTION_TERMINTED: transaction terminated
SipAudioCall﹕ onCallEstablished(): java.lang.NullPointerException
but call is established but on end call it does not giving call back

public void initiateCall(final String sipAddress,final IResponse m_listener) {
    this.m_listener = m_listener;

    //m_listener.connectionStatus(sipAddress);

    try {
        SipAudioCall.Listener listener = new SipAudioCall.Listener() {
            @Override
            public void onCallEstablished(SipAudioCall call) {
                //super.onCallEstablished(call);

                call.startAudio();
                call.setSpeakerMode(false);

                if (call.isMuted()) {
                    call.toggleMute();
                }
                //call.toggleMute();
                m_listener.callIsEtsablished(true);

                String useName = call.getPeerProfile().getDisplayName();

                if(useName == null) {
                    Log.d("hamid","useName is null");
                    useName = call.getPeerProfile().getUserName();
                }

            }

            // Much of the client's interaction with the SIP Stack will
            // happen via listeners.  Even making an outgoing m_audioCall, don't
            // forget to set up a listener to set things up once the m_audioCall is established.
           /* @Override
            public void onCallEstablished(SipAudioCall call) {
                //super.onCallEstablished(call);

            }*/
            @Override
            public void onCallEnded(SipAudioCall call) {
                //rejectIncomingCall();
                //m_listener.onCallEndedStatus("Call Ended");
                //m_listener.connectionStatus("Call Ended");
                m_listener.connectionStatus("Ready.");
                m_listener.callIsEtsablished(false);

            }

        };

        m_audioCall = m_manager.makeAudioCall(m_profile.getUriString(), sipAddress, listener, 30);

    }
    catch (Exception e) {
        Log.d("hamid", "Calling exception: "+e);

        Log.i("DialCallActivity/InitiateCall", "Error when trying to close manager.", e);

        if (m_profile != null) {

            try {
                m_manager.close(m_profile.getUriString());

            } catch (Exception ee) {
                Log.i("DialCallActivity/InitiateCall",
                        "Error when trying to close manager.", ee);
                ee.printStackTrace();
            }
        }
        if (m_audioCall != null) {
            m_audioCall.close();
        }
    }
}

Body:
Can you try to add

call.answerCall(-1);

in front of start audio.


问:
XAMPP relative URLs working on WordPress home but not pages
I have a testing site at tektonpress.piconmedia.com that is working correctly.

I'm having some problems with relative URLs and images on a local version.

I installed XAMPP, restored a copy of the database to my local machine, and copied FTP files over. After updating wp-config.php, just about everything is working correctly. That includes images that use relative URLs in my stylesheets.

My problem is with some images that I try to load through HTML. They display correctly on the home page, but not from other pages.

For example, the following HTML works on localhost/tektonpress/ but not localhost/tektonpress/editing/:

```<code><img src="resources/img/logo-white.png" alt="Tekton Press logo">
</code>```

Here's an example when the image doesn't work:

Example from page

The image in question is located at C:\xampp\htdocs\tektonpress\resources\img\logo-white.png

When I hover over the URL while inspecting the element in Chrome, here's what I see:

One layer too deep

I tried adding a slash to the front of the path, like so:

```<code><img src="/resources/img/logo-white.png" alt="Tekton Press logo">
</code>```

Unfortunately, the page ends up looking for the image at /localhost/resources/img/logo-white.png.

I've spent several hours on this with no luck. I thought I'd finally found a simple (but potentially maintenance-heavy) solution at stackoverflow.com/questions/7823260/xampp-relative-urls-not-working-correctly, but just ended up with a server error.

Here's the contents of my .htaccess file:

```<code><IfModule mod_rewrite.c>

RewriteEngine On

RewriteBase /tektonpress/

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . /tektonpress/index.php [L]

</IfModule>
</code>```

Any suggestions?

答:
I realize it is not much of a fix, but have you tried:

```<code><img src="/tektonpress/resources/img/logo-white.png" alt="Tekton Press logo">
</code>```

Should let you pull the image properly.

Body:
I have a testing site at tektonpress.piconmedia.com that is working correctly.

I'm having some problems with relative URLs and images on a local version.

I installed XAMPP, restored a copy of the database to my local machine, and copied FTP files over. After updating wp-config.php, just about everything is working correctly. That includes images that use relative URLs in my stylesheets.

My problem is with some images that I try to load through HTML. They display correctly on the home page, but not from other pages.

For example, the following HTML works on localhost/tektonpress/ but not localhost/tektonpress/editing/:

Here's an example when the image doesn't work:

Example from page

The image in question is located at C:\xampp\htdocs\tektonpress\resources\img\logo-white.png

When I hover over the URL while inspecting the element in Chrome, here's what I see:

One layer too deep

I tried adding a slash to the front of the path, like so:

Unfortunately, the page ends up looking for the image at /localhost/resources/img/logo-white.png.

I've spent several hours on this with no luck. I thought I'd finally found a simple (but potentially maintenance-heavy) solution at stackoverflow.com/questions/7823260/xampp-relative-urls-not-working-correctly, but just ended up with a server error.

Here's the contents of my .htaccess file:

<IfModule mod_rewrite.c>

RewriteEngine On

RewriteBase /tektonpress/

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . /tektonpress/index.php [L]

</IfModule>

Any suggestions?

Body:
I realize it is not much of a fix, but have you tried:

<img src="/tektonpress/resources/img/logo-white.png" alt="Tekton Press logo">

Should let you pull the image properly.


问:
Is there a way to ensure a specific visual studio project in a visual studio solution is only built on a build server (or a specific server)
Basically I want to block developers from building one of the projects in a solution that only the build server can/should build.

Alternatively, Developers would have a solution with projects A, B, C but not D. However, The build server would add project D to the solution. Then build the solution with projects A,B,C, & D.

Can this be done through code and/or configuration?

Thanks

答:
Well one of possible solution would be creating different build configurations. Each build configuration would include projects needed to run properly.

Simplified example:

Developers could use default Debug configuration to build projects A, B and C (D must be excluded from this configuration) to run application locally.

Production configuration would have all projects (A, B, C and D) included, and your continuous integration system would use that configuration to build your solution.

Keep in mind what others said, you won't be able to protect project D from manual or accidental builds, as long as it stays inside same solution.


问:
How to delete aws s3 bucket in aws cli
I have the ff s3 bucket, see image below:

I know how to delete them on the page but how can i delete them using aws cli?

I tried using

aws s3api delete-objects --bucket
  elasticbeanstalk-ap-southeast-1-613285248276

but it wont work.

答:
You can use 'rb' option

E.g. aws s3 rb s3://elasticbeanstalk-ap-southeast-1-613285248276

For more details  click here

If the bucket is not empty then use the --force flag

Title: How to delete aws s3 bucket in aws cli


问:
How to delete a single git repository clone, without the rm -rf sledgehammer?
It is not possible to remove a git repo simply with rm -r, because the .git directory contains lots of write-protected files. I have permission to delete these as I'm the owner, but it's not feasible to confirm them all one by one.

Now, it is possible to do it all in one command by adding the -f flag to rm, but that means I lose all protection against deleting stuff that's protected for good reason. Like, for instance, another git repository with local branches that I haven't pushed yet.

But it seems the only way, so I've found myself doing rm -rf quite a lot lately, but I always feel uneasy about it. Is there a better way to get rid of a single repo clone, that will not ask about thousands of individual files but will fail if I try to erase something but a single repo? Ideally, it should also check that the repo I'm trying to delete has some up-to-date remote, before actually deleting it.

I don't quite see what's unclear about this question... it is this:

How do I delete a repository with all contents, using commands that would not also nuke any other directory with write-protected files in it?

答:
First, you collect all garbage objects:

```<code>git gc --prune=all
</code>```

Then only one pack file remains, which is read-only, and the corresponding pack index, which is also read-only. Now

```<code>cd ..
rm -r repo
</code>```

will ask only twice for confirmation instead of thousands of times.

This does not protect against removal of checked-out submodules, though.

Body:
First, you collect all garbage objects:

git gc --prune=all

Then only one pack file remains, which is read-only, and the corresponding pack index, which is also read-only. Now

cd ..
rm -r repo

will ask only twice for confirmation instead of thousands of times.

This does not protect against removal of checked-out submodules, though.


问:
has_many :through with multiple sources
I have a model named AnswerConnection, who has two foreign keys from Answer model: answer_1 and answer_2.

In my Answer model I have defined:

has_many :connections, through: :answer_connections, source: :answer_2

However, the relationship is simmetrycal: if answer_1 is connected to answer_2, answer_2 is connected to answer_1. This means that when I search the connections of an specific answer, I need to check if its present in answer_1 or answer_2 field.

There is possible to define a relationship attending this (like if I could define two values in :source parameter)?

答:
I don't think you can set 2 sources, but if I understood it correctly you could do something like:</p>

```<code>has_many :connections_1, through: :answer_connections, source: :answer_1
has_many :connections_2, through: :answer_connections, source: :answer_2

def connections
  connections_1.merge(connections_2) # intersection
  # or connections_1.or(connections_2) for union
end
</code>```

Title: has_many :through with multiple sources

Body:
I don't think you can set 2 sources, but if I understood it correctly you could do something like:

has_many :connections_1, through: :answer_connections, source: :answer_1
has_many :connections_2, through: :answer_connections, source: :answer_2

def connections
  connections_1.merge(connections_2) # intersection
  # or connections_1.or(connections_2) for union
end


问:
Javascript, changing object value
It's pretty hard to explain so I'll just show an example.

```<code>for(i=1;i<position.length;i++)
        {
            if(position[i].lat() == position[i-1].lat() && position[i].lng() == position[i-1].lng())
            {

                position[i].lat = position[i].lat() + ((Math.random() -.5) / 1500);
                position[i].lng = position[i].lng() + ((Math.random() -.5) / 1500);
                //position[i].lng = position[i].lng() + ((Math.random() -.5) / 1500);
                //console.log(position[i].lat().value);
            }
        }
</code>```

Basically I'm trying to just change the value of lat and lng in the position array but I can't seem to find a solution.

```<code> $('#data').find('div[name=postalCode]').each(function(i) {
            var latlng = $(this).find('input[type=hidden]');
            position.push(new google.maps.LatLng(latlng[0].value, latlng[1].value));
            });
</code>```

And this is how the position array is filled up.

Any help is appreciated. thanks
Realize that the above comparison code does not fully compare, i'll put the new code here just in case anyone uses it

```<code>for (var i = 0; i < position.length; i++) {
            for(var k = i+1; k<position.length; k++){
        if (position[i].lat() == position[k].lat() && (position[i].lng() == position[k].lng())) {
            console.log("before change" + i + position[i].lat());
           position[i] = new google.maps.LatLng(
        position[i].lat() + ((Math.random() * 1.5) / 100),
        position[i].lng() + ((Math.random() * 1.5) / 100)
        );
        console.log("after change" +i + position[i].lat());
        }
        }
    }
</code>```

答:
https://developers.google.com/maps/documentation/javascript/reference

"Notice that you cannot modify the coordinates of a LatLng. If you want to compute another point, you have to create a new one."

In short, don't change the values, replace the entry.

Example:

```<code>for (var i = 1; i < position.length; i++) {
    if (position[i].lat() == position[i - 1].lat() && position[i].lng() == position[i - 1].lng()) {
        position[i] = new google.maps.LatLng(
            position[i].lat() + ((Math.random() - .5) / 1500),
            position[i].lng() + ((Math.random() - .5) / 1500)
        );
    }
}
</code>```

Title: Javascript, changing object value

Body:
It's pretty hard to explain so I'll just show an example.

for(i=1;i<position.length;i++)
        {
            if(position[i].lat() == position[i-1].lat() && position[i].lng() == position[i-1].lng())
            {

                position[i].lat = position[i].lat() + ((Math.random() -.5) / 1500);
                position[i].lng = position[i].lng() + ((Math.random() -.5) / 1500);
                //position[i].lng = position[i].lng() + ((Math.random() -.5) / 1500);
                //console.log(position[i].lat().value);
            }
        }

Basically I'm trying to just change the value of lat and lng in the position array but I can't seem to find a solution.

 $('#data').find('div[name=postalCode]').each(function(i) {
            var latlng = $(this).find('input[type=hidden]');
            position.push(new google.maps.LatLng(latlng[0].value, latlng[1].value));
            });

And this is how the position array is filled up.

Any help is appreciated. thanks
Realize that the above comparison code does not fully compare, i'll put the new code here just in case anyone uses it

for (var i = 0; i < position.length; i++) {
            for(var k = i+1; k<position.length; k++){
        if (position[i].lat() == position[k].lat() && (position[i].lng() == position[k].lng())) {
            console.log("before change" + i + position[i].lat());
           position[i] = new google.maps.LatLng(
        position[i].lat() + ((Math.random() * 1.5) / 100),
        position[i].lng() + ((Math.random() * 1.5) / 100)
        );
        console.log("after change" +i + position[i].lat());
        }
        }
    }

Body:
https://developers.google.com/maps/documentation/javascript/reference

"Notice that you cannot modify the coordinates of a LatLng. If you want to compute another point, you have to create a new one."

In short, don't change the values, replace the entry.

Example:

for (var i = 1; i < position.length; i++) {
    if (position[i].lat() == position[i - 1].lat() && position[i].lng() == position[i - 1].lng()) {
        position[i] = new google.maps.LatLng(
            position[i].lat() + ((Math.random() - .5) / 1500),
            position[i].lng() + ((Math.random() - .5) / 1500)
        );
    }
}


问:
IIS rewrite subfolder URL to subdomain content
I'm trying to load content hosted on a subdomain site as a subfolder on the same main domain - I've attempted a variety of IIS URL rewrites with no luck so far. The goal is for a user to go to:

```<code>domain.com/subdomain1
</code>```

which displays

```<code>subdomain1.domain.com
</code>```

but keeps the URL as

```<code>domain.com/subdomain1
</code>```

There are multiple subdomains which I need to do this with.

I have the URL Rewrite module installed and have tried all many of rules.

Any help would be appreciated :-)

答: A rewrite changes the path on the server only, if you want the URL to change you need a redirect. You can change this on the rule.</p>

Body:
I'm trying to load content hosted on a subdomain site as a subfolder on the same main domain - I've attempted a variety of IIS URL rewrites with no luck so far. The goal is for a user to go to:

domain.com/subdomain1

which displays

subdomain1.domain.com

but keeps the URL as

domain.com/subdomain1

There are multiple subdomains which I need to do this with.

I have the URL Rewrite module installed and have tried all many of rules.

Any help would be appreciated :-)


问:
WordPress, removing comments block programmatically
I want to remove Word Press comment block from specified 'n' posts. These posts are generated dynamically and don't want comment block</p>

答:
The easiest way to do that, without even going into the code, would be to uncheck "display comments" at the bottom of the post you create inside the wordpress admin area.

Alternatively, you could disable comments altogether by going into the "Settings » Discussion" part in your admin area and deselecting "Allow people to post comments on new articles".

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
What is the supported range for Hive's Timestamp data types

Hadoop Distro: HDP 2.4.2

Hive Version: 1.2.1

I have an ORC table tbl1 having timestamp column. I inserted these values:

```<code>insert into tbl1 values ('0001-01-01 00:00:20.0');
insert into tbl1 values ('9999-01-01 00:00:20.0');
</code>```

I created another ORC table tbl2 having timestamp column. Then I tried:

```<code>insert into tbl2 select * from tbl1;
</code>```

Data in tbl2 is corrupted:

```<code>1754-08-28 22:44:01.128654848
1815-03-31 05:56:28.066277376
</code>```

Am I using out of range values?

Is there any specific range for timestamp?

This problem is only for ORC file format. For other file formats like textfile, avro, parquet, etc it's working fine.

答:
Hive vectorization is enabled in my case.

```<code>hive.vectorized.execution.enabled = true;
</code>```

This is an issue due to vectorized execution.

It is fixed in 1.3.0, 2.0.1, 2.1.0

Check HIVE-9862 and wiki for more details.

To use vectorized query execution, you must store your data in ORC format. That's why the error is coming only in ORC file format.

Body:
Hadoop Distro: HDP 2.4.2

Hive Version: 1.2.1

I have an ORC table tbl1 having timestamp column. I inserted these values:

insert into tbl1 values ('0001-01-01 00:00:20.0');
insert into tbl1 values ('9999-01-01 00:00:20.0');

I created another ORC table tbl2 having timestamp column. Then I tried:

insert into tbl2 select * from tbl1;

Data in tbl2 is corrupted:

1754-08-28 22:44:01.128654848
1815-03-31 05:56:28.066277376

Am I using out of range values?

Is there any specific range for timestamp?

This problem is only for ORC file format. For other file formats like textfile, avro, parquet, etc it's working fine.

Body:
Hive vectorization is enabled in my case.

hive.vectorized.execution.enabled = true;

This is an issue due to vectorized execution.

It is fixed in 1.3.0, 2.0.1, 2.1.0

Check HIVE-9862 and wiki for more details.

To use vectorized query execution, you must store your data in ORC format. That's why the error is coming only in ORC file format.


问:
pyomo constraints section missing
I'm new at using pyomo and getting following error:
/var/folders/dk/932rtpm52sg0jdzzkz81mhn00000gn/T/tmp7Psz4a.pyomo.lp:5: constraints section missing

My constraint is:

```<code>matrix_bis = np.ones((size_node, size_node))
c11_param = matrix_bis.copy()
c11_param = np.tril(c11_param)
param11 = np.dot(c11_param, m.Y)

# Constraints
def c11_rule(m,j):
    for e in node_set:
        return (data.ix[e, 'cp_min'], c11_param[e,j]*m.Y[e], data.ix[e, 'cp_max']/interval)
    else:
        return pe.Constraint.Skip
m.c11 = pe.Constraint(node_set, rule = c11_rule)
</code>```

Any help much appreciated.

答:
I'm not sure if this is the cause of your error but the first issue I see is that you don't need the for loop inside of the constraint rule. By declaring the Constraint as indexed over node_set the rule will automatically be called once for every value in node_set. It looks like you are distinguishing between the index 'e' and the index 'j' in c11_param so I'm guessing that you want to index the constraint over the cross product of node_set. You also don't need Constraint.Skip. Maybe something like this:</p>

```<code>def c11_rule(m, j, e):
    return (data.ix[e,'cp_min'], c11_param[e,j]*m.Y[e], data.ix[e, 'cp_max']/interval)
m.c11 = Constraint(node_set, node_set, rule=c11_rule)
</code>```

Title: pyomo constraints section missing

Body:
I'm new at using pyomo and getting following error:
/var/folders/dk/932rtpm52sg0jdzzkz81mhn00000gn/T/tmp7Psz4a.pyomo.lp:5: constraints section missing

My constraint is:

matrix_bis = np.ones((size_node, size_node))
c11_param = matrix_bis.copy()
c11_param = np.tril(c11_param)
param11 = np.dot(c11_param, m.Y)

# Constraints
def c11_rule(m,j):
    for e in node_set:
        return (data.ix[e, 'cp_min'], c11_param[e,j]*m.Y[e], data.ix[e, 'cp_max']/interval)
    else:
        return pe.Constraint.Skip
m.c11 = pe.Constraint(node_set, rule = c11_rule)

Any help much appreciated.

Body:
I'm not sure if this is the cause of your error but the first issue I see is that you don't need the for loop inside of the constraint rule. By declaring the Constraint as indexed over node_set the rule will automatically be called once for every value in node_set. It looks like you are distinguishing between the index 'e' and the index 'j' in c11_param so I'm guessing that you want to index the constraint over the cross product of node_set. You also don't need Constraint.Skip. Maybe something like this:

def c11_rule(m, j, e):
    return (data.ix[e,'cp_min'], c11_param[e,j]*m.Y[e], data.ix[e, 'cp_max']/interval)
m.c11 = Constraint(node_set, node_set, rule=c11_rule)


问:
How to check if a string is a valid DATE, TIME or DATETIME
When I try to put a value into a DATE field which is invalid, MySQL seems to use 0000-00-00 instead. Is there a way I can do this "check" without updating a DATE field? And to do it from for example PHP?

Like, is there a way I can query the MySQL server and ask "Hey, is this DATE, TIME or DATETIME valid to you?"

Or is there maybe an even better way of doing it?

答:
DATETIME - in SQL

```<code>SELECT your_unreliable_datetime_column, CAST(your_unreliable_datetime_column as DATETIME)
FROM some_cool_table
WHERE
CAST(your_unreliable_datetime_column as DATETIME) IS NOT NULL
AND
your_unreliable_datetime_column = CAST(your_unreliable_datetime_column as DATETIME)
</code>```

This should only select valid DATETIMEs, also should be applicable to DATE and TIME accordingly, but not tested...

I did not found any documentation on CAST() return value on a convert failure, but documentation covers a special case - a possible failure - which returns NULL:

For conversion of a “zero” date string to a date, CONVERT() and CAST()
  return NULL and produce a warning when the NO_ZERO_DATE SQL mode is
  enabled.

Also, from my tests it seems that CAST() behaves the same on any convert failure - returns NULL and generates warning.

I actually tested this on MariaDB 10.0.30

Body:
DATETIME - in SQL

SELECT your_unreliable_datetime_column, CAST(your_unreliable_datetime_column as DATETIME)
FROM some_cool_table
WHERE
CAST(your_unreliable_datetime_column as DATETIME) IS NOT NULL
AND
your_unreliable_datetime_column = CAST(your_unreliable_datetime_column as DATETIME)

This should only select valid DATETIMEs, also should be applicable to DATE and TIME accordingly, but not tested...

I did not found any documentation on CAST() return value on a convert failure, but documentation covers a special case - a possible failure - which returns NULL:

For conversion of a “zero” date string to a date, CONVERT() and CAST()
  return NULL and produce a warning when the NO_ZERO_DATE SQL mode is
  enabled.

Also, from my tests it seems that CAST() behaves the same on any convert failure - returns NULL and generates warning.

I actually tested this on MariaDB 10.0.30


问:
php how to let the script running on the server even the ajax is completed
I'm trying to let the script running even the ajax is complete. But what I'm done is the ajax complete after the script processed. The following is my code.

index.php

```<code>$.ajax({

url:"terminal.php",
dataType:'json',
data: "test=122312&id=dsfsdf",
type: 'post',
success:function(data){

    console.log(data);

},
error:function(data){

    console.log('error');
}
})
</code>```

terminal.php

```<code>    system("curl http://127.0.0.1:8080/testing/process >/dev/null 2>dev/null &");
    exit;
</code>```

process.php

```<code>set_time_limit(0);
ignore_user_abort(true);

sleep(10);

$con = mysqli_connect('127.0.0.1','root','','testing');

$datetime = date("Y-m-d h:i:s");

$sql = "INSERT INTO tbl_hold VALUES('$datetime')";

$result = mysqli_query($con,$sql);

if(!$result)
{
    echo "Fail the process";
}

mysqli_close($con);
</code>```

Please help me if anyone know how to solve the issue

答:
PHP internally buffers whatever output is being generated and it flushes only at the end of the php script , but you can also force it to do so by using  flush() that way output will get sent and your php script would be running even after ajax is completed

```<code>ob_implicit_flush(true);  //update
ob_end_flush();  //update
echo json_encode('status'=>'200');
ob_end_flush(); //flush PHP buffers
ob_flush();
flush();  // flush OS buffers
</code>```

On some browsers you might notice that the loading symbol would keep spinning even when the browser had received all the response that's because the HTTP connection between server and browser is still open. So if you want to avoid that you also need to close the connection manually , add this after flush()

```<code>header("Content-Type", "appliation/json"); //update
header('Connection: close');
header('Content-Length: '.ob_get_length());
</code>```

Body:
I'm trying to let the script running even the ajax is complete. But what I'm done is the ajax complete after the script processed. The following is my code.

index.php

$.ajax({

url:"terminal.php",
dataType:'json',
data: "test=122312&id=dsfsdf",
type: 'post',
success:function(data){

    console.log(data);

},
error:function(data){

    console.log('error');
}
})

terminal.php

    system("curl http://127.0.0.1:8080/testing/process >/dev/null 2>dev/null &");
    exit;

process.php

set_time_limit(0);
ignore_user_abort(true);

sleep(10);

$con = mysqli_connect('127.0.0.1','root','','testing');

$datetime = date("Y-m-d h:i:s");

$sql = "INSERT INTO tbl_hold VALUES('$datetime')";

$result = mysqli_query($con,$sql);

if(!$result)
{
    echo "Fail the process";
}

mysqli_close($con);

Please help me if anyone know how to solve the issue

Body:
PHP internally buffers whatever output is being generated and it flushes only at the end of the php script , but you can also force it to do so by using  flush() that way output will get sent and your php script would be running even after ajax is completed

ob_implicit_flush(true);  //update
ob_end_flush();  //update
echo json_encode('status'=>'200');
ob_end_flush(); //flush PHP buffers
ob_flush();
flush();  // flush OS buffers

On some browsers you might notice that the loading symbol would keep spinning even when the browser had received all the response that's because the HTTP connection between server and browser is still open. So if you want to avoid that you also need to close the connection manually , add this after flush()

header("Content-Type", "appliation/json"); //update
header('Connection: close');
header('Content-Length: '.ob_get_length());


问:
Adding rows to SQL query result
I have a custom query in my Java application that looks like that:

```<code>select
    to_char(search.timestamp,'Mon') as mon,
    COUNT(DISTINCT(search.ip_address))
from
    searches
WHERE
    searches.city = 1
group by 1;
</code>```

which should return all months that occur within the database, and number of distinct IP addresses within each month. However, at this point, some months do not have any entries, and they are missing in the SQL query result. How can I make sure that all of the months are displayed there, even if their count is 0?

Got it working with:

```<code>select
    to_char (gs.m,'Mon') as mon,
    count (distinct search.ip_address)
from
    generate_series (
          date_trunc('month', current_date - interval '11 month'),
          current_date,
          '1 month'
      ) gs (m)
    left join searches
    on date_trunc('month', search.timestamp) = gs.m AND search.city = 1
group by gs.m
order by gs.m;
</code>```

答:
Something like this (untested):

```<code>select
    months.mon
    , COUNT(DISTINCT(searchs.ip_address))
from
    (select
        to_char(searches.timestamp,'Mon') as mon
     from
        searches
     group by 1
    ) months
    left join searches
    on to_char(searchs.timestamp,'Mon') = months.mon
    and searches.city = 1
group by 1;
</code>```

And if you wanted the years in there, too, try something like this (untested):

```<code>select
    months.mon
    , COUNT(DISTINCT(searchs.ip_address))
from
    (select
        extract(year from searches.timestamp) as yr
        , to_char(searches.timestamp,'Mon') as mon
        , to_char(yr,'9999') || mon yrmon
     from
        searches
     group by 1
    ) months
    left join searches
    on to_char(extract(year from searches.timestamp),'9999' ||
        to_char(searchs.timestamp,'Mon') = months.yrmon
    and searches.city = 1
group by 1;
</code>```

Title: Adding rows to SQL query result

Body:
I have a custom query in my Java application that looks like that:

select
    to_char(search.timestamp,'Mon') as mon,
    COUNT(DISTINCT(search.ip_address))
from
    searches
WHERE
    searches.city = 1
group by 1;

which should return all months that occur within the database, and number of distinct IP addresses within each month. However, at this point, some months do not have any entries, and they are missing in the SQL query result. How can I make sure that all of the months are displayed there, even if their count is 0?

Got it working with:

select
    to_char (gs.m,'Mon') as mon,
    count (distinct search.ip_address)
from
    generate_series (
          date_trunc('month', current_date - interval '11 month'),
          current_date,
          '1 month'
      ) gs (m)
    left join searches
    on date_trunc('month', search.timestamp) = gs.m AND search.city = 1
group by gs.m
order by gs.m;

Body:
Something like this (untested):

select
    months.mon
    , COUNT(DISTINCT(searchs.ip_address))
from
    (select
        to_char(searches.timestamp,'Mon') as mon
     from
        searches
     group by 1
    ) months
    left join searches
    on to_char(searchs.timestamp,'Mon') = months.mon
    and searches.city = 1
group by 1;

And if you wanted the years in there, too, try something like this (untested):

select
    months.mon
    , COUNT(DISTINCT(searchs.ip_address))
from
    (select
        extract(year from searches.timestamp) as yr
        , to_char(searches.timestamp,'Mon') as mon
        , to_char(yr,'9999') || mon yrmon
     from
        searches
     group by 1
    ) months
    left join searches
    on to_char(extract(year from searches.timestamp),'9999' ||
        to_char(searchs.timestamp,'Mon') = months.yrmon
    and searches.city = 1
group by 1;


问:
Added component-scan to a legacy Spring application
I have a legacy Spring application whether the context is configured entirely with XML. I would like to add a new controller to the application using the @Controller annotation so I begin to migrate to using annotations.

As a test I have added the following controller to the application

```<code>package uk.co.onevisionconsulting.engineermanager.webapp.controller2;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

     @RequestMapping("/hello")
     public String hello(){
          return "Hello";
     }
}
</code>```

I have also added the context:component-scan tag to my spring context

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans” xmlns:context="http://www.springframework.org/schema/context"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance”
             xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
             http://www.springframework.org/schema/context
             http://www.springframework.org/schema/context/spring-context-2.5.xsd">

     <context:component-scan base-package="uk.co.onevisionconsulting.engineermanager" />

     <bean name="jsonView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.JsonView" />

     <bean name="csvView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.CsvView" />

     <bean name="ajaxView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.AjaxView" />

     <bean name="dataTablesView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.DataTablesView" />

     <bean id="exceptionResolver"
          class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
          <property name="exceptionMappings">
               <props>
                    <prop key="org.springframework.dao.DataAccessException">
                         dataAccessFailure
                    </prop>
               </props>
          </property>
     </bean>

     <bean id=“someController"
          class="uk.co.onevisionconsulting.engineermanager.webapp.controller.SomeController" >
          <property name=“someManager" ref=“someManager" />
     </bean>

     <!-- Loads more controllers -->

     <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
          <property name="maxUploadSize" value="2097152" />
     </bean>

     <bean id="messageSource"
          class="org.springframework.context.support.ResourceBundleMessageSource">
          <property name="basename" value="ApplicationResources" />
          <property name="useCodeAsDefaultMessage" value="true" />
     </bean>

     <bean id="urlMapping"
          class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
          <property name="mappings">
               <value>
                    <!— Some URLs —>
               </value>
          </property>
          <property name="order" value="0" />
     </bean>

     <bean
          class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
          <property name="order" value="1" />
     </bean>

     <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
          <property name="order" value="2" />
     </bean>

     <!-- View Resolver for JSPs -->
     <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="requestContextAttribute" value="rc" />
          <property name="viewClass"
               value="org.springframework.web.servlet.view.JstlView" />
          <property name="prefix" value="/WEB-INF/pages/" />
          <property name="suffix" value=".jsp" />
     </bean>
</beans>
</code>```

All though the classpath scanner (ClassPathScanningCandidateComponentProvider) picks up the HelloController I get a 404 when I try and navigate to localhost:8080/hello

Can anyone see what else I need to do? Here is my web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <display-name>Engineer Manager</display-name>

    <!-- Define the default CSS Theme -->
    <context-param>
        <param-name>csstheme</param-name>
        <param-value>engineermanager</param-value>
    </context-param>

    <!-- Define the basename for a resource bundle for I18N -->
    <context-param>
        <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
        <param-value>ApplicationResources</param-value>
    </context-param>

    <!-- Fallback locale if no bundles found for browser's preferred locale -->
    <!-- Force a single locale using param-name 'javax.servlet.jsp.jstl.fmt.locale' -->
    <context-param>
        <param-name>javax.servlet.jsp.jstl.fmt.fallbackLocale</param-name>
        <param-value>en</param-value>
    </context-param>

    <!-- Context Configuration locations for Spring XML files -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:/applicationContext-resources.xml
            classpath:/applicationContext-dao.xml
            classpath:/applicationContext-service.xml
            classpath*:/applicationContext.xml
            /WEB-INF/applicationContext*.xml
            /WEB-INF/security.xml
        </param-value>
    </context-param>

    <filter>
        <filter-name>localeFilter</filter-name>
        <filter-class>org.appfuse.webapp.filter.LocaleFilter</filter-class>
    </filter>
    <filter>
        <filter-name>securityFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetBeanName</param-name>
            <param-value>springSecurityFilterChain</param-value>
        </init-param>
    </filter>
    <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
    </filter>
    <filter>
        <filter-name>staticFilter</filter-name>
        <filter-class>org.appfuse.webapp.filter.StaticFilter</filter-class>
        <init-param>
            <param-name>servletName</param-name>
            <param-value>dispatcher</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>securityFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>localeFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>*.html</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>*.jsp</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    <filter-mapping>
        <filter-name>staticFilter</filter-name>
        <url-pattern>*.html</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.appfuse.webapp.listener.StartupListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.appfuse.webapp.listener.UserCounterListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.json</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>3600</session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <error-page>
        <error-code>500</error-code>
        <location>/error.jsp</location>
    </error-page>
    <error-page>
        <error-code>400</error-code>
        <location>/index.jsp</location>
    </error-page>
    <error-page>
        <error-code>403</error-code>
        <location>/403.jsp</location>
    </error-page>
    <error-page>
        <error-code>404</error-code>
        <location>/404.jsp</location>
    </error-page>
</web-app>
</code>```

答:
Since you have mentioned that this is a legacy application, I believe it is working with the existing configuration.

Also, since your are trying to migrate using annotation for new Controllers, it is to do with annotation processing.

You will need to add the annotation mentioned below along with the mvc namespace configuraton in the root beans tag of your spring context xml file.

<mvc:annotation-driven/>

A partial code snippet for the configuration is as below

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd"
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:component-scan base-package="uk.co.onevisionconsulting.engineermanager" />
    <mvc:annotation-driven/>

    ...

</beans>
</code>```

A detailed explanation for the reason can be found at Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

Body:
I have a legacy Spring application whether the context is configured entirely with XML. I would like to add a new controller to the application using the @Controller annotation so I begin to migrate to using annotations.

As a test I have added the following controller to the application

package uk.co.onevisionconsulting.engineermanager.webapp.controller2;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

     @RequestMapping("/hello")
     public String hello(){
          return "Hello";
     }
}

I have also added the context:component-scan tag to my spring context

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans” xmlns:context="http://www.springframework.org/schema/context"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance”
             xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
             http://www.springframework.org/schema/context
             http://www.springframework.org/schema/context/spring-context-2.5.xsd">

     <context:component-scan base-package="uk.co.onevisionconsulting.engineermanager" />

     <bean name="jsonView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.JsonView" />

     <bean name="csvView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.CsvView" />

     <bean name="ajaxView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.AjaxView" />

     <bean name="dataTablesView"
          class="uk.co.onevisionconsulting.engineermanager.webapp.view.DataTablesView" />

     <bean id="exceptionResolver"
          class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
          <property name="exceptionMappings">
               <props>
                    <prop key="org.springframework.dao.DataAccessException">
                         dataAccessFailure
                    </prop>
               </props>
          </property>
     </bean>

     <bean id=“someController"
          class="uk.co.onevisionconsulting.engineermanager.webapp.controller.SomeController" >
          <property name=“someManager" ref=“someManager" />
     </bean>

     <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
          <property name="maxUploadSize" value="2097152" />
     </bean>

     <bean id="messageSource"
          class="org.springframework.context.support.ResourceBundleMessageSource">
          <property name="basename" value="ApplicationResources" />
          <property name="useCodeAsDefaultMessage" value="true" />
     </bean>

     <bean id="urlMapping"
          class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
          <property name="mappings">
               <value>
                    <!— Some URLs —>
               </value>
          </property>
          <property name="order" value="0" />
     </bean>

     <bean
          class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
          <property name="order" value="1" />
     </bean>

     <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
          <property name="order" value="2" />
     </bean>

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

All though the classpath scanner (ClassPathScanningCandidateComponentProvider) picks up the HelloController I get a 404 when I try and navigate to localhost:8080/hello

Can anyone see what else I need to do? Here is my web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <display-name>Engineer Manager</display-name>

    <context-param>
        <param-name>csstheme</param-name>
        <param-value>engineermanager</param-value>
    </context-param>

    <context-param>
        <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
        <param-value>ApplicationResources</param-value>
    </context-param>

    <context-param>
        <param-name>javax.servlet.jsp.jstl.fmt.fallbackLocale</param-name>
        <param-value>en</param-value>
    </context-param>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:/applicationContext-resources.xml
            classpath:/applicationContext-dao.xml
            classpath:/applicationContext-service.xml
            classpath*:/applicationContext.xml
            /WEB-INF/applicationContext*.xml
            /WEB-INF/security.xml
        </param-value>
    </context-param>

    <filter>
        <filter-name>localeFilter</filter-name>
        <filter-class>org.appfuse.webapp.filter.LocaleFilter</filter-class>
    </filter>
    <filter>
        <filter-name>securityFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetBeanName</param-name>
            <param-value>springSecurityFilterChain</param-value>
        </init-param>
    </filter>
    <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
    </filter>
    <filter>
        <filter-name>staticFilter</filter-name>
        <filter-class>org.appfuse.webapp.filter.StaticFilter</filter-class>
        <init-param>
            <param-name>servletName</param-name>
            <param-value>dispatcher</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>securityFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>localeFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>*.html</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>*.jsp</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    <filter-mapping>
        <filter-name>staticFilter</filter-name>
        <url-pattern>*.html</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.appfuse.webapp.listener.StartupListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.appfuse.webapp.listener.UserCounterListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.json</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>3600</session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <error-page>
        <error-code>500</error-code>
        <location>/error.jsp</location>
    </error-page>
    <error-page>
        <error-code>400</error-code>
        <location>/index.jsp</location>
    </error-page>
    <error-page>
        <error-code>403</error-code>
        <location>/403.jsp</location>
    </error-page>
    <error-page>
        <error-code>404</error-code>
        <location>/404.jsp</location>
    </error-page>
</web-app>

Body:
Since you have mentioned that this is a legacy application, I believe it is working with the existing configuration.

Also, since your are trying to migrate using annotation for new Controllers, it is to do with annotation processing.

You will need to add the annotation mentioned below along with the mvc namespace configuraton in the root beans tag of your spring context xml file.

<mvc:annotation-driven/>

A partial code snippet for the configuration is as below

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd"
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:component-scan base-package="uk.co.onevisionconsulting.engineermanager" />
    <mvc:annotation-driven/>

    ...

</beans>

A detailed explanation for the reason can be found at Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?


问:
Selecting random records for use on a web page
HI Guys,

I own a website I have a section called "mobile Section" this section contain many catagories (Nameoftheobject + a picture + little description and a download link)
Now the section is considered as an internal section. I want to view random records from that section on the first page (I dont know Like RSS but not Rss) showing
the name of the object and to which subcategories it belong and its picture if possible.
I hope any one understand what I'm trying to say.

This is my website HERE and this the link of the internal page HERE check the block that say Mobile Section Its kinda a mess.
is there any script or a tech to view it in a proper way to view it show me examples if possible

I'm using php and MySQL

Thanx in advance

答:
Do you really want it to be random? Its nice to have most popular on home pages and might turn out to be more useful and informative for your visitors.

That said, it would be really easy to write a method in Microsoft SQL to do so:

```<code>SELECT TOP 1 Name, Picture, Description, Link
FROM Software
WHERE Category = 'Mobile Section'
ORDER BY NEWID()
</code>```

In case you are not using Microsoft SQL, here is a site with random selectors for many databases.

OwnerDisplayName: shicosvnki

LastEditorDisplayName: Tom Anderson

Body:
Do you really want it to be random? Its nice to have most popular on home pages and might turn out to be more useful and informative for your visitors.

That said, it would be really easy to write a method in Microsoft SQL to do so:

SELECT TOP 1 Name, Picture, Description, Link
FROM Software
WHERE Category = 'Mobile Section'
ORDER BY NEWID()

In case you are not using Microsoft SQL, here is a site with random selectors for many databases.

OwnerDisplayName: David Thomas Garcia


问:
Getting an ArrayList of ArrayLists from another ArrayList in Java
I have an ArrayList of MyClass and I need to extract multiple lists from it according to the repetition of a property of the class.

MyClass:

```<code>public class MyClass{
    private int ID;
    private String Name;
    private String Position;

    public MyClass(int ID, String name, String position){
        this.ID = ID;
        Name = name;
        Position = position;
    }
}
</code>```

Example:

In my ArrayList I have 5 objects:

```<code>ID = 0, Name = "Name 0", Position = "G1.1";
ID = 1, Name = "Name 1", Position = "G2.1";
ID = 2, Name = "Name 2", Position = "G1.1";
ID = 3, Name = "Name 3", Position = "G1.1";
ID = 4, Name = "Name 4", Position = "G2.1";
</code>```

From this list I'll create 2 ArrayLists:

```<code>ArrayList 1 (Where Position = "G1.1")
    ID = 0, Name = "Name 0", Position = "G1.1";
    ID = 2, Name = "Name 2", Position = "G1.1";
    ID = 3, Name = "Name 3", Position = "G1.1";
ArrayList 2 (Where Position = "G2.1")
    ID = 1, Name = "Name 1", Position = "G2.1";
    ID = 4, Name = "Name 4", Position = "G2.1";
</code>```

The main list is created dynamically, so I don't know what will be the positions I will need to create to get the items.

答:
You could collect the items together into a Map like this:</p>

```<code>Map<String, List<MyClass>> grp = l.stream().collect(Collectors.groupingBy(o -> o.Position));
</code>```

Body:
I have an ArrayList of MyClass and I need to extract multiple lists from it according to the repetition of a property of the class.

MyClass:

public class MyClass{
    private int ID;
    private String Name;
    private String Position;

    public MyClass(int ID, String name, String position){
        this.ID = ID;
        Name = name;
        Position = position;
    }
}

Example:

In my ArrayList I have 5 objects:

ID = 0, Name = "Name 0", Position = "G1.1";
ID = 1, Name = "Name 1", Position = "G2.1";
ID = 2, Name = "Name 2", Position = "G1.1";
ID = 3, Name = "Name 3", Position = "G1.1";
ID = 4, Name = "Name 4", Position = "G2.1";

From this list I'll create 2 ArrayLists:

ArrayList 1 (Where Position = "G1.1")
    ID = 0, Name = "Name 0", Position = "G1.1";
    ID = 2, Name = "Name 2", Position = "G1.1";
    ID = 3, Name = "Name 3", Position = "G1.1";
ArrayList 2 (Where Position = "G2.1")
    ID = 1, Name = "Name 1", Position = "G2.1";
    ID = 4, Name = "Name 4", Position = "G2.1";

The main list is created dynamically, so I don't know what will be the positions I will need to create to get the items.

Body:
You could collect the items together into a Map like this:

Map<String, List<MyClass>> grp = l.stream().collect(Collectors.groupingBy(o -> o.Position));


问:
PL SQL Patterns Matching
How to only interpret a particular word(e.g test) from a big string if it’s really “start of line + optional white space + test + space”.Also allow mixed case for the word ‘test’</p>

答:
I am using your input string as below

```<code>'    TeSt this is how I am going to tEst going for '
</code>```

and intentionally keeping some white spaces in the beginning and end. Below code produces your desired output. Also as you mention, it will replace ALL instances of the word TEST without considering case.
I hope this helps.

```<code>  Select
REGEXP_REPLACE(     --Using RegExp_replace
    ltrim(rtrim(    --Trimming the white spaces
        input1)),   --using the input
        'TEST',     --search criteria
        '',         --Replace with string
        2,          --Starting with which character (you mentioned first occerance should remain
        0,          --Replace all subsequent occurances
        'i')        --case in-sensitive
        from (
Select '    TeSt this is how I am going to tEst going for' as input1 from dual --this is your INPUT)
</code>```

Thanks,
Santosh

Title: PL SQL Patterns Matching

Body:
I am using your input string as below

'    TeSt this is how I am going to tEst going for '

and intentionally keeping some white spaces in the beginning and end. Below code produces your desired output. Also as you mention, it will replace ALL instances of the word TEST without considering case.
I hope this helps.

  Select
REGEXP_REPLACE(     --Using RegExp_replace
    ltrim(rtrim(    --Trimming the white spaces
        input1)),   --using the input
        'TEST',     --search criteria
        '',         --Replace with string
        2,          --Starting with which character (you mentioned first occerance should remain
        0,          --Replace all subsequent occurances
        'i')        --case in-sensitive
        from (
Select '    TeSt this is how I am going to tEst going for' as input1 from dual --this is your INPUT)

Thanks,
Santosh


问:
Excel Substitute a substring in cell (sheet A) by the corresponding string in "lookup" (sheet B)

How to do this in MS Excel 15.4

I want to process Column A to become Column B

```<code>Column A                  | Column B
----------------------------------------------------------------------
one, 1, two, 2, three, 3  | one apple, two bananas, three strawberries
one, 1, four, 4           | one apple, four oranges
.......................
... many other rows ...
.......................
two, 2, four, 4, three, 3 | two bananas, four oranges, three strawberries
</code>```

The Column A can have n matching substrings in the lookup sheet.

I have another sheet (lookup table) with what to substitute the text in Column A with

```<code>Match col | Replace col
----------------------------
one, 1    | one apple
two, 2    | two bananas
three, 3  | three strawberries
four, 4   | four oranges
... and many more ...
</code>```

I want to replace all the substrings found in Column A with the Replace col value of the lookup table

It looks like I may be able to combine VLOOKUP with SUBSTITUTE, but I am struggling with it

答:
I have a rather clunky solution, but it'll work for you if you don't mind taking perhaps a few extra steps. (No VBA required).

With your original data, highlight all of it and do Text to Columns with a comma delimiter. Set the destination to wherever you like. I chose the column just right of it (so, B2):

So now you have it all split up.

I put the VLOOKUP() table in "Sheet2":

And back on Sheet1, in I2, I used this formula:

=IFERROR(VLOOKUP(TRIM(B2)&", "&TRIM(C2),Sheet2!$A$1:$B$4,2,FALSE),"")

And drag right.  You'll have some empty columns which you can hide/Delete, then copy all the data.

Body:
How to do this in MS Excel 15.4

I want to process Column A to become Column B

Column A                  | Column B
----------------------------------------------------------------------
one, 1, two, 2, three, 3  | one apple, two bananas, three strawberries
one, 1, four, 4           | one apple, four oranges
.......................
... many other rows ...
.......................
two, 2, four, 4, three, 3 | two bananas, four oranges, three strawberries

The Column A can have n matching substrings in the lookup sheet.

I have another sheet (lookup table) with what to substitute the text in Column A with

Match col | Replace col
----------------------------
one, 1    | one apple
two, 2    | two bananas
three, 3  | three strawberries
four, 4   | four oranges
... and many more ...

I want to replace all the substrings found in Column A with the Replace col value of the lookup table

It looks like I may be able to combine VLOOKUP with SUBSTITUTE, but I am struggling with it


问:
How do I send an HTML email?
I have successfully sent email in my web application using JMS, but the result only displays in plain text. I want the content to be able to display html. How do I do it? Here is roughly what I have:</p>
```<code>Message msg = new MimeMessage(mailSession);
try{
    msg.setSubject("Test Notification");
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(sentTo, false));
    String message = "<div style=\"color:red;\">BRIDGEYE</div>";
    msg.setText(message);
    msg.setSentDate(new Date());
    Transport.send(msg);
}catch(MessagingException me){
    logger.log(Level.SEVERE, "sendEmailNotification: {0}", me.getMessage());
}
</code>```

答:
Since JavaMail version 1.4, there is an overload of setText method that accepts the subtype.

```<code>// Passing null for second argument in order for the method to determine
// the actual charset on-the fly.
// If you know the charset, pass it. "utf-8" should be fine
msg.setText( message, null, "html" );
</code>```

Title: How do I send an HTML email?

Body:
I have successfully sent email in my web application using JMS, but the result only displays in plain text. I want the content to be able to display html. How do I do it? Here is roughly what I have:

Message msg = new MimeMessage(mailSession);
try{
    msg.setSubject("Test Notification");
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(sentTo, false));
    String message = "
BRIDGEYE
";
    msg.setText(message);
    msg.setSentDate(new Date());
    Transport.send(msg);
}catch(MessagingException me){
    logger.log(Level.SEVERE, "sendEmailNotification: {0}", me.getMessage());
}

Body:
Since JavaMail version 1.4, there is an overload of setText method that accepts the subtype.

// Passing null for second argument in order for the method to determine
// the actual charset on-the fly.
// If you know the charset, pass it. "utf-8" should be fine
msg.setText( message, null, "html" );


问:
Make an html number input always display 2 decimal places
I'm making a form where the user can enter a dollar amount using an html number input tag.  Is there a way to have the input box always display 2 decimal places?</p>

答:
What other folks posted here mainly worked, but using onchange doesn't work when I change the number using arrows in the same direction more than once. What did work was oninput. My code (mainly borrowing from MC9000):

HTML

```<code><input class="form-control" oninput="setTwoNumberDecimal(this)" step="0.01" value="0.00" type="number" name="item[amount]" id="item_amount">
</code>```

JS

```<code>function setTwoNumberDecimal(el) {
        el.value = parseFloat(el.value).toFixed(2);
    };
</code>```

Body:
What other folks posted here mainly worked, but using onchange doesn't work when I change the number using arrows in the same direction more than once. What did work was oninput. My code (mainly borrowing from MC9000):

HTML

<input class="form-control" oninput="setTwoNumberDecimal(this)" step="0.01" value="0.00" type="number" name="item[amount]" id="item_amount">

JS

function setTwoNumberDecimal(el) {
        el.value = parseFloat(el.value).toFixed(2);
    };


问:
Trigger doesn't work - why?
I don't know why this doesn't work and throws a 1064 error</p>

```<code>delimiter $$
CREATE or remplace TRIGGER verifyExist BEFORE INSERT ON entreprise
    For each row
    BEGIN
        IF new.numeroSiret in (
            select numeroSiret
            From entreprise
            where numeroSiret = new.numeroSiret
        ) THEN

UPDATE entreprise
SET nomEntreprise = new.nomEntreprise, adresse= new.adresse, ville = new.ville, commentaire = new.commentaire, entrepriseCreer = new.entrepriseCreer
WHERE idEntreprise = New.idEntreprise  ;

        END IF;
    END;$$
DELIMITER ;
</code>```

答:
```
delimiter $$
CREATE TRIGGER verifyExist BEFORE INSERT ON entreprise
    For each row
    BEGIN
        IF new.numeroSiret in (
            select numeroSiret
            From entreprise
            where numeroSiret = new.numeroSiret
        ) THEN

UPDATE entreprise
SET nomEntreprise = new.nomEntreprise, adresse= new.adresse, ville = new.ville, commentaire = new.commentaire, entrepriseCreer = new.entrepriseCreer
WHERE idEntreprise = New.idEntreprise  ;

        END IF;
    END;$$
DELIMITER ;
```

Title: Trigger doesn't work - why?

Body:
I don't know why this doesn't work and throws a 1064 error

delimiter $$
CREATE or remplace TRIGGER verifyExist BEFORE INSERT ON entreprise
    For each row
    BEGIN
        IF new.numeroSiret in (
            select numeroSiret
            From entreprise
            where numeroSiret = new.numeroSiret
        ) THEN

UPDATE entreprise
SET nomEntreprise = new.nomEntreprise, adresse= new.adresse, ville = new.ville, commentaire = new.commentaire, entrepriseCreer = new.entrepriseCreer
WHERE idEntreprise = New.idEntreprise  ;

        END IF;
    END;$$
DELIMITER ;


问:
Using prefix `o` in ui5 javascript
I have seen people are using  prefix o a lot when developing ui5 application.

```<code>var oRowsModel = new sap.ui.model.json.JSONModel();
    oValueHelpDialog.getTable().setModel(oRowsModel);
   if (oValueHelpDialog.getTable().bindRows){
    oValueHelpDialog.getTable().bindRows("/");
}

this.getView().setModel(oModel);

var oSelectedItem = oEvent.getParameter("selectedItem"),
            oTimeline = this.getView().byId("ActivityTimeline"),
            oTimelineBinding = oTimeline.getBinding("content");
</code>```

Does it help somehow ?
Is it a best practice ? What is the advantage?

I think that a lot of things are objects and specifying o does not help much.
Why then to use it?

答: The prefixing of variables is just a naming convention carried over from the native SAP programming language called ABAP. In ABAP it is a long standing convention to prefix variables so that one can tell the type of the variable and if the variable is local or global, for instance lv_myvar for a local variable, and gt_mytab for a table type that is global. There is really no particular reason to continue with this practice in Javascript and UI5 - if you don´t like, don´t do it.  </p>

Title: Using prefix `o` in ui5 javascript

Body:
I have seen people are using  prefix o a lot when developing ui5 application.

var oRowsModel = new sap.ui.model.json.JSONModel();
    oValueHelpDialog.getTable().setModel(oRowsModel);
   if (oValueHelpDialog.getTable().bindRows){
    oValueHelpDialog.getTable().bindRows("/");
}

this.getView().setModel(oModel);

var oSelectedItem = oEvent.getParameter("selectedItem"),
            oTimeline = this.getView().byId("ActivityTimeline"),
            oTimelineBinding = oTimeline.getBinding("content");

Does it help somehow ?
Is it a best practice ? What is the advantage?

I think that a lot of things are objects and specifying o does not help much.
Why then to use it?


问:
Running nose with a large number of test-data files
I want to write some tests for a web scraper. I want to use a lot of test web pages, but I'm not sure exactly how to get nose (or another unit testing framework) to do what I need without a huge amount of duplicate code.

My problem is that I want to test a lot of different pages and I'm not sure how to do this using nose. This is roughly what I want to do:

```<code>class TestPage(object):
    def setup(self):
        with open('test_data/page.html', 'r') as f:
            html = f.read()
        self.scraper = Scraper(html)
</code>```

This would be fine if the only page I wanted to test were 'page.html'. But I have hundreds of pages to test. I could duplicate the class and each time change both the class's name and the filename of the path, but this would obviously be ridiculous.

I thought of putting code in setup to create separate Scraper objects for each page and store them in a list in the test object. I could then have the test methods operate on each Scraper object. But I think I'd run into problems with keeping each test isolated and getting separate messages from nose.

I also tried to subclass a base test class and pass the path to init, but this creates problems for nose.

I'd appreciate any advice on how to solve this using nose, another approach to take, or any reading that might be useful.

答:
based on your code sample, you just need a class factory:

```<code>def make_test(page)
    class TestPage(object):
        def setup(self):
            with open(page, 'r') as f:
                html = f.read()
            self.scraper = Scraper(html)
     return TestPage
</code>```

Now you can just run over a list of pages and make one test for each one:

```<code>for page in list_of_pages:
    Test = make_test(page)
    Test().run()
</code>```

I'm not sure if that's how you run a nose test but It would be a full fledged class so you could do whatever you would normally do with it.

You could store all of your tests pages in one directory so that you could just loop over the files in the directory and get your list of pages that way. All you would have to do to create a new test is save the html in the given directory. Is that about what you were looking for?

Body:
I want to write some tests for a web scraper. I want to use a lot of test web pages, but I'm not sure exactly how to get nose (or another unit testing framework) to do what I need without a huge amount of duplicate code.

My problem is that I want to test a lot of different pages and I'm not sure how to do this using nose. This is roughly what I want to do:

class TestPage(object):
    def setup(self):
        with open('test_data/page.html', 'r') as f:
            html = f.read()
        self.scraper = Scraper(html)

This would be fine if the only page I wanted to test were 'page.html'. But I have hundreds of pages to test. I could duplicate the class and each time change both the class's name and the filename of the path, but this would obviously be ridiculous.

I thought of putting code in setup to create separate Scraper objects for each page and store them in a list in the test object. I could then have the test methods operate on each Scraper object. But I think I'd run into problems with keeping each test isolated and getting separate messages from nose.

I also tried to subclass a base test class and pass the path to init, but this creates problems for nose.

I'd appreciate any advice on how to solve this using nose, another approach to take, or any reading that might be useful.

Body:
based on your code sample, you just need a class factory:

def make_test(page)
    class TestPage(object):
        def setup(self):
            with open(page, 'r') as f:
                html = f.read()
            self.scraper = Scraper(html)
     return TestPage

Now you can just run over a list of pages and make one test for each one:

for page in list_of_pages:
    Test = make_test(page)
    Test().run()

I'm not sure if that's how you run a nose test but It would be a full fledged class so you could do whatever you would normally do with it.

You could store all of your tests pages in one directory so that you could just loop over the files in the directory and get your list of pages that way. All you would have to do to create a new test is save the html in the given directory. Is that about what you were looking for?


问:
Ruby Time object for midnight UTC
I need to be able to create UTC Time objects in Rails, but no matter what I try it ends up being a local Time object converted to UTC.

application.rb

```<code>config.time_zone = "UTC"
</code>```

Examples

I try to create a Time object for midnight on New Years 2017:

```<code>Time.new(year, month, 1, 0, 0, 0)
</code>```

=> 2017-03-01 00:00:00 -0500

```<code>Time.new(year, month, 1, 0, 0, 0).in_time_zone
</code>```

=> Wed, 01 Mar 2017 05:00:00 UTC +00:00

```<code>Time.new(year, month, 1, 0, 0, 0).in_time_zone('UTC')
</code>```

=> Wed, 01 Mar 2017 05:00:00 UTC +00:00

答:
I think the following might do what you want:

```<code>Time.new(year, month, 1, 0, 0, 0, "+00:00")
</code>```

See the documentation for more details.

Title: Ruby Time object for midnight UTC

Body:
I need to be able to create UTC Time objects in Rails, but no matter what I try it ends up being a local Time object converted to UTC.

application.rb

config.time_zone = "UTC"

Examples

I try to create a Time object for midnight on New Years 2017:

Time.new(year, month, 1, 0, 0, 0)

=> 2017-03-01 00:00:00 -0500

Time.new(year, month, 1, 0, 0, 0).in_time_zone

=> Wed, 01 Mar 2017 05:00:00 UTC +00:00

Time.new(year, month, 1, 0, 0, 0).in_time_zone('UTC')

=> Wed, 01 Mar 2017 05:00:00 UTC +00:00

Body:
I think the following might do what you want:

Time.new(year, month, 1, 0, 0, 0, "+00:00")

See the documentation for more details.


问:
Vertical align photos on the same row
Is there any way to vertical align the photos in this case with CSS?
I tried add vertical-align, but it doesn't work with div.

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

<style type="text/css">
.imageWrapper {
    margin: 1em;
    float: left;
/* vertical-align: middle; */
}

.imageTitle {
    text-align: center;
}

.row {
    float: left;
}

#albumList {
    width: 600px;
}
</style>

</head>
<body>
<div id="albumList">

    <div class="row">
        <div id="w1" class="imageWrapper">
            <img src="1.jpg" width="150px"/>
            <div class="imageTitle">Title1</div>
        </div>

        <div id="w2" class="imageWrapper">
            <img src="2.jpg" width="150px"//>
            <div class="imageTitle">Title1</div>
        </div>

        <div id="w3" class="imageWrapper">
            <img src="3.jpg" width="150px"//>
            <div class="imageTitle">Title3</div>
        </div>
    </div>

    <div class="row">
        <div id="w4" class="imageWrapper">
            <img src="4.jpg" width="150px"/>
            <div class="imageTitle">Title1</div>
        </div>

        <div id="w5" class="imageWrapper">
            <img src="5.jpg" width="150px"//>
            <div class="imageTitle">Title1</div>
        </div>
    </div>

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

[THIS IS WHAT I TRIED]
I can do it with JQuery but some photos added on the fly and some added on error handler (image_not_available.jpg), so this approach too hard to apply.

```<code>var maxHeight = 0;
var maxID = 'nothing';
$('.imageWrapper').each(function(i){
    var height = $(this).height();
    if(height > maxHeight) {
        maxHeight = height
        maxID = $(this).attr('id');
    }
});

$('.imageWrapper').each(function(i){
    var id = $(this).attr('id');
    if(id != maxID) {
        var minus = maxHeight - $(this).height();
        $(this).css('margin-top', minus / 2);
    }
});
</code>```

答:
The best answer I've found was

```<code>#footer-widgets .widget {
    display: inline-block;
    float: none;
    vertical-align: middle;
}
</code>```

Source

Title: Vertical align photos on the same row

Body:
Is there any way to vertical align the photos in this case with CSS?
I tried add vertical-align, but it doesn't work with div.

Title1

Title1

Title3

Title1

Title1

[THIS IS WHAT I TRIED]
I can do it with JQuery but some photos added on the fly and some added on error handler (image_not_available.jpg), so this approach too hard to apply.

var maxHeight = 0;
var maxID = 'nothing';
$('.imageWrapper').each(function(i){
    var height = $(this).height();
    if(height > maxHeight) {
        maxHeight = height
        maxID = $(this).attr('id');
    }
});

$('.imageWrapper').each(function(i){
    var id = $(this).attr('id');
    if(id != maxID) {
        var minus = maxHeight - $(this).height();
        $(this).css('margin-top', minus / 2);
    }
});

Body:
The best answer I've found was

#footer-widgets .widget {
    display: inline-block;
    float: none;
    vertical-align: middle;
}

Source


问:
Generating nested Numpy Arrays
I'm trying to write a function that will take as input a numpy array in the form:

```<code>a = [[0,0], [10,0], [10,10], [5,4]]
</code>```

and return a numpy array b such that:

```<code>b = [[[0,0]], [[10,0]], [[10,10]], [[5,4]]]
</code>```

For some reason I'm finding this surprisingly difficult.

The reason I'm doing this is that I have some contours generated using skimage that I'm attempting to use opencv2 on to calculate features ( area, perimeter etc...) but the opencv functions will only take arrays in the form of b as input, rather than a.

Title: Generating nested Numpy Arrays

Body:
I'm trying to write a function that will take as input a numpy array in the form:

a = [[0,0], [10,0], [10,10], [5,4]]

and return a numpy array b such that:

b = [[[0,0]], [[10,0]], [[10,10]], [[5,4]]]

For some reason I'm finding this surprisingly difficult.

The reason I'm doing this is that I have some contours generated using skimage that I'm attempting to use opencv2 on to calculate features ( area, perimeter etc...) but the opencv functions will only take arrays in the form of b as input, rather than a.

Body:
a is shape (4,2), b is (4,1,2)

a.reshape(4,1,2)
np.expanddims(a, 1)
a[:,None]

all work

In [503]: B
Out[503]:
array([[[ 0,  0]],

       [[10,  0]],

       [[10, 10]],

       [[ 5,  4]]])
In [504]: B.tolist()
Out[504]: [[[0, 0]], [[10, 0]], [[10, 10]], [[5, 4]]]


问:
Flash ComboBox Component customisation
Is there anyway to change the colour of items showing in the dropdown list?  By default, it's showing skyblue and I need to change it into grey? I'm using Flash CS4 IDE and AS3.  any thoughts?</p>

答:
There are two parts to the combo box component: the combo box skin and the actual >item cells.

The combo box can be edited by placing an instance of the component on the stage in the CS4 IDE, and then double clicking it to edit the individual button states (check the downSkin).

Once you have an instance on the stage, look in the Library. You will now have a few folders and files from the component. The skinning of the cell can be found in 'Component Assets' and then in the 'CellRendererSkins' folder. You can edit these in the same way.

To alter the blue colour you will need to change:

CellRenderer_selectedUpSkin

CellRenderer_selectedDownSkin

CellRenderer_overSkin

CellRenderer_downSkin

An alternative would be to look at creating a CSSStyleDeclaration and then apply that using AS3. This is useful if you want all your components to look the same.

Title: Flash ComboBox Component customisation


问:
Serializing Object to Json
I am attempting to use Gson to to take some Java Object and serialize that to json and get a byte array that represents that Json. I need a byte array because I am passing on the output to an external dependency that requires it to be a byte array.

```<code>public byte[] serialize(Object object){
  return gson.toJson(object).getBytes();
}
</code>```

I have 2 questions:

If the input is a String gson seems to return the String as is. It doesn't do any validation of the input. Is this expected? I'd like to use Gson in a way that it would validate that the input object is actually Json. How could I do this?

I'm gonna be invoking this serialize function several thousands of times over a short period. Converting to String and then to byte[] could be some unwanted overhead. Is there a more optimal way to get the byte[]?

答:
edit: my answer on point 1 was misinformed.

2) There will be a lot of unnecessary overhead in reflection if you just use the vanilla gson converter. It would very much be a performance benefit in your case to write a custom adapter. here is one article with more info on that
https://open.blogs.nytimes.com/2016/02/11/improving-startup-time-in-the-nytimes-android-app/?_r=0

Title: Serializing Object to Json

Body:
I am attempting to use Gson to to take some Java Object and serialize that to json and get a byte array that represents that Json. I need a byte array because I am passing on the output to an external dependency that requires it to be a byte array.

public byte[] serialize(Object object){
  return gson.toJson(object).getBytes();
}

I have 2 questions:

If the input is a String gson seems to return the String as is. It doesn't do any validation of the input. Is this expected? I'd like to use Gson in a way that it would validate that the input object is actually Json. How could I do this?

I'm gonna be invoking this serialize function several thousands of times over a short period. Converting to String and then to byte[] could be some unwanted overhead. Is there a more optimal way to get the byte[]?


问:
Natural sorting in SQL does not work
I am trying to sort a row "naturally" in SQL, and I found this answer which supposedly does exactly what I need:

https://stackoverflow.com/a/17354420/7563153

But when I tried recreating it in "SQL Fiddle" I couldn't get it to work...

Here's my attempt

What am I doing wrong?

答:
For your given database schema, is your attempt even necessary?

Try something like this,

```<code>SELECT `test`
FROM table1
ORDER BY LENGTH(`test`),
         `test`;
</code>```

Title: Natural sorting in SQL does not work

Body:
For your given database schema, is your attempt even necessary?

Try something like this,

SELECT `test`
FROM table1
ORDER BY LENGTH(`test`),
         `test`;


问:
NHibernate Session.Query<T>().FetchMany
In the following class I want to eager load child collection OrderDetailList using session.Query().FetchMany.

Entity:

```<code> public class Order
 {
    public Order()
    {
        OrderDetailList = new HashSet<OrderDetails>();
    }

    public virtual int Id { get; protected internal set; }
    public virtual string Description { get; set; }

    public virtual ISet<OrderDetails> OrderDetailList { get;set; }
 }
</code>```

Data Repository:

```<code> public IList<T> All()
 {
        IList<T> result;
        using (var _session = _factory.OpenSession())
        {
            result = _session.Query<T>().ToList();
        }
        return result;
}
</code>```

Using the above All method, the child collection returned is proxy object only which result into error as session is closed.
So I want to make the method as:

```<code>public IList<T> All()
{
        IList<T> result;
        using (var _session = _factory.OpenSession())
        {
            //result = _session.Query<Order>().FetchMany(x=>x.OrderDetailList).ToList();

            //Required Statement: Above statement must be like
            result = _session.Query<T>().FetchMany(x=>x.[Some children property Generic type List in type T]).ToList();

        }
        return result;
}
</code>```

But in this case my method is of generic type hence the property I require to add in FetchMany need to be read from the type T.

How can I achieve this or likewise ?

答:
Your going to need to transmit your fetch as an argument.

```<code>public IList<T> All<TFetched>(Expression<Func<T, IEnumerable<TFetched>>> fetchmany)
{
        IList<T> result;
        using (var _session = _factory.OpenSession())
        {
            //result = _session.Query<Order>().FetchMany(x=>x.OrderDetailList).ToList();

            var query = _session.Query<T>();
            if (fetchMany != null)
            {
                query = query.FetchMany(fetchmany);
            }
            result = query.ToList();
        }
        return result;
}
</code>```

Then you could call:

```<code>orderRepository.All(x=>x.OrderDetailList);
</code>```

This should solve your immediate trouble.

Notes:

But please bear in mind that what seems to be your current design is debatable. The session should be short lived, but not to that point. The session should span a unit of work, usually including many data access or writes. By example it may span up to the whole processing of an user triggered event in a desktop application, or the processing of an http request in a web application.

This would then probably enable you to use lazy-loading instead of eager fetching, provided you enable batch loading of lazy loads for avoiding N+1 loads, and of course provided the entities are no more used after session closing. (This can be achieved by fetching the required data into view-models before closing the session, by example.)

Moreover, you should use explicit transaction. Not doing it creates implicit transactions for each request, which is not good for performances. (But well, with what seems to be your current design, explicit transactions would not change anything currently.) Not using explicit transaction may disable some NHibernate functionalities such as second level cache.

Title: NHibernate Session.Query<T>().FetchMany

Body:
In the following class I want to eager load child collection OrderDetailList using session.Query().FetchMany.

Entity:

 public class Order
 {
    public Order()
    {
        OrderDetailList = new HashSet<OrderDetails>();
    }

    public virtual int Id { get; protected internal set; }
    public virtual string Description { get; set; }

    public virtual ISet<OrderDetails> OrderDetailList { get;set; }
 }

Data Repository:

 public IList<T> All()
 {
        IList<T> result;
        using (var _session = _factory.OpenSession())
        {
            result = _session.Query<T>().ToList();
        }
        return result;
}

Using the above All method, the child collection returned is proxy object only which result into error as session is closed.
So I want to make the method as:

public IList<T> All()
{
        IList<T> result;
        using (var _session = _factory.OpenSession())
        {
            //result = _session.Query<Order>().FetchMany(x=>x.OrderDetailList).ToList();

            //Required Statement: Above statement must be like
            result = _session.Query<T>().FetchMany(x=>x.[Some children property Generic type List in type T]).ToList();

        }
        return result;
}

But in this case my method is of generic type hence the property I require to add in FetchMany need to be read from the type T.

How can I achieve this or likewise ?

Body:
Your going to need to transmit your fetch as an argument.

public IList<T> All<TFetched>(Expression<Func<T, IEnumerable<TFetched>>> fetchmany)
{
        IList<T> result;
        using (var _session = _factory.OpenSession())
        {
            //result = _session.Query<Order>().FetchMany(x=>x.OrderDetailList).ToList();

            var query = _session.Query<T>();
            if (fetchMany != null)
            {
                query = query.FetchMany(fetchmany);
            }
            result = query.ToList();
        }
        return result;
}

Then you could call:

orderRepository.All(x=>x.OrderDetailList);

This should solve your immediate trouble.

Notes:

But please bear in mind that what seems to be your current design is debatable. The session should be short lived, but not to that point. The session should span a unit of work, usually including many data access or writes. By example it may span up to the whole processing of an user triggered event in a desktop application, or the processing of an http request in a web application.

This would then probably enable you to use lazy-loading instead of eager fetching, provided you enable batch loading of lazy loads for avoiding N+1 loads, and of course provided the entities are no more used after session closing. (This can be achieved by fetching the required data into view-models before closing the session, by example.)

Moreover, you should use explicit transaction. Not doing it creates implicit transactions for each request, which is not good for performances. (But well, with what seems to be your current design, explicit transactions would not change anything currently.) Not using explicit transaction may disable some NHibernate functionalities such as second level cache.


问:
Paxos algorithm in the context of distributed database transaction
I had some confusion about paxos, specifically in the context of database transactions:

In the paper "paxos made simple", it says in the second phase that the proposer needs to choose one of the values with the highest sequence number which one of the acceptors has accepted before (if no such value exists, the proposer is free to choose the original value is proposed).

Questions:

On one hand, I understand it does so to maintain the consensus.
But on the other hand, I had confusion about what the value actually is - what's the point of "having to send accepters the value that has been accepted before"?

In the context of database transactions, what if it needs to commit a new value? Does it need to start a new instance of Paxos?

If the answer to the above question is "Yes", then how does accepters reset the state? (In my understanding, if it doesn't reset the state, the proposer would be forced to send one of the old values that has been accepted before rather than being free to commit whatever the new value is.)

答:
This is from my experience of implementing raft and reading the ZAB paper. Which are the two prevalent incarnations of PAXOS. I haven't really gotten into simple paxos or multipaxos. </p>

<p>When a client sends a commit to any node in the cluster, it will redirect that commit to the leader the leader then sends the commit message to each node in the quorum, when all of the nodes confirm the commit it will commit to it's own log. </p>

Body:
This is from my experience of implementing raft and reading the ZAB paper. Which are the two prevalent incarnations of PAXOS. I haven't really gotten into simple paxos or multipaxos.

When a client sends a commit to any node in the cluster, it will redirect that commit to the leader the leader then sends the commit message to each node in the quorum, when all of the nodes confirm the commit it will commit to it's own log.


问:
Get month number from month name?
Quick question, I have  a list of months by name i.e. "Jan" "Feb" "Mar" "Apr" ... etc. that I want to convert into 1,2,3,4 ... etc. I have written some simple code to do this but was just curious if anyone knew a way to do this using any of the APIs. </p>

答:
For Swift User you can use:</p>

```<code>Calendar.current.component(.month, from: date)
Calendar.current.component(.day, from: date)
</code>```

Title: Get month number from month name?

Body:
For Swift User you can use:

Calendar.current.component(.month, from: date)
Calendar.current.component(.day, from: date)


问:
How can I get the list of Twitter user names by their location?
I've been using the twitter REST API and need to access the list of Twitter users by their location. I've looked through the GET request lists here: https://dev.twitter.com/rest/reference/get/users/lookup, but I can't seem to find the GET request that would accomplish what I need. I am working with R and have looked at TwitteR but didn't find anything useful. and I am new to using APIs so any help would appreciated.</p>

答:
To make a request, first load httr, then call GET() with a url:

library(httr)

r <- GET("http:enter your url here")