问:
Your app has stopped
I have been developing a simple app in android studio, but my app keeps crashing when i attempt to run it. The stacktrace:

```<code>03-29 23:32:34.720 2130-2206/com.google.android.googlequicksearchbox:search
E/AudioRecord: Could not get audio input for session 4801, record source
1999, sample rate 16000, format 0x1, channel mask 0x10, flags 0
03-29 23:32:34.720 2130-2206/com.google.android.googlequicksearchbox:search
E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check
failed with status -22.
03-29 23:32:34.720 2130-2206/com.google.android.googlequicksearchbox:search
E/android.media.AudioRecord: Error code -20 when initializing native
AudioRecord object.
03-29 23:32:34.721 2130-2206/com.google.android.googlequicksearchbox:search
E/ActivityThread: Failed to find provider info for
com.google.android.apps.gsa.testing.ui.audio.recorded
</code>```

: onFatalError, processing error from engine(4)
com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream
at com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)
at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531)
at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555)
at java.io.InputStream.read(InputStream.java:101)
at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362)
at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85) ```
</div>
</div>
</p>

<p>I don't understand why this is happening, I never attempt to use a microphone or anything audio related in my app.</p>

<p>Here is my AndroidManifest.xml:</p>

```<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nick.project2" >

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>
```

<p>When debugging my MainActivity.java, this is the block of code that crashes:</p>

```    public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getFragmentManager().beginTransaction().add(R.id.professorContainer, myTeacher).commit();

    //Check to see if we should get the layout for a phone or a tablet
    if(findViewById(R.id.professorContainer) != null){
        //
        getFragmentManager().beginTransaction().add(R.id.professorContainer, myTeacher);
    }

}
```

It crashes at the third line in the onCreate method, "getFragmentManager()...."

答:
I'm guessing you may have some quicksearch widget in your layout. Quicksearch uses Google Speech recognition API which needs Audio record permission. Add that permission.</p>

```<code><uses-permission android:name="android.permission.RECORD_AUDIO" />
</code>```

Title: Your app has stopped

Body:
I have been developing a simple app in android studio, but my app keeps crashing when i attempt to run it. The stacktrace:

03-29 23:32:34.720 2130-2206/com.google.android.googlequicksearchbox:search
E/AudioRecord: Could not get audio input for session 4801, record source
1999, sample rate 16000, format 0x1, channel mask 0x10, flags 0
03-29 23:32:34.720 2130-2206/com.google.android.googlequicksearchbox:search
E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check
failed with status -22.
03-29 23:32:34.720 2130-2206/com.google.android.googlequicksearchbox:search
E/android.media.AudioRecord: Error code -20 when initializing native
AudioRecord object.
03-29 23:32:34.721 2130-2206/com.google.android.googlequicksearchbox:search
E/ActivityThread: Failed to find provider info for
com.google.android.apps.gsa.testing.ui.audio.recorded

: onFatalError, processing error from engine(4)
com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream
at com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)
at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531)
at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555)
at java.io.InputStream.read(InputStream.java:101)
at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362)
at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)

I don't understand why this is happening, I never attempt to use a microphone or anything audio related in my app.

Here is my AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nick.project2" >

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

When debugging my MainActivity.java, this is the block of code that crashes:

    public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getFragmentManager().beginTransaction().add(R.id.professorContainer, myTeacher).commit();

    //Check to see if we should get the layout for a phone or a tablet
    if(findViewById(R.id.professorContainer) != null){
        //
        getFragmentManager().beginTransaction().add(R.id.professorContainer, myTeacher);
    }

}

It crashes at the third line in the onCreate method, "getFragmentManager()...."

Body:
I'm guessing you may have some quicksearch widget in your layout. Quicksearch uses Google Speech recognition API which needs Audio record permission. Add that permission.

<uses-permission android:name="android.permission.RECORD_AUDIO" />


来源: stackexchange

问:
Convert TIMESTAMP to date in hql
I have TIMESTAMP  and I want to convert it to Date format. I have tried with to_char method but it gives me an error that the format is not compatible. Plz help me with this.

This is the TIMESTAMP that I want to convert,

```<code>timestampCreated = 29-SEP-10 00.00.00.000000000
</code>```

and I want it from

```<code>"dd-MM-yyyy"
</code>```

this format. And I have tried with this,

```<code>to_char(ap.timestampCreated,'dd-MM-yyyy')
</code>```

But it's not working. Plz help me. Thank you.

答:
timestampCreated = 29-SEP-10 00.00.00.000000000

new SimpleDateFormat("dd-MM-yyyy").format(timestampCreated)

ContentLicense: CC BY-SA 3.0

Title: Convert TIMESTAMP to date in hql

Body:
I have TIMESTAMP  and I want to convert it to Date format. I have tried with to_char method but it gives me an error that the format is not compatible. Plz help me with this.

This is the TIMESTAMP that I want to convert,

timestampCreated = 29-SEP-10 00.00.00.000000000

and I want it from

"dd-MM-yyyy"

this format. And I have tried with this,

to_char(ap.timestampCreated,'dd-MM-yyyy')

But it's not working. Plz help me. Thank you.


问:
First occurrence in numpy logics
Let's say I have a numpy.ndarray:

```<code>a = np.array([0,4,10,0,11,10])
</code>```

I compared this with 10.

```<code>a >= 10
# array([False, False,  True, False,  True,  True], dtype=bool)
</code>```

I would like to have a single True, i.e. True only at the first occurrence.

I would like to apply this to a given axis in n-D numpy.ndarray.(say, 1000*1000*10)

```<code>a_2d = np.array([[0,4,10],[0,11,10]])
#if axis == 1: array([[False, False, True], [False, True, False]])
</code>```

What I have done:

As for a 1-D array, I managed to do it by using this.

```<code>b=np.zeros(a.size)
b[np.argmax(a>=10)]=True
#b=array([ 0.,  0.,  1.,  0.,  0.,  0.])
</code>```

However, I have no idea how to apply this to a large n-D array.

答:
This one should work with no for loops, for 1D or 2D:

```<code>def firstByRow(a, f = lambda x: x >= 10):
    b = (np.cumsum(f(a), axis = -1) == 1).T
    b[1:] = b[1:] * np.equal(b[1:], np.diff((f(a)).astype(int), axis = -1).T)
    return b.T
</code>```

Not sure if it would be faster than a slightly loopier code though, as it does both cumsum and diff

EDIT:

You can also do this, which is probably faster (leveraging that np.unique(return_index = True) picks the first occurrence):

```<code>def firstByAxis(a, f = lambda x: x >= 10, axis = 0):
    c = np.where(f(a))
    i = np.unique(c[axis], return_index = True)[1]
    b = np.zeros_like(a)
    b[tuple(np.take(c, i, axis = -1))] = 1
    return b
</code>```

ContentLicense: CC BY-SA 4.0

Title: First occurrence in numpy logics

Body:
Let's say I have a numpy.ndarray:

a = np.array([0,4,10,0,11,10])

I compared this with 10.

a >= 10
# array([False, False,  True, False,  True,  True], dtype=bool)

I would like to have a single True, i.e. True only at the first occurrence.

I would like to apply this to a given axis in n-D numpy.ndarray.(say, 1000*1000*10)

a_2d = np.array([[0,4,10],[0,11,10]])
#if axis == 1: array([[False, False, True], [False, True, False]])

What I have done:

As for a 1-D array, I managed to do it by using this.

b=np.zeros(a.size)
b[np.argmax(a>=10)]=True
#b=array([ 0.,  0.,  1.,  0.,  0.,  0.])

However, I have no idea how to apply this to a large n-D array.

Body:
This one should work with no for loops, for 1D or 2D:

def firstByRow(a, f = lambda x: x >= 10):
    b = (np.cumsum(f(a), axis = -1) == 1).T
    b[1:] = b[1:] * np.equal(b[1:], np.diff((f(a)).astype(int), axis = -1).T)
    return b.T

Not sure if it would be faster than a slightly loopier code though, as it does both cumsum and diff

EDIT:

You can also do this, which is probably faster (leveraging that np.unique(return_index = True) picks the first occurrence):

def firstByAxis(a, f = lambda x: x >= 10, axis = 0):
    c = np.where(f(a))
    i = np.unique(c[axis], return_index = True)[1]
    b = np.zeros_like(a)
    b[tuple(np.take(c, i, axis = -1))] = 1
    return b


问:
Error 12501 authenticating with google sign-in
I'm using google sign-in services to authenticate users that use my app. I got it to work when I just requested email information

```<code>GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail().build();
</code>```

Then, I figured out I also need to request ID token to be able to authenticate with my backend so I did:

```<code>GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestIdToken(String.valueOf(R.string.server_client_id))
                    .requestEmail().build();
