问:
How to fix NullPointerException in a ListView?
I'm getting a NullPointerException while making a ListView using a custom adapter and don't know the part of code causing the error. Following is the code snippet:

ChatMessageAdapter.java

```<code>package com.myappcompany.rajan.thefictionalchat;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class ChatMessageAdapter extends ArrayAdapter<ChatText> {

    ChatMessageAdapter(Context context, ArrayList<ChatText> list) {
        super(context, 0, list);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View currentView = convertView;
        if(currentView==null) {
            LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
        }
        ChatText chatText = getItem(position);

        TextView textView;
        textView = (TextView)currentView.findViewById(R.id.chat_text);
        textView.setText(chatText.getMessage());

        if(chatText.getMessageType().equals("PERSON_1")) {
            textView.setGravity(Gravity.LEFT);
        }
        else if(chatText.getMessageType().equals("PERSON_2")) {
            textView.setGravity(Gravity.RIGHT);
        }
        else {
            textView.setGravity(Gravity.CENTER_HORIZONTAL);
        }

        return currentView;
    }
}

</code>```

list_items.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/chat_text"
        tools:text="Hello" />

</LinearLayout>
</code>```

I'm getting the following run-time error from the log as the app crashes:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
        at com.myappcompany.rajan.thefictionalchat.ChatMessageAdapter.getView(ChatMessageAdapter.java:32)
</code>```

答:
You inflate view but you don't save inflated view into currentView

Change this code :

```<code>View currentView = convertView;
if(currentView==null) {
     LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
}
</code>```

To this :

```<code>View currentView = convertView;
if(currentView==null) {
    currentView = LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
}
</code>```

Body:
I'm getting a NullPointerException while making a ListView using a custom adapter and don't know the part of code causing the error. Following is the code snippet:

ChatMessageAdapter.java

package com.myappcompany.rajan.thefictionalchat;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class ChatMessageAdapter extends ArrayAdapter<ChatText> {

    ChatMessageAdapter(Context context, ArrayList<ChatText> list) {
        super(context, 0, list);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View currentView = convertView;
        if(currentView==null) {
            LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
        }
        ChatText chatText = getItem(position);

        TextView textView;
        textView = (TextView)currentView.findViewById(R.id.chat_text);
        textView.setText(chatText.getMessage());

        if(chatText.getMessageType().equals("PERSON_1")) {
            textView.setGravity(Gravity.LEFT);
        }
        else if(chatText.getMessageType().equals("PERSON_2")) {
            textView.setGravity(Gravity.RIGHT);
        }
        else {
            textView.setGravity(Gravity.CENTER_HORIZONTAL);
        }

        return currentView;
    }
}

list_items.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/chat_text"
        tools:text="Hello" />

</LinearLayout>

I'm getting the following run-time error from the log as the app crashes:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
        at com.myappcompany.rajan.thefictionalchat.ChatMessageAdapter.getView(ChatMessageAdapter.java:32)

Body:
You inflate view but you don't save inflated view into currentView

Change this code :

View currentView = convertView;
if(currentView==null) {
     LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
}

To this :

View currentView = convertView;
if(currentView==null) {
    currentView = LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
}


来源: stackexchange

问:
New Function constructor in Angular how to reference imported scripts in revived object
I have a json with function stored in it as strings and when I revive it using new Function and try to use the method which happens to use a library imported by angular like lodash I get a reference error. Here is the code the ZombieLoader will revive the json object and in the angular class test will try to run it i will get the error _ not found.

```<code>// This class takes a json and produces an object with methods
export class ZombieLoader {
  static revive(st: string): object {
    const result = {};
    const obj = JSON.parse(st);
    for (const key of Object.keys(obj)) {
      if (key.startsWith('@')) {
        result[key.substring(1)] = new Function('return ' + obj[key])();
        continue;
      }
      result[key] = obj[key];
    }
    return result;
  }
}

// the json with function in string form that will be hydrated back for use
{
script: '{"@run":"function () { return _.chunk(['a', 'b', 'c', 'd'], 2); };}'
}

// here I test the method which fails because it cant find _
import * as _ from 'lodash';
import {ZombieLoader} from './zombie-loader';

export class Test {
    constructor(script: string) {
         const sceneScript = ZombieLoader.revive(script);
         sceneScript.run();
    }
}
</code>```

Why does the reconstructed object not have reference to Angular loaded scripts is there a way to reconstruct the object and bind it to an angular.
If I add the lodash to the index.html file it works but I don't want to have to do this to several other libraries

答:
By adding () at the end - new Function('return ' + obj[key])() you execute function and it can't be aware of any dependencies in its caller.

I dont know what run() does here sceneScript.run();, but Function constructor accepts arguments parameters, so you can just pass in needed dependency: new Function('_', 'return ' + obj[key]); and invoke functions later by passing that from the caller:

```<code>sceneScript.run(_);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a json with function stored in it as strings and when I revive it using new Function and try to use the method which happens to use a library imported by angular like lodash I get a reference error. Here is the code the ZombieLoader will revive the json object and in the angular class test will try to run it i will get the error _ not found.

// This class takes a json and produces an object with methods
export class ZombieLoader {
  static revive(st: string): object {
    const result = {};
    const obj = JSON.parse(st);
    for (const key of Object.keys(obj)) {
      if (key.startsWith('@')) {
        result[key.substring(1)] = new Function('return ' + obj[key])();
        continue;
      }
      result[key] = obj[key];
    }
    return result;
  }
}

// the json with function in string form that will be hydrated back for use
{
script: '{"@run":"function () { return _.chunk(['a', 'b', 'c', 'd'], 2); };}'
}

// here I test the method which fails because it cant find _
import * as _ from 'lodash';
import {ZombieLoader} from './zombie-loader';

export class Test {
    constructor(script: string) {
         const sceneScript = ZombieLoader.revive(script);
         sceneScript.run();
    }
}

Why does the reconstructed object not have reference to Angular loaded scripts is there a way to reconstruct the object and bind it to an angular.
If I add the lodash to the index.html file it works but I don't want to have to do this to several other libraries

Body:
By adding () at the end - new Function('return ' + obj[key])() you execute function and it can't be aware of any dependencies in its caller.

I dont know what run() does here sceneScript.run();, but Function constructor accepts arguments parameters, so you can just pass in needed dependency: new Function('_', 'return ' + obj[key]); and invoke functions later by passing that from the caller:

sceneScript.run(_);


问:
Query CONTAINS not working only selecting where equals
Queries using contains have recently stopped working correctly.
When value in source data column is 1,2,3 and the query is WHERE B contains '3'

See test sheet here:
https://docs.google.com/spreadsheets/d/1tCJBerHOmVfKbtb81JEyWEp6ZYP0EXyJqG-_7zVWpLw/edit?usp=sharing

Update
It appears that google is now first applying the Number Formatting to the cell then running the QUERY. Ensure your data column is set to PLAIN TEXT.

答: In your example, add say z (any text) into B7 and John should appear in the output of your query.


问:
" Cloud Firestore Override a deprecated API " Error occurs when build the flutter application

" Cloud Firestore Override a deprecated API "

Error occurs when building the flutter application.

```<code>Note: C:\Work\flutter\.pub-cache\hosted\pub.dartlang.org\cloud_firestore-0.11.0+2\android\src\main\java\io\flutter\plugins\firebase\cloudfirestore\CloudFirestorePlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\Work\flutter\.pub-cache\hosted\pub.dartlang.org\cloud_firestore-0.11.0+2\android\src\main\java\io\flutter\plugins\firebase\cloudfirestore\CloudFirestorePlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Note: C:\Work\flutter\.pub-cache\hosted\pub.dartlang.org\connectivity-0.4.3+1\android\src\main\java\io\flutter\plugins\connectivity\ConnectivityPlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\Work\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_core-0.4.0+1\android\src\main\java\io\flutter\plugins\firebase\core\FirebaseCorePlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
</code>```

答:
In my case, ->android->app->build.gradle
at first I was using library as "compile", changing it to "implementation" my issue got solved</p>

Body:
" Cloud Firestore Override a deprecated API "

Error occurs when building the flutter application.

Note: C:\Work\flutter\.pub-cache\hosted\pub.dartlang.org\cloud_firestore-0.11.0+2\android\src\main\java\io\flutter\plugins\firebase\cloudfirestore\CloudFirestorePlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\Work\flutter\.pub-cache\hosted\pub.dartlang.org\cloud_firestore-0.11.0+2\android\src\main\java\io\flutter\plugins\firebase\cloudfirestore\CloudFirestorePlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Note: C:\Work\flutter\.pub-cache\hosted\pub.dartlang.org\connectivity-0.4.3+1\android\src\main\java\io\flutter\plugins\connectivity\ConnectivityPlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\Work\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_core-0.4.0+1\android\src\main\java\io\flutter\plugins\firebase\core\FirebaseCorePlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.


问:
How to setup a request.py for this machine learning models?
I am following this online tutorial and deploying a machine learning models using Python. I have done all the parts as instructed, including having created the model.py, and request.py files, and run those in Terminal.

But, I failed to create a request.py file to generate the prediction. My server.py is:

```<code># Import libraries
import numpy as np
import flask
import pickle

app = flask.Flask(__name__)

model = pickle.load(open("model.pkl","rb"))

@app.route('/predict', methods=['POST'])
def predict():
    feature_array = request.get_json()['feature_array']

    #our model rates the wine based on the input array
    prediction = model.predict([feature_array]).tolist()

    #preparing a response object and storing the model's predictions
    response = {}
    response['predictions'] = prediction

    #sending our response object back as json
    return flask.jsonify(response)
