问:
React-Navigation Parameters not ever passing
Ok, I have managed to pass parameters so far, but on this specific situation, I wasn't able to identify why this functionality is not working.

Basically these are my navigators that are set:

login-nav.js:

```<code>import React from 'react';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';

import { LoginScreen } from '../screens/login-scr';
import { SignupScreen } from '../screens/signup-scr';
import { NewPassScreen } from '../screens/new-pass-scr';

import { MainStack } from './main-nav';

const LoginStack = createStackNavigator (
  {
      Login: {
                screen: LoginScreen,
                navigationOptions: {
                 header: null,
                },
      },

      NewPass: {
                screen: NewPassScreen,

      },

      SignUp: {
                screen: SignupScreen,
      },

      MainStack: {
        screen: MainStack,
        navigationOptions: {
          header: null,
        },
      },
  },
);

const AppContainer =  createAppContainer(LoginStack);

export {AppContainer};
</code>```

main-nav.js:

```<code>import React from 'react';

import { createStackNavigator } from 'react-navigation-stack';
import { createMaterialBottomTabNavigator } from 'react-navigation-material-bottom-tabs';

import { MainScreen } from '../screens/main-scr';
import { TasksScreen } from '../screens/tasks-scr';
import { AgendaScreen } from '../screens/agenda-scr';

import Ionicons from 'react-native-vector-icons/Ionicons';

const BottomTabNavigator = createMaterialBottomTabNavigator({
  Home:     {
              screen: MainScreen,
              navigationOptions: {
                tabBarLabel:"Home",
                tabBarIcon: ({ tintColor }) => (
                  <Ionicons name="ios-home" size={20} color={tintColor} />
                )
              }

            },
  Tasks:    {
              screen: TasksScreen,
              navigationOptions: {
                tabBarLabel:"Tarefas",
                tabBarIcon: ({ tintColor }) => (
                  <Ionicons name="ios-checkbox-outline" size={20} color={tintColor} />
                ),
              },
            },

 // Agenda:   {screen: AgendaScreen},
}, {
  initialRouteName: 'Home',
});

const MainStack = createStackNavigator (
  {
      Main: {
        screen: BottomTabNavigator,
        navigationOptions: {
          header: null,
        },
      },

  },
);

export  { MainStack };

</code>```