</code>```

The problem is that it wouldn't let me log in after the changes. The status I keep getting each time I try to login is Status{statusCode=unknown status code: 12501, resolution=null}.

I've been searching around and I found this post that is pretty much about the same thing. However, I didn't make any of the mistakes named by the people who answered, the oAuth Client ID in my dev console is for web application:

And R.string.server_client_id is the first client ID from the picture. the package names are of course correct in all placed otherwise it wouldn't even work without the token request. 2 people also suggested that the app needs to be signed for this to work, but googles documentation says that debug key should work too, and it doesn't make sense to make people sign the apps for debugging.

I've been trying to figure this out for hours but with no success. What could be the problem? Please feel free to request more information I might have forgotten to put here.

答:
1.Specify signingConfigs in your gradle file

```<code>signingConfigs {
        config {
            keyAlias 'appalias'
            keyPassword 'hunter123'
            storePassword 'hunter123'
            storeFile file('path/to/keystore.jks')
        }
}
</code>```

2.Go to Build Types in Project Structure (in Android Studio) and specify signingConfigs to "config"

Now clean your project and build again. It should work.

If the above doesn't work then below is your last resort.

Try step one and build and check. If it's not working go to next step and try to build again.

Build a signed apk (With remember password checked).

Before signing check the filename of the keystore file and the one yo give in while signing the apk (in android studio).

Install the signed apk in your device.

Wait for five minutes.

Try singing in to google. If still 12501 is coming wait five more minutes. While doing that hit gradle sync.

Try again. It should work.

Edit: Google have added apk signing in the console. If you already signed your apk, ignore it OR if you want to use it be careful with it because it can break your current google signin settings

Body:
I'm using google sign-in services to authenticate users that use my app. I got it to work when I just requested email information

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail().build();

Then, I figured out I also need to request ID token to be able to authenticate with my backend so I did:

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestIdToken(String.valueOf(R.string.server_client_id))
                    .requestEmail().build();

The problem is that it wouldn't let me log in after the changes. The status I keep getting each time I try to login is Status{statusCode=unknown status code: 12501, resolution=null}.

I've been searching around and I found this post that is pretty much about the same thing. However, I didn't make any of the mistakes named by the people who answered, the oAuth Client ID in my dev console is for web application:

And R.string.server_client_id is the first client ID from the picture. the package names are of course correct in all placed otherwise it wouldn't even work without the token request. 2 people also suggested that the app needs to be signed for this to work, but googles documentation says that debug key should work too, and it doesn't make sense to make people sign the apps for debugging.

I've been trying to figure this out for hours but with no success. What could be the problem? Please feel free to request more information I might have forgotten to put here.

Body:
1.Specify signingConfigs in your gradle file

signingConfigs {
        config {
            keyAlias 'appalias'
            keyPassword 'hunter123'
            storePassword 'hunter123'
            storeFile file('path/to/keystore.jks')
        }
}

2.Go to Build Types in Project Structure (in Android Studio) and specify signingConfigs to "config"

Now clean your project and build again. It should work.

If the above doesn't work then below is your last resort.

Try step one and build and check. If it's not working go to next step and try to build again.

Build a signed apk (With remember password checked).

Before signing check the filename of the keystore file and the one yo give in while signing the apk (in android studio).

Install the signed apk in your device.

Wait for five minutes.

Try singing in to google. If still 12501 is coming wait five more minutes. While doing that hit gradle sync.

Try again. It should work.

Edit: Google have added apk signing in the console. If you already signed your apk, ignore it OR if you want to use it be careful with it because it can break your current google signin settings


问:
Escaping values with apostrophes for MySQL insert
I am trying to create some SQL insert statements and a few variables have names like the following:

"Aamma's Pastries"

I want to escape the quote (') as I am adding the value into the MySQL database. How do I do that with PHP?

答: Please use prepare statements and let mysql handle escaping itself and you doing at code level</p>

ContentLicense: CC BY-SA 2.5


问:
Confusion about front end framework
I have a question if we don't use any front end framework like angular or react so can we stick with node express or mongodb please answer my question i am very confused about it please help me</p>

答:
This isn't a code-related question, but I'll answer it anyway.

You can definitely stick with node/express/mongoDB for an application without using a front-end framework.

That's actually what people used to do before SPAs (single-page applications) became commonplace. In PHP, for example, it was common for you to hit a URL, then the URL params were used to make the DB query, and render the right info on the page and then display the page.

What you'll end up doing is making the user navigate the express routes from page to page and serving the rendered html directly from node.

That said, I highly recommend using a front-end framework. It makes the entire experience more dynamic and flexible, and also will reduce a lot of overhead JS-wise.

Hope that helps!

Title: Confusion about front end framework


问:
Spring security Remember me and Custom Authentication provider
issue with spring remember me

in my spring security application i have custom authentication provider that authenticate and return custom authentication object and authentication works perfectly but i have issue with spring Remember me service it's not working correctly

but when i authenticate through normal spring security, by using UserDetailService then Remember me works perfectly my code for both is as below

```<code>package com.websopti.wotms.auth;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.websopti.wotms.entity.User;
import com.websopti.wotms.enums.ErrorKey;
import com.websopti.wotms.service.UserService;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    public UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String email = authentication.getPrincipal().toString();
        String password = authentication.getCredentials().toString();

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        String username = null;

        try {
            username = userService.authenticate(email, password);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(username != null && !username.equals("0")){

            User user = userService.findByEmail(email);

            if (user != null) {

                authorities.add(new SimpleGrantedAuthority(user.getRole().name()));
                return (new UsernamePasswordAuthenticationToken(user, null, authorities));

            } else {

                User newUser = new User();
                newUser.setName(username);
                newUser.setEmail(email);
                newUser.setPassword(password);

                userService.register(newUser);

                newUser = userService.findById(newUser.getId());
                authorities.add(new SimpleGrantedAuthority(newUser.getRole().name()));

                return (new UsernamePasswordAuthenticationToken(newUser, null, authorities));
            }

        } else {

            throw new UsernameNotFoundException(ErrorKey.USER_NOT_FOUND.name());

        }

    }

    @Override
    public boolean supports(Class<?> authentication) {

        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}
</code>```

if i use following code for authenticate then it works okay

```<code>package com.websopti.wotms.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.websopti.wotms.entity.User;
import com.websopti.wotms.enums.ErrorKey;
import com.websopti.wotms.service.UserService;

@Service
public class AuthenticationService implements UserDetailsService {

    @Autowired
    public UserService userService;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

        User user = userService.findByEmail(email);