</code>```

And my request.py:

```<code>import requests
# URL
url = 'http://localhost:5000/request'

r = requests.post(url,json=[7.4,0.66,0,1.8,0.075,13,40,0.9978,3.51,0.56,9.4])
print(r.json())
</code>```

答:
Import this in server.py file:

```<code>from flask import request
</code>```

Add this at the end of your server.py file(used to run the server at port 5000 and debug=True to debug and solve the error, if we get any):

```<code>if __name__ == '__main__':
    app.run(port=5000, debug=True)
</code>```

Updated request.py file(your code is missing feature_array key which you are referring in server.py file):

```<code>import requests, json
# URL
url = 'http://localhost:5000/predict'
r = requests.post(url, json={"feature_array":[7.4,0.66,0,1.8,0.075,13,40,0.9978,3.51,0.56,9.4]})
print(r.json())
</code>```

Run server.py before running request.py file.

Body:
I am following this online tutorial and deploying a machine learning models using Python. I have done all the parts as instructed, including having created the model.py, and request.py files, and run those in Terminal.

But, I failed to create a request.py file to generate the prediction. My server.py is:

# Import libraries
import numpy as np
import flask
import pickle

app = flask.Flask(__name__)

model = pickle.load(open("model.pkl","rb"))

@app.route('/predict', methods=['POST'])
def predict():
    feature_array = request.get_json()['feature_array']

    #our model rates the wine based on the input array
    prediction = model.predict([feature_array]).tolist()

    #preparing a response object and storing the model's predictions
    response = {}
    response['predictions'] = prediction

    #sending our response object back as json
    return flask.jsonify(response)

And my request.py:

import requests
# URL
url = 'http://localhost:5000/request'

r = requests.post(url,json=[7.4,0.66,0,1.8,0.075,13,40,0.9978,3.51,0.56,9.4])
print(r.json())

Body:
Import this in server.py file:

from flask import request

Add this at the end of your server.py file(used to run the server at port 5000 and debug=True to debug and solve the error, if we get any):

if __name__ == '__main__':
    app.run(port=5000, debug=True)

Updated request.py file(your code is missing feature_array key which you are referring in server.py file):

import requests, json
# URL
url = 'http://localhost:5000/predict'
r = requests.post(url, json={"feature_array":[7.4,0.66,0,1.8,0.075,13,40,0.9978,3.51,0.56,9.4]})
print(r.json())

Run server.py before running request.py file.


问:
Is there Android Intent concept in iPhone SDK
Just switching from Android to iPhone. In Android I can make several apps and use a tabView to call each app as intent.

In iPhone, I can make several apps. I need a tab to call each apps or app views. Is there similar concept as intent in iPhone? Just switched to iPhone, copying all the other projects into the tabbar does not work out. If you have other methods to solve, I really appreciate. Thanks,

答:
Android and iOS are very different in this regard. Android is very open about letting you use intents to mix and match activities from other apps. iOS isn't like that; each app runs in its own private space and generally cannot even see other apps' data, let alone use their services. It is possible to cause other apps to run via custom URLs, but that's not the same thing.

What you'll need to do is to copy or move the code for the view controllers, views, etc. of your various iOS apps into your tab bar app project. You'll build them all into a single application, and the tab bar will switch between the view controllers.

ContentLicense: CC BY-SA 3.0


问:
Is it possible to install CDH on a RHEL7 server where Hadoop and few other components are installed seperatly
I have an RHEL7 server in which i am trying to create a common datalake platform for POC and learning purpose. I have setup Hadoop,Hive,Zookeeper,Kafka,Spark,Sqoop separately.

Installing these components separately turns out to be a tricky affair and is taking lot of effort even though this is for an internal purpose and not production specific.

I am now trying to install CDH package in this Server now.
Is it possible to do so? Will it overlap with the current installations?
How can this be achieved.

Note: Reason why we went with separate installation is due to unavailability of internet in the server at that point of time.

Reason why going for CDH now is due to availability of internet for few days after some approvals plus CDH saves lot of time and effort and includes the
components required to setup a datalake.

Can someone please help me out here.

答:
Yes it is feasible to setup CDH without disturbing existing configs with docker. Checkout the below link for setup guide. I have tested this and it works fine even if I have individual tools setup.

https://www.cloudera.com/documentation/enterprise/5-6-x/topics/quickstart_docker_container.html


问:
Is that possible to replace text from html code
I have variable label1= "please pay $ 50:#000000"
and is that possible to replace :#000000 and set color :#000000 from html code

Now my html code is like this

```<code><labe>{{label1}}</label>
</code>```

but I need to make it like:

if(label1 contains :#000000 or :DC143C then replace it with empty string("") and set font color as color which is available in variable label1

答:
Yes, you can split text in html directly..

Html:

{{label1.split(':')[0]}}

No need write extra code in typescript.
Happy coding.

Body:
I have variable label1= "please pay $ 50:#000000"
and is that possible to replace :#000000 and set color :#000000 from html code

Now my html code is like this

<labe>{{label1}}

but I need to make it like:

if(label1 contains :#000000 or :DC143C then replace it with empty string("") and set font color as color which is available in variable label1

Body:
Yes, you can split text in html directly..

Html:

<label [ngStyle]="{ 'color': label1.split(':')[1]}">{{label1.split(':')[0]}}  </label>

No need write extra code in typescript.
Happy coding.


问:
A question about let when it acts as a global variable in ES6
As shown in the code below, I used var value = 1, and the value obtained is 1 . I can understand this because return this.value here the this points to the window, so I can print out the global variable value.

var value = 1;
let obj = {
  getValue: function() {
    return function() {
      return this.value;
    }
  }
}
console.log(obj.getValue()());  // 1```
</div>
</div>
</p>

<p>But if I use let to declare the value, I can't get the value of the value, the print is undefined. This is very puzzled, whether it is using let, or var statement, value is a global variable. Why is there such a difference?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let value = 1;
let obj = {
  getValue: function() {
    return function() {
      return this.value;
    }
  }
}
console.log(obj.getValue()());  // undefined</code>```

Do you know why？ Can you tell me? Thank you very much.

答:
From MDN's documentation:

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

and:

At the top level of programs and functions, let, unlike var, does not create a property on the global object. For example:

Body:
As shown in the code below, I used var value = 1, and the value obtained is 1 . I can understand this because return this.value here the this points to the window, so I can print out the global variable value.

var value = 1;
let obj = {
  getValue: function() {
    return function() {
      return this.value;
    }
  }
}
console.log(obj.getValue()());  // 1

But if I use let to declare the value, I can't get the value of the value, the print is undefined. This is very puzzled, whether it is using let, or var statement, value is a global variable. Why is there such a difference?

let value = 1;
let obj = {
  getValue: function() {
    return function() {
      return this.value;
    }
  }
}
console.log(obj.getValue()());  // undefined

Do you know why？ Can you tell me? Thank you very much.


问:
What value is returned in a grid search score?
I ran a GridSearchCV on a prediction model with scoring set to accuracy. X and Y are the test splits.

```<code>from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.svm import SVC

tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],
                 'C': [10, 100, 1000]}]

print("Tuning hyperparameters for accuracy")

clf_gs = GridSearchCV(SVC(), tuned_parameters, cv=5,
               scoring = 'accuracy')
clf_gs.fit(X, Y)

print(clf_gs.best_params_)

print("Grid scores on development set:")

means = clf_gs.cv_results_['mean_test_score']
stds = clf_gs.cv_results_['std_test_score']
for mean, std, params in zip(means, stds, clf_gs.cv_results_['params']):
    print("%0.3f (+/-%0.03f) for %r"
          % (mean, std * 2, params))

print("The scores are computed on the full evaluation set.")

y_true, y_pred = Y, clf_gs.predict(X)
print(classification_report(y_true, y_pred))
</code>```

I got the grid scores as

```<code>Tuning hyperparameters for accuracy

{'C': 1000, 'gamma': 0.001, 'kernel': 'rbf'}

Grid scores on development set:

0.994 (+/-0.000) for {'C': 10, 'gamma': 0.001, 'kernel': 'rbf'}
0.986 (+/-0.000) for {'C': 10, 'gamma': 0.0001, 'kernel': 'rbf'}
0.995 (+/-0.001) for {'C': 100, 'gamma': 0.001, 'kernel': 'rbf'}
0.988 (+/-0.000) for {'C': 100, 'gamma': 0.0001, 'kernel': 'rbf'}
0.995 (+/-0.001) for {'C': 1000, 'gamma': 0.001, 'kernel': 'rbf'}
0.994 (+/-0.001) for {'C': 1000, 'gamma': 0.0001, 'kernel': 'rbf'}

The scores are computed on the full evaluation set.
              precision    recall  f1-score   support

           0       1.00      1.00      1.00     67343
           3       0.88      0.78      0.83       995

    accuracy                           1.00     68338
   macro avg       0.94      0.89      0.91     68338
weighted avg       1.00      1.00      1.00     68338
</code>```

sklearn.metrics.GridSearchCV.score says it returns the score of the given data. Is it the accuracy score of the prediction model or a different score related to GridSearchCV? I am just confused as I got above 99% score here when I only got below 90% accuracy with parameter values set to default using SVC and didn't expect to see this much improvement.

答:
Yes, according to this line of code:

```<code>clf_gs = GridSearchCV(SVC(), tuned_parameters, cv=5,
               scoring = 'accuracy')
</code>```

, your scoring metric is accuracy.

The difference between CV/eval scores comes from the data set: CV is trained and tested on the 5-fold cross validation sets, which are subsets of your training data. In contrast, eval is trained on the whole training data, and tested on the test data, which is independent of your training set.