Now this is how I pass the parameter from the Login screen (Actually how I am doing now, I've tried several different ways):

login-scr.js:

```<code>...

handleSubmit = ()=>{

...
                  console.log("Login passed from login-scr ===> " + this.state.login);
                  const setParamsAction = NavigationActions.setParams({
                    params: { Login: this.state.login },
                    key: 'Home',
                  });

                  this.props.navigation.dispatch(setParamsAction);

                  this.props.navigation.navigate("MainStack");

...

}

</code>```

And this is how I'm receiving:

main-scr.js:

```<code>async componentDidMount() {

...
        let llogin = this.props.navigation.getParam('Login', 'notFound');
        console.log("Login on Main Screen ====>  " + llogin  );
...

}

</code>```

I wanted to save the llogin variable to my states, but it is always comming as 'notFound'.

Is there anything peculiar in this route that I didn't find out, that I should treat differently+

答: Because of upgrades on React-Native to use stateless functions, React-Navigation changed a lot the way it works on version five. That also changed a bit the way the routes are passed. Best solution was to migrate to version ^5 and rewrite the code accordingly.</p>

Body:
Ok, I have managed to pass parameters so far, but on this specific situation, I wasn't able to identify why this functionality is not working.

Basically these are my navigators that are set:

login-nav.js:

import React from 'react';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';

import { LoginScreen } from '../screens/login-scr';
import { SignupScreen } from '../screens/signup-scr';
import { NewPassScreen } from '../screens/new-pass-scr';

import { MainStack } from './main-nav';

const LoginStack = createStackNavigator (
  {
      Login: {
                screen: LoginScreen,
                navigationOptions: {
                 header: null,
                },
      },

      NewPass: {
                screen: NewPassScreen,

      },

      SignUp: {
                screen: SignupScreen,
      },

      MainStack: {
        screen: MainStack,
        navigationOptions: {
          header: null,
        },
      },
  },
);

const AppContainer =  createAppContainer(LoginStack);

export {AppContainer};

main-nav.js:

import React from 'react';

import { createStackNavigator } from 'react-navigation-stack';
import { createMaterialBottomTabNavigator } from 'react-navigation-material-bottom-tabs';

import { MainScreen } from '../screens/main-scr';
import { TasksScreen } from '../screens/tasks-scr';
import { AgendaScreen } from '../screens/agenda-scr';

import Ionicons from 'react-native-vector-icons/Ionicons';

const BottomTabNavigator = createMaterialBottomTabNavigator({
  Home:     {
              screen: MainScreen,
              navigationOptions: {
                tabBarLabel:"Home",
                tabBarIcon: ({ tintColor }) => (
                  <Ionicons name="ios-home" size={20} color={tintColor} />
                )
              }

            },
  Tasks:    {
              screen: TasksScreen,
              navigationOptions: {
                tabBarLabel:"Tarefas",
                tabBarIcon: ({ tintColor }) => (
                  <Ionicons name="ios-checkbox-outline" size={20} color={tintColor} />
                ),
              },
            },

 // Agenda:   {screen: AgendaScreen},
}, {
  initialRouteName: 'Home',
});

const MainStack = createStackNavigator (
  {
      Main: {
        screen: BottomTabNavigator,
        navigationOptions: {
          header: null,
        },
      },

  },
);

export  { MainStack };

Now this is how I pass the parameter from the Login screen (Actually how I am doing now, I've tried several different ways):

login-scr.js:

...

handleSubmit = ()=>{

...
                  console.log("Login passed from login-scr ===> " + this.state.login);
                  const setParamsAction = NavigationActions.setParams({
                    params: { Login: this.state.login },
                    key: 'Home',
                  });

                  this.props.navigation.dispatch(setParamsAction);

                  this.props.navigation.navigate("MainStack");

...

}

And this is how I'm receiving:

main-scr.js:

async componentDidMount() {

...
        let llogin = this.props.navigation.getParam('Login', 'notFound');
        console.log("Login on Main Screen ====>  " + llogin  );
...

}

I wanted to save the llogin variable to my states, but it is always comming as 'notFound'.

Is there anything peculiar in this route that I didn't find out, that I should treat differently+


来源: stackexchange

问:
UseSelector State is Undefined
The page does not render, citing TypeError: state is undefined, tracing back to this line in SelectForm.js: const filter = useSelector(state => state.filter);.

I've spent hours trying to figure out what I'm doing wrong. I've tried createSelector but that didn't work. I've tried dispatching a "Fetch Initial State" action, and that didn't work. The component is wrapped in provider tags. I'm not sure why I don't have access to the state. At this point I'm unable to see any flaws I've been looking at it for so long.

Code Snippets

reducer.js

```<code>let initialState = {
    filter: {
        country: null,
        state: null,
        level: null,
        team: null
    },

    isDBConnecting: false,
    isDBConnected: false,
    isDBError: false
}

const SelectorReducer = (state=initialState, action) => {
    switch (action.type) {
        case 'DB_CONNECT_INIT':
            return {
                ...state,
                isDBConnecting: true,
                isDBConnected: false,
                isDBError: false,
            };
...
...
}

export default SelectorReducer;
</code>```

actions.js

```<code>export const initializeDBConnection = () => {
    return {
        type: 'DB_CONNECT_INIT'
    }
};
</code>```

ParentComponent.js

```<code>import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux'; //import provider to provide component access to the state

//Component imports
import SelectForm from './components/SelectForm'
import SelectorReducer from '.../reducer.js'

const SelectorStore = createStore(SelectorReducer);

const ParentComponent = () => {

    return (
        <div className="page-container">
            <div id="carousel">
                <div id="wrapper">
                    <Provider store={SelectorStore}>
                        <SelectForm />
                    </Provider>
                </div>
            </div>
    </div>
    )
}
</code>```

SelectForm.js (Child Component, wrapped in Provider tags above)

```<code>//IMPORTS
import React from 'react'; //import react
import { useSelector, useDispatch } from 'react-redux';

//COMPONENT IMPORTS
import FormGroup from '../FormGroup';
import { * as actions } from '.../actions.js';

const SelectForm = (props) => {

    //STATEFUL IMPORTS
    //filter
    const filter = useSelector(state => state.filter);
</code>```

答: Inside ParentComponent.js you are saying <Provider store={TeamSelectorStore}>. I think you meant to say <Provider store={SelectorStore}>

ContentLicense: CC BY-SA 4.0

Title: UseSelector State is Undefined

Body:
The page does not render, citing TypeError: state is undefined, tracing back to this line in SelectForm.js: const filter = useSelector(state => state.filter);.

I've spent hours trying to figure out what I'm doing wrong. I've tried createSelector but that didn't work. I've tried dispatching a "Fetch Initial State" action, and that didn't work. The component is wrapped in provider tags. I'm not sure why I don't have access to the state. At this point I'm unable to see any flaws I've been looking at it for so long.

Code Snippets

reducer.js

let initialState = {
    filter: {
        country: null,
        state: null,
        level: null,
        team: null
    },

    isDBConnecting: false,
    isDBConnected: false,
    isDBError: false
}

const SelectorReducer = (state=initialState, action) => {
    switch (action.type) {
        case 'DB_CONNECT_INIT':
            return {
                ...state,
                isDBConnecting: true,
                isDBConnected: false,
                isDBError: false,
            };
...
...
}

export default SelectorReducer;

actions.js

export const initializeDBConnection = () => {
    return {
        type: 'DB_CONNECT_INIT'
    }
};

ParentComponent.js

import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux'; //import provider to provide component access to the state

//Component imports
import SelectForm from './components/SelectForm'
import SelectorReducer from '.../reducer.js'

const SelectorStore = createStore(SelectorReducer);

const ParentComponent = () => {

    return (

                    <Provider store={SelectorStore}>
                        <SelectForm />
                    </Provider>

    )
}

SelectForm.js (Child Component, wrapped in Provider tags above)

//IMPORTS
import React from 'react'; //import react
import { useSelector, useDispatch } from 'react-redux';

//COMPONENT IMPORTS
import FormGroup from '../FormGroup';
import { * as actions } from '.../actions.js';

const SelectForm = (props) => {

    //STATEFUL IMPORTS
    //filter
    const filter = useSelector(state => state.filter);


问:
Retrieval of certificate/keys related information from keystore in android
I am new to Android. I have created the Keystore file. Under the PrivateActivity class, I have also loaded the Keystore. My task is to get any key/certificate-related information after putting the name of the alias (that I have created),  on the android emulator . I have also changed the path in Gradle build, but I wanted to understand if I have to add the Keystore file name or path somewhere in the code or I have to write a method that will retrieve all the keys and certificate-related information from the Keystore? Because after writing the method, I couldn't get the certificate/key-related information.
PrivateActivity.java</p>

```<code>``` package org.jssec.android.activity.privateactivity;```

```import java.io.IOException;
import java.security.*;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import java.io.InputStream;```

import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.CertificateException;
import java.util.Enumeration;

import javax.crypto.KeyGenerator;

//Appropriate libraries need to be also imported

public class PrivateActivity extends Activity {

    private KeyStore my_ks;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.private_activity);

        // Handle the received Intent carefully and securely,
        // even though the Intent was sent from the same application.

        Intent intent=this.getIntent();
        PrivateUserActivity.keystore_info param = (PrivateUserActivity.keystore_info) intent.getSerializableExtra("CL_k");

        //CODE MUST BE ADDED HERE IN ORDER TO HANDLE the COLLECTED OBJECT from the Intent
        Bundle extras = intent.getExtras();

        String data = getIntent().getExtras().getString("Cl_k");

    }

    public void onReturnResultClick(View view) throws KeyStoreException,
            UnrecoverableEntryException, NoSuchAlgorithmException, CertificateException, IOException, NoSuchProviderException {

        // Sensitive information can be sent since it is sending
        // and receiving all within the same application.
        Intent intent = new Intent();
        Intent i = new Intent(this, PrivateUserActivity.class);

        //Create instance
        KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);
        Enumeration<String> aliases = ks.aliases();

        //CODE MUST BE ADDED HERE IN ORDER TO send the appropriate values to the PrivateUserActivity
        //i.e. the "Sensitive Info" value should be changed with something different

       //// return new KeyPair (publicKey,privateKey);

        intent.putExtra("RESULT", "Sensitive Info");

        setResult(RESULT_OK, intent);
        finish();
    }
}```

Another class is this PrivateUserActivity.java
```/*
 * Copyright (C) 2012-2019 Japan Smartphone Security Association
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jssec.android.activity.privateactivity;

import java.io.IOException;
import java.security.*;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import java.io.InputStream;

import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.CertificateException;
import java.util.Enumeration;

import javax.crypto.KeyGenerator;

//Appropriate libraries need to be also imported

public class PrivateActivity extends Activity {

    private KeyStore my_ks;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.private_activity);

        // Handle the received Intent carefully and securely,
        // even though the Intent was sent from the same application.

        Intent intent=this.getIntent();
        PrivateUserActivity.keystore_info param = (PrivateUserActivity.keystore_info) intent.getSerializableExtra("CL_k");

        //CODE MUST BE ADDED HERE IN ORDER TO HANDLE the COLLECTED OBJECT from the Intent
        Bundle extras = intent.getExtras();

        String data = getIntent().getExtras().getString("Cl_k");

    }

    public void onReturnResultClick(View view) throws KeyStoreException,
            UnrecoverableEntryException, NoSuchAlgorithmException, CertificateException, IOException, NoSuchProviderException {

        // Sensitive information can be sent since it is sending
        // and receiving all within the same application.
        Intent intent = new Intent();
        Intent i = new Intent(this, PrivateUserActivity.class);

        //Create instance
        KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);
        Enumeration<String> aliases = ks.aliases();

        //CODE MUST BE ADDED HERE IN ORDER TO send the appropriate values to the PrivateUserActivity
        //i.e. the "Sensitive Info" value should be changed with something different

       //// return new KeyPair (publicKey,privateKey);

        intent.putExtra("RESULT", "Sensitive Info");

        setResult(RESULT_OK, intent);
        finish();
    }
}```
</code>```

答:
Not clear exactly what your problem is, but if you are using KeyStore.getInstance("AndroidKeyStore"), there is no file you need to load.
Android manages the keys and any underlying files automatically.

To actually generate a file saved in the Android keystore, you need to specify "AndroidKeyStore" when you setup the generation parameters.
See the documentation here: https://developer.android.com/training/articles/keystore

Body:
I am new to Android. I have created the Keystore file. Under the PrivateActivity class, I have also loaded the Keystore. My task is to get any key/certificate-related information after putting the name of the alias (that I have created),  on the android emulator . I have also changed the path in Gradle build, but I wanted to understand if I have to add the Keystore file name or path somewhere in the code or I have to write a method that will retrieve all the keys and certificate-related information from the Keystore? Because after writing the method, I couldn't get the certificate/key-related information.
PrivateActivity.java

``` package org.jssec.android.activity.privateactivity;```

```import java.io.IOException;
import java.security.*;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import java.io.InputStream;```

import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.CertificateException;
import java.util.Enumeration;

import javax.crypto.KeyGenerator;

//Appropriate libraries need to be also imported

public class PrivateActivity extends Activity {

    private KeyStore my_ks;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.private_activity);

        // Handle the received Intent carefully and securely,
        // even though the Intent was sent from the same application.

        Intent intent=this.getIntent();
        PrivateUserActivity.keystore_info param = (PrivateUserActivity.keystore_info) intent.getSerializableExtra("CL_k");

        //CODE MUST BE ADDED HERE IN ORDER TO HANDLE the COLLECTED OBJECT from the Intent
        Bundle extras = intent.getExtras();

        String data = getIntent().getExtras().getString("Cl_k");

    }

    public void onReturnResultClick(View view) throws KeyStoreException,
            UnrecoverableEntryException, NoSuchAlgorithmException, CertificateException, IOException, NoSuchProviderException {

        // Sensitive information can be sent since it is sending
        // and receiving all within the same application.
        Intent intent = new Intent();
        Intent i = new Intent(this, PrivateUserActivity.class);

        //Create instance
        KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);
        Enumeration<String> aliases = ks.aliases();

        //CODE MUST BE ADDED HERE IN ORDER TO send the appropriate values to the PrivateUserActivity
        //i.e. the "Sensitive Info" value should be changed with something different

       //// return new KeyPair (publicKey,privateKey);

        intent.putExtra("RESULT", "Sensitive Info");

        setResult(RESULT_OK, intent);
        finish();
    }
}```

Another class is this PrivateUserActivity.java
```/*
 * Copyright (C) 2012-2019 Japan Smartphone Security Association
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jssec.android.activity.privateactivity;

import java.io.IOException;
import java.security.*;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import java.io.InputStream;

import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.CertificateException;
import java.util.Enumeration;

import javax.crypto.KeyGenerator;

//Appropriate libraries need to be also imported

public class PrivateActivity extends Activity {

    private KeyStore my_ks;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.private_activity);

        // Handle the received Intent carefully and securely,
        // even though the Intent was sent from the same application.

        Intent intent=this.getIntent();
        PrivateUserActivity.keystore_info param = (PrivateUserActivity.keystore_info) intent.getSerializableExtra("CL_k");

        //CODE MUST BE ADDED HERE IN ORDER TO HANDLE the COLLECTED OBJECT from the Intent
        Bundle extras = intent.getExtras();

        String data = getIntent().getExtras().getString("Cl_k");

    }

    public void onReturnResultClick(View view) throws KeyStoreException,
            UnrecoverableEntryException, NoSuchAlgorithmException, CertificateException, IOException, NoSuchProviderException {

        // Sensitive information can be sent since it is sending
        // and receiving all within the same application.
        Intent intent = new Intent();
        Intent i = new Intent(this, PrivateUserActivity.class);

        //Create instance
        KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);
        Enumeration<String> aliases = ks.aliases();

        //CODE MUST BE ADDED HERE IN ORDER TO send the appropriate values to the PrivateUserActivity
        //i.e. the "Sensitive Info" value should be changed with something different

       //// return new KeyPair (publicKey,privateKey);

        intent.putExtra("RESULT", "Sensitive Info");

        setResult(RESULT_OK, intent);
        finish();
    }
}```


问:
Is Amazon EC2 free tier server appropriate for my little web application?
I'm building a little software activation web service in Java, so I need a cloud-based server which will run Apache and Tomcat and MySQL.

It will get very little usage as I don't expect to sell very much product at first.  I'll be very lucky if the server handles one quick activation a day ... if it got 20 in a day that would be an amazing success.

I'm looking at Amazon EC2 pricing here ...

https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&all-free-tier.sort-order=asc

I see that there is a "Free Tier" which provides "750 hours per month of Linux t2.micro or t3.micro instance".  And it's free for year.

STUPID QUESTION #1: 24h/day x 31 days/month is 744 hours ... so, does that mean I'm getting a free linux server running 24/7 for a year or is there a catch that I'm missing?

STUPID QUESTION #2: t2.micro/t2.micro has 1 vCPU, 1GB Memory ... is that enough power to run a simple Apache + Tomcat + MySQL web service reliably?

STUPID QUESTION #3: Any reason why I should skip the free tier and invest in a powerful pay $$$ option?

答:
You describe your service as: "Accept an encrypted license key, decrypt it, verify it, return and encrypted boolean response".

This sounds like an excellent candidate for a serverless solution:

AWS API Gateway providing an HTTPS endpoint that the application can call

It then triggers an AWS Lambda function that performs the logic and exits

However, you also mention a MySQL database. This could be provided by Amazon RDS. Or, you could go serverless and use DynamoDB (a NoSQL database).

The benefit of a serverless architecture is that it can scale to handle high loads and doesn't cost you anything (except potentially for the database) when not being used.

There is a free tier available for AWS API Gateway, AWS Lambda, Amazon DynamoDB and Amazon RDS.


问:
Error while creating app package with "fullTrustProcess" pointing to a executable
I am trying to deploy the sample application for bridging AppServices with a UWP application. The sample runs and builds just fine but when I try to follow the guide to package the whole thing it gives me an error.

Link to the packaging guide

AppService Bridge Sample repository here.

Error message:

```<code> Error Manifest validation error: Line 36, Column 64, Reason: The file name  "BackgroundProcess.exe" declared for element "*[local-name()='Applications']/*[local-name()='Application']/*[local-name()='Extensions']/*[local-name()='Extension' and @Category='windows.fullTrustProcess']" doesn't exist in the package.
</code>```

I've found the code-snippet generating the error, but I have haven't found a fix for it yet.

If I remove the following code from the file Package.appxmanifest, visual studio successfully builds the package:

```<code><Extensions>
  <uap:Extension Category="windows.appService">
    <uap:AppService Name="CommunicationService" />
  </uap:Extension>
  <desktop:Extension Category="windows.fullTrustProcess" Executable="BackgroundProcess.exe" />
</Extensions>
</code>```

But this will clearly also remove the bridging to the process which is the whole point of this exercise.

This seems to be somewhat related to this question but the difference is I have a .exe and that question seems to answer it for .dlls:

Error when building universal app for the store: "Manifest references file 'MyAppName.dll' which is not part of the payload."

(Updating UWP Tools did not seem to fix it.)

答:
Wrong path will cause the same error.

For me, my wrong code is

```<code><Extensions>
    <desktop:Extension Category="windows.startupTask" EntryPoint="Windows.FullTrustApplication" Executable="ClipboardEx.exe">
      <desktop:StartupTask DisplayName="ClipboardEx" Enabled="true" TaskId="ClipboardExStartUpId"/>
    </desktop:Extension>
</Extensions>
</code>```

my project dir like this:

```<code>bin
│  ├─x64
│  │  └─Release
│  │      ├─AppX
│  │      │  ├─ClipboardEx
|  |      |  |  └─ClipboardEx.exe
│  │      │  ├─Images
│  │      │  └─WinMetadata
</code>```

So I changed Executable fromClipboardEx.exetoClipboardEx\ClipboardEx.exe, pack successfully.

It's kind of like what kibitzerCZ said. But i dont need to make a new dir, just make sure your path is correct

ContentLicense: CC BY-SA 3.0

Body:
I am trying to deploy the sample application for bridging AppServices with a UWP application. The sample runs and builds just fine but when I try to follow the guide to package the whole thing it gives me an error.

Link to the packaging guide

AppService Bridge Sample repository here.

Error message:

 Error Manifest validation error: Line 36, Column 64, Reason: The file name  "BackgroundProcess.exe" declared for element "*[local-name()='Applications']/*[local-name()='Application']/*[local-name()='Extensions']/*[local-name()='Extension' and @Category='windows.fullTrustProcess']" doesn't exist in the package.

I've found the code-snippet generating the error, but I have haven't found a fix for it yet.

If I remove the following code from the file Package.appxmanifest, visual studio successfully builds the package:

<Extensions>
  <uap:Extension Category="windows.appService">
    <uap:AppService Name="CommunicationService" />
  </uap:Extension>
  <desktop:Extension Category="windows.fullTrustProcess" Executable="BackgroundProcess.exe" />
</Extensions>

But this will clearly also remove the bridging to the process which is the whole point of this exercise.

This seems to be somewhat related to this question but the difference is I have a .exe and that question seems to answer it for .dlls:

Error when building universal app for the store: "Manifest references file 'MyAppName.dll' which is not part of the payload."

(Updating UWP Tools did not seem to fix it.)

Body:
Wrong path will cause the same error.

For me, my wrong code is

<Extensions>
    <desktop:Extension Category="windows.startupTask" EntryPoint="Windows.FullTrustApplication" Executable="ClipboardEx.exe">
      <desktop:StartupTask DisplayName="ClipboardEx" Enabled="true" TaskId="ClipboardExStartUpId"/>
    </desktop:Extension>
</Extensions>

my project dir like this:

bin
│  ├─x64
│  │  └─Release
│  │      ├─AppX
│  │      │  ├─ClipboardEx
|  |      |  |  └─ClipboardEx.exe
│  │      │  ├─Images
│  │      │  └─WinMetadata

So I changed Executable fromClipboardEx.exetoClipboardEx\ClipboardEx.exe, pack successfully.

It's kind of like what kibitzerCZ said. But i dont need to make a new dir, just make sure your path is correct


问:
How to avoid the ugly empty space of the placeholder for the vertical scrollbar in QTableView?
In a QTableView instance, rows are variable, the row count are not fixed most of the time. In a moment, if the row count is lower than the display count of the viewport, a ugly empty-space placeholder for the vertical scroll bar will show up as in the below picture.

I tried viewportSizeHint(), maximumViewPortSize(), ... finally, a very simple solution.

答:
Solution: If there is a n-column table originally, super().__init(m,n+1) should be called. The extra empty column is  to fix the visual effect.
The last thing to remind, just ignore this extra column. Ignore it! No need any other specific codes for it. No any bad side effects have been found until now.
Feel free to post your reviews.

```<code>class KBWWTableModel(QtGui.QStandardItemModel):
    def __init__(self, parent: QtCore.QObject=None):
        # add a extra empty column to fix the visual effect
        # super().__init__(1, 3, parent=parent)
        super().__init__(1, 4, parent=parent)
</code>```

Body:
Solution: If there is a n-column table originally, super().__init(m,n+1) should be called. The extra empty column is  to fix the visual effect.
The last thing to remind, just ignore this extra column. Ignore it! No need any other specific codes for it. No any bad side effects have been found until now.
Feel free to post your reviews.

class KBWWTableModel(QtGui.QStandardItemModel):
    def __init__(self, parent: QtCore.QObject=None):
        # add a extra empty column to fix the visual effect
        # super().__init__(1, 3, parent=parent)
        super().__init__(1, 4, parent=parent)


问:
Handling Dollar Sign in Input numeric text
I'm running into an issue with my Python program.

In fact, I have a sales price input which can contain a dollar sign and must respect the following constraints :

It must be numeric

The sales price must be at least $100, including dollars and cents

The problem I'm facing is : if the user inputs a sales price including a dollar sign, how to "ignore" it in order to determine if the input is numeric ? The same issue applies when it comes to a decimal point.

Also, note that :

If the input is not a numeric entry, I would like it to prompt "price must be numeric".

If the entry is less than $100, I would like it to prompt "Price must be at least $100".

This is what I have so far :

```<code>salesPrice= input("What is the sales price of the new phone? ")

if salesPrice[0]=="$":
    val= int(salesPrice[1:])
    if val < 100
        print('Price must be at least $100')
    else:
        price=float(salesPrice[1:])
elif ValueError:
    print('Price must be numeric')
else:
    if salesPrice[0]!= '$':
        if salesPrice[0:]< Min_price:
        print('Price must be at least $100')
        else:
            price=float(salesPrice[0:])
</code>```

答:
I would separate two concerns: dealing $ sign and number logic, separately.

salesPrice= input("What is the sales price of the new phone? ")

# remove the optional $ sign
if salesPrice[0]=="$":
    salesPrice = salesPrice[1:]

# your number logic
...

```

Body:
I'm running into an issue with my Python program.

In fact, I have a sales price input which can contain a dollar sign and must respect the following constraints :

It must be numeric

The sales price must be at least $100, including dollars and cents

The problem I'm facing is : if the user inputs a sales price including a dollar sign, how to "ignore" it in order to determine if the input is numeric ? The same issue applies when it comes to a decimal point.

Also, note that :

If the input is not a numeric entry, I would like it to prompt "price must be numeric".

If the entry is less than $100, I would like it to prompt "Price must be at least $100".

This is what I have so far :

salesPrice= input("What is the sales price of the new phone? ")

if salesPrice[0]=="$":
    val= int(salesPrice[1:])
    if val < 100
        print('Price must be at least $100')
    else:
        price=float(salesPrice[1:])
elif ValueError:
    print('Price must be numeric')
else:
    if salesPrice[0]!= '$':
        if salesPrice[0:]< Min_price:
        print('Price must be at least $100')
        else:
            price=float(salesPrice[0:])


问:
iOS simulator looking fuzzy and pixelated
After upgrading to Xcode 7.2 the iOS simulator looks fuzzy and pixelated. The simulator version is 9.2.

Simulator Screenshot:

答: Showing on external non-retina display may also seem fuzzy.


问:
Spring Security : Add custom message for authentication failure ( "Bad Credentials" to "Invalid Credentials")
```<code>Authentication authentication = authenticationManager.authenticate(
    new UsernamePasswordAuthenticationToken(
        loginRequest.getUserName(),
        loginRequest.getPassword()
    )
);
</code>```

Currently the response is like below:

```<code>{
  "timestamp": "2020-05-30T17:50:38.307+0000",
  "message": "Bad credentials",
  "details": "uri=/auth"
}
</code>```

I want this to be like this:

```<code>{
  "timestamp": "2020-05-30T17:50:38.307+0000",
  "message": "Invalid credentials",
  "details": "uri=/auth"
}
</code>```

答:
Spring Security uses the messages.properties which consist of default messages, we can add our custom message with the same. Add messages.properties and add a message as shown below.

messages.properties

```<code>AbstractUserDetailsAuthenticationProvider.badCredentials=Invalid credentials
</code>```

Defaults

```<code>AbstractAccessDecisionManager.accessDenied=Access is denied
AbstractLdapAuthenticationProvider.emptyPassword=Empty Password
AbstractSecurityInterceptor.authenticationNotFound=An Authentication object was not found in the SecurityContext
AbstractUserDetailsAuthenticationProvider.badCredentials=Bad credentials
AbstractUserDetailsAuthenticationProvider.credentialsExpired=User credentials have expired
AbstractUserDetailsAuthenticationProvider.disabled=User is disabled
AbstractUserDetailsAuthenticationProvider.expired=User account has expired
AbstractUserDetailsAuthenticationProvider.locked=User account is locked
AbstractUserDetailsAuthenticationProvider.onlySupports=Only UsernamePasswordAuthenticationToken is supported
AccountStatusUserDetailsChecker.credentialsExpired=User credentials have expired
AccountStatusUserDetailsChecker.disabled=User is disabled
AccountStatusUserDetailsChecker.expired=User account has expired
AccountStatusUserDetailsChecker.locked=User account is locked
AclEntryAfterInvocationProvider.noPermission=Authentication {0} has NO permissions to the domain object {1}
AnonymousAuthenticationProvider.incorrectKey=The presented AnonymousAuthenticationToken does not contain the expected key
BindAuthenticator.badCredentials=Bad credentials
BindAuthenticator.emptyPassword=Empty Password
CasAuthenticationProvider.incorrectKey=The presented CasAuthenticationToken does not contain the expected key
CasAuthenticationProvider.noServiceTicket=Failed to provide a CAS service ticket to validate
ConcurrentSessionControlAuthenticationStrategy.exceededAllowed=Maximum sessions of {0} for this principal exceeded
DigestAuthenticationFilter.incorrectRealm=Response realm name {0} does not match system realm name of {1}
DigestAuthenticationFilter.incorrectResponse=Incorrect response
DigestAuthenticationFilter.missingAuth=Missing mandatory digest value for 'auth' QOP; received header {0}
DigestAuthenticationFilter.missingMandatory=Missing mandatory digest value; received header {0}
DigestAuthenticationFilter.nonceCompromised=Nonce token compromised {0}
DigestAuthenticationFilter.nonceEncoding=Nonce is not encoded in Base64; received nonce {0}
DigestAuthenticationFilter.nonceExpired=Nonce has expired/timed out
DigestAuthenticationFilter.nonceNotNumeric=Nonce token should have yielded a numeric first token, but was {0}
DigestAuthenticationFilter.nonceNotTwoTokens=Nonce should have yielded two tokens but was {0}
DigestAuthenticationFilter.usernameNotFound=Username {0} not found
JdbcDaoImpl.noAuthority=User {0} has no GrantedAuthority
JdbcDaoImpl.notFound=User {0} not found
LdapAuthenticationProvider.badCredentials=Bad credentials
LdapAuthenticationProvider.badLdapConnection=Connection to LDAP server failed
LdapAuthenticationProvider.credentialsExpired=User credentials have expired
LdapAuthenticationProvider.disabled=User is disabled
LdapAuthenticationProvider.expired=User account has expired
LdapAuthenticationProvider.locked=User account is locked
LdapAuthenticationProvider.emptyUsername=Empty username not allowed
LdapAuthenticationProvider.onlySupports=Only UsernamePasswordAuthenticationToken is supported
PasswordComparisonAuthenticator.badCredentials=Bad credentials
PersistentTokenBasedRememberMeServices.cookieStolen=Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack.
ProviderManager.providerNotFound=No AuthenticationProvider found for {0}
RememberMeAuthenticationProvider.incorrectKey=The presented RememberMeAuthenticationToken does not contain the expected key
RunAsImplAuthenticationProvider.incorrectKey=The presented RunAsUserToken does not contain the expected key
SubjectDnX509PrincipalExtractor.noMatching=No matching pattern was found in subjectDN: {0}
SwitchUserFilter.noCurrentUser=No current user associated with this request
SwitchUserFilter.noOriginalAuthentication=Could not find original Authentication object
</code>```

Body:
Authentication authentication = authenticationManager.authenticate(
    new UsernamePasswordAuthenticationToken(
        loginRequest.getUserName(),
        loginRequest.getPassword()
    )
);

Currently the response is like below:

{
  "timestamp": "2020-05-30T17:50:38.307+0000",
  "message": "Bad credentials",
  "details": "uri=/auth"
}

I want this to be like this:

{
  "timestamp": "2020-05-30T17:50:38.307+0000",
  "message": "Invalid credentials",
  "details": "uri=/auth"
}

Body:
Spring Security uses the messages.properties which consist of default messages, we can add our custom message with the same. Add messages.properties and add a message as shown below.

messages.properties

AbstractUserDetailsAuthenticationProvider.badCredentials=Invalid credentials

Defaults

AbstractAccessDecisionManager.accessDenied=Access is denied
AbstractLdapAuthenticationProvider.emptyPassword=Empty Password
AbstractSecurityInterceptor.authenticationNotFound=An Authentication object was not found in the SecurityContext
AbstractUserDetailsAuthenticationProvider.badCredentials=Bad credentials
AbstractUserDetailsAuthenticationProvider.credentialsExpired=User credentials have expired
AbstractUserDetailsAuthenticationProvider.disabled=User is disabled
AbstractUserDetailsAuthenticationProvider.expired=User account has expired
AbstractUserDetailsAuthenticationProvider.locked=User account is locked
AbstractUserDetailsAuthenticationProvider.onlySupports=Only UsernamePasswordAuthenticationToken is supported
AccountStatusUserDetailsChecker.credentialsExpired=User credentials have expired
AccountStatusUserDetailsChecker.disabled=User is disabled
AccountStatusUserDetailsChecker.expired=User account has expired
AccountStatusUserDetailsChecker.locked=User account is locked
AclEntryAfterInvocationProvider.noPermission=Authentication {0} has NO permissions to the domain object {1}
AnonymousAuthenticationProvider.incorrectKey=The presented AnonymousAuthenticationToken does not contain the expected key
BindAuthenticator.badCredentials=Bad credentials
BindAuthenticator.emptyPassword=Empty Password
CasAuthenticationProvider.incorrectKey=The presented CasAuthenticationToken does not contain the expected key
CasAuthenticationProvider.noServiceTicket=Failed to provide a CAS service ticket to validate
ConcurrentSessionControlAuthenticationStrategy.exceededAllowed=Maximum sessions of {0} for this principal exceeded
DigestAuthenticationFilter.incorrectRealm=Response realm name {0} does not match system realm name of {1}
DigestAuthenticationFilter.incorrectResponse=Incorrect response
DigestAuthenticationFilter.missingAuth=Missing mandatory digest value for 'auth' QOP; received header {0}
DigestAuthenticationFilter.missingMandatory=Missing mandatory digest value; received header {0}
DigestAuthenticationFilter.nonceCompromised=Nonce token compromised {0}
DigestAuthenticationFilter.nonceEncoding=Nonce is not encoded in Base64; received nonce {0}
DigestAuthenticationFilter.nonceExpired=Nonce has expired/timed out
DigestAuthenticationFilter.nonceNotNumeric=Nonce token should have yielded a numeric first token, but was {0}
DigestAuthenticationFilter.nonceNotTwoTokens=Nonce should have yielded two tokens but was {0}
DigestAuthenticationFilter.usernameNotFound=Username {0} not found
JdbcDaoImpl.noAuthority=User {0} has no GrantedAuthority
JdbcDaoImpl.notFound=User {0} not found
LdapAuthenticationProvider.badCredentials=Bad credentials
LdapAuthenticationProvider.badLdapConnection=Connection to LDAP server failed
LdapAuthenticationProvider.credentialsExpired=User credentials have expired
LdapAuthenticationProvider.disabled=User is disabled
LdapAuthenticationProvider.expired=User account has expired
LdapAuthenticationProvider.locked=User account is locked
LdapAuthenticationProvider.emptyUsername=Empty username not allowed
LdapAuthenticationProvider.onlySupports=Only UsernamePasswordAuthenticationToken is supported
PasswordComparisonAuthenticator.badCredentials=Bad credentials
PersistentTokenBasedRememberMeServices.cookieStolen=Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack.
ProviderManager.providerNotFound=No AuthenticationProvider found for {0}
RememberMeAuthenticationProvider.incorrectKey=The presented RememberMeAuthenticationToken does not contain the expected key
RunAsImplAuthenticationProvider.incorrectKey=The presented RunAsUserToken does not contain the expected key
SubjectDnX509PrincipalExtractor.noMatching=No matching pattern was found in subjectDN: {0}
SwitchUserFilter.noCurrentUser=No current user associated with this request
SwitchUserFilter.noOriginalAuthentication=Could not find original Authentication object


问:
Kafka-consumer. commitSync vs commitAsync
The quote from https://www.safaribooksonline.com/library/view/kafka-the-definitive/9781491936153/ch04.html#callout_kafka_consumers__reading_data_from_kafka_CO2-1

The drawback is that while commitSync() will retry the commit until it
  either succeeds or encounters a non-retriable failure, commitAsync()
  will not retry.

This phrase is not clear to me. I suppose that consumer sends commit request to broker and in case if the broker doesn't respond within some timeout it means that the commit failed. Am I wrong?

Can you clarify the difference of commitSync  and commitAsync in details?

Also, please provide use cases when which commit type should I prefer.

答:
commitAync will not retry because if it retries it will make a mess.

Imagine that you are trying to commit offset 20 (async), and it did not commit (failed), and then the next poll block tries to commit the offset 40 (async), and it succeeded.

Now, commit offset 20 is still waiting to commit, if it reties and succeed it will make a mess.

The mess is that the committed offset should be 40 not 20.


问:
Make My Raspberry Pi Live Stream Online With A Permanent Address
I have successfully made a live video stream using raspberry pi3
Following this tutorial

https://github.com/Arijit1080/Live-Video-Stream-from-Raspberry-Pi-Camera-over-the-Network

And it works. What i want to do is make this availble from any where in the world. Is there any idea to do so. Currently i have to set my IP address every time i need to start streaming as it changes frequently.

Thanks In Advance

答:
I found a solution Using Dataplicity.
Dataplicity can be used easily for this.  Installing Dataplicity in our pi and configure it. We get a permanent  web url for our raspberry pi. They provide a wormhole service and by enabling it we can stream live video from anywhere in the world without even coding!</p>


问:
Returning value from asynchronous JavaScript method?
I have run into a problem where I can't seem to get a value from an asynchronous JavaScript method I am running in Jquery. My Jquery looks like this:

```<code>$(document).ready( function() {
$('#splash_image_upload').change( function() {
    var file = this.files[0];
    var blob_string = create_blob(file);
    alert(blob_string);
 });
</code>```

I am able to access the value that comes from the 'onload' event but I cannot seem to return the actual value. I have tried this:`

```<code>function create_blob(file) {
    var reader = new FileReader();
    reader.onload = (function() { return function(e) { return e.target.result; }; })();
    reader.readAsDataURL(file);
}
</code>```

Every time I execute this function the value of the 'blob_str' variable is 'undefined' presumably because the assignment is done before the function is finished. I am not really sure how to go about this. Is there a way I can return this value from this function??

答:
This is the issue with callbacks. The 'answer' is going to happen later in another moment and not during the evaluation of the method. Little use making a return here.

Your callback needs to handle the return value making the code looks more complicated :

```<code>reader.onload = function(e) {
  // handle here the result
  // do something with e.target.result
};
</code>```

Body:
I have run into a problem where I can't seem to get a value from an asynchronous JavaScript method I am running in Jquery. My Jquery looks like this:

$(document).ready( function() {
$('#splash_image_upload').change( function() {
    var file = this.files[0];
    var blob_string = create_blob(file);
    alert(blob_string);
 });

I am able to access the value that comes from the 'onload' event but I cannot seem to return the actual value. I have tried this:`

function create_blob(file) {
    var reader = new FileReader();
    reader.onload = (function() { return function(e) { return e.target.result; }; })();
    reader.readAsDataURL(file);
}

Every time I execute this function the value of the 'blob_str' variable is 'undefined' presumably because the assignment is done before the function is finished. I am not really sure how to go about this. Is there a way I can return this value from this function??

Body:
This is the issue with callbacks. The 'answer' is going to happen later in another moment and not during the evaluation of the method. Little use making a return here.

Your callback needs to handle the return value making the code looks more complicated :

reader.onload = function(e) {
  // handle here the result
  // do something with e.target.result
};


问:
Consider defining a bean of type 'package' in your configuration [Spring-Boot]
I am getting the following error:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method setApplicant in webService.controller.RequestController required a bean of type 'com.service.applicant.Applicant' that could not be found.

Action:

Consider defining a bean of type 'com.service.applicant.Applicant' in your configuration.
</code>```

I have never seen this error before but it's odd that the @Autowire is not working. Here is the project structure:

Applicant Interface

```<code>public interface Applicant {

    TApplicant findBySSN(String ssn) throws ServletException;

    void deleteByssn(String ssn) throws ServletException;

    void createApplicant(TApplicant tApplicant) throws ServletException;

    void updateApplicant(TApplicant tApplicant) throws ServletException;

    List<TApplicant> getAllApplicants() throws ServletException;
}
</code>```

ApplicantImpl

```<code>@Service
@Transactional
public class ApplicantImpl implements Applicant {

private static Log log = LogFactory.getLog(ApplicantImpl.class);

    private TApplicantRepository applicantRepo;

@Override
    public List<TApplicant> getAllApplicants() throws ServletException {

        List<TApplicant> applicantList = applicantRepo.findAll();

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

Now I should be able to just Autowire Applicant and be able to access, however in this case it is not working when I call it in my @RestController:

```<code>@RestController
public class RequestController extends LoggingAware {

    private Applicant applicant;

    @Autowired
    public void setApplicant(Applicant applicant){
        this.applicant = applicant;
    }

    @RequestMapping(value="/", method = RequestMethod.GET)
    public String helloWorld() {

        try {
            List<TApplicant> applicantList = applicant.getAllApplicants();

            for (TApplicant tApplicant : applicantList){
                System.out.println("Name: "+tApplicant.getIndivName()+" SSN "+tApplicant.getIndSsn());
            }

            return "home";
        }
        catch (ServletException e) {
            e.printStackTrace();
        }

        return "error";
    }

}
</code>```

------------------------UPDATE 1-----------------------

I added

```<code>@SpringBootApplication
@ComponentScan("module-service")
public class WebServiceApplication extends SpringBootServletInitializer {

    @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(WebServiceApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(WebServiceApplication.class, args);
    }

}
</code>```

and the error went away but nothing happened. However when I commented out everything dealing with Applicant in the RestController prior to adding @ComponentScan() I was able to return a string the UI, thus meaning my RestController was working, now it is being skipped. I ugly Whitelabel Error Page now.

---------------------UPDATE 2------------------------------

I added the base package of the bean it was complaining about. Error reads:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method setApplicantRepo in com.service.applicant.ApplicantImpl required a bean of type 'com.delivery.service.request.repository.TApplicantRepository' that could not be found.

Action:

Consider defining a bean of type 'com.delivery.request.request.repository.TApplicantRepository' in your configuration.
</code>```

I added @ComponentScan

```<code>@SpringBootApplication
@ComponentScan({"com.delivery.service","com.delivery.request"})
public class WebServiceApplication extends SpringBootServletInitializer {

    @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(WebServiceApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(WebServiceApplication.class, args);
    }

}
</code>```

----------------------------Update 3----------------------

adding:

```<code>@SpringBootApplication
@ComponentScan("com")
public class WebServiceApplication extends SpringBootServletInitializer {
</code>```

still is complaining about my ApplicantImpl class which @Autowires my repo TApplicantRepository into it.

答:
I faced the same issue. Mongo DB repository was identified by Spring boot, but it was not creating Bean for a repository interface that extended the mongo repository.

The issue in my case was incorrect version specification in maven pom for "spring + mango". I have changed the artifact's group id and it all worked like magic. no annotations needed as spring boot took care of everything.

During my problem resolution, I was all over web searching for solutions and realized that this problem is actually project configuration related, anyone facing this issue should first check their project setup and enable debug from spring to get more details on failure and pay close attention to where exactly in the process, the creation has failed.

Body:
I am getting the following error:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method setApplicant in webService.controller.RequestController required a bean of type 'com.service.applicant.Applicant' that could not be found.

Action:

Consider defining a bean of type 'com.service.applicant.Applicant' in your configuration.

I have never seen this error before but it's odd that the @Autowire is not working. Here is the project structure:

Applicant Interface

public interface Applicant {

    TApplicant findBySSN(String ssn) throws ServletException;

    void deleteByssn(String ssn) throws ServletException;

    void createApplicant(TApplicant tApplicant) throws ServletException;

    void updateApplicant(TApplicant tApplicant) throws ServletException;

    List<TApplicant> getAllApplicants() throws ServletException;
}

ApplicantImpl

@Service
@Transactional
public class ApplicantImpl implements Applicant {

private static Log log = LogFactory.getLog(ApplicantImpl.class);

    private TApplicantRepository applicantRepo;

@Override
    public List<TApplicant> getAllApplicants() throws ServletException {

        List<TApplicant> applicantList = applicantRepo.findAll();

        return applicantList;
    }
}

Now I should be able to just Autowire Applicant and be able to access, however in this case it is not working when I call it in my @RestController:

@RestController
public class RequestController extends LoggingAware {

    private Applicant applicant;

    @Autowired
    public void setApplicant(Applicant applicant){
        this.applicant = applicant;
    }

    @RequestMapping(value="/", method = RequestMethod.GET)
    public String helloWorld() {

        try {
            List<TApplicant> applicantList = applicant.getAllApplicants();

            for (TApplicant tApplicant : applicantList){
                System.out.println("Name: "+tApplicant.getIndivName()+" SSN "+tApplicant.getIndSsn());
            }

            return "home";
        }
        catch (ServletException e) {
            e.printStackTrace();
        }

        return "error";
    }

}

------------------------UPDATE 1-----------------------

I added

@SpringBootApplication
@ComponentScan("module-service")
public class WebServiceApplication extends SpringBootServletInitializer {

    @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(WebServiceApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(WebServiceApplication.class, args);
    }

}

and the error went away but nothing happened. However when I commented out everything dealing with Applicant in the RestController prior to adding @ComponentScan() I was able to return a string the UI, thus meaning my RestController was working, now it is being skipped. I ugly Whitelabel Error Page now.

---------------------UPDATE 2------------------------------

I added the base package of the bean it was complaining about. Error reads:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method setApplicantRepo in com.service.applicant.ApplicantImpl required a bean of type 'com.delivery.service.request.repository.TApplicantRepository' that could not be found.

Action:

Consider defining a bean of type 'com.delivery.request.request.repository.TApplicantRepository' in your configuration.

I added @ComponentScan

@SpringBootApplication
@ComponentScan({"com.delivery.service","com.delivery.request"})
public class WebServiceApplication extends SpringBootServletInitializer {

    @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(WebServiceApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(WebServiceApplication.class, args);
    }

}

----------------------------Update 3----------------------

adding:

@SpringBootApplication
@ComponentScan("com")
public class WebServiceApplication extends SpringBootServletInitializer {

still is complaining about my ApplicantImpl class which @Autowires my repo TApplicantRepository into it.


问:
Way to achieve overlapping GROUP BY groups with correct subtotals in Clickhouse
Assuming following schema:

CREATE TABLE test
(
    date Date,
    user_id UInt32,
    user_answer UInt8,
    user_multi_choice_answer Array(UInt8),
    events UInt32
)
ENGINE = MergeTree() ORDER BY date;
```

<p>And contents:</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO test VALUES
  ('2020-01-01', 1, 5, [2, 3], 15),
  ('2020-01-01', 2, 6, [1, 2], 7);
</code>```

Let's say I want to make a query "give me # of users and # of their events grouped by date and user_answer, with subtotals". That's easy:

select date, user_answer, count(distinct user_id), sum(events) from test group by date, user_answer with rollup;
┌───────date─┬─user_answer─┬─uniqExact(user_id)─┬─sum(events)─┐
│ 2020-01-01 │           5 │                  1 │          15 │
│ 2020-01-01 │           6 │                  1 │           7 │
│ 2020-01-01 │           0 │                  2 │          22 │
│ 0000-00-00 │           0 │                  2 │          22 │
└────────────┴─────────────┴────────────────────┴─────────────┘
```

<p>What I can't easily do is making queries with overlapping groups, like when grouping by invidivual options of multiple choice question. For example:</p>

<ul>
<li># of users and # of their events grouped by date and user_multi_choice_answer, with subtotals</li>
<li># of users and # of their events grouped by arbitrary hand-written grouping conditions, like "compare users with user_answer=5 and has(user_multi_choice_answer, 1) to users with has(user_multi_choice_answer, 2)"</li>
</ul>

<p>For example, with the first query, I would like to see the following:</p>

<pre class="lang-sql prettyprint-override"><code>┌───────date─┬─user_multi_choice_answer─┬─uniqExact(user_id)─┬─sum(events)─┐
│ 2020-01-01 │                        1 │                  1 │          15 │
│ 2020-01-01 │                        2 │                  2 │          22 │
│ 2020-01-01 │                        3 │                  1 │           7 │
│ 2020-01-01 │                        0 │                  2 │          22 │
│ 0000-00-00 │                        0 │                  2 │          22 │
└────────────┴──────────────────────────┴────────────────────┴─────────────┘
</code>```

And for the second:

┌─my_grouping_id─┬─uniqExact(user_id)─┬─sum(events)─┐
│              1 │                  1 │          15 │ # users fulfilling arbitrary condition #1
│              2 │                  2 │          22 │ # users fulfilling arbitrary condition #2
│              0 │                  2 │          22 │ # subtotal
└────────────────┴────────────────────┴─────────────┘
```

<p>The closest I can get to that is by using <code>arrayJoin()</code>:</p>

<pre class="lang-sql prettyprint-override"><code>select date, arrayJoin(user_multi_choice_answer) as multi_answer, count(distinct user_id), sum(events)
from test group by date, multi_answer with rollup;

select arrayJoin(
  arrayConcat(
    if(user_answer=5 and has(user_multi_choice_answer, 3), [1], []),
    if(has(user_multi_choice_answer, 2), [2], [])
  )
) as my_grouping_id, count(distinct user_id), sum(events)
from test group by my_grouping_id with rollup;
</code>```

But that's not a good solution for two reasons:

While it calculates correct results for grouping, the result for sum(events) is not correct for subtotals (as duplicated rows count multiple times)

It doesn't seem efficient, as it makes a lot of data duplication (while I just want the same row to get aggregated into several groups)

So, again, I'm looking for a way that would allow me to easily make grouping of answers to multiple choice questions and gropings by arbitrary conditions on some columns. I'm okay with changing the schema to make that possible, but I'm mostly hoping Clickhouse has a built-in way to achieve that.

答:
While it calculates correct results for grouping, the result for sum(events) is not correct for subtotals (as duplicated rows count multiple times)

You can manually create my_grouping_id = 0 without using rollup. For example,

select arrayJoin(
  arrayConcat(
    [0],
    if(user_answer=5 and has(user_multi_choice_answer, 3), [1], []),
    if(has(user_multi_choice_answer, 2), [2], [])
  )
) as my_grouping_id, count(distinct user_id), sum(events)
from test group by my_grouping_id
```

It doesn't seem efficient, as it makes a lot of data duplication (while I just want the same row to get aggregated into several groups)

Currently it's not possible. But I see possibilities. I'll try to make a POC of GROUP BY ARRAY. It seems to be a valid use case.

Body:
Assuming following schema:

CREATE TABLE test
(
    date Date,
    user_id UInt32,
    user_answer UInt8,
    user_multi_choice_answer Array(UInt8),
    events UInt32
)
ENGINE = MergeTree() ORDER BY date;

And contents:

INSERT INTO test VALUES
  ('2020-01-01', 1, 5, [2, 3], 15),
  ('2020-01-01', 2, 6, [1, 2], 7);

Let's say I want to make a query "give me # of users and # of their events grouped by date and user_answer, with subtotals". That's easy:

select date, user_answer, count(distinct user_id), sum(events) from test group by date, user_answer with rollup;
┌───────date─┬─user_answer─┬─uniqExact(user_id)─┬─sum(events)─┐
│ 2020-01-01 │           5 │                  1 │          15 │
│ 2020-01-01 │           6 │                  1 │           7 │
│ 2020-01-01 │           0 │                  2 │          22 │
│ 0000-00-00 │           0 │                  2 │          22 │
└────────────┴─────────────┴────────────────────┴─────────────┘

What I can't easily do is making queries with overlapping groups, like when grouping by invidivual options of multiple choice question. For example:

# of users and # of their events grouped by date and user_multi_choice_answer, with subtotals

# of users and # of their events grouped by arbitrary hand-written grouping conditions, like "compare users with user_answer=5 and has(user_multi_choice_answer, 1) to users with has(user_multi_choice_answer, 2)"

For example, with the first query, I would like to see the following:

┌───────date─┬─user_multi_choice_answer─┬─uniqExact(user_id)─┬─sum(events)─┐
│ 2020-01-01 │                        1 │                  1 │          15 │
│ 2020-01-01 │                        2 │                  2 │          22 │
│ 2020-01-01 │                        3 │                  1 │           7 │
│ 2020-01-01 │                        0 │                  2 │          22 │
│ 0000-00-00 │                        0 │                  2 │          22 │
└────────────┴──────────────────────────┴────────────────────┴─────────────┘

And for the second:

┌─my_grouping_id─┬─uniqExact(user_id)─┬─sum(events)─┐
│              1 │                  1 │          15 │ # users fulfilling arbitrary condition #1
│              2 │                  2 │          22 │ # users fulfilling arbitrary condition #2
│              0 │                  2 │          22 │ # subtotal
└────────────────┴────────────────────┴─────────────┘

The closest I can get to that is by using arrayJoin():

select date, arrayJoin(user_multi_choice_answer) as multi_answer, count(distinct user_id), sum(events)
from test group by date, multi_answer with rollup;

select arrayJoin(
  arrayConcat(
    if(user_answer=5 and has(user_multi_choice_answer, 3), [1], []),
    if(has(user_multi_choice_answer, 2), [2], [])
  )
) as my_grouping_id, count(distinct user_id), sum(events)
from test group by my_grouping_id with rollup;

But that's not a good solution for two reasons:

While it calculates correct results for grouping, the result for sum(events) is not correct for subtotals (as duplicated rows count multiple times)

It doesn't seem efficient, as it makes a lot of data duplication (while I just want the same row to get aggregated into several groups)

So, again, I'm looking for a way that would allow me to easily make grouping of answers to multiple choice questions and gropings by arbitrary conditions on some columns. I'm okay with changing the schema to make that possible, but I'm mostly hoping Clickhouse has a built-in way to achieve that.

Body:
While it calculates correct results for grouping, the result for sum(events) is not correct for subtotals (as duplicated rows count multiple times)

You can manually create my_grouping_id = 0 without using rollup. For example,

select arrayJoin(
  arrayConcat(
    [0],
    if(user_answer=5 and has(user_multi_choice_answer, 3), [1], []),
    if(has(user_multi_choice_answer, 2), [2], [])
  )
) as my_grouping_id, count(distinct user_id), sum(events)
from test group by my_grouping_id

It doesn't seem efficient, as it makes a lot of data duplication (while I just want the same row to get aggregated into several groups)

Currently it's not possible. But I see possibilities. I'll try to make a POC of GROUP BY ARRAY. It seems to be a valid use case.


问:
Trying to add a '[RCTVirtualText 507]' to a '[RCTView 509]')?
I had been developing my app for Web, and it has been working properly. However, when I ran the same app within Expo / Android, I got this error. Hard to know what it is about from the description.

This is the full error message:

```<code>Cannot add a child that doesn't have a YogaNode to a parent without a measure function! (Trying to add a '[RCTVirtualText 507]' to a '[RCTView 509]')
</code>```

Do you know what it could possibly be?

This seems to be the js file that is triggering it:

```<code>...
export class SubjectListAssignScreen extends React.Component {

    state = {

        subjectList: [],

        subListLoading: true,

    };

    constructor(props) {
        super(props);
    };

    scrollDimensions = [{
        width: Math.round(Dimensions.get('window').width - 20),
        maxHeight: Math.round(Dimensions.get('window').height - 200)
    }];
...
    _getSubjects = async(text) => {

        try {

            await this.setState({ subListLoading: true });

            let lQueryRes = await API.graphql(graphqlOperation(cqueries.listSubjectsCustom, {}));

            await console.log('==> Subjects Query');
            await console.log(lQueryRes);

            await this.setState({ subjectList: lQueryRes.data.listSubjects.items });

            await this.setState({ subListLoading: false });

        }
        catch (e) {

            console.log("==> DB Error");
            console.log(e);

            await this.setState({ subListLoading: false });

        };
    };

...
 _subjectItems = (value) => {

        console.log(value.desc);

        let lnum = (typeof value["num"] !== 'undefined') ? value["num"].toString() : null;
        let desc = value["desc"].toString();
        let lastName = (typeof value["users"][0] !== 'undefined') ? value["users"][0]["lastname"].toString() : null;
        let ltype = value["type"].toString();

        return (
            <DataTable.Row onPress={() => {
                this.props.navigation.navigate("UserListScreen", {pnum: lnum, ptype: ltype});
            }}>
                <DataTable.Cell>
                    {this._getTypeIcon(ltype)}
                </DataTable.Cell>
                <DataTable.Cell>
                    <Text>{desc}</Text>
                </DataTable.Cell>
                <DataTable.Cell>
                    <Text>{ lastName }</Text>
                </DataTable.Cell>
            </DataTable.Row>
        );
    };

    async componentDidMount() {
        try {
            await this._getSubjects();
        }
        catch (e) {
            console.log("==> componentDidMount error");
            console.log(e);
        };
    };

    isCloseToBottom = ({ layoutMeasurement, contentOffset, contentSize }) => {
        const paddingToBottom = 20;
        return layoutMeasurement.height + contentOffset.y >=
            contentSize.height - paddingToBottom;
    };

    fetchMore = () => {

    };

    render() {

        let sDimensions = this.scrollDimensions;

        return (

            <View style={{flex:20, margin:4, flexDirection:"column", justifyContent:"flex-start"}}>
    <Title style={{flex:1}}>Lista de Demandas</Title>
    <SafeAreaView style={[{flex:19, }, sDimensions]}>
        <ScrollView
            contentContainerStyle={{}}
            onScroll={({nativeEvent}) => {
            if (this.isCloseToBottom(nativeEvent)) {
                this.fetchMore();
            }}}
            >
            <DataTable>
                <DataTable.Header>
                    <DataTable.Title>Type</DataTable.Title>
                    <DataTable.Title>Subj</DataTable.Title>
                    <DataTable.Title>Resp.</DataTable.Title>
                </DataTable.Header>

                { !this.state.subListLoading ?
                    <FlatList
                        data={this.state.subjectList}
                        renderItem={({item})=>this._subjectItems(item)}
                        keyExtractor={item => item.desc}
                    />
                    :
                    <ActivityIndicator />
                }

            </DataTable>
        </ScrollView>

    </SafeAreaView>
</View>
        )
    }
}
</code>```

Using Expo 37, React Native paper and AWS Amplify.

答: As I had such a hard time trying to find which components were not compatible, I simply dropped my full development environment, create a clean one and pulled the latest commit again, checking all components version by version and making sure all of them were at the -g version. The error has stopped after that.</p>

Body:
I had been developing my app for Web, and it has been working properly. However, when I ran the same app within Expo / Android, I got this error. Hard to know what it is about from the description.

This is the full error message:

Cannot add a child that doesn't have a YogaNode to a parent without a measure function! (Trying to add a '[RCTVirtualText 507]' to a '[RCTView 509]')

Do you know what it could possibly be?

This seems to be the js file that is triggering it:

...
export class SubjectListAssignScreen extends React.Component {

    state = {

        subjectList: [],

        subListLoading: true,

    };

    constructor(props) {
        super(props);
    };

    scrollDimensions = [{
        width: Math.round(Dimensions.get('window').width - 20),
        maxHeight: Math.round(Dimensions.get('window').height - 200)
    }];
...
    _getSubjects = async(text) => {

        try {

            await this.setState({ subListLoading: true });

            let lQueryRes = await API.graphql(graphqlOperation(cqueries.listSubjectsCustom, {}));

            await console.log('==> Subjects Query');
            await console.log(lQueryRes);

            await this.setState({ subjectList: lQueryRes.data.listSubjects.items });

            await this.setState({ subListLoading: false });

        }
        catch (e) {

            console.log("==> DB Error");
            console.log(e);

            await this.setState({ subListLoading: false });

        };
    };

...
 _subjectItems = (value) => {

        console.log(value.desc);

        let lnum = (typeof value["num"] !== 'undefined') ? value["num"].toString() : null;
        let desc = value["desc"].toString();
        let lastName = (typeof value["users"][0] !== 'undefined') ? value["users"][0]["lastname"].toString() : null;
        let ltype = value["type"].toString();

        return (
            <DataTable.Row onPress={() => {
                this.props.navigation.navigate("UserListScreen", {pnum: lnum, ptype: ltype});
            }}>
                <DataTable.Cell>
                    {this._getTypeIcon(ltype)}
                </DataTable.Cell>
                <DataTable.Cell>
                    <Text>{desc}</Text>
                </DataTable.Cell>
                <DataTable.Cell>
                    <Text>{ lastName }</Text>
                </DataTable.Cell>
            </DataTable.Row>
        );
    };

    async componentDidMount() {
        try {
            await this._getSubjects();
        }
        catch (e) {
            console.log("==> componentDidMount error");
            console.log(e);
        };
    };

    isCloseToBottom = ({ layoutMeasurement, contentOffset, contentSize }) => {
        const paddingToBottom = 20;
        return layoutMeasurement.height + contentOffset.y >=
            contentSize.height - paddingToBottom;
    };

    fetchMore = () => {

    };

    render() {

        let sDimensions = this.scrollDimensions;

        return (

            <View style={{flex:20, margin:4, flexDirection:"column", justifyContent:"flex-start"}}>
    <Title style={{flex:1}}>Lista de Demandas</Title>
    <SafeAreaView style={[{flex:19, }, sDimensions]}>
        <ScrollView
            contentContainerStyle={{}}
            onScroll={({nativeEvent}) => {
            if (this.isCloseToBottom(nativeEvent)) {
                this.fetchMore();
            }}}
            >
            <DataTable>
                <DataTable.Header>
                    <DataTable.Title>Type</DataTable.Title>
                    <DataTable.Title>Subj</DataTable.Title>
                    <DataTable.Title>Resp.</DataTable.Title>
                </DataTable.Header>

                { !this.state.subListLoading ?
                    <FlatList
                        data={this.state.subjectList}
                        renderItem={({item})=>this._subjectItems(item)}
                        keyExtractor={item => item.desc}
                    />
                    :
                    <ActivityIndicator />
                }

            </DataTable>
        </ScrollView>

    </SafeAreaView>
</View>
        )
    }
}

Using Expo 37, React Native paper and AWS Amplify.


问:
Calculate the standard deviation of a moving windows using 2d convolution
I am doing a image processing project.
I want to calculate the standard deviation of a silding window using 2d convolution. I can now calculate the mean, but I cannot find a way to calculate the standard deviation. Here is my code:

import torch
import numpy as np
import cv2
import matplotlib.pyplot as plt
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
torch.set_default_tensor_type('torch.cuda.FloatTensor')
testvideo=cv2.VideoCapture ("test.mp4")
if testvideo.isOpened():
    ret, frame = testvideo.read()
    if ret == True:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        imgarr=np.asarray(gray)
        #plt.imshow(imgarr,cmap="gray")
        imgtensor=torch.from_numpy(imgarr).float().to(device).unsqueeze(0).unsqueeze(0)
        print(imgtensor.device)
        #print(intensity.device)
        MeanConv=torch.nn.Conv2d(1, 1, kernel_size=100)
        kernel=(torch.ones(100,100)/10000).unsqueeze(0).unsqueeze(0)
        MeanConv.weight = torch.nn.Parameter(kernel)
        print(kernel)
        intensity=MeanConv(imgtensor)
        plt.imshow(intensity.squeeze(0).squeeze(0).detach().cpu().numpy(),cmap="gray")
        #for i in range(714):
            #for j in range(714):
                #intensity[i,j]=torch.mean(imgtensor[i:i+7,j:j+7])
                #sd[i,j]=torch.std(imgtensor[i:i+7,j:j+7])
        #x=(sd/intensity).cpu()
        #plt.imshow(x.numpy(),cmap="gray")
testvideo.release()
```

答:
I think it can be somehow like this:

mean (img) using convolution.

Subtract from the original image of p. 1

Calculate the square of each element.

By convolution we find the average, p. 3

Calculates the square root of the elements of p. 4


问:
How to use PageTransitionsBuilder when navigating to a different screen?
```<code>final builder = OpenUpwardsPageTransitionsBuilder();

Navigator.push(
  context,
  PageRouteBuilder(
    pageBuilder: (_, __, ___) => Page2(),
    transitionsBuilder: builder, // error
  ),
);
</code>```

What I understand is, I can only setup PageTransitionsBuilder inside a Theme, is there any way to use it inside Navigator?

答:
The most simple solution is a custom PageRouteBuilder:

```<code>class MyPageRouteBuilder<T> extends PageRouteBuilder<T> {
  final PageTransitionsBuilder pageTransitionsBuilder;

  MyPageRouteBuilder({
    @required RoutePageBuilder pageBuilder,
    @required this.pageTransitionsBuilder,
  }) : assert(pageTransitionsBuilder != null), super(pageBuilder: pageBuilder);

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    return pageTransitionsBuilder.buildTransitions(this, context, animation, secondaryAnimation, child);
  }
}
</code>```

Here only pageBuilder is passed to super() but you can add any named parameter that PageRouteBuilder accepts (like transitionDuration for example)

Now, you can use it with:

```<code>Navigator.of(context).push(
  MyPageRouteBuilder(
    pageBuilder: (ctx, a1, a2) => Page2(),
    pageTransitionsBuilder: OpenUpwardsPageTransitionsBuilder(),
  )
);
</code>```

Body:
final builder = OpenUpwardsPageTransitionsBuilder();

Navigator.push(
  context,
  PageRouteBuilder(
    pageBuilder: (_, __, ___) => Page2(),
    transitionsBuilder: builder, // error
  ),
);

What I understand is, I can only setup PageTransitionsBuilder inside a Theme, is there any way to use it inside Navigator?

Body:
The most simple solution is a custom PageRouteBuilder:

class MyPageRouteBuilder<T> extends PageRouteBuilder<T> {
  final PageTransitionsBuilder pageTransitionsBuilder;

  MyPageRouteBuilder({
    @required RoutePageBuilder pageBuilder,
    @required this.pageTransitionsBuilder,
  }) : assert(pageTransitionsBuilder != null), super(pageBuilder: pageBuilder);

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    return pageTransitionsBuilder.buildTransitions(this, context, animation, secondaryAnimation, child);
  }
}

Here only pageBuilder is passed to super() but you can add any named parameter that PageRouteBuilder accepts (like transitionDuration for example)

Now, you can use it with:

Navigator.of(context).push(
  MyPageRouteBuilder(
    pageBuilder: (ctx, a1, a2) => Page2(),
    pageTransitionsBuilder: OpenUpwardsPageTransitionsBuilder(),
  )
);


问:
Indented trace in C++
I want to develop indented trace for our large C++ code base that will be perticularly helpful for developers to find the issues. I want to have indented trace functionality. E.g Consider following code:-

```<code> void FunctionA()
{
     TR_ENTER("Function A");
     TR_PRINT("Dignostic message Function A");
     FunctionB(); // Call function B
}

 void FunctionB()
{
    TR_ENTER("Function B");
    TR_PRINT("Dignostic message Function B");
    FunctionC(); // Call function B
}

void FunctionC()
{
   TR_ENTER("Function C");
   TR_PRINT("Dignostic message Function C");
}
</code>```

As you can see the calls above are nested within each other. I want to generate trace log as shown below:

```<code>Function A - Start
Dignostic message Function A
     Function B - Start
     Dignostic message Function B
            Function C - Start
            Dignostic message Function C
            Function C - End
     Function B - End
Function A - End
</code>```

TR_ENTER and TR_PRINT are some macros that I have use as example. To say that the function start I have use TR_ENTER and for printing some dignostic messages I have used TR_PRINT.

As you can see traces for nested function call are indented within each other. May I know is there anything already available so that I could prevent myself to work on reinventing the wheel.

Thanks,
Omky

答:
You need to keep track of the call depth:

```<code>class trace_entry;

class trace_log {
public:
    trace_log() : depth_(0) { }

private:
    // noncopyable so we don't accidentally copy it
    trace_log(trace_log&);
    void operator=(trace_log);

    friend trace_entry;

    int depth_;
};

class trace_entry {
public:
    trace_entry(trace_log& log, const std::string& frame)
        : log_(log), frame_(frame) {
        std::cout << std::string(4 * log.depth_, ' ')
                  << "ENTER " << frame_ << std::endl;
        ++log_.depth_;
    }

    ~trace_entry() {
        --log_.depth_;
        std::cout << std::string(4 * log_.depth_, ' ')
                  << "EXIT " << frame_ << std::endl;
    }
private:
    // noncopyable so we don't accidentally copy it
    trace_entry(trace_entry&);
    void operator=(trace_entry);

    trace_log& log_;
    std::string frame_;
};
</code>```

Usage example:

```<code>void a(trace_log& log) {
    trace_entry e(log, "a");
}

void b(trace_log& log) {
    trace_entry e(log, "b");
    return a(log);
}

int main() {
    trace_log log;
    trace_entry e(log, "main");
    b(log);
}
</code>```

Output:

```<code>ENTER main
    ENTER b
        ENTER a
        EXIT a
    EXIT b
EXIT main
</code>```

This is easily extensible to support alternative forms of logging, allowing additional log messages, and just about anything else you want to do.  (It would be far better to have the trace_log actually perform the logging, but for exposition purposes, this is the simplest way to demonstrate what you are trying to do.)

Title: Indented trace in C++

Body:
I want to develop indented trace for our large C++ code base that will be perticularly helpful for developers to find the issues. I want to have indented trace functionality. E.g Consider following code:-

 void FunctionA()
{
     TR_ENTER("Function A");
     TR_PRINT("Dignostic message Function A");
     FunctionB(); // Call function B
}

 void FunctionB()
{
    TR_ENTER("Function B");
    TR_PRINT("Dignostic message Function B");
    FunctionC(); // Call function B
}

void FunctionC()
{
   TR_ENTER("Function C");
   TR_PRINT("Dignostic message Function C");
}

As you can see the calls above are nested within each other. I want to generate trace log as shown below:

Function A - Start
Dignostic message Function A
     Function B - Start
     Dignostic message Function B
            Function C - Start
            Dignostic message Function C
            Function C - End
     Function B - End
Function A - End

TR_ENTER and TR_PRINT are some macros that I have use as example. To say that the function start I have use TR_ENTER and for printing some dignostic messages I have used TR_PRINT.

As you can see traces for nested function call are indented within each other. May I know is there anything already available so that I could prevent myself to work on reinventing the wheel.

Thanks,
Omky

Body:
You need to keep track of the call depth:

class trace_entry;

class trace_log {
public:
    trace_log() : depth_(0) { }

private:
    // noncopyable so we don't accidentally copy it
    trace_log(trace_log&);
    void operator=(trace_log);

    friend trace_entry;

    int depth_;
};

class trace_entry {
public:
    trace_entry(trace_log& log, const std::string& frame)
        : log_(log), frame_(frame) {
        std::cout << std::string(4 * log.depth_, ' ')
                  << "ENTER " << frame_ << std::endl;
        ++log_.depth_;
    }

    ~trace_entry() {
        --log_.depth_;
        std::cout << std::string(4 * log_.depth_, ' ')
                  << "EXIT " << frame_ << std::endl;
    }
private:
    // noncopyable so we don't accidentally copy it
    trace_entry(trace_entry&);
    void operator=(trace_entry);

    trace_log& log_;
    std::string frame_;
};

Usage example:

void a(trace_log& log) {
    trace_entry e(log, "a");
}

void b(trace_log& log) {
    trace_entry e(log, "b");
    return a(log);
}

int main() {
    trace_log log;
    trace_entry e(log, "main");
    b(log);
}

Output:

ENTER main
    ENTER b
        ENTER a
        EXIT a
    EXIT b
EXIT main

This is easily extensible to support alternative forms of logging, allowing additional log messages, and just about anything else you want to do.  (It would be far better to have the trace_log actually perform the logging, but for exposition purposes, this is the simplest way to demonstrate what you are trying to do.)


问:
How to determine which chromium version is used by QtWebEngine in Qt 5 at run-time?
I couldn't find any function in Qt 5 to determine which chromium version is used by QtWebEngine.

I don't want to hard-code the chromium version in my code because I frequently update my application and the chromium version is usually changed in each version. And also Qt is backward-compatible and it is possible to update it without updating my application.

答:
There is no direct solution but looking at the source code You can see that it is used to set the default user agent:

```<code>std::string ContentBrowserClientQt::getUserAgent()
{
    // Mention the Chromium version we're based on to get passed stupid UA-string-based feature detection (several WebRTC demos need this)
    return content::BuildUserAgentFromProduct("QtWebEngine/" QTWEBENGINECORE_VERSION_STR " Chrome/" CHROMIUM_VERSION);
}
</code>```

So it can be extracted from that data:

```<code>QString version;
QString user_agent = QWebEngineProfile::defaultProfile()->httpUserAgent();
for(const QString & text : user_agent.split(" ")){
    if(text.startsWith(QStringLiteral("Chrome/"))){
        version = text.mid(QStringLiteral("Chrome/").length());
    }
}
qDebug().noquote()<< "Qt version:" << QT_VERSION_STR << "chromium version:" << version;
</code>```

Output:

```<code>Qt version: 5.14.2 chromium version: 77.0.3865.129
</code>```

Body:
There is no direct solution but looking at the source code You can see that it is used to set the default user agent:

std::string ContentBrowserClientQt::getUserAgent()
{
    // Mention the Chromium version we're based on to get passed stupid UA-string-based feature detection (several WebRTC demos need this)
    return content::BuildUserAgentFromProduct("QtWebEngine/" QTWEBENGINECORE_VERSION_STR " Chrome/" CHROMIUM_VERSION);
}

So it can be extracted from that data:

QString version;
QString user_agent = QWebEngineProfile::defaultProfile()->httpUserAgent();
for(const QString & text : user_agent.split(" ")){
    if(text.startsWith(QStringLiteral("Chrome/"))){
        version = text.mid(QStringLiteral("Chrome/").length());
    }
}
qDebug().noquote()<< "Qt version:" << QT_VERSION_STR << "chromium version:" << version;

Output:

Qt version: 5.14.2 chromium version: 77.0.3865.129


问:
PHP Run background script from cli script
From a php script I need to launch a new php script in background.
I expect this to be working:

```<code>shell_exec("php mySecondScript.php &");
</code>```

Execution of main script hangs and secondScript is not even started. Of course if I remove '&' the script is executed, but synchronously. Any reason for this?

答:
You don't redirect output of command.</p>

```<code>shell_exec("php mySecondScript.php > /dev/null &");
</code>```

Body:
From a php script I need to launch a new php script in background.
I expect this to be working:

shell_exec("php mySecondScript.php &");

Execution of main script hangs and secondScript is not even started. Of course if I remove '&' the script is executed, but synchronously. Any reason for this?

Body:
You don't redirect output of command.

shell_exec("php mySecondScript.php > /dev/null &");


问:
how to use popup in django admin to select from another class
i want to use popup to fill input in django admin i saw it in class Email addresses as the follwing pic

答:
It's an attribute raw_id_fields that you can use while registering your models in the admin section.
raw_id_fields = ('author',)
Its use is that the author field is displayed with a lookup widget that can scale much better than a drop-down select input when you have thousands of users.


问:
Scala - Handle empty strings when instantiating a class
I have a case class with a couple of String fields. I use the values result of a string split to instantiate the class, but want to get an error when any of the fields is an empty string. For example:

```<code>case class SomeClass(a: String, b: String)
val line = ",a"
val values = line.split(",")
SomeClass(values(0), values(1))
</code>```

Would result in:

```<code>SomeClass = SomeClass(,a)
</code>```

Obviously I can check if each element is empty individually, but is there any more elegant and practical way to prevent instantiating when there is an empty field?

答:
```<code>case class SomeClass(a: String, b: String) {
  require(a.nonEmpty && b.nonEmpty, "a and b cannot be empty")
}
</code>```

You can achieve it with simple require. But if you want to stricten it based on the type at compile-time, you can use NonEmptyString as suggested in the above answers by @sinanspd.

https://scastie.scala-lang.org/shankarshastri/uPk8ZMqCQUa5G3RcKfZtwA/

Body:
I have a case class with a couple of String fields. I use the values result of a string split to instantiate the class, but want to get an error when any of the fields is an empty string. For example:

case class SomeClass(a: String, b: String)
val line = ",a"
val values = line.split(",")
SomeClass(values(0), values(1))

Would result in:

SomeClass = SomeClass(,a)

Obviously I can check if each element is empty individually, but is there any more elegant and practical way to prevent instantiating when there is an empty field?

Body:
case class SomeClass(a: String, b: String) {
  require(a.nonEmpty && b.nonEmpty, "a and b cannot be empty")
}

You can achieve it with simple require. But if you want to stricten it based on the type at compile-time, you can use NonEmptyString as suggested in the above answers by @sinanspd.

https://scastie.scala-lang.org/shankarshastri/uPk8ZMqCQUa5G3RcKfZtwA/


问:
ASP.NET - redirect 301
How do I redirect permanently in ASP DOT NET? I'd like to do a 301 redirect from one page on my site to another page. </p>

答:
If you want to always redirect from one URL to another you can use the IIS rewrite module.

In you web.config file, add the following:

```<code><system.webServer>
  <rule name="Redirect Source to Destination" stopProcessing="true">
    <match url="/source.aspx" />
    <action type="Redirect" url="/destination.aspx" redirectType="Permanent" />
  </rule>
</system.webServer>
</code>```

OwnerDisplayName: Arjun

ContentLicense: CC BY-SA 2.5

Title: ASP.NET - redirect 301

LastEditorDisplayName: Joel Coehoorn

Body:
If you want to always redirect from one URL to another you can use the IIS rewrite module.

In you web.config file, add the following:

<system.webServer>
  <rule name="Redirect Source to Destination" stopProcessing="true">
    <match url="/source.aspx" />
    <action type="Redirect" url="/destination.aspx" redirectType="Permanent" />
  </rule>
</system.webServer>


问:
Msysgit bash is horrendously slow in Windows 7
I love git and use it on OS X pretty much constantly at home.  At work, we use svn on Windows, but want to migrate to git as soon as the tools have fully matured (not just TortoiseGit, but also something akin the really nice Visual Studio integration provided by VisualSVN).  But I digress...

I recently installed msysgit on my Windows 7 machine, and when using the included version of bash, it is horrendously slow.  And not just the git operations; clear takes about five seconds.  AAAAH!

Has anyone experienced a similar issue?

Edit:  It appears that msysgit is not playing nicely with UAC and might just be a tiny design oversight resulting from developing on XP or running Vista or 7 with UAC disabled; starting Git Bash using Run as administrator results in the lightning speed I see with OS X (or on 7 after starting Git Bash w/o a network connection - see @Gauthier answer).

Edit 2: AH HA!  See my answer.

答:
This worked for me. Don't expect it will be a one size fits all solution.

Check the $HOME environment variable in bash and windows.
If it points to a user account, check the user's windows profile/permissions.
Change either the user account or the $HOME accordingly.


问:
How to convert to datetime even if the column contains strings
I have a dataframe with column date as dtype object.

```<code>id           date         name
1           1/1/2020       A
2           2/1/2020       B
3           2/1/2020
Total      3 Entries      2 Entries
</code>```

I want to convert this date column to pd.datetime. But as it contains a Total it gives an error: dateutil.parser._parser.ParserError: Unknown string format: 3 Entries

How can I tell pandas to change only the date format rows should be changed to datetime ? Actually I just want the month from that date to a new column.
What are my alternatives to achieve this ?

desired result:

```<code>id           date         name          month
1           1/1/2020       A              1
2           2/1/2020       B              1
3           2/1/2020                      1
Total      3 Entries      2 Entries     Nan/0

</code>```

答:
```<code>for d in df['date']:
    try:
        pd.to_datetime(d)
</code>```

Or, you could use .apply():

```<code>convert_to_datetime = lambda d: pd.to_datetime(d).month

df['date'].apply(convert_to_datetime)
</code>```

The month will be of type float, so you might need to convert it to int.

Body:
I have a dataframe with column date as dtype object.

id           date         name
1           1/1/2020       A
2           2/1/2020       B
3           2/1/2020
Total      3 Entries      2 Entries

I want to convert this date column to pd.datetime. But as it contains a Total it gives an error: dateutil.parser._parser.ParserError: Unknown string format: 3 Entries

How can I tell pandas to change only the date format rows should be changed to datetime ? Actually I just want the month from that date to a new column.
What are my alternatives to achieve this ?

desired result:

id           date         name          month
1           1/1/2020       A              1
2           2/1/2020       B              1
3           2/1/2020                      1
Total      3 Entries      2 Entries     Nan/0

Body:
for d in df['date']:
    try:
        pd.to_datetime(d)

Or, you could use .apply():

convert_to_datetime = lambda d: pd.to_datetime(d).month

df['date'].apply(convert_to_datetime)

The month will be of type float, so you might need to convert it to int.


问:
If data has linear frelationship, won't linear regression lead to zero in-sample error
I am using the Learning from Data textbook by Yaser Abu-Mostafa et al.  I am curious about the following statement in the linear regression chapter and would like to verify that my understanding is correct.

After talking about the "pseudo-inverse" way to get the "best weights" (best for minimizing squared error), i.e w_lin = (X^T X)^-1 X^T y

The statement is "The linear regression weight vector is an attempt to map the inputs X to the outputs y.  However, w_lin does not produce y exactly, but produces an estimate X w_lin which differs from y due to in sample error.

If the data is on a hyper-plane, won't X w_lin exactly match y (i.e in-sample error = 0)?   I.e above statement is only talking about data that is not linearly separable.

答:
The community might not get whole context unless the book is opened because not everything that the author of the book says might have been covered in your post. But let me try to answer.

Whenever any model is formed, there are certain constants used whose value is not known beforehand but are used to fit the line/curve as good as possible. Also, the equations, many a times, contain an element of randomness. Variables that take random values cause some errors when actual and expected outputs are computed.

Suggested reading: Errors and residuals