        if(user != null)
            return user;
        else
            throw new UsernameNotFoundException(ErrorKey.USER_NOT_FOUND.name());
    }

}
</code>```

can some one guide me what is the issue here in my code?

答:
When you are using Spring custom authentication provider you need to make your own remember me service and configure it in to spring security config file.

Below is the link for reference:
https://samerabdelkafi.wordpress.com/2016/01/25/secure-angularjs-application-with-spring-security/

problem with remember me and custom Authentication provider is :

You already authenticated in custom authentication provider.

After that remember me filter in spring security chain again going to call userdetails service. At that time userdetail service take authentication principal as a input parameter and you cant get any user detail from dbo and it will not execute this filter.

public UserDetails loadUserByUsername(String mobile) throws
  UsernameNotFoundException {
  System.out.println(mobile); //here you can
  get the authenticated principal user object if you already authenticated and you
  will not get any user deatils. }

I am not sure below solution is right or not but it works fine for me.

```<code>public Authentication authenticate(Authentication auth) throws AuthenticationException {

    Customer user = null;

    user = customerDataManager.findCustomerByMobile(auth.getName());
    if ((user == null)) {
        throw new BadCredentialsException("Invalid username or password");
    }
    final Authentication result = super.authenticate(auth);

    return result;
}
</code>```

instead of returning UsernamePasswordAuthenticationToken object return authentication object.

Body:
issue with spring remember me

in my spring security application i have custom authentication provider that authenticate and return custom authentication object and authentication works perfectly but i have issue with spring Remember me service it's not working correctly

but when i authenticate through normal spring security, by using UserDetailService then Remember me works perfectly my code for both is as below

package com.websopti.wotms.auth;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.websopti.wotms.entity.User;
import com.websopti.wotms.enums.ErrorKey;
import com.websopti.wotms.service.UserService;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    public UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String email = authentication.getPrincipal().toString();
        String password = authentication.getCredentials().toString();

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        String username = null;

        try {
            username = userService.authenticate(email, password);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(username != null && !username.equals("0")){

            User user = userService.findByEmail(email);

            if (user != null) {

                authorities.add(new SimpleGrantedAuthority(user.getRole().name()));
                return (new UsernamePasswordAuthenticationToken(user, null, authorities));

            } else {

                User newUser = new User();
                newUser.setName(username);
                newUser.setEmail(email);
                newUser.setPassword(password);

                userService.register(newUser);

                newUser = userService.findById(newUser.getId());
                authorities.add(new SimpleGrantedAuthority(newUser.getRole().name()));

                return (new UsernamePasswordAuthenticationToken(newUser, null, authorities));
            }

        } else {

            throw new UsernameNotFoundException(ErrorKey.USER_NOT_FOUND.name());

        }

    }

    @Override
    public boolean supports(Class<?> authentication) {

        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}

if i use following code for authenticate then it works okay

package com.websopti.wotms.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.websopti.wotms.entity.User;
import com.websopti.wotms.enums.ErrorKey;
import com.websopti.wotms.service.UserService;

@Service
public class AuthenticationService implements UserDetailsService {

    @Autowired
    public UserService userService;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

        User user = userService.findByEmail(email);

        if(user != null)
            return user;
        else
            throw new UsernameNotFoundException(ErrorKey.USER_NOT_FOUND.name());
    }

}

can some one guide me what is the issue here in my code?

Body:
When you are using Spring custom authentication provider you need to make your own remember me service and configure it in to spring security config file.

Below is the link for reference:
https://samerabdelkafi.wordpress.com/2016/01/25/secure-angularjs-application-with-spring-security/

problem with remember me and custom Authentication provider is :

You already authenticated in custom authentication provider.

After that remember me filter in spring security chain again going to call userdetails service. At that time userdetail service take authentication principal as a input parameter and you cant get any user detail from dbo and it will not execute this filter.

public UserDetails loadUserByUsername(String mobile) throws
  UsernameNotFoundException {
  System.out.println(mobile); //here you can
  get the authenticated principal user object if you already authenticated and you
  will not get any user deatils. }

I am not sure below solution is right or not but it works fine for me.

public Authentication authenticate(Authentication auth) throws AuthenticationException {

    Customer user = null;

    user = customerDataManager.findCustomerByMobile(auth.getName());
    if ((user == null)) {
        throw new BadCredentialsException("Invalid username or password");
    }
    final Authentication result = super.authenticate(auth);

    return result;
}

instead of returning UsernamePasswordAuthenticationToken object return authentication object.


问:
Min vs max in linq.
Please help me understand why second line returns exception if  my runs are empty.
I can take maxDate even if some of my schedules haven't runs

```<code>var maxDate = schedulingList.Max(p => p.Runs.Max(x => x.StartDate));
var minDate = schedulingList.Min(s => s.Runs.Min(r => r.StartDate));
</code>```

what is the best way to get minDate ( null is posible ) ?
Great thanks in advance

答:
var minDate = schedulingList.Min(s => s.Runs.Min(r => r.StartDate)).FirstorDefault();

Hope this work,

Title: Min vs max in linq.

Body:
Please help me understand why second line returns exception if  my runs are empty.
I can take maxDate even if some of my schedules haven't runs

var maxDate = schedulingList.Max(p => p.Runs.Max(x => x.StartDate));
var minDate = schedulingList.Min(s => s.Runs.Min(r => r.StartDate));

what is the best way to get minDate ( null is posible ) ?
Great thanks in advance


问:
Substitue non-capturing groups for regex in XML Schema?
I'm linting my first custom XML Schema and lxml gets caught on the expression representing a tuple such as "10.1,-900":

```<code><xs:simpleType name="pair_dec">
    <xs:restriction base="xs:string">
        <xs:pattern value="-?\d+(?:.\d+),-?\d+(?:.\d+)"/>
    </xs:restriction>
</xs:simpleType>
</code>```

I've read that this is because there is no support for non-capturing groups. Is this right and is there a work around?

答:
Mind that in XSD regex flavor:

Non-capturing groups are not supported, but can be replaced with capturing ones

\d and all other shorthand character classes are Unicode aware, so it is safer to use [0-9] instead of \d

A dot must be escaped to match a literal dot

Use

```<code><xs:pattern value="-?[0-9]+(\.[0-9]+)?,-?[0-9]+(\.[0-9]+)?"/>
</code>```

Body:
I'm linting my first custom XML Schema and lxml gets caught on the expression representing a tuple such as "10.1,-900":

<xs:simpleType name="pair_dec">
    <xs:restriction base="xs:string">
        <xs:pattern value="-?\d+(?:.\d+),-?\d+(?:.\d+)"/>
    </xs:restriction>
</xs:simpleType>

I've read that this is because there is no support for non-capturing groups. Is this right and is there a work around?

Body:
Mind that in XSD regex flavor:

Non-capturing groups are not supported, but can be replaced with capturing ones

\d and all other shorthand character classes are Unicode aware, so it is safer to use [0-9] instead of \d

A dot must be escaped to match a literal dot

Use

<xs:pattern value="-?[0-9]+(\.[0-9]+)?,-?[0-9]+(\.[0-9]+)?"/>


问:
Input validation to only accept numbers
I'm creating  program and it should only be allowed to accept numbers if a letter is entered it should re-ask the use to enter a number. When i run the code i get an error saying there's a problem with the break heres a copy of my code

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

class Triangle
{
    private:
        double base;
        double height;
    public:
        void setBase(double);
        void setHeight(double);
        double getBase() const;
        double getHeight() const;
        double getArea() const;
};

void Triangle::setBase(double b)
{
    base = b;
}

void Triangle::setHeight(double hg)
{
    height = hg;
}

double Triangle::getBase() const
{
    return base;
}

ouble Triangle::getHeight() const
{
    return height;
}

double Triangle::getArea() const
{
    return .50 *(base * height);
}

int main()
{
    double number;
    double totalArea;
    Triangle one;
    Triangle two;
    Triangle three;

    do
    {
        cout << "What is the base of Triangle One:";
        cin >> number;

        one.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle One:";
        cin >> number;
        one.setHeight(number);
            cout << "You have entered " << number << " for the height of the triangle.\n";

            cout << "What is the base of Triangle Two: ";
        cin >> number;
        two.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle Two:";
        cin >> number;
        two.setHeight(number);
            cout << "You have entered " << number << " for the height of the triangle.\n";

            cout << "What is the base of Triangle Three:";
        cin >> number;
        three.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle Three:";
        cin >> number;
        three.setHeight(number);
             cout << "You have entered " << number << " for the height of the triangle.\n";
    }
    while (0);
    {
        if (cin >> number)
        {
            break;
        }
        else
        {
            cout << "Invalid Input! Please input a numerical value." << endl;
                    cin.clear();
            while (cin.get() != '\n') ;
        }
    }

    totalArea = one.getArea() + two.getArea() + three.getArea();

    cout << "The total area of the three triangles is " << totalArea << endl;

    return 0;

}
</code>```