You can google 'k-fold cross-validation washinton' to see more detail on the underlying algorithms.

Body:
I ran a GridSearchCV on a prediction model with scoring set to accuracy. X and Y are the test splits.

from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.svm import SVC

tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],
                 'C': [10, 100, 1000]}]

print("Tuning hyperparameters for accuracy")

clf_gs = GridSearchCV(SVC(), tuned_parameters, cv=5,
               scoring = 'accuracy')
clf_gs.fit(X, Y)

print(clf_gs.best_params_)

print("Grid scores on development set:")

means = clf_gs.cv_results_['mean_test_score']
stds = clf_gs.cv_results_['std_test_score']
for mean, std, params in zip(means, stds, clf_gs.cv_results_['params']):
    print("%0.3f (+/-%0.03f) for %r"
          % (mean, std * 2, params))

print("The scores are computed on the full evaluation set.")

y_true, y_pred = Y, clf_gs.predict(X)
print(classification_report(y_true, y_pred))

I got the grid scores as

Tuning hyperparameters for accuracy

{'C': 1000, 'gamma': 0.001, 'kernel': 'rbf'}

Grid scores on development set:

0.994 (+/-0.000) for {'C': 10, 'gamma': 0.001, 'kernel': 'rbf'}
0.986 (+/-0.000) for {'C': 10, 'gamma': 0.0001, 'kernel': 'rbf'}
0.995 (+/-0.001) for {'C': 100, 'gamma': 0.001, 'kernel': 'rbf'}
0.988 (+/-0.000) for {'C': 100, 'gamma': 0.0001, 'kernel': 'rbf'}
0.995 (+/-0.001) for {'C': 1000, 'gamma': 0.001, 'kernel': 'rbf'}
0.994 (+/-0.001) for {'C': 1000, 'gamma': 0.0001, 'kernel': 'rbf'}

The scores are computed on the full evaluation set.
              precision    recall  f1-score   support

           0       1.00      1.00      1.00     67343
           3       0.88      0.78      0.83       995

    accuracy                           1.00     68338
   macro avg       0.94      0.89      0.91     68338
weighted avg       1.00      1.00      1.00     68338

sklearn.metrics.GridSearchCV.score says it returns the score of the given data. Is it the accuracy score of the prediction model or a different score related to GridSearchCV? I am just confused as I got above 99% score here when I only got below 90% accuracy with parameter values set to default using SVC and didn't expect to see this much improvement.

Body:
Yes, according to this line of code:

clf_gs = GridSearchCV(SVC(), tuned_parameters, cv=5,
               scoring = 'accuracy')

, your scoring metric is accuracy.

The difference between CV/eval scores comes from the data set: CV is trained and tested on the 5-fold cross validation sets, which are subsets of your training data. In contrast, eval is trained on the whole training data, and tested on the test data, which is independent of your training set.

You can google 'k-fold cross-validation washinton' to see more detail on the underlying algorithms.


问:
The method update(String) from the type RequestContext is deprecated
When I use next code part in my code :
    RequestContext.getCurrentInstance().update("growl");

there is a warning as "The method update(String) from the type RequestContext is deprecated" and in code part and crossed of "update".

```<code>RequestContext.getCurrentInstance().update("growl");
</code>```

there is a warning as "The method update(String) from the type RequestContext is deprecated" and in code part and crossed of "update".

It is clear that  this way is overdue. What is the modern way of doing this.

答:
It has been replaced with:

```<code>PrimeFaces.current().ajax().update(expressions);
</code>```

See also:

https://primefaces.github.io/primefaces/10_0_0/#/../migrationguide/7_0

https://primefaces.github.io/primefaces/7_0/#/ajax/rendering?id=dynamicruntime-updates

Body:
When I use next code part in my code :
    RequestContext.getCurrentInstance().update("growl");

there is a warning as "The method update(String) from the type RequestContext is deprecated" and in code part and crossed of "update".

RequestContext.getCurrentInstance().update("growl");

there is a warning as "The method update(String) from the type RequestContext is deprecated" and in code part and crossed of "update".

It is clear that  this way is overdue. What is the modern way of doing this.

Body:
It has been replaced with:

PrimeFaces.current().ajax().update(expressions);

See also:

https://primefaces.github.io/primefaces/10_0_0/#/../migrationguide/7_0

https://primefaces.github.io/primefaces/7_0/#/ajax/rendering?id=dynamicruntime-updates


问:
Cannot apply indexing to an expression of type 'IntPtr' == IntPtr ptr1 = [...] --> ptr1[0]
I found a code snippet which I want to implement. Now is the problem that one function isn't running. Cannot apply indexing to an expression of type 'IntPtr'

```<code>        fixed (byte* numRef = this.tribuf)
        {
            for (int i = 0; i < num; i++)
            {
                item = this.trihash.GetItem(ch + S.Substring(i, 3));
                if (item != null)
                {
                    this.TrigramChecked += item.Count;
                    foreach (int num3 in item)
                    {
                        if ((num3 != id) && (numRef[num3] < 0xff))
                        {
                            IntPtr ptr1 = (IntPtr) (numRef + num3);
                            /* ToDo: Error */
                            ptr1[0] = (IntPtr) ((byte) (ptr1[0] + 1));
                        }
                    }
                }
            }
        }
</code>```

regards Chris

答:
As I said in a comment, I would try to avoid unsafe code in the first place, but it looks like it's really just trying to do:

```<code>if ((num3 != id) && (numRef[num3] < 0xff))
{
    numRef[num3]++;
}
</code>```

Or perhaps more efficiently (to only read from numRef[num3] once):

```<code>if (num3 != id)
{
    byte value = numRef[num3];
    if (value < 0xff)
    {
        numRef[num3] = (byte) (value + 1);
    }
}
</code>```

Body:
I found a code snippet which I want to implement. Now is the problem that one function isn't running. Cannot apply indexing to an expression of type 'IntPtr'

        fixed (byte* numRef = this.tribuf)
        {
            for (int i = 0; i < num; i++)
            {
                item = this.trihash.GetItem(ch + S.Substring(i, 3));
                if (item != null)
                {
                    this.TrigramChecked += item.Count;
                    foreach (int num3 in item)
                    {
                        if ((num3 != id) && (numRef[num3] < 0xff))
                        {
                            IntPtr ptr1 = (IntPtr) (numRef + num3);
                            /* ToDo: Error */
                            ptr1[0] = (IntPtr) ((byte) (ptr1[0] + 1));
                        }
                    }
                }
            }
        }

regards Chris

Body:
As I said in a comment, I would try to avoid unsafe code in the first place, but it looks like it's really just trying to do:

if ((num3 != id) && (numRef[num3] < 0xff))
{
    numRef[num3]++;
}

Or perhaps more efficiently (to only read from numRef[num3] once):

if (num3 != id)
{
    byte value = numRef[num3];
    if (value < 0xff)
    {
        numRef[num3] = (byte) (value + 1);
    }
}


问:
Is there a way to alter many tables to add default values to a common column name?
We have a set of 45 tables which carry a common column {variety}.
The need is to set all such columns with a default value {comedy}.

The ALTER TABLE (SCHEMA.TABLE_NAME) MODIFY(VARIETY DEFAULT 'COMEDY')

Will get it done, but I am wondering if there is a way to create a sql script in Oracle 11g that will change all tables within the schema which have a common coloumn name to the common default value.

答:
The alter table statement can be written as following,
using alternate quoting mechanism.</p>

```<code>'alter table ' || x.table_name || q'[ modify (variety default 'COMEDY')]'
</code>```

Body:
The alter table statement can be written as following,
using alternate quoting mechanism.

'alter table ' || x.table_name || q'[ modify (variety default 'COMEDY')]'


答:
At the top level of programs and functions, let, unlike var, does not
  create a property on the global object. For example:  Scopping rules MDN

var x = 'global';
let y = 'global';
console.log(this.x); // "global"
console.log(this.y); // undefined```

Title: A question about let when it acts as a global variable in ES6


问:
Validation of Guid
I have a strongly-typed view which has a DropDownListFor attribute on it.

Each item in the dropdown list is represented by a GUID.

What I'm after is a way to validate if a user selects an item from the dropdown list. At present i don't see anyway of doing this using Data Annotations.

Is there anyway of achieving this using Data Annotations so client and server side validation would work.

I'm guessing i need to make a custom method to do this but was wondering if anything already existed.

答:
If the custom validation doesn't require a high reuse in your system (i.e. without the need for a custom validation attribute), there's another way to add custom validation to a ViewModel / Posted data model, viz by using IValidatableObject.

Each error can be bound to one or more model properties, so this approach still works with e.g. Unobtrusive validation in MVC Razor.

Here's how to check a Guid for default (C# 7.1):

```<code>public class MyModel : IValidatableObject // Implement IValidatableObject
{
    [Required]
    public string Name {get; set;}
    public Guid SomeGuid {get; set;}
    ... other properties here

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (SomeGuid == default)
        {
            yield return new ValidationResult(
                "SomeGuid must be provided",
                new[] { nameof(SomeGuid) });
        }
    }
 }
</code>```

More on IValidatableObject here

Title: Validation of Guid

Body:
If the custom validation doesn't require a high reuse in your system (i.e. without the need for a custom validation attribute), there's another way to add custom validation to a ViewModel / Posted data model, viz by using IValidatableObject.

Each error can be bound to one or more model properties, so this approach still works with e.g. Unobtrusive validation in MVC Razor.

Here's how to check a Guid for default (C# 7.1):