Here's the error im receiving

答:
You are missing the d in double on:</p>

```<code>ouble Triangle::getHeight() const
{
    return height;
}
</code>```

Title: Input validation to only accept numbers

Body:
I'm creating  program and it should only be allowed to accept numbers if a letter is entered it should re-ask the use to enter a number. When i run the code i get an error saying there's a problem with the break heres a copy of my code

#include <iostream>
using namespace std;

class Triangle
{
    private:
        double base;
        double height;
    public:
        void setBase(double);
        void setHeight(double);
        double getBase() const;
        double getHeight() const;
        double getArea() const;
};

void Triangle::setBase(double b)
{
    base = b;
}

void Triangle::setHeight(double hg)
{
    height = hg;
}

double Triangle::getBase() const
{
    return base;
}

ouble Triangle::getHeight() const
{
    return height;
}

double Triangle::getArea() const
{
    return .50 *(base * height);
}

int main()
{
    double number;
    double totalArea;
    Triangle one;
    Triangle two;
    Triangle three;

    do
    {
        cout << "What is the base of Triangle One:";
        cin >> number;

        one.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle One:";
        cin >> number;
        one.setHeight(number);
            cout << "You have entered " << number << " for the height of the triangle.\n";

            cout << "What is the base of Triangle Two: ";
        cin >> number;
        two.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle Two:";
        cin >> number;
        two.setHeight(number);
            cout << "You have entered " << number << " for the height of the triangle.\n";

            cout << "What is the base of Triangle Three:";
        cin >> number;
        three.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle Three:";
        cin >> number;
        three.setHeight(number);
             cout << "You have entered " << number << " for the height of the triangle.\n";
    }
    while (0);
    {
        if (cin >> number)
        {
            break;
        }
        else
        {
            cout << "Invalid Input! Please input a numerical value." << endl;
                    cin.clear();
            while (cin.get() != '\n') ;
        }
    }

    totalArea = one.getArea() + two.getArea() + three.getArea();

    cout << "The total area of the three triangles is " << totalArea << endl;

    return 0;

}

Here's the error im receiving

Body:
You are missing the d in double on:

ouble Triangle::getHeight() const
{
    return height;
}


问:
Mocking not able to mock method call
I am trying to mock a call in my test but I am getting a error as its calling the real method than mocking it.

This is my method

```<code>@Value("${omega.aws.nonprod-profile}")
private String nonProdProfile;

@Autowired
AwsService awsService;

public List<SecurityGroup> getAllSecurityGroups() {
    AmazonEC2 ec2 = configSetter();
    return awsService.getAllSecurityGroups(ec2);
}

protected AmazonEC2 configSetter() {

    ProfileCredentialsProvider credentials = new ProfileCredentialsProvider(nonProdProfile);
    ClientConfiguration clientCfg = new ClientConfiguration();
    clientCfg.setProxyHost(this.proxyHost);
    clientCfg.setProxyPort(Integer.valueOf(proxyPort));
    clientCfg.setProtocol(Protocol.HTTPS);
    return new AmazonEC2Client(credentials, clientCfg);
</code>```

}

Here is my test class

```<code>@InjectMocks
    private AwsConfigurationLocal subject;

    @Mock
    private AwsService awsService;

    @Test
    public void TestgetAllSecurityGroups() throws Exception {

        ec2 = Mockito.mock(AmazonEC2Client.class);
        securityGroup = new SecurityGroup();
        List<SecurityGroup> result = Collections.singletonList(securityGroup);
        Mockito.when(awsService.getAllSecurityGroups(ec2)).thenReturn(result);
        List<SecurityGroup> actual = subject.getAllSecurityGroups();
        assertThat(actual, CoreMatchers.is(equals(result)));
    }
</code>```

The test actually calls the protected method configSetter and fails when setting a proxy. Help me understand what I am doing wrong here.

答:
Try using powerMockito to return the mocked instance of AmazonEC2

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest({AwsConfigurationLocal.class})//assuming this is your test class

@InjectMocks
private AwsConfigurationLocal subject=PowerMockito.spy(AwsConfigurationLocal.class);//or try Mockito.spy instead, whichever works

@Test
    public void TestgetAllSecurityGroups() throws Exception {

        ec2 = Mockito.mock(AmazonEC2Client.class);
        PowerMockito.doReturn(ec2).when(subject).configSetter().withNoArguments();
        //your code
    }
</code>```

Title: Mocking not able to mock method call

Body:
I am trying to mock a call in my test but I am getting a error as its calling the real method than mocking it.

This is my method

@Value("${omega.aws.nonprod-profile}")
private String nonProdProfile;

@Autowired
AwsService awsService;

public List<SecurityGroup> getAllSecurityGroups() {
    AmazonEC2 ec2 = configSetter();
    return awsService.getAllSecurityGroups(ec2);
}

protected AmazonEC2 configSetter() {

    ProfileCredentialsProvider credentials = new ProfileCredentialsProvider(nonProdProfile);
    ClientConfiguration clientCfg = new ClientConfiguration();
    clientCfg.setProxyHost(this.proxyHost);
    clientCfg.setProxyPort(Integer.valueOf(proxyPort));
    clientCfg.setProtocol(Protocol.HTTPS);
    return new AmazonEC2Client(credentials, clientCfg);

}

Here is my test class

@InjectMocks
    private AwsConfigurationLocal subject;

    @Mock
    private AwsService awsService;

    @Test
    public void TestgetAllSecurityGroups() throws Exception {

        ec2 = Mockito.mock(AmazonEC2Client.class);
        securityGroup = new SecurityGroup();
        List<SecurityGroup> result = Collections.singletonList(securityGroup);
        Mockito.when(awsService.getAllSecurityGroups(ec2)).thenReturn(result);
        List<SecurityGroup> actual = subject.getAllSecurityGroups();
        assertThat(actual, CoreMatchers.is(equals(result)));
    }

The test actually calls the protected method configSetter and fails when setting a proxy. Help me understand what I am doing wrong here.

Body:
Try using powerMockito to return the mocked instance of AmazonEC2

@RunWith(PowerMockRunner.class)
@PrepareForTest({AwsConfigurationLocal.class})//assuming this is your test class

@InjectMocks
private AwsConfigurationLocal subject=PowerMockito.spy(AwsConfigurationLocal.class);//or try Mockito.spy instead, whichever works

@Test
    public void TestgetAllSecurityGroups() throws Exception {

        ec2 = Mockito.mock(AmazonEC2Client.class);
        PowerMockito.doReturn(ec2).when(subject).configSetter().withNoArguments();
        //your code
    }


问:
Logging setLevel is being ignored
The below code is copied from the documentation. I am supposed to be able to see all the info logs. But I don't. I am only able to see the warn and above even though I've set setLevel to INFO.

Why is this happening? foo.py:

```<code>import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
</code>```

Output:

```<code>workingDirectory$ python foo.py
warn message
error message
critical message
</code>```

Where did the info and debug messages go??

答:
Try running logging.basicConfig() in there.  Of note, I see you mention INFO, but use DEBUG.  As written, it should show all five messages.  Swap out DEBUG with INFO, and you should see four messages.

```<code>import logging

logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
</code>```

edit:  Do you have logging set up elsewhere in your code already?  Can't reproduce the exact behavior you note with the specific code provided.

Title: Logging setLevel is being ignored

Body:
The below code is copied from the documentation. I am supposed to be able to see all the info logs. But I don't. I am only able to see the warn and above even though I've set setLevel to INFO.

Why is this happening? foo.py:

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

Output:

workingDirectory$ python foo.py
warn message
error message
critical message

Where did the info and debug messages go??

Body:
Try running logging.basicConfig() in there.  Of note, I see you mention INFO, but use DEBUG.  As written, it should show all five messages.  Swap out DEBUG with INFO, and you should see four messages.

import logging

logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

edit:  Do you have logging set up elsewhere in your code already?  Can't reproduce the exact behavior you note with the specific code provided.


问:
There was an error parsing the query. [ Token line number = 1,Token line offset = 39,Token in error = ( ]
I'm working in WinForms application. My requirement is loading the data from sql on demand(i.e load 100 records for a page, when moves to that page). So i tried below SqlCommand but it throws the exception at place of "ROW_NUMBER()" syntax in the below command,

```<code>SELECT *
FROM (SELECT *
      , ROW_NUMBER() (ORDER BY [ID]) AS RowNum
      FROM [tblVGTest]
      WHERE [ID]) AS Temp
WHERE RowNum BETWEEN 0 AND 100
</code>```

Please let me know, is there any mistakes in command or provide any suggestion for my scenario.

Thanks

答:
If you use SQL Server Compact 4.0, you can use the OFFSET / FECTCH syntax:</p>

```<code>SELECT * FROM TransactionHistory
ORDER BY TransactionDate DESC
OFFSET 0 ROWS FETCH NEXT 100 ROWS ONLY;
</code>```

Body:
I'm working in WinForms application. My requirement is loading the data from sql on demand(i.e load 100 records for a page, when moves to that page). So i tried below SqlCommand but it throws the exception at place of "ROW_NUMBER()" syntax in the below command,

SELECT *
FROM (SELECT *
      , ROW_NUMBER() (ORDER BY [ID]) AS RowNum
      FROM [tblVGTest]
      WHERE [ID]) AS Temp
WHERE RowNum BETWEEN 0 AND 100

Please let me know, is there any mistakes in command or provide any suggestion for my scenario.

Thanks

Body:
If you use SQL Server Compact 4.0, you can use the OFFSET / FECTCH syntax:

SELECT * FROM TransactionHistory
ORDER BY TransactionDate DESC
OFFSET 0 ROWS FETCH NEXT 100 ROWS ONLY;


问:
How to use bindings in angular 1.5 components
Trying to write a simple login page I've encounter some difficulty in understanding why the .components bindings doesn't work.

Example

template: login.html

```<code>    <form>
  <fieldset>
        <label>Email</label>
        <input id="email" type="email" ng-model="login.user.email">

        <label>Senha</label>
        <input type="password" ng-model="login.user.pass">

        <button ng-click="login.test({text: login.user})">
          Entrar
        </button>
  </fieldset>
</form>
</code>```

component: login.js

```<code>angular
  .module('app')
  .component('login', {
    bindings: {
      user: '<',
      test: '&'
    },
    templateUrl: 'app/login/login.html',
    controller: function ($log) {
      var vm = this;
      vm.user = {
        mail: 'email@provider.net',
        pass: ''
      };
      vm.test = consoleTest;

      function consoleTest(text) {
        $log.info('test! text:'+text);
      }
    }
  });
</code>```

route: router.js

```<code>angular
  .module('app')
  .config(routesConfig);