public class MyModel : IValidatableObject // Implement IValidatableObject
{
    [Required]
    public string Name {get; set;}
    public Guid SomeGuid {get; set;}
    ... other properties here

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (SomeGuid == default)
        {
            yield return new ValidationResult(
                "SomeGuid must be provided",
                new[] { nameof(SomeGuid) });
        }
    }
 }

More on IValidatableObject here


问:
Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries
I have two classes in my sqlite database, a parent table named Categorie and the child table called Article. I created first the child table class and addes entries. So first I had this:

```<code>class Article(models.Model):
    titre=models.CharField(max_length=100)
    auteur=models.CharField(max_length=42)
    contenu=models.TextField(null=True)
    date=models.DateTimeField(
        auto_now_add=True,
        auto_now=False,
        verbose_name="Date de parution"
    )

    def __str__(self):
        return self.titre
</code>```

And after I have added parent table, and now my models.py looks like this:

```<code>from django.db import models

# Create your models here.
class Categorie(models.Model):
    nom = models.CharField(max_length=30)

    def __str__(self):
        return self.nom

class Article(models.Model):
    titre=models.CharField(max_length=100)
    auteur=models.CharField(max_length=42)
    contenu=models.TextField(null=True)
    date=models.DateTimeField(
        auto_now_add=True,
        auto_now=False,
        verbose_name="Date de parution"
    )
    categorie = models.ForeignKey('Categorie')

    def __str__(self):
        return self.titre
</code>```

So when I run python manage.py makemigrations <my_app_name>, I get this error:

```<code>Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\core\management\__init__.py", line 354, in execute_from_command_line
    utility.execute()
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\core\management\__init__.py", line 330, in execute
    django.setup()
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\apps\registry.py", line 112, in populate
    app_config.import_models()
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\apps\config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "C:\Users\lislis\Django\mon_site\blog\models.py", line 6, in <module>
    class Article(models.Model):
  File "C:\Users\lislis\Django\mon_site\blog\models.py", line 16, in Article
    categorie = models.ForeignKey('Categorie')
TypeError: __init__() missing 1 required positional argument: 'on_delete'
</code>```

I've seen some similar issues in stackoverflow, but it seems to not be the same problem: __init__() missing 1 required positional argument: 'quantity'

答:
This worked for me
pip install django-csvimport --upgrade

Body:
I have two classes in my sqlite database, a parent table named Categorie and the child table called Article. I created first the child table class and addes entries. So first I had this:

class Article(models.Model):
    titre=models.CharField(max_length=100)
    auteur=models.CharField(max_length=42)
    contenu=models.TextField(null=True)
    date=models.DateTimeField(
        auto_now_add=True,
        auto_now=False,
        verbose_name="Date de parution"
    )

    def __str__(self):
        return self.titre

And after I have added parent table, and now my models.py looks like this:

from django.db import models

# Create your models here.
class Categorie(models.Model):
    nom = models.CharField(max_length=30)

    def __str__(self):
        return self.nom

class Article(models.Model):
    titre=models.CharField(max_length=100)
    auteur=models.CharField(max_length=42)
    contenu=models.TextField(null=True)
    date=models.DateTimeField(
        auto_now_add=True,
        auto_now=False,
        verbose_name="Date de parution"
    )
    categorie = models.ForeignKey('Categorie')

    def __str__(self):
        return self.titre

So when I run python manage.py makemigrations <my_app_name>, I get this error:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\core\management\__init__.py", line 354, in execute_from_command_line
    utility.execute()
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\core\management\__init__.py", line 330, in execute
    django.setup()
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\apps\registry.py", line 112, in populate
    app_config.import_models()
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\apps\config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "C:\Users\lislis\Django\mon_site\blog\models.py", line 6, in <module>
    class Article(models.Model):
  File "C:\Users\lislis\Django\mon_site\blog\models.py", line 16, in Article
    categorie = models.ForeignKey('Categorie')
TypeError: __init__() missing 1 required positional argument: 'on_delete'

I've seen some similar issues in stackoverflow, but it seems to not be the same problem: __init__() missing 1 required positional argument: 'quantity'


答:
Because let doesn't add anything to the global window object - that's why dynamic variable names like this:

var dynamicR = "Hello World!";
console.log(this["dynamic" + "R"]);```
</div>
</div>
</p>

<p>Don't work with <code>let</code> or <code>const</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let dynamicR = "Hello World!";
console.log(this["dynamic" + "R"]);</code>```

So when you're calling the function, it's looking in the window object due to the calling context, and as demonstrated above, this won't work with let.

Body:
Because let doesn't add anything to the global window object - that's why dynamic variable names like this:

var dynamicR = "Hello World!";
console.log(this["dynamic" + "R"]);

Don't work with let or const:

let dynamicR = "Hello World!";
console.log(this["dynamic" + "R"]);

So when you're calling the function, it's looking in the window object due to the calling context, and as demonstrated above, this won't work with let.


答:
As MDN explains:

At the top level of programs and functions, let, unlike var, does not create a property on the global object.

This is because let always creates a lexically scoped variable. If it were to create properties of a global object instead, those properties would be visible to code in other scopes. They wouldn't be lexically scoped anymore, defeating the point of using let.

If you're wondering how there can be "other scopes" not lexically contained within the global scope, there can be multiple script files. Or look at this variation of your example:

let getValue = function() {
  return this.value;
};

let value = 1;
console.log(getValue());```

Using var value = 1; this would still output 1. But with let it outputs undefined because the function is defined lexically outside the block in which value was declared, so it can't access it, even by going through the global object.

Or as MDN puts it:

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used.

That's let's purpose for which it was designed.

Body:
As MDN explains:

At the top level of programs and functions, let, unlike var, does not create a property on the global object.

This is because let always creates a lexically scoped variable. If it were to create properties of a global object instead, those properties would be visible to code in other scopes. They wouldn't be lexically scoped anymore, defeating the point of using let.

If you're wondering how there can be "other scopes" not lexically contained within the global scope, there can be multiple script files. Or look at this variation of your example:

let getValue = function() {
  return this.value;
};

let value = 1;
console.log(getValue());

Using var value = 1; this would still output 1. But with let it outputs undefined because the function is defined lexically outside the block in which value was declared, so it can't access it, even by going through the global object.

Or as MDN puts it:

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used.

That's let's purpose for which it was designed.


问:
Converting sql result into Serializable JSON
I use python. I create a cloud function to return results from the search query connected with PostgreSQL.  I swear the sql is connect. When it comes to retuning fetch result  from the sql, it says the row object is not serialisable JSON . How should I convert this row results into json ?

Here is my code

```<code>def freebie(request):

  engine = create_engine('postgresql://ABC' , echo=True)

  conn = engine.connect()

  x_sql = sa.text('''
            SELECT user_label from "database"."user"
            WHERE "_id" = :userId
        ''')

  record = conn.execute(x_sql, userId = '82f3f82f-5bae-45d3-971f-b4af3a06182f',
            current_time = datetime.now(), ).fetchall()

  user_labbel = record[0][0]

  campaign_sql = sa.text('''
            SELECT * from "database"."user_fav_books"
            WHERE "user_label" = :campaign_id
        ''')

  result = conn.execute(campaign_sql, campaign_id = user_labbel,
            current_time = datetime.now(), ).fetchall()

  if len(result) == 0 :
    return "No result"
  else:
    return json.dump(result, indent=4 , check_circular=True)
</code>```

答:
Try this,

```<code>import json
</code>```

And return as shown below,

```<code>return json.dumps(results, indent=4)
</code>```

Body:
I use python. I create a cloud function to return results from the search query connected with PostgreSQL.  I swear the sql is connect. When it comes to retuning fetch result  from the sql, it says the row object is not serialisable JSON . How should I convert this row results into json ?

Here is my code

def freebie(request):

  engine = create_engine('postgresql://ABC' , echo=True)

  conn = engine.connect()

  x_sql = sa.text('''
            SELECT user_label from "database"."user"
            WHERE "_id" = :userId
        ''')

  record = conn.execute(x_sql, userId = '82f3f82f-5bae-45d3-971f-b4af3a06182f',
            current_time = datetime.now(), ).fetchall()

  user_labbel = record[0][0]

  campaign_sql = sa.text('''
            SELECT * from "database"."user_fav_books"
            WHERE "user_label" = :campaign_id
        ''')

  result = conn.execute(campaign_sql, campaign_id = user_labbel,
            current_time = datetime.now(), ).fetchall()

  if len(result) == 0 :
    return "No result"
  else:
    return json.dump(result, indent=4 , check_circular=True)

Body:
Try this,

import json

And return as shown below,

return json.dumps(results, indent=4)


问:
I want to randomize responses in Python for a custom Alexa skill, question-answer project
I'm creating a skill for Alexa where she would answer a question "Who is right, me or ..." I followed a tutorial here https://medium.com/crowdbotics/how-to-build-a-custom-amazon-alexa-skill-step-by-step-my-favorite-chess-player-dcc0edae53fb
but I need to randomize Alexa responses

```<code>Player_LIST = ["me or my wife", "me or my husband"]
Player_BIOGRAPHY = {"me or my wife":"She is.",

"me or my husband":"He is."}
</code>```

```<code>#------------------------------Part3--------------------------------
# Here we define the Request handler functions

def on_start():
    print("Session Started.")

def on_launch(event):
    onlunch_MSG = "Hi, you could say, for example: who is right me or my husband?"
    reprompt_MSG = "you can say, who is right, me or my wife?"
    card_TEXT = "Who is right, me or... ?."
    card_TITLE = "Choose your question."
    return output_json_builder_with_reprompt_and_card(onlunch_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)

def on_end():
    print("Session Ended.")
</code>```

```<code>#---------------------------Part3.1.1-------------------------------
# Here we define the intent handler functions