/** @ngInject */
function routesConfig($stateProvider, $urlRouterProvider, $locationProvider) {
  $locationProvider.html5Mode(true).hashPrefix('!');
  $urlRouterProvider.otherwise('/');

  $stateProvider
    .state('login', {
      url: '/login',
      component: 'login'
    });
}
</code>```

The route does not load and shows up the errors:

```<code>stateService.ts:530 TypeError: Cannot read property '2' of null
    at http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7096:54
    at Array.map (native)
    at scopeBindings (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7096:7)
    at getBindings (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7101:17)
    at Array.map (native)
    at getComponentInputs (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7109:21)
    at config.templateProvider (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7074:34)
    at invokeResolveFn (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:2786:37)
    at processQueue (http://localhost:3000/bower_components/angular/angular.js:16843:37)
    at http://localhost:3000/bower_components/angular/angular.js:16887:27
$defaultErrorHandler @ stateService.ts:530
(anonymous) @ stateService.ts:352
processQueue @ angular.js:16843
(anonymous) @ angular.js:16887
$digest @ angular.js:17982
$apply @ angular.js:18280
bootstrapApply @ angular.js:1912
invoke @ angular.js:5003
doBootstrap @ angular.js:1910
bootstrap @ angular.js:1930
angularInit @ angular.js:1815
(anonymous) @ angular.js:33340
trigger @ angular.js:3435
stateService.ts:531 TypeError: Cannot read property '2' of null
    at http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7096:54
    at Array.map (native)
    at scopeBindings (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7096:7)
    at getBindings (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7101:17)
    at Array.map (native)
    at getComponentInputs (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7109:21)
    at config.templateProvider (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7074:34)
    at invokeResolveFn (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:2786:37)
    at processQueue (http://localhost:3000/bower_components/angular/angular.js:16843:37)
    at http://localhost:3000/bower_components/angular/angular.js:16887:27
</code>```

Just removing the test: '&' property in bindings and the route loads with no errors in console, but the ng-model does not link up to the controller so it doesn't update the input field with the hard-coded value.

How can I make those bindings work?

答:
You will need to use angularjs lifecycle hooks to initialise the data you want:

```<code>vm.$onInit = function() {
  vm.user = {
    mail: 'email@provider.net',
    pass: ''
  };
}
</code>```

You also won't need to bind test as you will have access to the controller in the component, as you are using a routed component not a stateless one.

If you were using a stateless component you would need to bind test and use it as a callback function to pass the data back after an event.

Body:
Trying to write a simple login page I've encounter some difficulty in understanding why the .components bindings doesn't work.

Example

template: login.html

    <form>
  <fieldset>
        Email
        <input id="email" type="email" ng-model="login.user.email">

        Senha
        <input type="password" ng-model="login.user.pass">

        <button ng-click="login.test({text: login.user})">
          Entrar
        </button>
  </fieldset>
</form>

component: login.js

angular
  .module('app')
  .component('login', {
    bindings: {
      user: '<',
      test: '&'
    },
    templateUrl: 'app/login/login.html',
    controller: function ($log) {
      var vm = this;
      vm.user = {
        mail: 'email@provider.net',
        pass: ''
      };
      vm.test = consoleTest;

      function consoleTest(text) {
        $log.info('test! text:'+text);
      }
    }
  });

route: router.js

angular
  .module('app')
  .config(routesConfig);

/** @ngInject */
function routesConfig($stateProvider, $urlRouterProvider, $locationProvider) {
  $locationProvider.html5Mode(true).hashPrefix('!');
  $urlRouterProvider.otherwise('/');

  $stateProvider
    .state('login', {
      url: '/login',
      component: 'login'
    });
}

The route does not load and shows up the errors:

stateService.ts:530 TypeError: Cannot read property '2' of null
    at http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7096:54
    at Array.map (native)
    at scopeBindings (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7096:7)
    at getBindings (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7101:17)
    at Array.map (native)
    at getComponentInputs (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7109:21)
    at config.templateProvider (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7074:34)
    at invokeResolveFn (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:2786:37)
    at processQueue (http://localhost:3000/bower_components/angular/angular.js:16843:37)
    at http://localhost:3000/bower_components/angular/angular.js:16887:27
$defaultErrorHandler @ stateService.ts:530
(anonymous) @ stateService.ts:352
processQueue @ angular.js:16843
(anonymous) @ angular.js:16887
$digest @ angular.js:17982
$apply @ angular.js:18280
bootstrapApply @ angular.js:1912
invoke @ angular.js:5003
doBootstrap @ angular.js:1910
bootstrap @ angular.js:1930
angularInit @ angular.js:1815
(anonymous) @ angular.js:33340
trigger @ angular.js:3435
stateService.ts:531 TypeError: Cannot read property '2' of null
    at http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7096:54
    at Array.map (native)
    at scopeBindings (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7096:7)
    at getBindings (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7101:17)
    at Array.map (native)
    at getComponentInputs (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7109:21)
    at config.templateProvider (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:7074:34)
    at invokeResolveFn (http://localhost:3000/bower_components/angular-ui-router/release/angular-ui-router.js:2786:37)
    at processQueue (http://localhost:3000/bower_components/angular/angular.js:16843:37)
    at http://localhost:3000/bower_components/angular/angular.js:16887:27

Just removing the test: '&' property in bindings and the route loads with no errors in console, but the ng-model does not link up to the controller so it doesn't update the input field with the hard-coded value.

How can I make those bindings work?

Body:
You will need to use angularjs lifecycle hooks to initialise the data you want:

vm.$onInit = function() {
  vm.user = {
    mail: 'email@provider.net',
    pass: ''
  };
}

You also won't need to bind test as you will have access to the controller in the component, as you are using a routed component not a stateless one.

If you were using a stateless component you would need to bind test and use it as a callback function to pass the data back after an event.


问:
Shading with multiple plots using Plots.jl
I would like to replicate the figure using Plots.jl.

However, I have two problems

I do not know how to shade certain period of the figure

I want to draw multiple plots as the example

How can I do that?

答:
Maybe this can get you started:

```<code>using Plots

subplots = 3
time = 250
shade_xlims = [125,140]
data_matrix = Plots.fakedata(time, subplots)

p = plot(data_matrix, layout=(subplots,1), xlabel = "time");
for i in 1:subplots
   ymin,ymax = extrema(data_matrix[:,i]) # determine ylims for shade
   plot!(p[i],                    # apply shade to each subplot
         shade_xlims,             # xlims for shade
         [0,0],                   # dummy y coordinates
         fillrange = (ymin,ymax), # apply ylims
         fillalpha = 0.5,         # set transparency
         fillcolor=:gray,         # set shade color
         label = "")              # avoid shade labels
end
p # show the final graph
</code>```

Cheers!

Body:
Maybe this can get you started:

using Plots

subplots = 3
time = 250
shade_xlims = [125,140]
data_matrix = Plots.fakedata(time, subplots)

p = plot(data_matrix, layout=(subplots,1), xlabel = "time");
for i in 1:subplots
   ymin,ymax = extrema(data_matrix[:,i]) # determine ylims for shade
   plot!(p[i],                    # apply shade to each subplot
         shade_xlims,             # xlims for shade
         [0,0],                   # dummy y coordinates
         fillrange = (ymin,ymax), # apply ylims
         fillalpha = 0.5,         # set transparency
         fillcolor=:gray,         # set shade color
         label = "")              # avoid shade labels
end
p # show the final graph

Cheers!


问:
Cannot create instance of repository object in action filter MVC
```<code>public interface IUserRepository : IBaseRepository<user>
{

   user GetUser(int userId);
   user Get(string Email);

}
public class UserRepository : BaseRepository<user>, IUserRepository
{
    public UserRepository(IUnitOfWork unit) : base(unit)
    {

    }
    public void Dispose()
    {
        throw new NotImplementedException();
    }

    public user GetUser(int userId)
    {
        return dbSet.Where(x => x.ID == userId).FirstOrDefault();
    }
    public user Get(string Email)
    {
        var obj = dbSet.Where(s => s.Email == Email).FirstOrDefault();
        return obj;
    }
}
</code>```

And I am using the repository in my controller as below

```<code> public class AccountController : Controller
{
    private readonly ApplicationUserManager UserManager;
    private readonly ApplicationSignInManager SignInManager;
    private readonly IAuthenticationManager AuthenticationManager;
    private readonly IUnitOfWork uow;
    private readonly UserRepository userrepo;

    public AccountController(UserRepository _userrepo, ApplicationUserManager userManager,                                 ApplicationSignInManager signInManager, IAuthenticationManager authenticationManager,IUnitOfWork _uow)
    {
        this.UserManager = userManager;
        this.SignInManager = signInManager;
        this.AuthenticationManager = authenticationManager;
        this.uow = _uow;
        userrepo = _userrepo;
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid )
        {
         var user = UserManager.FindByEmail(model.Email);

         var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);

         if (result)
          {
            var myUser = userRepo.Get(user.Id);
            if (myUser.SubscriptionStatus == 1)
            {
               return RedirectToAction("ChangePassword", "Manage", new { ReturnUrl = returnUrl });
            }
            else
            {
              return RedirectToAction("Index","Admin");
            }
        }
     }
   }
</code>```

And this is my action filter

```<code>public class CheckFirstLoginAttribute : ActionFilterAttribute
{
    private readonly ApplicationUserManager UserManager;
    private readonly IUnitOfWork uow;
    private readonly UserRepository userrepo;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        string uName = HttpContext.Current.User.Identity.Name;

        if (!string.IsNullOrEmpty(uName))
        {
            //var user = UserManager.FindByEmailAsync(uName);
            //The above & below lines are not creating instance of the UserManager & UserRepository object, it is always null
            user cUser= userrepo.GetUserId(uName);
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                controller = "Manage",
                action = "ChangePassword"
            }));
        }
    }
}
</code>```

And I am using Unity for the dependency injection

```<code>public class UnityConfig
{
    #region Unity Container
    private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    public static IUnityContainer GetConfiguredContainer()
    {
        return container.Value;
    }
    #endregion

    private static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<MyDbContext>();
        container.RegisterType<UserRepository>();
        container.RegisterType<IUnitOfWork, UnitOfWork>();
        container.RegisterType<ApplicationDbContext>();
        container.RegisterType<ApplicationSignInManager>();
        container.RegisterType<ApplicationUserManager>();
        container.RegisterType<HomeController>();
        container.RegisterType<AccessCodeController>();
        container.RegisterType<AdminController>();

        container.RegisterType<IAuthenticationManager>(
            new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));

        container.RegisterType<IUserStore<MyUser, int>, UserStore<MyUser, MyRole, int, MyUserLogin, MyUserRole, MyUserClaim>>(
            new InjectionConstructor(typeof(ApplicationDbContext)));
    }
}
</code>```

How can I create the instance of the repository class and access the Get(string email) method. So that I can check the subscription status from the database.

I tried many ways and always failed to create the instance.

Kindly Help me.

Thanks
Tarak

答:
```<code>public class CheckFirstLoginAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        string uName = HttpContext.Current.User.Identity.Name;

        if (!string.IsNullOrEmpty(uName))
        {
            //Here is how I could get the instance of the repository
            //I had to register the repository type and then
            //I resolved it to obtain the object of the repository and
            //access the methods in the repository
            var container = new UnityContainer();
            container.RegisterType<IUnitOfWork, UnitOfWork>();
            container.RegisterType<UserRepository>();

            UserRepository repo = container.Resolve<UserRepository>();

            user cUser = repo.GetUserId(uName);
            if (cUser.SubscriptionStatus == 1)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                {
                    controller = "Manage",
                    action = "ChangePassword"
                }));
            }
        }
    }
}
</code>```

Body:
public interface IUserRepository : IBaseRepository<user>
{

   user GetUser(int userId);
   user Get(string Email);

}
public class UserRepository : BaseRepository<user>, IUserRepository
{
    public UserRepository(IUnitOfWork unit) : base(unit)
    {

    }
    public void Dispose()
    {
        throw new NotImplementedException();
    }

    public user GetUser(int userId)
    {
        return dbSet.Where(x => x.ID == userId).FirstOrDefault();
    }
    public user Get(string Email)
    {
        var obj = dbSet.Where(s => s.Email == Email).FirstOrDefault();
        return obj;
    }
}

And I am using the repository in my controller as below

 public class AccountController : Controller
{
    private readonly ApplicationUserManager UserManager;
    private readonly ApplicationSignInManager SignInManager;
    private readonly IAuthenticationManager AuthenticationManager;
    private readonly IUnitOfWork uow;
    private readonly UserRepository userrepo;

    public AccountController(UserRepository _userrepo, ApplicationUserManager userManager,                                 ApplicationSignInManager signInManager, IAuthenticationManager authenticationManager,IUnitOfWork _uow)
    {
        this.UserManager = userManager;
        this.SignInManager = signInManager;
        this.AuthenticationManager = authenticationManager;
        this.uow = _uow;
        userrepo = _userrepo;
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid )
        {
         var user = UserManager.FindByEmail(model.Email);

         var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);

         if (result)
          {
            var myUser = userRepo.Get(user.Id);
            if (myUser.SubscriptionStatus == 1)
            {
               return RedirectToAction("ChangePassword", "Manage", new { ReturnUrl = returnUrl });
            }
            else
            {
              return RedirectToAction("Index","Admin");
            }
        }
     }
   }

And this is my action filter

public class CheckFirstLoginAttribute : ActionFilterAttribute
{
    private readonly ApplicationUserManager UserManager;
    private readonly IUnitOfWork uow;
    private readonly UserRepository userrepo;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        string uName = HttpContext.Current.User.Identity.Name;

        if (!string.IsNullOrEmpty(uName))
        {
            //var user = UserManager.FindByEmailAsync(uName);
            //The above & below lines are not creating instance of the UserManager & UserRepository object, it is always null
            user cUser= userrepo.GetUserId(uName);
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                controller = "Manage",
                action = "ChangePassword"
            }));
        }
    }
}

And I am using Unity for the dependency injection

public class UnityConfig
{
    #region Unity Container
    private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    public static IUnityContainer GetConfiguredContainer()
    {
        return container.Value;
    }
    #endregion

    private static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<MyDbContext>();
        container.RegisterType<UserRepository>();
        container.RegisterType<IUnitOfWork, UnitOfWork>();
        container.RegisterType<ApplicationDbContext>();
        container.RegisterType<ApplicationSignInManager>();
        container.RegisterType<ApplicationUserManager>();
        container.RegisterType<HomeController>();
        container.RegisterType<AccessCodeController>();
        container.RegisterType<AdminController>();

        container.RegisterType<IAuthenticationManager>(
            new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));

        container.RegisterType<IUserStore<MyUser, int>, UserStore<MyUser, MyRole, int, MyUserLogin, MyUserRole, MyUserClaim>>(
            new InjectionConstructor(typeof(ApplicationDbContext)));
    }
}

How can I create the instance of the repository class and access the Get(string email) method. So that I can check the subscription status from the database.

I tried many ways and always failed to create the instance.

Kindly Help me.

Thanks
Tarak


问:
Multiple identical jar files in an ear file
I have produced an ear file with a war file inside but the ear file contains jar files which are already in the lib folder of the war file. How can I remove the duplicate jar files and where should those jar files be? In the war file's lib folder or outside the war file? (I am using maven ear plugin and maven war plugin in my project).</p>

答:
I finally figured out a way to do this by producing skinny war files inside an ear file. I was inspired by the maven-war-plugin example from here
skinny-wars

Followed the instructions of the example, I moved all the jar files out of the war module and put it into a lib folder within ear file.

So the final ear file structure will be:

```<code>  ear-app
   -- lib (all the jar files will be here)
   -- webModule1
      -- lib (empty)
   -- webModule2
      -- lib (empty)
   -- ejbModule