def player_bio(event):
    name=event['request']['intent']['slots']['player']['value']
    player_list_lower=[w.lower() for w in Player_LIST]
    if name.lower() in player_list_lower:
        reprompt_MSG = ""
        card_TEXT = "You've picked " + name.lower()
        card_TITLE = "You've picked " + name.lower()
        return output_json_builder_with_reprompt_and_card(Player_BIOGRAPHY[name.lower()], card_TEXT, card_TITLE, reprompt_MSG, False)
    else:
        wrongname_MSG = "Some questions may not yet be present in my database. Try to rephrase your sentence."
        reprompt_MSG = "For example, who is right, me or my wife?"
        card_TEXT = "Use the full question."
        card_TITLE = "Wrong question."
        return output_json_builder_with_reprompt_and_card(wrongname_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)
</code>```

When I say "Alexa, who is right, me or my wife?", she always says: "She is"
I want her to give me every time different responses like: He is or Him or her or listen to your wife! or of course you or any other answer. I tried to do this:

```<code>Player_BIOGRAPHY = {"me or my wife":"She is.",
"me or my wife":"you.",
"me or my wife":"Of course your wife",

"me or my husband":"He is.",
"me or my husband":"You are right.",
"me or my husband":"He is not right."}
</code>```

but Alexa always picks only the last response "Of course your wife."
How can I randomize many of these responses? I don't know how to code, but if I have come this far, I will be able to do it with your help, please. I can post the whole code it's just twice as much as here.

答:
Player_BIOGRAPHY is a dict, which means each key has only one value. If you initialize it as

```<code>Player_BIOGRAPHY = {"me or my wife":"She is.",
"me or my wife":"you.",
"me or my wife":"Of course your wife",

"me or my husband":"He is.",
"me or my husband":"You are right.",
"me or my husband":"He is not right."}
</code>```

The actual print output is:

```<code>{'me or my wife': 'Of course your wife', 'me or my husband': 'He is not right.'}
</code>```

What you should do is have a list of possible responses for each key, and then use something like random.choice in order to pick from the list. Like so,

```<code>Player_BIOGRAPHY = {"me or my wife": ["She is.","you.","Of course your wife"],

"me or my husband": ["He is.","You are right.","He is not right."]}
</code>```

And for random selection (you need to import random)

```<code>random.choice(Player_BIOGRAPHY[name.lower()])
# This will select a random item from the list mapped to name.lower()
</code>```

So your full code would be as follows:

```<code>import random # this can be at the top of the file too
def player_bio(event):
    name=event['request']['intent']['slots']['player']['value']
    player_list_lower=[w.lower() for w in Player_LIST]
    if name.lower() in player_list_lower:
        reprompt_MSG = ""
        card_TEXT = "You've picked " + name.lower()
        card_TITLE = "You've picked " + name.lower()
        return output_json_builder_with_reprompt_and_card(random.choice(Player_BIOGRAPHY[name.lower()]), card_TEXT, card_TITLE, reprompt_MSG, False)
    else:
        wrongname_MSG = "Some questions may not yet be present in my database. Try to rephrase your sentence."
        reprompt_MSG = "For example, who is right, me or my wife?"
        card_TEXT = "Use the full question."
        card_TITLE = "Wrong question."
        return output_json_builder_with_reprompt_and_card(wrongname_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)
</code>```

Body:
I'm creating a skill for Alexa where she would answer a question "Who is right, me or ..." I followed a tutorial here https://medium.com/crowdbotics/how-to-build-a-custom-amazon-alexa-skill-step-by-step-my-favorite-chess-player-dcc0edae53fb
but I need to randomize Alexa responses

Player_LIST = ["me or my wife", "me or my husband"]
Player_BIOGRAPHY = {"me or my wife":"She is.",

"me or my husband":"He is."}

#------------------------------Part3--------------------------------
# Here we define the Request handler functions

def on_start():
    print("Session Started.")

def on_launch(event):
    onlunch_MSG = "Hi, you could say, for example: who is right me or my husband?"
    reprompt_MSG = "you can say, who is right, me or my wife?"
    card_TEXT = "Who is right, me or... ?."
    card_TITLE = "Choose your question."
    return output_json_builder_with_reprompt_and_card(onlunch_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)

def on_end():
    print("Session Ended.")

#---------------------------Part3.1.1-------------------------------
# Here we define the intent handler functions

def player_bio(event):
    name=event['request']['intent']['slots']['player']['value']
    player_list_lower=[w.lower() for w in Player_LIST]
    if name.lower() in player_list_lower:
        reprompt_MSG = ""
        card_TEXT = "You've picked " + name.lower()
        card_TITLE = "You've picked " + name.lower()
        return output_json_builder_with_reprompt_and_card(Player_BIOGRAPHY[name.lower()], card_TEXT, card_TITLE, reprompt_MSG, False)
    else:
        wrongname_MSG = "Some questions may not yet be present in my database. Try to rephrase your sentence."
        reprompt_MSG = "For example, who is right, me or my wife?"
        card_TEXT = "Use the full question."
        card_TITLE = "Wrong question."
        return output_json_builder_with_reprompt_and_card(wrongname_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)

When I say "Alexa, who is right, me or my wife?", she always says: "She is"
I want her to give me every time different responses like: He is or Him or her or listen to your wife! or of course you or any other answer. I tried to do this:

Player_BIOGRAPHY = {"me or my wife":"She is.",
"me or my wife":"you.",
"me or my wife":"Of course your wife",

"me or my husband":"He is.",
"me or my husband":"You are right.",
"me or my husband":"He is not right."}

but Alexa always picks only the last response "Of course your wife."
How can I randomize many of these responses? I don't know how to code, but if I have come this far, I will be able to do it with your help, please. I can post the whole code it's just twice as much as here.

Body:
Player_BIOGRAPHY is a dict, which means each key has only one value. If you initialize it as

Player_BIOGRAPHY = {"me or my wife":"She is.",
"me or my wife":"you.",
"me or my wife":"Of course your wife",

"me or my husband":"He is.",
"me or my husband":"You are right.",
"me or my husband":"He is not right."}

The actual print output is:

{'me or my wife': 'Of course your wife', 'me or my husband': 'He is not right.'}

What you should do is have a list of possible responses for each key, and then use something like random.choice in order to pick from the list. Like so,

Player_BIOGRAPHY = {"me or my wife": ["She is.","you.","Of course your wife"],

"me or my husband": ["He is.","You are right.","He is not right."]}

And for random selection (you need to import random)

random.choice(Player_BIOGRAPHY[name.lower()])
# This will select a random item from the list mapped to name.lower()

So your full code would be as follows:

import random # this can be at the top of the file too
def player_bio(event):
    name=event['request']['intent']['slots']['player']['value']
    player_list_lower=[w.lower() for w in Player_LIST]
    if name.lower() in player_list_lower:
        reprompt_MSG = ""
        card_TEXT = "You've picked " + name.lower()
        card_TITLE = "You've picked " + name.lower()
        return output_json_builder_with_reprompt_and_card(random.choice(Player_BIOGRAPHY[name.lower()]), card_TEXT, card_TITLE, reprompt_MSG, False)
    else:
        wrongname_MSG = "Some questions may not yet be present in my database. Try to rephrase your sentence."
        reprompt_MSG = "For example, who is right, me or my wife?"
        card_TEXT = "Use the full question."
        card_TITLE = "Wrong question."
        return output_json_builder_with_reprompt_and_card(wrongname_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)


问:
firebase get only required data javascript
I'm using get() to read data into my react native app, using the following..

```<code>    firebase
  .firestore()
  .collection("users")
  .doc("test")
  .get()
  .then(response => {
    console.log(response);
  });
</code>```

I only want the test document, but what I'm getting is a 17000 line json doc, it does contain the data I need but the doc I'm after only has one field!

答: I found that I needed to use response.data() rather than just response!</p>

Body:
I'm using get() to read data into my react native app, using the following..

    firebase
  .firestore()
  .collection("users")
  .doc("test")
  .get()
  .then(response => {
    console.log(response);
  });

I only want the test document, but what I'm getting is a 17000 line json doc, it does contain the data I need but the doc I'm after only has one field!


问:
How can I allow any user to access data under a "uid" in Firestore?
I am building an app and I want the user to be able to tap on a URL using the URL scheme and be sent to a specific view controller on my app. That is working OK. However, I also need to get specific data onto that view controller. I need it so that User A can send an invite (URL) through Messages to User B. User B can tap on that invite (URL) to open a screen with details about the invitation from Firebase. The user can then accept the invite, or decline the invite.

I have setup my database like so:

users(collection)

"uid"(document)

parties(collection)

"partyName"(document)

respondedYes(field)

respondedNo(field)

This is the code that is in the AppDelegate for someone taps on a URL.

```<code>func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
    // Open the RSVPViewController.
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let rsvpViewController = storyboard.instantiateViewController(withIdentifier: "RSVPViewController") as! RSVPViewController

    if let window = self.window, let rootViewController = window.rootViewController {
        var currentController = rootViewController
        while let presentedController = currentController.presentedViewController {
            currentController = presentedController
        }
        currentController.present(rsvpViewController, animated: true, completion: nil)
    }
    return true
}
</code>```

I don't know how to get it so I know which invitation is being displayed after User B taps the URL so I cannot display the data. How can I get my app to work like I explained in my concept in the first paragraph? Let me know if you need more info. It is really hard to explain what I need help with.

答:
In this scenario, the invite URL needs to include parameters that will tell your app which invite  User B is opening. This can be achieved with simple GET params in your URL. So for instance your URL now  might look like this: myapp:Invite?invite_id=2, where the  invite_id param will be dealt with when User B opens the app.

Since it's not the best idea to give other user's access to data under the first user's UID, I would create a new "invitations" collection on firestore, where a new invitation document gets created when user A sends it. The UUID of the newly created invitation document would be the parameter you send in the URL above.

To create this URL, see this answer, Basically you would do the following:

let queryItems = [NSURLQueryItem(name: "invite_id", value: "123")]
let urlComps = NSURLComponents(string: "myapp:Invite")!
urlComps.queryItems = queryItems
let URL = urlComps.URL!
```

<p>Now, in the <code>application(_:,handleOpen:)</code> (for the receiver's app) you can parse URL params by extending the <code>URL</code> class as explained in this answer. </p>

<p>Assuming you use the extension described in the linked answer(which I tested on playground before recommending here), you can rewrite your function as follows:</p>

<pre class="lang-swift prettyprint-override"><code>func application(_ application: UIApplication, handleOpen url: URL) -> Bool {

    let invite_id = url.valueOf("invite_id")

    // get data from firestore for this invite id and store it in a struct called invite_data
    // (i'm going to assume that the variable invite_data is defined now).

    // Open the RSVPViewController.
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let rsvpViewController = storyboard.instantiateViewController(withIdentifier: "RSVPViewController") as! RSVPViewController

    // tell the rsvpViewController about the data:
    // this assumes you have a variable in rsvpVC that takes this info to display it.
    rsvpViewController.invite_data = invite_data

    if let window = self.window, let rootViewController = window.rootViewController {
        var currentController = rootViewController
        while let presentedController = currentController.presentedViewController {
            currentController = presentedController
        }
        currentController.present(rsvpViewController, animated: true, completion: nil)
    }
    return true
}
</code>```

Note that invite_data above is a struct and can contain whatever info you need to both display relevant details in the RSVP VC plus handle things like accepting or declining invites.

An alternate approach would be to simply send all the data you want to display in the rsvpViewController and not bother with an invitation document. Might be easier if the number of fields is small. But I suspect in this scenario you will want to pass things like party_id etc, so depends on your use case.

Body:
I am building an app and I want the user to be able to tap on a URL using the URL scheme and be sent to a specific view controller on my app. That is working OK. However, I also need to get specific data onto that view controller. I need it so that User A can send an invite (URL) through Messages to User B. User B can tap on that invite (URL) to open a screen with details about the invitation from Firebase. The user can then accept the invite, or decline the invite.

I have setup my database like so:

users(collection)

"uid"(document)

parties(collection)

"partyName"(document)

respondedYes(field)

respondedNo(field)

This is the code that is in the AppDelegate for someone taps on a URL.

func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
    // Open the RSVPViewController.
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let rsvpViewController = storyboard.instantiateViewController(withIdentifier: "RSVPViewController") as! RSVPViewController

    if let window = self.window, let rootViewController = window.rootViewController {
        var currentController = rootViewController
        while let presentedController = currentController.presentedViewController {
            currentController = presentedController
        }
        currentController.present(rsvpViewController, animated: true, completion: nil)
    }
    return true
}

I don't know how to get it so I know which invitation is being displayed after User B taps the URL so I cannot display the data. How can I get my app to work like I explained in my concept in the first paragraph? Let me know if you need more info. It is really hard to explain what I need help with.

Body:
In this scenario, the invite URL needs to include parameters that will tell your app which invite  User B is opening. This can be achieved with simple GET params in your URL. So for instance your URL now  might look like this: myapp:Invite?invite_id=2, where the  invite_id param will be dealt with when User B opens the app.

Since it's not the best idea to give other user's access to data under the first user's UID, I would create a new "invitations" collection on firestore, where a new invitation document gets created when user A sends it. The UUID of the newly created invitation document would be the parameter you send in the URL above.

To create this URL, see this answer, Basically you would do the following:

let queryItems = [NSURLQueryItem(name: "invite_id", value: "123")]
let urlComps = NSURLComponents(string: "myapp:Invite")!
urlComps.queryItems = queryItems
let URL = urlComps.URL!

Now, in the application(_:,handleOpen:) (for the receiver's app) you can parse URL params by extending the URL class as explained in this answer.

Assuming you use the extension described in the linked answer(which I tested on playground before recommending here), you can rewrite your function as follows:

func application(_ application: UIApplication, handleOpen url: URL) -> Bool {

    let invite_id = url.valueOf("invite_id")

    // get data from firestore for this invite id and store it in a struct called invite_data
    // (i'm going to assume that the variable invite_data is defined now).

    // Open the RSVPViewController.
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let rsvpViewController = storyboard.instantiateViewController(withIdentifier: "RSVPViewController") as! RSVPViewController

    // tell the rsvpViewController about the data:
    // this assumes you have a variable in rsvpVC that takes this info to display it.
    rsvpViewController.invite_data = invite_data

    if let window = self.window, let rootViewController = window.rootViewController {
        var currentController = rootViewController
        while let presentedController = currentController.presentedViewController {
            currentController = presentedController
        }
        currentController.present(rsvpViewController, animated: true, completion: nil)
    }
    return true
}

Note that invite_data above is a struct and can contain whatever info you need to both display relevant details in the RSVP VC plus handle things like accepting or declining invites.

An alternate approach would be to simply send all the data you want to display in the rsvpViewController and not bother with an invitation document. Might be easier if the number of fields is small. But I suspect in this scenario you will want to pass things like party_id etc, so depends on your use case.


问:
Search for string to move one row lower
Sheet contains commission data for employees.

Data is dumped out of Accounting system each week.

Need to move a cell value "Totals" down 1 row to align with the relevant data.

Have tried to search for the string "Totals" then cut and paste 1 row lower.

The string is in col-A.  The dataset size and content rows is variable each week but the target string is always in col-A and needs to drop down 1 row, probably with an offset (1, 0) style of command?

Dim m As Integer
m = 2

Do Until m = 300 'this is set to cover the expected occurrences

    On Error Resume Next
    Range(A1, A300).Cells("m", 0).Find(What:="Totals").Offset(1, 0) = "TOTALS"
    m = m + 1
    On Error GoTo 0

Loop
```

Getting no error messages but no results either!

答:
Forget the 'Cut & Paste'. Simply insert a new row at the 'Totals' row.

```<code>dim m as variant

m = application.match("totals", range("A:A"), 0)

if not iserror(m) then

    rows(m).insert

end if
</code>```

(and YES you should qualify your parent worksheets!)

Title: Search for string to move one row lower

Body:
Sheet contains commission data for employees.

Data is dumped out of Accounting system each week.

Need to move a cell value "Totals" down 1 row to align with the relevant data.

Have tried to search for the string "Totals" then cut and paste 1 row lower.

The string is in col-A.  The dataset size and content rows is variable each week but the target string is always in col-A and needs to drop down 1 row, probably with an offset (1, 0) style of command?

Dim m As Integer
m = 2

Do Until m = 300 'this is set to cover the expected occurrences

    On Error Resume Next
    Range(A1, A300).Cells("m", 0).Find(What:="Totals").Offset(1, 0) = "TOTALS"
    m = m + 1
    On Error GoTo 0

Loop

Getting no error messages but no results either!

Body:
Forget the 'Cut & Paste'. Simply insert a new row at the 'Totals' row.

dim m as variant

m = application.match("totals", range("A:A"), 0)

if not iserror(m) then

    rows(m).insert

end if

(and YES you should qualify your parent worksheets!)


问:
WhatsApp Business API send image to customer as first message
As far as I know, to use the WhatsApp Business API one must use the APIs developed by WhatsApp regional partners

Looking at our a regional partner API, one cannot send an image to the customer as for the first message of the conversation

Is this a WhatsApp Business API restriction or is can be the partner API restriction?

答: Right now this is a restriction by WhatsApp Business API. You can only use Message Templates as your first message which do not support images at the moment. You can read more about the API here: https://developers.facebook.com/docs/whatsapp/api/messages#cutoffcontrol</p>


问:
How to fix NullPointerException in a ListView?
I'm getting a NullPointerException while making a ListView using a custom adapter and don't know the part of code causing the error. Following is the code snippet:

ChatMessageAdapter.java

```<code>package com.myappcompany.rajan.thefictionalchat;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class ChatMessageAdapter extends ArrayAdapter<ChatText> {

    ChatMessageAdapter(Context context, ArrayList<ChatText> list) {
        super(context, 0, list);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View currentView = convertView;
        if(currentView==null) {
            LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
        }
        ChatText chatText = getItem(position);

        TextView textView;
        textView = (TextView)currentView.findViewById(R.id.chat_text);
        textView.setText(chatText.getMessage());

        if(chatText.getMessageType().equals("PERSON_1")) {
            textView.setGravity(Gravity.LEFT);
        }
        else if(chatText.getMessageType().equals("PERSON_2")) {
            textView.setGravity(Gravity.RIGHT);
        }
        else {
            textView.setGravity(Gravity.CENTER_HORIZONTAL);
        }

        return currentView;
    }
}

</code>```

list_items.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/chat_text"
        tools:text="Hello" />

</LinearLayout>
</code>```

I'm getting the following run-time error from the log as the app crashes:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
        at com.myappcompany.rajan.thefictionalchat.ChatMessageAdapter.getView(ChatMessageAdapter.java:32)
</code>```

答:
You need to find the view from where you inflated the parent.</p>

```<code>View rootView = LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
TextView textView ;
textView = rootView.findViewById(R.id.chat_text);
</code>```

Body:
I'm getting a NullPointerException while making a ListView using a custom adapter and don't know the part of code causing the error. Following is the code snippet:

ChatMessageAdapter.java

package com.myappcompany.rajan.thefictionalchat;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class ChatMessageAdapter extends ArrayAdapter<ChatText> {

    ChatMessageAdapter(Context context, ArrayList<ChatText> list) {
        super(context, 0, list);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View currentView = convertView;
        if(currentView==null) {
            LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
        }
        ChatText chatText = getItem(position);

        TextView textView;
        textView = (TextView)currentView.findViewById(R.id.chat_text);
        textView.setText(chatText.getMessage());

        if(chatText.getMessageType().equals("PERSON_1")) {
            textView.setGravity(Gravity.LEFT);
        }
        else if(chatText.getMessageType().equals("PERSON_2")) {
            textView.setGravity(Gravity.RIGHT);
        }
        else {
            textView.setGravity(Gravity.CENTER_HORIZONTAL);
        }

        return currentView;
    }
}

list_items.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/chat_text"
        tools:text="Hello" />

</LinearLayout>

I'm getting the following run-time error from the log as the app crashes:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
        at com.myappcompany.rajan.thefictionalchat.ChatMessageAdapter.getView(ChatMessageAdapter.java:32)

Body:
You need to find the view from where you inflated the parent.

View rootView = LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
TextView textView ;
textView = rootView.findViewById(R.id.chat_text);


问:
How do I remove values that are under a specified length of characters from a dictionary?
In this code, I am trying to remove values (synonyms) within a list that are 7 or fewer characters from the dictionary. For some reason, my code is only partially removing the values that are 7 or fewer characters. Also, please do not remove any of the functions or use imports and sets to solve and keep the current code as intact as possible.

My current output:

```<code>{'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}

</code>```

Desired output:

```<code>{'show' : ['demonstrate', 'indicate', 'point to'],
'slow' : ['leisurely', 'unhurried'],
'dangerous' : ['hazardous', 'perilous', 'uncertain']}
</code>```

```<code>word_dict = {'show': ['display', 'exhibit', 'convey', 'communicate', 'manifest', 'disclose'],
             'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious', 'slack'],
             'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    for key, value in word_dict.items():
        for item in value:
            if len(item) <= 7:
                value.remove(item)
    return word_dict

main()
</code>```

答:
This can be done using a dict and list comp:

```<code>edited_synonyms = {k: [w for w in v if len(w) >= 7] for k, v in word_dict.items()}
</code>```

I suggest you use this instead of trying to modify a collection while iterating over it. It’s also more efficient than the other options present.

Body:
In this code, I am trying to remove values (synonyms) within a list that are 7 or fewer characters from the dictionary. For some reason, my code is only partially removing the values that are 7 or fewer characters. Also, please do not remove any of the functions or use imports and sets to solve and keep the current code as intact as possible.

My current output:

{'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}

Desired output:

{'show' : ['demonstrate', 'indicate', 'point to'],
'slow' : ['leisurely', 'unhurried'],
'dangerous' : ['hazardous', 'perilous', 'uncertain']}

word_dict = {'show': ['display', 'exhibit', 'convey', 'communicate', 'manifest', 'disclose'],
             'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious', 'slack'],
             'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    for key, value in word_dict.items():
        for item in value:
            if len(item) <= 7:
                value.remove(item)
    return word_dict

main()

Body:
This can be done using a dict and list comp:

edited_synonyms = {k: [w for w in v if len(w) >= 7] for k, v in word_dict.items()}

I suggest you use this instead of trying to modify a collection while iterating over it. It’s also more efficient than the other options present.


问:
How to make a list of tuples from several lists?
I have 3 lists:

```<code>a = [0, 1, 2]
b = [3, 4, 5]
c = [6, 7, 8]
</code>```

And I need to create a list of tuples from them.

The output should look like this:

```<code>[(0, 3, 6), (1, 4, 7), (2, 5, 8)]
</code>```

Body:
I have 3 lists:

a = [0, 1, 2]
b = [3, 4, 5]
c = [6, 7, 8]

And I need to create a list of tuples from them.

The output should look like this:

[(0, 3, 6), (1, 4, 7), (2, 5, 8)]

Body:
Try this,

>>> a,b,c =[0, 1, 2],[3, 4, 5],[6, 7, 8]
>>> [(i,j,k) for i,j,k in zip(a,b,c)]
[(0, 3, 6), (1, 4, 7), (2, 5, 8)]


问:
React Native Release Signed APK crash on app start
I have an issue with react native release APK.

The app run on debug mode but it crash immediately on release mode

Some Phone it will be installed but when i will run it then it crash immediately and some other phone it will not installed Here is my app like looking this...

Here is my packege dependencies list

```<code>"dependencies": {
    "axios": "^0.18.0",
    "jwt-decode": "^2.2.0",
    "native-base": "^2.12.1",
    "react": "16.8.3",
    "react-native": "0.59.8",
    "react-native-awesome-alerts": "^1.2.0",
    "react-native-elements": "^1.1.0",
    "react-native-gesture-handler": "^1.2.1",
    "react-native-maps": "^0.24.2",
    "react-native-otp-inputs": "^3.0.2",
    "react-native-swiper": "^1.5.14",
    "react-native-vector-icons": "^6.4.2",
    "react-navigation": "^3.9.2",
    "react-redux": "^5.0.7",
    "redux": "^3.7.2",
    "redux-thunk": "^2.2.0"
},
</code>```

And my android/build.gradle file is -

```<code>buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
        multiDexEnabled = true
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1'
    }
}
</code>```

My android studio log cat crash ....

答:
based on your crash log, and the fact that app runs in debug it is very likely that you have bundling problem. Run this command again in order to create a fresh new bundle

```<code>react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/
</code>```

or

```<code>react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/
</code>```

if you don't have index.android.js, and create a new release

Body:
I have an issue with react native release APK.

The app run on debug mode but it crash immediately on release mode

Some Phone it will be installed but when i will run it then it crash immediately and some other phone it will not installed Here is my app like looking this...

Here is my packege dependencies list

"dependencies": {
    "axios": "^0.18.0",
    "jwt-decode": "^2.2.0",
    "native-base": "^2.12.1",
    "react": "16.8.3",
    "react-native": "0.59.8",
    "react-native-awesome-alerts": "^1.2.0",
    "react-native-elements": "^1.1.0",
    "react-native-gesture-handler": "^1.2.1",
    "react-native-maps": "^0.24.2",
    "react-native-otp-inputs": "^3.0.2",
    "react-native-swiper": "^1.5.14",
    "react-native-vector-icons": "^6.4.2",
    "react-navigation": "^3.9.2",
    "react-redux": "^5.0.7",
    "redux": "^3.7.2",
    "redux-thunk": "^2.2.0"
},

And my android/build.gradle file is -

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
        multiDexEnabled = true
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1'
    }
}