</code>```

Body:
I finally figured out a way to do this by producing skinny war files inside an ear file. I was inspired by the maven-war-plugin example from here
skinny-wars

Followed the instructions of the example, I moved all the jar files out of the war module and put it into a lib folder within ear file.

So the final ear file structure will be:

  ear-app
   -- lib (all the jar files will be here)
   -- webModule1
      -- lib (empty)
   -- webModule2
      -- lib (empty)
   -- ejbModule


问:
Firebase Database Rules: Unknown variable '$memberId1'
I have the following Firebase database:

I would like to add database rules to protect the that only the appropriate users can access their messages.

When I add the following, I get an error:

Please can anyone advise?

Thanks

UPDATE

```<code>findMessages(chatItem: any): Observable<any[]> { // populates the firelist
    return this.af.database.list('/message/', {
        query: {
            orderByChild: 'negativtimestamp'
        }
    }).map(items => {
        const filtered = items.filter(
            item => ((item.memberId1 === chatItem.memberId1 && item.memberId2 === chatItem.memberId2)
                || (item.memberId1 === chatItem.memberId2 && item.memberId2 === chatItem.memberId1))
        );
        return filtered;
    });
}
</code>```

答:
You should have variables that define the members and then refer to the variables.

here is chat example from Firebase security docs.

```<code>{
  "rules": {
    "room_names": {
      // any logged in user can get a list of room names
      ".read": "auth !== null",
  "$room_id": {
    // this is just for documenting the structure of rooms, since
    // they are read-only and no write rule allows this to be set
    ".validate": "newData.isString()"
  }
},

"members": {
   // I can join or leave any room (otherwise it would be a boring demo)
   // I can have a different name in each room just for fun
   "$room_id": {
      // any member can read the list of member names
      ".read": "data.child(auth.uid).exists()",

      // room must already exist to add a member
      ".validate": "root.child('room_names/'+$room_id).exists()",

      "$user_id": {
         ".write": "auth.uid === $user_id",
         ".validate": "newData.isString() && newData.val().length > 0 && newData.val().length < 20"
      }
   }
},

"messages": {
  "$room_id": {
    // the list of messages for a room can be read by any member
    ".read": "root.child('members/'+$room_id+'/'+auth.uid).exists()",

    // room we want to write a message to must be valid
    ".validate": "root.child('room_names/'+$room_id).exists()",

    "$message_id": {
      // a new message can be created if it does not exist, but it
      // cannot be modified or deleted
      // any member of a room can write a new message
      ".write": "root.child('members/'+$room_id+'/'+auth.uid).exists() && !data.exists() && newData.exists()",

      // the room attribute must be a valid key in room_names/ (the room must exist)
      // the object to write must have a name, message, and timestamp
      ".validate": "newData.hasChildren(['user', 'message', 'timestamp'])",

      // the message must be written by logged in user
      "user": {
         ".validate": "newData.val() === auth.uid"
      },

      // the message must be longer than 0 chars and less than 50
      "message": { ".validate": "newData.isString() && newData.val().length > 0 && newData.val().length < 50" },

      // messages cannot be added in the past or the future
      // clients should use firebase.database.ServerValue.TIMESTAMP
      // to ensure accurate timestamps
      "timestamp": { ".validate": "newData.val() <= now" },

      // no other fields can be included in a message
      "$other": { ".validate": false }
    }
  }
}
</code>```

}
}

Body:
I have the following Firebase database:

I would like to add database rules to protect the that only the appropriate users can access their messages.

When I add the following, I get an error:

Please can anyone advise?

Thanks

UPDATE

findMessages(chatItem: any): Observable<any[]> { // populates the firelist
    return this.af.database.list('/message/', {
        query: {
            orderByChild: 'negativtimestamp'
        }
    }).map(items => {
        const filtered = items.filter(
            item => ((item.memberId1 === chatItem.memberId1 && item.memberId2 === chatItem.memberId2)
                || (item.memberId1 === chatItem.memberId2 && item.memberId2 === chatItem.memberId1))
        );
        return filtered;
    });
}

Body:
You should have variables that define the members and then refer to the variables.

here is chat example from Firebase security docs.

{
  "rules": {
    "room_names": {
      // any logged in user can get a list of room names
      ".read": "auth !== null",
  "$room_id": {
    // this is just for documenting the structure of rooms, since
    // they are read-only and no write rule allows this to be set
    ".validate": "newData.isString()"
  }
},

"members": {
   // I can join or leave any room (otherwise it would be a boring demo)
   // I can have a different name in each room just for fun
   "$room_id": {
      // any member can read the list of member names
      ".read": "data.child(auth.uid).exists()",

      // room must already exist to add a member
      ".validate": "root.child('room_names/'+$room_id).exists()",

      "$user_id": {
         ".write": "auth.uid === $user_id",
         ".validate": "newData.isString() && newData.val().length > 0 && newData.val().length < 20"
      }
   }
},

"messages": {
  "$room_id": {
    // the list of messages for a room can be read by any member
    ".read": "root.child('members/'+$room_id+'/'+auth.uid).exists()",

    // room we want to write a message to must be valid
    ".validate": "root.child('room_names/'+$room_id).exists()",

    "$message_id": {
      // a new message can be created if it does not exist, but it
      // cannot be modified or deleted
      // any member of a room can write a new message
      ".write": "root.child('members/'+$room_id+'/'+auth.uid).exists() && !data.exists() && newData.exists()",

      // the room attribute must be a valid key in room_names/ (the room must exist)
      // the object to write must have a name, message, and timestamp
      ".validate": "newData.hasChildren(['user', 'message', 'timestamp'])",

      // the message must be written by logged in user
      "user": {
         ".validate": "newData.val() === auth.uid"
      },

      // the message must be longer than 0 chars and less than 50
      "message": { ".validate": "newData.isString() && newData.val().length > 0 && newData.val().length < 50" },

      // messages cannot be added in the past or the future
      // clients should use firebase.database.ServerValue.TIMESTAMP
      // to ensure accurate timestamps
      "timestamp": { ".validate": "newData.val() <= now" },

      // no other fields can be included in a message
      "$other": { ".validate": false }
    }
  }
}

}
}


问:
How to create a queryset that filters multiple fields based on a single condition in Django?
My model is

```<code>class TestModel(models.Model)
    field1 = models.IntegerField()
    field2 = models.IntegerField()
    field3 = models.IntegerField()
    field4 = models.IntegerField()
    field5 = models.IntegerField()
</code>```

I need a simple queryset that applies a single condition on all the five fields of the model without writing every combination of fields and filtering them.

For example I want to apply a condition of checking for None to two or more fields

```<code>TestModel.objects.filter(two_or_more_fields=None)
</code>```

I don't want write every possible combination of 5 fields to find the queryset with any two or more fields as None. In other words, is there a better way to accomplish this than:

```<code>from django.db.models import Q
TestModel.objects.filter(
    #condition for exactly 2 None
    Q(field1=None & field2=None) |
    Q(field2=None & field3=None) |
    Q(field3=None & field4=None) |
    Q(field4=None & field5=None) |
    Q(field5=None & field1=None) |
    #condition for more than 2 None
    Q(field1=None & field2=None & field3 = None) |
    '''''
    .
    .
    #so on to cover all possible cases of any two or more fields as None
     )
</code>```

I think there should be a better and simple way to accomplish this.

答:
This solution is POSTGRESQL specific because of the functions used here. However, the idea can be used if you are using another database.

You could use a mixture of RawSQL and some ARRAY magic.

The idea is to annotate each item in the queryset with the number of fields which are not null:

```<code>from django.db.models import Func
from django.db.models.expressions import RawSQL

field_list = ['field1', 'field2', 'field3', 'field4', 'field5']

# field1 IS NULL, field2 IS NULL, field3 IS NULL, .....
statements = ", ".join("{} IS NULL".format(field) for field in field_list)

# create an array for each field by checking if those are NULL
# then, remove the False values e.g. not null ones.
# ARRAY_REMOVE(ARRAY[field1 IS NULL, field2 IS NULL, .....], false)
raw_sql = "ARRAY_REMOVE(ARRAY[{statements}], false)".format(statements=statements)

# now annotate each item with the number of null fields
qs = TestModel.objects.annotate(num_null=Func(RawSQL(sql, ()), function='CARDINALITY')

# on this queryset you can filter by the number of null items you want to check
qs = qs.filter(num_null__gte=2)
</code>```

Body:
My model is

class TestModel(models.Model)
    field1 = models.IntegerField()
    field2 = models.IntegerField()
    field3 = models.IntegerField()
    field4 = models.IntegerField()
    field5 = models.IntegerField()

I need a simple queryset that applies a single condition on all the five fields of the model without writing every combination of fields and filtering them.

For example I want to apply a condition of checking for None to two or more fields

TestModel.objects.filter(two_or_more_fields=None)

I don't want write every possible combination of 5 fields to find the queryset with any two or more fields as None. In other words, is there a better way to accomplish this than:

from django.db.models import Q
TestModel.objects.filter(
    #condition for exactly 2 None
    Q(field1=None & field2=None) |
    Q(field2=None & field3=None) |
    Q(field3=None & field4=None) |
    Q(field4=None & field5=None) |
    Q(field5=None & field1=None) |
    #condition for more than 2 None
    Q(field1=None & field2=None & field3 = None) |
    '''''
    .
    .
    #so on to cover all possible cases of any two or more fields as None
     )

I think there should be a better and simple way to accomplish this.

Body:
This solution is POSTGRESQL specific because of the functions used here. However, the idea can be used if you are using another database.

You could use a mixture of RawSQL and some ARRAY magic.

The idea is to annotate each item in the queryset with the number of fields which are not null:

from django.db.models import Func
from django.db.models.expressions import RawSQL

field_list = ['field1', 'field2', 'field3', 'field4', 'field5']

# field1 IS NULL, field2 IS NULL, field3 IS NULL, .....
statements = ", ".join("{} IS NULL".format(field) for field in field_list)

# create an array for each field by checking if those are NULL
# then, remove the False values e.g. not null ones.
# ARRAY_REMOVE(ARRAY[field1 IS NULL, field2 IS NULL, .....], false)
raw_sql = "ARRAY_REMOVE(ARRAY[{statements}], false)".format(statements=statements)

# now annotate each item with the number of null fields
qs = TestModel.objects.annotate(num_null=Func(RawSQL(sql, ()), function='CARDINALITY')

# on this queryset you can filter by the number of null items you want to check
qs = qs.filter(num_null__gte=2)


问:
Creating a grid from map model with obstacles
I have a simple tower defense map with the road is for the enemy (which is the player can't build the tower there), and the other is for the tower can build there and with any obstacles (trees, rocks, etc).. However, i am not sure on how to make a grid (probably 2x2) loop through the map size and with differentiate with "red" for the obstacles and the road (I am thinking on using the Layer Mask to achieve this), and "white" for the tower can build there.

My map is like below (the red color is for the obstacles and the road, and the green color is for the tower that can build)

Image:

But the problem is, I can't get it started and I am not sure where to start.

Create a grid (probably 2x2) loop through the map size.

Place a tower within the "white" color, and not "red" color.

Any idea on how to achieve this?

Your answer much appreciated.

Thanks

答: If you make a Box Collider for your road,  you can allow the player to make a tower as long as the GameObject tower is not colliding with your Box Colider. You can do the same for your enviroment.


答:
Within the .read rule's expression, the variables that begin with $ represent keys in the path.

However, the member IDs are not keys; they are data members. To use them in the expression, you can use the data snapshot's child and val methods. Like this:

```<code>{
  "rules": {
    "message": {
      "$key": {
        ".read": "data.child('memberId1').val() === auth.uid || data.child('memberId2').val() === auth.uid"
      }
    }
  }
}
</code>```

Title: Firebase Database Rules: Unknown variable '$memberId1'

Body:
Within the .read rule's expression, the variables that begin with $ represent keys in the path.

However, the member IDs are not keys; they are data members. To use them in the expression, you can use the data snapshot's child and val methods. Like this:

{
  "rules": {
    "message": {
      "$key": {
        ".read": "data.child('memberId1').val() === auth.uid || data.child('memberId2').val() === auth.uid"
      }
    }
  }
}


问:
ArrayList in J2ME?
I have an arraylist of database records. I want to put it in my J2ME List. But there is no split or arraylist in J2ME. How can I do it? A code example would be nice.</p>

答: It is better if you use Vector (java.util.Vector). It will help you.

Title: ArrayList in J2ME?