My android studio log cat crash ....

Body:
based on your crash log, and the fact that app runs in debug it is very likely that you have bundling problem. Run this command again in order to create a fresh new bundle

react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/

or

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/

if you don't have index.android.js, and create a new release


问:
How to find all possible consecutive and not overlapping sublists with minimum length of 3
What i actually want to do is to fit all possible straight lines in some data and find the best group of fitted lines by measuring their average R squared.

The step that i got stuck, is how to obtain with a sufficient method all those possible sublists so that i can make the fit afterwards. That's also the reason why i want a minimum length of 3 because every line that passes through two points has a perfect fit and i don't want that.

For example my first try was something like that:

```<code>def sub_lists(lst):
    lr = [lst[:i] for i in range(3,len(lst)-2)]
    rl = [lst[i:] for i in range(len(lst)-3,2,-1)]
    return [[lr[i], rl[-i-1]] for i in range(len(lr))]

>>> tst = [489, 495, 501, 506, 508, 514, 520, 522]
>>> sub_lists(tst)
[[[489, 495, 501], [506, 508, 514, 520, 522]],
[[489, 495, 501, 506], [508, 514, 520, 522]],
[[489, 495, 501, 506, 508], [514, 520, 522]]]
</code>```

but then i came across the below list with a length of 5 and it didn't work.Thus the expected output would be just the list:

```<code>>>> tst = [489, 495, 501, 506, 508]
>>> sub_lists_revised(tst)
[489, 495, 501, 506, 508]
</code>```

and following the same logic when i have a bigger length of data, like 10 for example:

```<code>>>> tst = [489, 495, 501, 506, 508, 514, 520, 525, 527, 529]
>>> sub_lists_revised(tst)
# the whole list
[489, 495, 501, 506, 508, 514, 520, 525, 527, 529]
# all possible pairs
[[[489, 495, 501], [506, 508, 514, 520, 525, 527, 529]],
[[489, 495, 501, 506], [508, 514, 520, 525, 527, 529]],
[[489, 495, 501, 506, 508], [514, 520, 525, 527, 529]],
[[489, 495, 501, 506, 508, 514], [520, 525, 527, 529]],
[[489, 495, 501, 506, 508, 514, 520], [525, 527, 529]]]
# and finally, all possible triplets which i couldn't figure out
[[[489, 495, 501], [506, 508, 514], [520, 525, 527, 529]],
[[489, 495, 501], [506, 508, 514, 520], [525, 527, 529]],
[[489, 495, 501, 506], [508, 514, 520], [525, 527, 529]]]
</code>```

So to conclude, what i want is a general approach that will work for even more data, although i don't think i would really need more than triplets at the moment.

I also add the figures from the first example after the fit: fig1, fig2,
 fig3

答:
Here is a way to do it recursively.

The first function generates the possible cut points for a list of length n producing sublists of length 3 at least.

The second one just yields the sublists, cut according to the cutting points.

Both are generators, so the sublists get produced on the fly, one at a time, if you use them in a loop. That might be useful as the number of possible sublists can grow very high when your data gets longer.

```<code>def cut_points(n, already_cut=None):
    # The first cut point is at 0
    if already_cut is None:
        already_cut = [0]

    # We can cut at all places between the last cut plus 3
    # and the length minus 3, and yield recursively the solutions for each choice
    for i in range(already_cut[-1]+3, n-2):
        cuts = already_cut[:] + [i]
        yield from cut_points(n, cuts)

    # When we tried all cut points and reached the total length, we yield the cut points list
    yield already_cut[:] + [n]

def all_possible_sublists(data):
    n = len(data)
    for cut in cut_points(n):
        yield [data[cut[i]:cut[i+1]] for i in range(len(cut)-1)]
</code>```

Some tests:

```<code>list(all_possible_sublists([0, 1, 2, 3]))
# [[[0, 1, 2, 3]]]

list(all_possible_sublists([0, 1, 2, 3, 4, 5, 6]))
# [[[0, 1, 2], [3, 4, 5, 6]],
#  [[0, 1, 2, 3], [4, 5, 6]],
#  [[0, 1, 2, 3, 4, 5, 6]]]

for sublist in all_possible_sublists([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]):
    print(sublist)
# [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
# [[0, 1, 2], [3, 4, 5, 6], [7, 8, 9]]
# [[0, 1, 2], [3, 4, 5, 6, 7, 8, 9]]
# [[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]
# [[0, 1, 2, 3], [4, 5, 6, 7, 8, 9]]
# [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
# [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9]]
# [[0, 1, 2, 3, 4, 5, 6], [7, 8, 9]]
# [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
</code>```

Body:
What i actually want to do is to fit all possible straight lines in some data and find the best group of fitted lines by measuring their average R squared.

The step that i got stuck, is how to obtain with a sufficient method all those possible sublists so that i can make the fit afterwards. That's also the reason why i want a minimum length of 3 because every line that passes through two points has a perfect fit and i don't want that.

For example my first try was something like that:

def sub_lists(lst):
    lr = [lst[:i] for i in range(3,len(lst)-2)]
    rl = [lst[i:] for i in range(len(lst)-3,2,-1)]
    return [[lr[i], rl[-i-1]] for i in range(len(lr))]

>>> tst = [489, 495, 501, 506, 508, 514, 520, 522]
>>> sub_lists(tst)
[[[489, 495, 501], [506, 508, 514, 520, 522]],
[[489, 495, 501, 506], [508, 514, 520, 522]],
[[489, 495, 501, 506, 508], [514, 520, 522]]]

but then i came across the below list with a length of 5 and it didn't work.Thus the expected output would be just the list:

>>> tst = [489, 495, 501, 506, 508]
>>> sub_lists_revised(tst)
[489, 495, 501, 506, 508]

and following the same logic when i have a bigger length of data, like 10 for example:

>>> tst = [489, 495, 501, 506, 508, 514, 520, 525, 527, 529]
>>> sub_lists_revised(tst)
# the whole list
[489, 495, 501, 506, 508, 514, 520, 525, 527, 529]
# all possible pairs
[[[489, 495, 501], [506, 508, 514, 520, 525, 527, 529]],
[[489, 495, 501, 506], [508, 514, 520, 525, 527, 529]],
[[489, 495, 501, 506, 508], [514, 520, 525, 527, 529]],
[[489, 495, 501, 506, 508, 514], [520, 525, 527, 529]],
[[489, 495, 501, 506, 508, 514, 520], [525, 527, 529]]]
# and finally, all possible triplets which i couldn't figure out
[[[489, 495, 501], [506, 508, 514], [520, 525, 527, 529]],
[[489, 495, 501], [506, 508, 514, 520], [525, 527, 529]],
[[489, 495, 501, 506], [508, 514, 520], [525, 527, 529]]]

So to conclude, what i want is a general approach that will work for even more data, although i don't think i would really need more than triplets at the moment.

I also add the figures from the first example after the fit: fig1, fig2,
 fig3

Body:
Here is a way to do it recursively.

The first function generates the possible cut points for a list of length n producing sublists of length 3 at least.

The second one just yields the sublists, cut according to the cutting points.

Both are generators, so the sublists get produced on the fly, one at a time, if you use them in a loop. That might be useful as the number of possible sublists can grow very high when your data gets longer.

def cut_points(n, already_cut=None):
    # The first cut point is at 0
    if already_cut is None:
        already_cut = [0]

    # We can cut at all places between the last cut plus 3
    # and the length minus 3, and yield recursively the solutions for each choice
    for i in range(already_cut[-1]+3, n-2):
        cuts = already_cut[:] + [i]
        yield from cut_points(n, cuts)

    # When we tried all cut points and reached the total length, we yield the cut points list
    yield already_cut[:] + [n]

def all_possible_sublists(data):
    n = len(data)
    for cut in cut_points(n):
        yield [data[cut[i]:cut[i+1]] for i in range(len(cut)-1)]

Some tests:

list(all_possible_sublists([0, 1, 2, 3]))
# [[[0, 1, 2, 3]]]

list(all_possible_sublists([0, 1, 2, 3, 4, 5, 6]))
# [[[0, 1, 2], [3, 4, 5, 6]],
#  [[0, 1, 2, 3], [4, 5, 6]],
#  [[0, 1, 2, 3, 4, 5, 6]]]

for sublist in all_possible_sublists([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]):
    print(sublist)
# [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
# [[0, 1, 2], [3, 4, 5, 6], [7, 8, 9]]
# [[0, 1, 2], [3, 4, 5, 6, 7, 8, 9]]
# [[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]
# [[0, 1, 2, 3], [4, 5, 6, 7, 8, 9]]
# [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
# [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9]]
# [[0, 1, 2, 3, 4, 5, 6], [7, 8, 9]]
# [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]


问:
SQL Server changing value of float
I created console application where I'm using EF. I've got model where are some float variables. In my Database I also use FLOAT.

In c# I have got this value: 3,3
After insert it to my database there is value: 3,29999995231628

Why is it happening?

答: You can use real instead of float and its true to save

Title: SQL Server changing value of float


问:
perl win32::gui remove elements
I have a dialogbox, to which i populate elements(labels) on activate event.
I want to remove these elements(labels) when the window is being deactivated. something like:[its erroneous fragment of main code but explanatory]

```<code>my $wchRW = Win32::GUI::DialogBox->new(
-name   =>  "wchR",
-title  =>  "whed",
-left   =>  CW_USEDEFAULT,
-size   =>  [300, 130],
-parent =>  $mw,
);

$wchRW->AddGroupbox(
-name   =>  "wchR_gb",
-text   =>  "being watched",
-width  =>  $wchRW->ScaleWidth() - $padding,
-height =>  100,
-left   =>  $padding/2,
);

sub wchR_Activate {
my $wchtxt = "sample";
# lbleft, lbtop are calculated here
$wchRW->AddLabel(
            -name   =>  "wchR_lb0",
            -text   =>  $wchTxt,
            -left   =>  $lbLeft,
            -top    =>  $lbTop,
        );
}
sub gitni_wchR_Deactivate {
print "Here\n";
Win32::GUI::DestroyWindow($wchRW->wchR_lb0); #this is line n
}
#i have a button in main window $mw.
#onclick of this button this dialogbox is shown.
#sub b1_Click { $wchRW->DoModal(); return 0; }
</code>```

But the problem is, "Here" in deactivate is called many times and an exception is thrown thereafter [can't locate auto/wchR_.al in @INC .... line n]. Freezing the main window and only option is to end process through task-manager.

 Please help me out.
Why "here" is printed many times?
How to remove element permanently?
Thanks

答:
The sub wchR_Deactivate will be invoked many times because it happens every time when dialog lost focus.

Normally you should not do AddLabel in _Activeate() event handler. All the thing should be created ahead. You could do Win32::GUI::Hide or Win32::GUI::Show to manipulate the control display status, and using $wchRW->wchR_lb0->Text($new_message) to change the message.

ContentLicense: CC BY-SA 2.5

Title: perl win32::gui remove elements

Body:
I have a dialogbox, to which i populate elements(labels) on activate event.
I want to remove these elements(labels) when the window is being deactivated. something like:[its erroneous fragment of main code but explanatory]

my $wchRW = Win32::GUI::DialogBox->new(
-name   =>  "wchR",
-title  =>  "whed",
-left   =>  CW_USEDEFAULT,
-size   =>  [300, 130],
-parent =>  $mw,
);

$wchRW->AddGroupbox(
-name   =>  "wchR_gb",
-text   =>  "being watched",
-width  =>  $wchRW->ScaleWidth() - $padding,
-height =>  100,
-left   =>  $padding/2,
);

sub wchR_Activate {
my $wchtxt = "sample";
# lbleft, lbtop are calculated here
$wchRW->AddLabel(
            -name   =>  "wchR_lb0",
            -text   =>  $wchTxt,
            -left   =>  $lbLeft,
            -top    =>  $lbTop,
        );
}
sub gitni_wchR_Deactivate {
print "Here\n";
Win32::GUI::DestroyWindow($wchRW->wchR_lb0); #this is line n
}
#i have a button in main window $mw.
#onclick of this button this dialogbox is shown.
#sub b1_Click { $wchRW->DoModal(); return 0; }

But the problem is, "Here" in deactivate is called many times and an exception is thrown thereafter [can't locate auto/wchR_.al in @INC .... line n]. Freezing the main window and only option is to end process through task-manager.

 Please help me out.
Why "here" is printed many times?
How to remove element permanently?
Thanks