问:
How to write HTML to a file dynamically in Python
I have the following code:

```<code>for item in soup.select('.profile-detail'):
    f= open('htmlfile.html', 'w')
    f.write(item)
    f.close()
</code>```

I want to write items into "htmlfile.html" but it's giving me the error:

TypeError: write() argument must be str, not Tag

答:
I gather from the soup in your snipped that you're using BeautifulSoup to extract elements with the class "profile-detail". Given that, there are two problems with the code you have:

The value item in the list returned by the select() function is an instance of the Tag class and the the write method of the file object expects a string. As @PRMoureu wrote, you can cast the Tag instance to a string and it'll return the raw HTML string it represents by replacing the file writing line with this:

```<code>f.write(str(item))
</code>```

The file you've open is opened in write ("w") mode in the loop. This means that for each iteration of the loop the file would be overwritten and if you were trying to collect all the elements returned by your query, you would only get the last one. If you want to have all of them in the file, the following are alternative ways to fix it:

```<code># Open the file in append mode
for item in soup.select('.profile-detail'):
    f = open('htmlfile.html', 'a')
    f.write(item)
    f.close()
</code>```

This isn't too good though since it is unnecessary to open and close the file on each iteration. We can keep the file open for all our writes:

```<code># Open and close file just once
f = open('htmlfile.html', 'w')            # Okay to open in write mode now
for item in soup.select('.profile-detail'):
    f.write(item)
    f.write('\n') # In case you're expecting each on a new line
f.close()
</code>```

Or, my personal favourite, doing pretty much the same but with contexts so you don't worry about forgetting the f.close() or accidentally giving it the wrong indentation or something later:

```<code># With contexts
with open('htmlfile.html', 'w') as f:
    for item in soup.select('.profile-detail'):
         f.write(item)
         f.write('\n') # In case you're expecting each on a new line
# File is auto-magically closed by the time you get here
</code>```

Body:
I have the following code:

for item in soup.select('.profile-detail'):
    f= open('htmlfile.html', 'w')
    f.write(item)
    f.close()

I want to write items into "htmlfile.html" but it's giving me the error:

TypeError: write() argument must be str, not Tag

Body:
I gather from the soup in your snipped that you're using BeautifulSoup to extract elements with the class "profile-detail". Given that, there are two problems with the code you have:

The value item in the list returned by the select() function is an instance of the Tag class and the the write method of the file object expects a string. As @PRMoureu wrote, you can cast the Tag instance to a string and it'll return the raw HTML string it represents by replacing the file writing line with this:

f.write(str(item))

The file you've open is opened in write ("w") mode in the loop. This means that for each iteration of the loop the file would be overwritten and if you were trying to collect all the elements returned by your query, you would only get the last one. If you want to have all of them in the file, the following are alternative ways to fix it:

# Open the file in append mode
for item in soup.select('.profile-detail'):
    f = open('htmlfile.html', 'a')
    f.write(item)
    f.close()

This isn't too good though since it is unnecessary to open and close the file on each iteration. We can keep the file open for all our writes:

# Open and close file just once
f = open('htmlfile.html', 'w')            # Okay to open in write mode now
for item in soup.select('.profile-detail'):
    f.write(item)
    f.write('\n') # In case you're expecting each on a new line
f.close()

Or, my personal favourite, doing pretty much the same but with contexts so you don't worry about forgetting the f.close() or accidentally giving it the wrong indentation or something later:

# With contexts
with open('htmlfile.html', 'w') as f:
    for item in soup.select('.profile-detail'):
         f.write(item)
         f.write('\n') # In case you're expecting each on a new line
# File is auto-magically closed by the time you get here


来源: stackexchange

问:
Select row from DataGrid and press Delete button ERROR: 42601
```<code>private void Delete_Click(object sender, RoutedEventArgs e)
        {
            if (dataGrid1.SelectedItem == null)
                return;
            DataRowView rowview = (DataRowView)dataGrid1.SelectedItem;
            NpgsqlConnection con = new NpgsqlConnection("Server=10.0.5.22;Port=5432;Database=TEST_DB;User Id=postgres;Password=test;");
            con.Open();
            NpgsqlCommand cmd = new NpgsqlCommand("delete from Product where productcode="+rowview["productcode"]+"'", con);
            cmd.ExecuteNonQuery();  // here it is showing error as ERROR: 42601: syntax error at or near ":"
            con.Close();
        }
</code>```

When i select the row from DataGrid and press Delete button, it shows ERROR:

42601: syntax error at or near ":" (near to cmd.ExecuteNonQuery

答:
I think you missed an apostrophe (') near productcode='"
Please try with this.

```<code>private void Delete_Click(object sender, RoutedEventArgs e)
    {
        if (dataGrid1.SelectedItem == null)
            return;
        DataRowView rowview = (DataRowView)dataGrid1.SelectedItem;
        NpgsqlConnection con = new NpgsqlConnection("Server=10.0.5.22;Port=5432;Database=TEST_DB;User Id=postgres;Password=test;");
        con.Open();
        NpgsqlCommand cmd = new NpgsqlCommand("delete from Product where productcode='" + rowview["productcode"] + "'", con);
        cmd.ExecuteNonQuery();  // here it is showing error as ERROR: 42601: syntax error at or near ":"
        con.Close();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
private void Delete_Click(object sender, RoutedEventArgs e)
        {
            if (dataGrid1.SelectedItem == null)
                return;
            DataRowView rowview = (DataRowView)dataGrid1.SelectedItem;
            NpgsqlConnection con = new NpgsqlConnection("Server=10.0.5.22;Port=5432;Database=TEST_DB;User Id=postgres;Password=test;");
            con.Open();
            NpgsqlCommand cmd = new NpgsqlCommand("delete from Product where productcode="+rowview["productcode"]+"'", con);
            cmd.ExecuteNonQuery();  // here it is showing error as ERROR: 42601: syntax error at or near ":"
            con.Close();
        }

When i select the row from DataGrid and press Delete button, it shows ERROR:

42601: syntax error at or near ":" (near to cmd.ExecuteNonQuery

Body:
I think you missed an apostrophe (') near productcode='"
Please try with this.

private void Delete_Click(object sender, RoutedEventArgs e)
    {
        if (dataGrid1.SelectedItem == null)
            return;
        DataRowView rowview = (DataRowView)dataGrid1.SelectedItem;
        NpgsqlConnection con = new NpgsqlConnection("Server=10.0.5.22;Port=5432;Database=TEST_DB;User Id=postgres;Password=test;");
        con.Open();
        NpgsqlCommand cmd = new NpgsqlCommand("delete from Product where productcode='" + rowview["productcode"] + "'", con);
        cmd.ExecuteNonQuery();  // here it is showing error as ERROR: 42601: syntax error at or near ":"
        con.Close();
    }


问:
How to print Chinese characters in text file
I am reading the data From text file and Printing in HTML file using java and Html code, But junk characters printing in HTML file

report.reportGenerator("result.txt", reportHTMLFile, testCaseSheetMasterMap, environmentUrl, "01/01/01", "02/02/02");

StringBuilder htmlStringBuilder = new StringBuilder();

        // append html header and title
        //<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
        htmlStringBuilder.append(
                " <meta charset=\"UTF-8\"><title>CitiGR Automation Report</title>");
        // append body
        htmlStringBuilder.append("");
        htmlStringBuilder.append("

" + pageTitle + "

");
        htmlStringBuilder.append("
Environment URL : "+environmentUrl+"");
        htmlStringBuilder.append("

Start Run Time: "+startRunTime);
        htmlStringBuilder.append("
End  Run Time  : "+endRunTime+"
");

        /* append 1st table */
        htmlStringBuilder.append(
                "
<col width=\"50\"><col width=\"200\"><col width=\"200\"><col width=\"100\"><col width=\"100\"><col width=\"100\"><col width=\"100\">");
        // append row - table header
        htmlStringBuilder.append(
                "
"
                + "Si.No.	"
                + "TestCase Name	"
                + "Total no. of scripts executed	"
                + "Pass	"
                + "Fail	"
                + "Pass %	"
                + "Fail %	"
                + "
");

        int count=1;
        for (int i = 0; i < eachTestCaseMenuList.size(); ) {
            htmlStringBuilder.append(""
                    + "
"
                    + ""+count+"	"
                    + ""+ eachTestCaseMenuList.get(i) + "	"
                    + ""+ eachTestCaseMenuList.get(i+1) + "	"
                    + "" + eachTestCaseMenuList.get(i+2)+ "	"
                    + "" + eachTestCaseMenuList.get(i+3) + "	"
                    + "" + eachTestCaseMenuList.get(i+4)+ "	"
                    + "" + eachTestCaseMenuList.get(i+5) + "	"
                    + "
");
            i+=6;
            count++;
        }

        htmlStringBuilder.append(
                "
"
                + "	"
                + "Total	"
                + ""+totalTestCaseCount+"	"
                + ""+totalPassCount+"	"
                + ""+totalFailCount+"	"
                + ""+totalPassPercent+" %	"
                + ""+totalFailPercent+" %	"
                + "
");
```

答:
Include inside your  tags an encoding tag

Try as follows,

```<code><meta charset="utf-8">
</code>```

or

```<code><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</code>```

Body:
Include inside your <head> tags an encoding tag

Try as follows,

<meta charset="utf-8">

or

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">


问:
Stop word-wrap dividing words
```<code>body { word-wrap: break-word;}
</code>```

I've been using that code (above) to fit the text in the body into it's container. However what I don't like about it, is that it breaks up words.

Is there another way where it will not break up words and only line break after or before a word?

EDIT: This is for use within a UIWebView.

答:
Please use nowrap and wrap value didn't come for me. nowrap solved the issue.

white-space: nowrap;
```

ContentLicense: CC BY-SA 2.5

Title: Stop word-wrap dividing words

Body:
body { word-wrap: break-word;}

I've been using that code (above) to fit the text in the body into it's container. However what I don't like about it, is that it breaks up words.

Is there another way where it will not break up words and only line break after or before a word?

EDIT: This is for use within a UIWebView.

ContentLicense: CC BY-SA 4.0


问:
Can I use a FB share dialog with a access token?
The situation

I'm developing a web tool that will be used inside a iPhone/Android app.
Inside the app the User have to log into facebook, with the FB app or a regular fallback.

We discovered that the FB session between the app and the webview was not carried over. (If you logged in on FB in the app, you still had to log in to FB in the webview)

To solve this we made the App send the access token to the webview through a POST.

In the web view I use the Graph API to fetch the users FB ID.
The ID is used in a API that the App and the webview-site uses to share data.

So far so good.

The Problem

We want to use a share dialog on some parts of the webview.
But we don't want to login again (We want to use the Access Token for this as well)

(I cannot do any changes to the App itself so I'm stuck with what I have.
A Access Token)

Tries

1) I have tried to find if it is possible to use a regular Share Dialog with a Access Token. It doesn't seem to work from the documentation.

2) It doesn't work to "login" to FB with a access token from what I can tell. No way to pass the Access Token.

3) I can't create a Share Dialog with FB.ui since that function doesn't take a Access Token.

4) Using the URL Redirection method doesn't work either because you will get a login dialog. (Since I can't pass the Access Token from what I can tell)

5) I can post directly to a users feed with fb.api() and the "publish_actions" permission. With fb.api() I can pass the Access Token to the function. But the user can't control what is being sent. I'm worried that might anger users.

I could build a custom dialog for the user and send what they wrote there. That is a last resort if no other solution is found.

When I tried to test this solution in the Graph API Explorer my FB account accused my app for spamming.. So I'm not sure this is a valid solution.

Conclusion

It seems very difficult to share content with only a Access Token.
Solution nr 5 works but I would rather use a regular share dialog.

I know that it seems impossible according to the documentation but FB are not the best at updating their documentation. So I'm hoping someone can give me a definite answer.

Resources

If I understood correctly I'm only allowed to share 2 links, since I don't have enough reputation.

https://developers.facebook.com/docs/plugins/share-button

https://developers.facebook.com/docs/javascript/reference/

答:
you can use this.

```<code>https://www.facebook.com/dialog/share?
app_id=xxxxxxxxxx&display=popup
&href=http://google.com
&access_token=<user access token>
</code>```

check your app access token first at

graph.facebook.com/debug_token?
input_token={token-to-inspect}
&access_token={app-token-or-admin-token}

check that your app has access to user public-profile

graph.facebook.com/debug_token?
input_token=
&access_token=

Body:
you can use this.

https://www.facebook.com/dialog/share?
app_id=xxxxxxxxxx&display=popup
&href=http://google.com
&access_token=<user access token>

check your app access token first at

graph.facebook.com/debug_token?
input_token={token-to-inspect}
&access_token={app-token-or-admin-token}

check that your app has access to user public-profile

graph.facebook.com/debug_token?
input_token=
&access_token=


问:
PHP : how to convert object to array using loop
(
    [0] => stdClass Object
        (
            [name] => Ford
            [models] => Array
                (
                    [0] => Fiesta
                    [1] => Focus
                    [2] => Mustang
                )

```<code>    )

[1] => stdClass Object
    (
        [name] => BMW
        [models] => Array
            (
                [0] => 320
                [1] => X3
                [2] => X5
            )

    )

[2] => stdClass Object
    (
        [name] => Fiat
        [models] => Array
            (
                [0] => 500
                [1] => Panda
            )

    )
</code>```

)

答:
Yes we can use JSON functions to encode to JSON and then decode back to an array. This will not include private and protected members, however.

```<code>$array = json_decode(json_encode($object), true);
</code>```

Alternatively, the following function will convert from an object to an array including private and protected members:

```<code>function objectToArray ($object) {
    if(!is_object($object) && !is_array($object))
        return $object;

    return array_map('objectToArray', (array) $object);
}
</code>```

Body:
(
    [0] => stdClass Object
        (
            [name] => Ford
            [models] => Array
                (
                    [0] => Fiesta
                    [1] => Focus
                    [2] => Mustang
                )

    )

[1] => stdClass Object
    (
        [name] => BMW
        [models] => Array
            (
                [0] => 320
                [1] => X3
                [2] => X5
            )

    )

[2] => stdClass Object
    (
        [name] => Fiat
        [models] => Array
            (
                [0] => 500
                [1] => Panda
            )

    )

)

Body:
Yes we can use JSON functions to encode to JSON and then decode back to an array. This will not include private and protected members, however.

$array = json_decode(json_encode($object), true);

Alternatively, the following function will convert from an object to an array including private and protected members:

function objectToArray ($object) {
    if(!is_object($object) && !is_array($object))
        return $object;

    return array_map('objectToArray', (array) $object);
}


问:
Django Serializer page jump
I'm freshman in the Restful,I have some issues to figure out about 'Serializer page jump',the class is as follows, I want to know how to decide name_instance return to which page and how I can redirect other page with some object data?

```<code>class NameInteractiveSerializer(serializers.ModelSerializer):
    class Meta:
        model = Name
        fields = '__all__'
    def create(self, validated_data):
        if validated_data['Name'] and validated_data['Name_SC']:
            pref_flag = "2"
            pref_name = validated_data['Name']
        elif validated_data['Name_SC']:
            pref_flag = "1"
            pref_name = validated_data['Name_SC']
        else:
            pref_flag = "2"
            pref_name = ""
        Name_instance = Name(
            Name=validated_data['Name'],
            Name_SC=validated_data['Name_SC'],
            Pref_Name_Flg=pref_flag,
            Status = '1',
        )
        name_instance.save()
        name=name_instance.save()
        return name
</code>```

答:
I have solved the issue by myself. Serializer is just to send data just like Json to fore-end,I can realize the function in the fore-end as follows,Angularjs is for example as follows:

```<code>var str_path = '/ui-contact/add/';
 $location.path(str_path).search({company_id: values.id});
  scope.$apply();
</code>```

Yes! it's the answer what I want!

Title: Django Serializer page jump

Body:
I'm freshman in the Restful,I have some issues to figure out about 'Serializer page jump',the class is as follows, I want to know how to decide name_instance return to which page and how I can redirect other page with some object data?

class NameInteractiveSerializer(serializers.ModelSerializer):
    class Meta:
        model = Name
        fields = '__all__'
    def create(self, validated_data):
        if validated_data['Name'] and validated_data['Name_SC']:
            pref_flag = "2"
            pref_name = validated_data['Name']
        elif validated_data['Name_SC']:
            pref_flag = "1"
            pref_name = validated_data['Name_SC']
        else:
            pref_flag = "2"
            pref_name = ""
        Name_instance = Name(
            Name=validated_data['Name'],
            Name_SC=validated_data['Name_SC'],
            Pref_Name_Flg=pref_flag,
            Status = '1',
        )
        name_instance.save()
        name=name_instance.save()
        return name

Body:
I have solved the issue by myself. Serializer is just to send data just like Json to fore-end,I can realize the function in the fore-end as follows,Angularjs is for example as follows:

var str_path = '/ui-contact/add/';
 $location.path(str_path).search({company_id: values.id});
  scope.$apply();

Yes! it's the answer what I want!


问:
Combining w2vec and feature selection in pipeline
Based on this article: http://nadbordrozd.github.io/blog/2016/05/20/text-classification-with-word2vec/ I am trying to implement a gensim word2vec model with the pretrained vectors of GloVe in a text classification task. However, I would like to do FeatureSelection also in my text data. I tried multiple sequences in the pipeline but i get fast a memory error which points to the transform part of TfidfEmbeddingVectorizer.

```<code>   return np.array([
                np.mean([self.word2vec[w] * self.word2weight[w]
                         for w in words if w in self.word2vec] or
                        [np.zeros(self.dim)], axis=0)
                for words in X
</code>```

If I replace the TfidfEmbeddingVectorizer class with a regular TfIdfVectorizer it works properly. Is there a way I could combine SelectFromModel and W2vec in the pipeline?

```<code>from sklearn.base import BaseEstimator, TransformerMixin
import pandas as pd
import numpy as np
import itertools
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import precision_recall_fscore_support as score, f1_score
import pickle
from sklearn.externals import joblib
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectFromModel
from sklearn.pipeline import FeatureUnion
from sklearn.feature_extraction import DictVectorizer
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.svm import LinearSVC
import gensim
import collections

class ItemSelector(BaseEstimator, TransformerMixin):

    def __init__(self, column):
        self.column = column

    def fit(self, X, y=None, **fit_params):
        return self

    def transform(self, X):
        return (X[self.column])

class TextStats(BaseEstimator, TransformerMixin):
    """Extract features from each document for DictVectorizer"""

    def fit(self, x, y=None):
        return self

    def transform(self, posts):
        return [{'REPORT_M': text}
                for text in posts]

class TfidfEmbeddingVectorizer(object):
  def __init__(self, word2vec):
    self.word2vec = word2vec
    self.word2weight = None
    self.dim = len(word2vec.values())

  def fit(self, X, y):
    tfidf = TfidfVectorizer(analyzer=lambda x: x)
    tfidf.fit(X)
    # if a word was never seen - it must be at least as infrequent
    # as any of the known words - so the default idf is the max of
    # known idf's
    max_idf = max(tfidf.idf_)
    self.word2weight = collections.defaultdict(
        lambda: max_idf,
        [(w, tfidf.idf_[i]) for w, i in tfidf.vocabulary_.items()])

    return self

  def transform(self, X):
    return np.array([
            np.mean([self.word2vec[w] * self.word2weight[w]
                     for w in words if w in self.word2vec] or
                    [np.zeros(self.dim)], axis=0)
            for words in X
        ])

# training model
 def train(data_train, data_val):

    with open("glove.6B/glove.6B.50d.txt", "rb") as lines:
        w2v = {line.split()[0]: np.array(map(float, line.split()[1:]))
               for line in lines}
    classifier = Pipeline([
                    ('union', FeatureUnion([

                            ('text', Pipeline([
                                ('selector', ItemSelector(column='TEXT')),
                                ("word2vec vectorizer", TfidfEmbeddingVectorizer(w2v)),
                                ('feature_selection', SelectFromModel(LinearSVC(penalty="l1", dual=False),threshold=0.01))
                            ])),

                            ('category', Pipeline([
                                ('selector', ItemSelector(column='category')),
                                ('stats', TextStats()),
                                ('vect', DictVectorizer())
                            ]))
    ])),
                    ('clf',ExtraTreesClassifier(n_estimators=200, max_depth=500, min_samples_split=6, class_weight= 'balanced'))])

    classifier.fit(data_train,data_train.CLASSES)
    predicted = classifier.predict(data_val)
</code>```

答:
I think in here self.dim = len(word2vec.values()) you should specify the dimension of the model. If you are using glove.6B.50d.txt, then the dimension should be 50.

len(word2vec.values()) is the total number of words, thus will create a huge matrix, i.e., memory error.

Body:
Based on this article: http://nadbordrozd.github.io/blog/2016/05/20/text-classification-with-word2vec/ I am trying to implement a gensim word2vec model with the pretrained vectors of GloVe in a text classification task. However, I would like to do FeatureSelection also in my text data. I tried multiple sequences in the pipeline but i get fast a memory error which points to the transform part of TfidfEmbeddingVectorizer.

   return np.array([
                np.mean([self.word2vec[w] * self.word2weight[w]
                         for w in words if w in self.word2vec] or
                        [np.zeros(self.dim)], axis=0)
                for words in X

If I replace the TfidfEmbeddingVectorizer class with a regular TfIdfVectorizer it works properly. Is there a way I could combine SelectFromModel and W2vec in the pipeline?

from sklearn.base import BaseEstimator, TransformerMixin
import pandas as pd
import numpy as np
import itertools
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import precision_recall_fscore_support as score, f1_score
import pickle
from sklearn.externals import joblib
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectFromModel
from sklearn.pipeline import FeatureUnion
from sklearn.feature_extraction import DictVectorizer
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.svm import LinearSVC
import gensim
import collections

class ItemSelector(BaseEstimator, TransformerMixin):

    def __init__(self, column):
        self.column = column

    def fit(self, X, y=None, **fit_params):
        return self

    def transform(self, X):
        return (X[self.column])

class TextStats(BaseEstimator, TransformerMixin):
    """Extract features from each document for DictVectorizer"""

    def fit(self, x, y=None):
        return self

    def transform(self, posts):
        return [{'REPORT_M': text}
                for text in posts]

class TfidfEmbeddingVectorizer(object):
  def __init__(self, word2vec):
    self.word2vec = word2vec
    self.word2weight = None
    self.dim = len(word2vec.values())

  def fit(self, X, y):
    tfidf = TfidfVectorizer(analyzer=lambda x: x)
    tfidf.fit(X)
    # if a word was never seen - it must be at least as infrequent
    # as any of the known words - so the default idf is the max of
    # known idf's
    max_idf = max(tfidf.idf_)
    self.word2weight = collections.defaultdict(
        lambda: max_idf,
        [(w, tfidf.idf_[i]) for w, i in tfidf.vocabulary_.items()])

    return self

  def transform(self, X):
    return np.array([
            np.mean([self.word2vec[w] * self.word2weight[w]
                     for w in words if w in self.word2vec] or
                    [np.zeros(self.dim)], axis=0)
            for words in X
        ])

# training model
 def train(data_train, data_val):

    with open("glove.6B/glove.6B.50d.txt", "rb") as lines:
        w2v = {line.split()[0]: np.array(map(float, line.split()[1:]))
               for line in lines}
    classifier = Pipeline([
                    ('union', FeatureUnion([

                            ('text', Pipeline([
                                ('selector', ItemSelector(column='TEXT')),
                                ("word2vec vectorizer", TfidfEmbeddingVectorizer(w2v)),
                                ('feature_selection', SelectFromModel(LinearSVC(penalty="l1", dual=False),threshold=0.01))
                            ])),

                            ('category', Pipeline([
                                ('selector', ItemSelector(column='category')),
                                ('stats', TextStats()),
                                ('vect', DictVectorizer())
                            ]))
    ])),
                    ('clf',ExtraTreesClassifier(n_estimators=200, max_depth=500, min_samples_split=6, class_weight= 'balanced'))])

    classifier.fit(data_train,data_train.CLASSES)
    predicted = classifier.predict(data_val)


问:
Autofac cannot resolve DbContext
I am receiving this error message from Autofac;:

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyService`1[MyContext]' can be invoked with the available services and parameters:
Cannot resolve parameter 'MyContext context' of constructor 'Void .ctor(MyContext)'.

The error occurs on this line of code (also shown in the code below):

```<code>IMyService myService = container.Resolve<IMyService>();  // error here
</code>```

I am interested to note that when I include this line in my registrations, everything works:

```<code>builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
</code>```

The fact that it all works when I register AnyConcreteType... leads me to believe I am not not registering  something.  My question is what am I not registering?  The error message appears to name MyContext as the culprit but clearly I am registering it as shown below.

I really dont want to use the AnyConcreteType... catch all because I want to explicity register only the the classes I need.

My service is constructed like this:

```<code>public class MyService<T> : BaseService<T>, IMyService where T:DbContext,IMyContext
{
    public MyService(T context) : base(context)
    {
    }
}
</code>```

MyService derives from BaseService:

```<code>public abstract class BaseService<T> : IDisposable where T:DbContext, IMyContext
{
    internal T db;

    public BaseService(T context)
    {
        db = context;
    }
}
</code>```

MyContext is passed to MyService and is constructed like this:

```<code>public partial class MyContext : DbContext, IMyContext
{
    public MyContext(INamedConnectionString conn)
        : base(conn.ConnectionString)
    {
        Configuration.ProxyCreationEnabled = false;
    }
}
</code>```

Here is NamedConnectionString

```<code>public class NamedConnectionString : INamedConnectionString
{
    public string ConnectionString { get; set; }
}
</code>```

Here is how I register the above:

```<code>builder.RegisterType<MyService<MyContext>>().As<IMyService>();
builder.RegisterType<NamedConnectionString>().As<INamedConnectionString>().SingleInstance();
builder.RegisterType<MyContext>().As<IMyContext>().InstancePerLifetimeScope();
builder.RegisterType<DbContext>(); // is this necessary??
</code>```

And here is how I call it:

```<code>    var container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    INamedConnectionString namedConnectionString = container.Resolve<INamedConnectionString>();
    namedConnectionString.ConnectionString = myConnectionString;
    IMyService myService = container.Resolve<IMyService>();  // error here
</code>```

答:
This worked for me

builder.RegisterType().As().InstancePerLifetimeScope();

Title: Autofac cannot resolve DbContext

Body:
I am receiving this error message from Autofac;:

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyService`1[MyContext]' can be invoked with the available services and parameters:
Cannot resolve parameter 'MyContext context' of constructor 'Void .ctor(MyContext)'.

The error occurs on this line of code (also shown in the code below):

IMyService myService = container.Resolve<IMyService>();  // error here

I am interested to note that when I include this line in my registrations, everything works:

builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());

The fact that it all works when I register AnyConcreteType... leads me to believe I am not not registering  something.  My question is what am I not registering?  The error message appears to name MyContext as the culprit but clearly I am registering it as shown below.

I really dont want to use the AnyConcreteType... catch all because I want to explicity register only the the classes I need.

My service is constructed like this:

public class MyService<T> : BaseService<T>, IMyService where T:DbContext,IMyContext
{
    public MyService(T context) : base(context)
    {
    }
}

MyService derives from BaseService:

public abstract class BaseService<T> : IDisposable where T:DbContext, IMyContext
{
    internal T db;

    public BaseService(T context)
    {
        db = context;
    }
}

MyContext is passed to MyService and is constructed like this:

public partial class MyContext : DbContext, IMyContext
{
    public MyContext(INamedConnectionString conn)
        : base(conn.ConnectionString)
    {
        Configuration.ProxyCreationEnabled = false;
    }
}

Here is NamedConnectionString

public class NamedConnectionString : INamedConnectionString
{
    public string ConnectionString { get; set; }
}

Here is how I register the above:

builder.RegisterType<MyService<MyContext>>().As<IMyService>();
builder.RegisterType<NamedConnectionString>().As<INamedConnectionString>().SingleInstance();
builder.RegisterType<MyContext>().As<IMyContext>().InstancePerLifetimeScope();
builder.RegisterType<DbContext>(); // is this necessary??

And here is how I call it:

    var container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    INamedConnectionString namedConnectionString = container.Resolve<INamedConnectionString>();
    namedConnectionString.ConnectionString = myConnectionString;
    IMyService myService = container.Resolve<IMyService>();  // error here


问:
Conversion required from general in to text format in vba
I want to convert the value of my variable valueTofind from the general into text format but below the line of code gives me an error, Kindly help me with the updated version of the code.

```<code> valuetoFind=rngfound
    valuetoFind.numberformat="@"
</code>```

This variable value changes everytime with the new set of data.
Thanks in advance.

答:
As the comments above say, hard to know without seeing your declarations.

But the correct syntax would be:

Set rngFound = Range(x:y)

rngFound.Numberformat = "@"

Body:
I want to convert the value of my variable valueTofind from the general into text format but below the line of code gives me an error, Kindly help me with the updated version of the code.

 valuetoFind=rngfound
    valuetoFind.numberformat="@"

This variable value changes everytime with the new set of data.
Thanks in advance.


问:
Delete data which is in date range 2016 to 2015 elasticsearch 1.6
data request which is created in 2015 and 2016 are processed in 2017.So, these are in 2017 indices data. I want to delete these date based on creation date. I'm unable to do this. Below is the query I'm using.

```<code>curl -XDELETE 'http://host:port/logging_2017*/_query' -d '{
>   "query": {
>     "match": {
>       "actionType": {
>         "query": "update_device_space",
>         "type": "boolean",
>         "operator": "AND"
>       }
>     }
>   },
>   "filter": {
>     "range": {
>       "requestedAt": {
>         "gte": "1420070400000",
>         "lte": "1483228799000"
>       }
>     }
>   }
> }'
</code>```

What I have to do. Please help me

答:
I am able to do this by below curl command. Along with date range, if we want to add another condition, we can do it by using term

```<code>curl -XDELETE 'http://host:port/logging_*/_query' -d '{
  "query": {
    "filtered": {
      "filter": {
        "and": [
          {
            "range": {
              "requestedAt": {
                "gte": 1420070400000,
                "lte": 1483228799000
              }
            }
          },
          {
            "term": {
              "field": "value"
            }
          }
        ]
      }
    }
  }
}'
</code>```

Body:
data request which is created in 2015 and 2016 are processed in 2017.So, these are in 2017 indices data. I want to delete these date based on creation date. I'm unable to do this. Below is the query I'm using.

curl -XDELETE 'http://host:port/logging_2017*/_query' -d '{
>   "query": {
>     "match": {
>       "actionType": {
>         "query": "update_device_space",
>         "type": "boolean",
>         "operator": "AND"
>       }
>     }
>   },
>   "filter": {
>     "range": {
>       "requestedAt": {
>         "gte": "1420070400000",
>         "lte": "1483228799000"
>       }
>     }
>   }
> }'

What I have to do. Please help me

Body:
I am able to do this by below curl command. Along with date range, if we want to add another condition, we can do it by using term

curl -XDELETE 'http://host:port/logging_*/_query' -d '{
  "query": {
    "filtered": {
      "filter": {
        "and": [
          {
            "range": {
              "requestedAt": {
                "gte": 1420070400000,
                "lte": 1483228799000
              }
            }
          },
          {
            "term": {
              "field": "value"
            }
          }
        ]
      }
    }
  }
}'


问:
Redux items in an array are having their ids updated
I'm working on a react-native (expo) events app and I'm encountering a problem with the ids of my mock events being updated when they shouldn't be only if they're integers, when the id's are strings I don't have this issue.

The basic flow is I show a list of events, when a users presses on that event they're brought to that event view. I do this by using eventInFocus and events* reducers and finding the event I need in the **eventView container.

When I press on a particular event all the event ids get updated and its difficult to debug because it states that the previous state already had the mixed up ids, which is very confusing because there are no issues in rendering the items in the home view (loop through array, use id as key).
If I select the first event, i  get an an error that the event can't be found, if I select any of the other 2 events, the event ids are randomly updated.

events reducer

```<code>const defaultEvents = [{
    id: 0,
    name: 'my birthday',
    date: new Date(),
    repeatAnnually: false,
    wallPaperSource: null
  },{
    id: 1,
    name: 'yosemite trip',
    date:  new Date(),
    repeatAnnually: true,
    wallPaperSource: null
  }, {
   id: 2,
   name: 'trip to dublin',
   date: new Date(),
   repeatAnnually: false,
   wallPaperSource: null
}];

const event = (state, action) => {
  switch (action.type) {
    case EVENT_EDITED:
      if(state.id !== action.event.id){
        return state;
      }
      return action.event;
    default:
      return state;
  }
}

function events(state = defaultEvents, action){
  switch(action.type){
    case ADD_EVENT:
      return [
        ...state,
        {
          id: action.event.id,
          name: action.event.name,
          date: action.event.date,
          repeatAnnually: action.event.repeatAnnually,
          wallPaperSource: action.event.wallPaperSource || null
        }];
    case EVENT_EDITED:
      return state.map(e =>
        event(e, action)
      )
    default:
      return state;
  }
}
</code>```

eventInFocus reducer

```<code>function eventInFocus(state = {}, action){
  switch(action.type){
    case "UPDATE_EVENT_IN_FOCUS":
      return Object.assign({}, state, action.event);
    case VIEW_EVENT:
      return Object.assign({}, action.event);
    default:
      return state;
  }
}
</code>```

eventContainer - container around each item in the list (home view)

```<code>const mapStateToProps = (state, ownProps) => {
  return {
    ownProps
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    onPress: (event)=> {
      dispatch(viewEvent(event));
    }
  }
}
</code>```

viewEventContainer - for the single event view

```<code>const mapStateToProps = (state, ownProps) => {
  const {events, eventInFocus } = state;
  viewEvent = find(events, e => e.id = eventInFocus.id);
  return {
    event: viewEvent,
    ownProps
  }
}

const mapDispatchToProps = (dispatch, state) => {
  return {
    onEditEvent: (event) => {
      dispatch(editEvent(event));
    }
  }
}

const EventViewContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(EventView);
</code>```

viewEvent action

```<code>export const viewEvent = (event) => {
  return {
    type: VIEW_EVENT,
    event
  }
}
</code>```

Is there something that I'm missing about redux? Are my reducers poorly structured? The confusing part for me is why it only happens with integers and not strings. Thank you in advance!

State when I press on an event, as you can see the previous state already had the mutated ids for the events

答:
Here is a line with the bug in your code:

```<code>viewEvent = find(events, e => e.id = eventInFocus.id);
                                   ^
                                   here
</code>```

As you can see state is being mutated on every invocation of mapStateToProps.

Body:
I'm working on a react-native (expo) events app and I'm encountering a problem with the ids of my mock events being updated when they shouldn't be only if they're integers, when the id's are strings I don't have this issue.

The basic flow is I show a list of events, when a users presses on that event they're brought to that event view. I do this by using eventInFocus and events* reducers and finding the event I need in the **eventView container.

When I press on a particular event all the event ids get updated and its difficult to debug because it states that the previous state already had the mixed up ids, which is very confusing because there are no issues in rendering the items in the home view (loop through array, use id as key).
If I select the first event, i  get an an error that the event can't be found, if I select any of the other 2 events, the event ids are randomly updated.

events reducer

const defaultEvents = [{
    id: 0,
    name: 'my birthday',
    date: new Date(),
    repeatAnnually: false,
    wallPaperSource: null
  },{
    id: 1,
    name: 'yosemite trip',
    date:  new Date(),
    repeatAnnually: true,
    wallPaperSource: null
  }, {
   id: 2,
   name: 'trip to dublin',
   date: new Date(),
   repeatAnnually: false,
   wallPaperSource: null
}];

const event = (state, action) => {
  switch (action.type) {
    case EVENT_EDITED:
      if(state.id !== action.event.id){
        return state;
      }
      return action.event;
    default:
      return state;
  }
}

function events(state = defaultEvents, action){
  switch(action.type){
    case ADD_EVENT:
      return [
        ...state,
        {
          id: action.event.id,
          name: action.event.name,
          date: action.event.date,
          repeatAnnually: action.event.repeatAnnually,
          wallPaperSource: action.event.wallPaperSource || null
        }];
    case EVENT_EDITED:
      return state.map(e =>
        event(e, action)
      )
    default:
      return state;
  }
}

eventInFocus reducer

function eventInFocus(state = {}, action){
  switch(action.type){
    case "UPDATE_EVENT_IN_FOCUS":
      return Object.assign({}, state, action.event);
    case VIEW_EVENT:
      return Object.assign({}, action.event);
    default:
      return state;
  }
}

eventContainer - container around each item in the list (home view)

const mapStateToProps = (state, ownProps) => {
  return {
    ownProps
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    onPress: (event)=> {
      dispatch(viewEvent(event));
    }
  }
}

viewEventContainer - for the single event view

const mapStateToProps = (state, ownProps) => {
  const {events, eventInFocus } = state;
  viewEvent = find(events, e => e.id = eventInFocus.id);
  return {
    event: viewEvent,
    ownProps
  }
}

const mapDispatchToProps = (dispatch, state) => {
  return {
    onEditEvent: (event) => {
      dispatch(editEvent(event));
    }
  }
}

const EventViewContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(EventView);

viewEvent action

export const viewEvent = (event) => {
  return {
    type: VIEW_EVENT,
    event
  }
}

Is there something that I'm missing about redux? Are my reducers poorly structured? The confusing part for me is why it only happens with integers and not strings. Thank you in advance!

State when I press on an event, as you can see the previous state already had the mutated ids for the events

Body:
Here is a line with the bug in your code:

viewEvent = find(events, e => e.id = eventInFocus.id);
                                   ^
                                   here

As you can see state is being mutated on every invocation of mapStateToProps.


问:
Android and getting a view with id cast as a string
In the Java code of an Android project if you want the reference for a view resource you can do something like:

```<code>View addButton = findViewById(R.id.button_0);
</code>```

In the above R.id.button_0 is not a String. Is it possible to dynamically refer to a resource by a string, such as "R.id.button_0"?

I'd like to refer to a button by "R.id.button_%i" where %i is replaced by some valid index.

答: You could try putting all the ids you want in an array and then using that array to dynamically refer to your resources instead.</p>

Body:
In the Java code of an Android project if you want the reference for a view resource you can do something like:

View addButton = findViewById(R.id.button_0);

In the above R.id.button_0 is not a String. Is it possible to dynamically refer to a resource by a string, such as "R.id.button_0"?

I'd like to refer to a button by "R.id.button_%i" where %i is replaced by some valid index.


问:
Edit MailMerge via OpenXml
I have a .docx which includes a MailMerge, I need to change its source via code (C#). As library I'm using OpenXml. By Opening the docx as a zip file and looking for the paths, I have found that the link of the datasource is stored in two different places: in the word/settings.xml and in the word/_rels/settings.xml.rels.

To replace the fisrt:

```<code>var template = new MemoryStream(myDocxInByteArray);

using (var doc = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(template, true))
{
    var s = doc.MainDocumentPart.DocumentSettingsPart.Settings;
    foreach (var els in s.ChildElements)
    {
        if (els is DocumentFormat.OpenXml.Wordprocessing.MailMerge)
        {
            var mm = (DocumentFormat.OpenXml.Wordprocessing.MailMerge)els;

            mm.Query.Val = "SELECT * FROM " + myNewPath;

            break;
        }
    }
}
</code>```

This works fine, however when the file is opened Word asks to load the file from the new path but also from the old one, since it is defined in the word/_rels/settings.xml.rels.

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
    <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/mailMergeSource" Target="oldPath" TargetMode="External"/>
</Relationships>
</code>```

How can I find this object(Relation) in the WordprocessingDocument? Cannot find it...
Or is there another way to change it?

EDIT:

I created two different empty files with a different source and then opened with the OpenXml Productivity Tool in order to compare them. As I already have seen the differences are in the word/settings.xml and in the word/_rels/settings.xml.rels.

答:
At the end I came up with the following solution:</p>

```<code>using (WordprocessingDocument doc = WordprocessingDocument.Open(docInByteArray, isEditable: true))
{
    Settings settings = doc.MainDocumentPart.DocumentSettingsPart.Settings;
    OpenXmlElement openXmlElement = null;
    foreach (OpenXmlElement element in settings.ChildElements)
    {
        if (element is MailMerge mailMerge)
        {
            mailMerge.Query.Val = "SELECT * FROM " + csvPath;
            mailMerge.DataSourceObject.Remove();
        }
        else if (element is AttachedTemplate)
        {
            openXmlElement = element;
        }
    }
    if (openXmlElement != null)
    {
        openXmlElement.Remove();
    }
    doc.Save();
}
</code>```

Title: Edit MailMerge via OpenXml

Body:
I have a .docx which includes a MailMerge, I need to change its source via code (C#). As library I'm using OpenXml. By Opening the docx as a zip file and looking for the paths, I have found that the link of the datasource is stored in two different places: in the word/settings.xml and in the word/_rels/settings.xml.rels.

To replace the fisrt:

var template = new MemoryStream(myDocxInByteArray);

using (var doc = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(template, true))
{
    var s = doc.MainDocumentPart.DocumentSettingsPart.Settings;
    foreach (var els in s.ChildElements)
    {
        if (els is DocumentFormat.OpenXml.Wordprocessing.MailMerge)
        {
            var mm = (DocumentFormat.OpenXml.Wordprocessing.MailMerge)els;

            mm.Query.Val = "SELECT * FROM " + myNewPath;

            break;
        }
    }
}

This works fine, however when the file is opened Word asks to load the file from the new path but also from the old one, since it is defined in the word/_rels/settings.xml.rels.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
    <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/mailMergeSource" Target="oldPath" TargetMode="External"/>
</Relationships>

How can I find this object(Relation) in the WordprocessingDocument? Cannot find it...
Or is there another way to change it?

EDIT:

I created two different empty files with a different source and then opened with the OpenXml Productivity Tool in order to compare them. As I already have seen the differences are in the word/settings.xml and in the word/_rels/settings.xml.rels.

Body:
At the end I came up with the following solution:

using (WordprocessingDocument doc = WordprocessingDocument.Open(docInByteArray, isEditable: true))
{
    Settings settings = doc.MainDocumentPart.DocumentSettingsPart.Settings;
    OpenXmlElement openXmlElement = null;
    foreach (OpenXmlElement element in settings.ChildElements)
    {
        if (element is MailMerge mailMerge)
        {
            mailMerge.Query.Val = "SELECT * FROM " + csvPath;
            mailMerge.DataSourceObject.Remove();
        }
        else if (element is AttachedTemplate)
        {
            openXmlElement = element;
        }
    }
    if (openXmlElement != null)
    {
        openXmlElement.Remove();
    }
    doc.Save();
}


问:
config Jmeter Generating Report Dashboard Average response time millisecond to second
in Jmeter http://jmeter.apache.org/usermanual/generating-dashboard.html
we can see the response time is second not millisecond
transaction response time example from Jmeter

but in my report it is millisecond not second, how can I config millisecond to second?
My test result

答:
The report is in Milliseconds not in seconds and it’s not configrable.

So check if you are not receiving error pages with a 200 response code and add assertions:

http://www.ubik-ingenierie.com/blog/best-practice-using-jmeter-assertions/

Also check your are following the prerequisites for the report:

http://jmeter.apache.org/usermanual/generating-dashboard.html#configuration_requirements


问:
Mach-O 64-bit format does not support 32-bit absolute addresses. NASM Accessing Array
Running this code off my Mac computer, using command:

```<code>nasm -f macho64 -o max.a maximum.asm
</code>```

This is the code I am attempting to run on my computer that finds the largest number inside an array.

```<code>section .data

data_items:
    dd 3,67,34,222,45,75,54,34,44,33,22,11,66,0

    section .text

global _start

_start:
    mov edi, 0
    mov eax, [data_items + edi*4]
    mov ebx, eax

start_loop:
    cmp eax, 0
    je loop_exit
    inc edi
    mov eax, [data_items + edi*4]
    cmp eax, ebx
    jle start_loop

mov ebx, eax
jmp start_loop

loop_exit:

mov eax, 1
int 0x80
</code>```

Error:

```<code>maximum.asm:14: error: Mach-O 64-bit format does not support 32-bit absolute addresses
maximum.asm:21: error: Mach-O 64-bit format does not support 32-bit absolute addresses
</code>```

答:
First of all, beware of NASM bugs with the macho64 output format with 64-bit absolute addressing (NASM 2.13.02+) and with RIP-relative in NASM 2.11.08.  64-bit absolute addressing is not recommended, so this answer should work even for buggy NASM 2.13.02 and higher.  (The bugs don't cause this error, they lead to wrong addresses being used at runtime.)

[data_items + edi*4] is a 32-bit addressing mode.  Even [data_items + rdi*4] can only use a 32-bit absolute displacement, so it wouldn't work either.  Note that using an address as a 32-bit (sign-extended) immediate like cmp rdi, data_items is also a problem: only mov allows a 64-bit immediate.

64-bit code on OS X can't use 32-bit absolute addressing at all.  Executables are loaded at a base address above 4GiB, so label addresses just plain don't fit in 32-bit integers, with zero- or sign-extension.  RIP-relative addressing is the best / most efficient solution, whether you need it to be position-independent or not1.

In NASM, default rel at the top of your file will make all [] memory operands prefer RIP-relative addressing.  See also Section 3.3 Effective Addresses in the NASM manual.

```<code>default rel                     ; near the top of file; affects all instructions

my_func:
    ...
    mov   ecx, [data_items]         ; uses the default: RIP-relative

    ;mov  ecx, [abs data_items]     ; override to absolute [disp32], unusuable
    mov   ecx, [rel data_items]     ; explicitly RIP-relative
</code>```

But RIP-relative is only possible when there are no other registers involved, so for indexing a static array you need to get the address in a register first.  Use a RIP-relative lea rsi, [rel data_items].

```<code> lea   rsi, [data_items]    ; can be outside the loop
 ...
 mov   eax, [rsi + rdi*4]
</code>```

Or you could add rsi, 4 inside the loop and use a simpler addressing mode like mov eax, [rsi].

Note that mov rsi, data_items will work for getting an address into a register, but you don't want that because it's less efficient.

Technically, any address within +-2GiB of your array will work, so if you have multiple arrays you can address the others relative to one common base address, only tieing up one register with a pointer.  e.g. lea rbx, [arr1] / ... / mov eax, [rbx + rdi*4 + arr2-arr1].  Relative Addressing errors - Mac 10.10 mentions that Agner Fog's "optimizing assembly" guide has some examples of array addressing, including one using the __mh_execute_header as a reference point.  (The code in that question looks like another attempt to port this 32-bit Linux example from the PGU book to 64-bit OS X, at the same time as learning asm in the first place.)

Note that on Linux, position-dependent executables are loaded in the low 32 bits of virtual address space, so you will see code like mov eax, [array + rdi*4] or mov edi, symbol_name in Linux examples or compiler output on http://gcc.godbolt.org/.  gcc -pie -fPIE will make position-independent executables on Linux, and is the default on many recent distros, but not Godbolt.

This doesn't help you on MacOS, but I mention it in case anyone's confused about code they've seen for other OSes, or why AMD64 architects bothered to allow [disp32] addressing modes at all on x86-64.

And BTW, prefer using 64-bit addressing modes in 64-bit code.  e.g. use [rsi + rdi*4], not [esi + edi*4].  You usually don't want to truncate pointers to 32-bit, and it costs an extra address-size prefix to encode.

Similarly, you should be using syscall to make 64-bit system calls, not int 0x80.  What are the calling conventions for UNIX & Linux system calls on i386 and x86-64 for the differences in which registers to pass args in.

Footnote 1:
64-bit absolute addressing is supported on OS X, but only in position-dependent executables (non-PIE).  This related question x64 nasm: pushing memory addresses onto the stack & call function includes an ld warning from using gcc main.o to link:

```<code>ld: warning: PIE disabled. Absolute addressing (perhaps -mdynamic-no-pic) not
allowed in code signed PIE, but used in _main from main.o. To fix this warning,
don't compile with -mdynamic-no-pic or link with -Wl,-no_pie
</code>```

So the linker checks if any 64-bit absolute relocations are used, and if so disables creation of a Position-Independent Executable.  A PIE can benefit from ASLR for security.  I think shared-library code always has to be position-independent on OS X; I don't know if jump tables or other cases of pointers-as-data are allowed (i.e. fixed up by the dynamic linker), or if they need to be initialized at runtime if you aren't making a position-dependent executable.

mov r64, imm64 is larger (10 bytes) and not faster than lea r64, [RIP_rel32] (7 bytes).

So you could use mov rsi, qword data_items instead of a RIP-relative LEA which runs about as fast, and takes less space in code caches and the uop cache.  64-bit immediates also have a uop-cache fetch penalty for on Sandybridge-family (http://agner.org/optimize/): they take 2 cycles to read from a uop cache line instead of 1.

x86 also has a form of mov that loads/store from/to a 64-bit absolute address, but only for AL/AX/EAX/RAX.  See http://felixcloutier.com/x86/MOV.html.  You don't want this either, because it's larger and not faster than mov eax, [rel foo].

(Related: an AT&T syntax version of the same question)

Body:
Running this code off my Mac computer, using command:

nasm -f macho64 -o max.a maximum.asm

This is the code I am attempting to run on my computer that finds the largest number inside an array.

section .data

data_items:
    dd 3,67,34,222,45,75,54,34,44,33,22,11,66,0

    section .text

global _start

_start:
    mov edi, 0
    mov eax, [data_items + edi*4]
    mov ebx, eax

start_loop:
    cmp eax, 0
    je loop_exit
    inc edi
    mov eax, [data_items + edi*4]
    cmp eax, ebx
    jle start_loop

mov ebx, eax
jmp start_loop

loop_exit:

mov eax, 1
int 0x80

Error:

maximum.asm:14: error: Mach-O 64-bit format does not support 32-bit absolute addresses
maximum.asm:21: error: Mach-O 64-bit format does not support 32-bit absolute addresses

Body:
First of all, beware of NASM bugs with the macho64 output format with 64-bit absolute addressing (NASM 2.13.02+) and with RIP-relative in NASM 2.11.08.  64-bit absolute addressing is not recommended, so this answer should work even for buggy NASM 2.13.02 and higher.  (The bugs don't cause this error, they lead to wrong addresses being used at runtime.)

[data_items + edi*4] is a 32-bit addressing mode.  Even [data_items + rdi*4] can only use a 32-bit absolute displacement, so it wouldn't work either.  Note that using an address as a 32-bit (sign-extended) immediate like cmp rdi, data_items is also a problem: only mov allows a 64-bit immediate.

64-bit code on OS X can't use 32-bit absolute addressing at all.  Executables are loaded at a base address above 4GiB, so label addresses just plain don't fit in 32-bit integers, with zero- or sign-extension.  RIP-relative addressing is the best / most efficient solution, whether you need it to be position-independent or not1.

In NASM, default rel at the top of your file will make all [] memory operands prefer RIP-relative addressing.  See also Section 3.3 Effective Addresses in the NASM manual.

default rel                     ; near the top of file; affects all instructions

my_func:
    ...
    mov   ecx, [data_items]         ; uses the default: RIP-relative

    ;mov  ecx, [abs data_items]     ; override to absolute [disp32], unusuable
    mov   ecx, [rel data_items]     ; explicitly RIP-relative

But RIP-relative is only possible when there are no other registers involved, so for indexing a static array you need to get the address in a register first.  Use a RIP-relative lea rsi, [rel data_items].

 lea   rsi, [data_items]    ; can be outside the loop
 ...
 mov   eax, [rsi + rdi*4]

Or you could add rsi, 4 inside the loop and use a simpler addressing mode like mov eax, [rsi].

Note that mov rsi, data_items will work for getting an address into a register, but you don't want that because it's less efficient.

Technically, any address within +-2GiB of your array will work, so if you have multiple arrays you can address the others relative to one common base address, only tieing up one register with a pointer.  e.g. lea rbx, [arr1] / ... / mov eax, [rbx + rdi*4 + arr2-arr1].  Relative Addressing errors - Mac 10.10 mentions that Agner Fog's "optimizing assembly" guide has some examples of array addressing, including one using the __mh_execute_header as a reference point.  (The code in that question looks like another attempt to port this 32-bit Linux example from the PGU book to 64-bit OS X, at the same time as learning asm in the first place.)

Note that on Linux, position-dependent executables are loaded in the low 32 bits of virtual address space, so you will see code like mov eax, [array + rdi*4] or mov edi, symbol_name in Linux examples or compiler output on http://gcc.godbolt.org/.  gcc -pie -fPIE will make position-independent executables on Linux, and is the default on many recent distros, but not Godbolt.

This doesn't help you on MacOS, but I mention it in case anyone's confused about code they've seen for other OSes, or why AMD64 architects bothered to allow [disp32] addressing modes at all on x86-64.

And BTW, prefer using 64-bit addressing modes in 64-bit code.  e.g. use [rsi + rdi*4], not [esi + edi*4].  You usually don't want to truncate pointers to 32-bit, and it costs an extra address-size prefix to encode.

Similarly, you should be using syscall to make 64-bit system calls, not int 0x80.  What are the calling conventions for UNIX & Linux system calls on i386 and x86-64 for the differences in which registers to pass args in.

Footnote 1:
64-bit absolute addressing is supported on OS X, but only in position-dependent executables (non-PIE).  This related question x64 nasm: pushing memory addresses onto the stack & call function includes an ld warning from using gcc main.o to link:

ld: warning: PIE disabled. Absolute addressing (perhaps -mdynamic-no-pic) not
allowed in code signed PIE, but used in _main from main.o. To fix this warning,
don't compile with -mdynamic-no-pic or link with -Wl,-no_pie

So the linker checks if any 64-bit absolute relocations are used, and if so disables creation of a Position-Independent Executable.  A PIE can benefit from ASLR for security.  I think shared-library code always has to be position-independent on OS X; I don't know if jump tables or other cases of pointers-as-data are allowed (i.e. fixed up by the dynamic linker), or if they need to be initialized at runtime if you aren't making a position-dependent executable.

mov r64, imm64 is larger (10 bytes) and not faster than lea r64, [RIP_rel32] (7 bytes).

So you could use mov rsi, qword data_items instead of a RIP-relative LEA which runs about as fast, and takes less space in code caches and the uop cache.  64-bit immediates also have a uop-cache fetch penalty for on Sandybridge-family (http://agner.org/optimize/): they take 2 cycles to read from a uop cache line instead of 1.

x86 also has a form of mov that loads/store from/to a 64-bit absolute address, but only for AL/AX/EAX/RAX.  See http://felixcloutier.com/x86/MOV.html.  You don't want this either, because it's larger and not faster than mov eax, [rel foo].

(Related: an AT&T syntax version of the same question)


问:
How can I make design as shown in the attached image?

I want to design a screen like this. For displaying the grid items, I am using recycle view. But my concern is how to apply pagination and implement slide for next section of items when user swipe.

In case swipe is not possible, at least on click of the dots below the layout.

答:
Create a new XML layout under layout and name it as grid_layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/grid_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:numColumns="auto_fit"
    android:columnWidth="90dp"
    android:horizontalSpacing="10dp"
    android:verticalSpacing="10dp"
    android:gravity="center"
    android:stretchMode="columnWidth" >

</GridView>
</code>```

Create a new Class by right clicking on (Right Click) src ⇒ package folder ⇒ New ⇒ Class and name your class as ImageAdapter.java Extend your ImageAdapter.java class from BaseAdapter and fill it with following code.

ImageAdapter.java

```<code>package com.example.dilip;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    // Keep all Images in array
    public Integer[] mThumbIds = {
            R.drawable.pic_1, R.drawable.pic_2,
            R.drawable.pic_3, R.drawable.pic_4,
            R.drawable.pic_5, R.drawable.pic_6,
            R.drawable.pic_7, R.drawable.pic_8,
            R.drawable.pic_9, R.drawable.pic_10,
            R.drawable.pic_11, R.drawable.pic_12,
            R.drawable.pic_13, R.drawable.pic_14,
            R.drawable.pic_15
    };

    // Constructor
    public ImageAdapter(Context c){
        mContext = c;
    }

    @Override
    public int getCount() {
        return mThumbIds.length;
    }

    @Override
    public Object getItem(int position) {
        return mThumbIds[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView = new ImageView(mContext);
        imageView.setImageResource(mThumbIds[position]);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
        return imageView;
    }

}
</code>```

Open your main activity class as shown below.

```<code>AndroidGridLayoutActivity.java

    package com.example.dilip;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.GridView;

    public class AndroidGridLayoutActivity extends Activity {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.grid_layout);

            GridView gridView = (GridView) findViewById(R.id.grid_view);

            // Instance of ImageAdapter Class
            gridView.setAdapter(new ImageAdapter(this));
        }
    }
</code>```

Body:
Create a new XML layout under layout and name it as grid_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/grid_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:numColumns="auto_fit"
    android:columnWidth="90dp"
    android:horizontalSpacing="10dp"
    android:verticalSpacing="10dp"
    android:gravity="center"
    android:stretchMode="columnWidth" >

</GridView>

Create a new Class by right clicking on (Right Click) src ⇒ package folder ⇒ New ⇒ Class and name your class as ImageAdapter.java Extend your ImageAdapter.java class from BaseAdapter and fill it with following code.

ImageAdapter.java

package com.example.dilip;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    // Keep all Images in array
    public Integer[] mThumbIds = {
            R.drawable.pic_1, R.drawable.pic_2,
            R.drawable.pic_3, R.drawable.pic_4,
            R.drawable.pic_5, R.drawable.pic_6,
            R.drawable.pic_7, R.drawable.pic_8,
            R.drawable.pic_9, R.drawable.pic_10,
            R.drawable.pic_11, R.drawable.pic_12,
            R.drawable.pic_13, R.drawable.pic_14,
            R.drawable.pic_15
    };

    // Constructor
    public ImageAdapter(Context c){
        mContext = c;
    }

    @Override
    public int getCount() {
        return mThumbIds.length;
    }

    @Override
    public Object getItem(int position) {
        return mThumbIds[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView = new ImageView(mContext);
        imageView.setImageResource(mThumbIds[position]);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
        return imageView;
    }

}

Open your main activity class as shown below.

AndroidGridLayoutActivity.java

    package com.example.dilip;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.GridView;

    public class AndroidGridLayoutActivity extends Activity {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.grid_layout);

            GridView gridView = (GridView) findViewById(R.id.grid_view);

            // Instance of ImageAdapter Class
            gridView.setAdapter(new ImageAdapter(this));
        }
    }


问:
Where to put inner classes?
Some might like to argue that this is a candidate for the least important issue of all times. Yet code style is a very important topic for me, and I want to ensure that I write code in a readable way - for me and the majority of developers.

That's why I'm wondering where you guys are declaring your inner classes.

I'm following the following method ordering scheme, because it is quite common:

```<code>public void foo() {
    usedByFoo();
}

private void usedByFoo() {
}

public void bar() {
}
</code>```

I order them from top to bottom, every method as close to where it is used.

Now I could do the same with inner classes, like this:

```<code>class Outer {
    private Inner inner;

    private class Inner {};

    public Outer() {
    }

    ...
}
</code>```

I think this is the most consistent style to follow for me, but I've also often seen people declare all inner classes either at the top or at the bottom of the file.

Which style should I follow, given my way of ordering methods? What is the most common way to do this?

答: I would declare inner-classes in the bottom of the file - usually you're not interested in their implementations and just want to get to your main class' methods, so they shouldn't get in the way.</p>

Title: Where to put inner classes?

Body:
Some might like to argue that this is a candidate for the least important issue of all times. Yet code style is a very important topic for me, and I want to ensure that I write code in a readable way - for me and the majority of developers.

That's why I'm wondering where you guys are declaring your inner classes.

I'm following the following method ordering scheme, because it is quite common:

public void foo() {
    usedByFoo();
}

private void usedByFoo() {
}

public void bar() {
}

I order them from top to bottom, every method as close to where it is used.

Now I could do the same with inner classes, like this:

class Outer {
    private Inner inner;

    private class Inner {};

    public Outer() {
    }

    ...
}

I think this is the most consistent style to follow for me, but I've also often seen people declare all inner classes either at the top or at the bottom of the file.

Which style should I follow, given my way of ordering methods? What is the most common way to do this?


问:
Is there a shorter way for if-else chains?
```<code>if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"
</code>```

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

答:
If numpy is acceptable there is searchsorted. Free bonus: it can handle an entire list of marks in one go:

```<code>import numpy as np

bnds = np.arange(50, 90, 10)
grades = np.array(list('UDCBA'))

marks = [52, 16, 50, 80, 69, 99]

result = grades[np.searchsorted(bnds, marks, side='right')]

print(result)

# ['D' 'U' 'D' 'A' 'C' 'A']
</code>```

Body:
if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

Body:
If numpy is acceptable there is searchsorted. Free bonus: it can handle an entire list of marks in one go:

import numpy as np

bnds = np.arange(50, 90, 10)
grades = np.array(list('UDCBA'))

marks = [52, 16, 50, 80, 69, 99]

result = grades[np.searchsorted(bnds, marks, side='right')]

print(result)

# ['D' 'U' 'D' 'A' 'C' 'A']


问:
Firebase ID Token change when password reset
I use Firebase ID Tokens to show data on my site when someone is logging in.
I save the token in a cookie on the client side and when the client accesses the website it takes the token from his cookie file and sends it to my backend server.

I would like to remove all ID Tokens when a password is reset so all the logged in clients using that username and password would disconnect.

Is this option valid? If so how can you do it? They don't seem to mention it in their docs.

答:
When a user's password is reset, changed or the associated email is updated, Firebase Auth will invalidate all existing sessions for that user for security reasons. This effectively invalidates that user's ID token from the perspective of Firebase Auth backend. The refresh token will also not be able to issue a new ID token.

Also I agree with Scott. You should use currentUser.getIdToken() to get the ID token instead of storing it yourself. This API takes care of refreshing the ID token for you when it expires.


问:
What all things can you access when you require a gem?
Let us take Rails gem for example

Before require 'rails'

```<code>irb(main):001:0> Rails
NameError: uninitialized constant Rails

irb(main):002:0> ActionPack
NameError: uninitialized constant ActionPack
</code>```

After require 'rails'

```<code>irb(main):005:0> require 'rails'
true
irb(main):007:0> Rails.constants
[:Railtie, :Rack, :Initializable, :Configuration, :WelcomeController, :InfoController, :VERSION, :Paths, :Info, :MailersController, :Application, :Engine]

irb(main):009:0> ActionPack.methods-Object.methods
[:gem_version, :version, :initialize_copy]
</code>```

So now the ActionPack module is available in the console, what other modules or class (if any) are available and how to know about those modules?

答:
Thats up to the gem developer. To see how your Name- and Objectspace changed there should be many clever ways.

I answer shortly how to find out which new Module (-Constants) there are:

```<code>  initial_modules = Module.constants
  # -> [:Object, :Module, :Class, :BasicObject, :Kernel, :NilClass, ...]

  require 'rails'

  Module.constants - initial_modules # all NEW constants
  # -> [:Pathname, :OpenSSL, :Digest, :SecureRandom, :Concurrent, :I18n, :CGI, :ActiveSupport, :Set, :SortedSet, :Timeout, :TimeoutError, :Logger, :LoggerSilence, :DateAndTime, :Psych, :StringScanner, :ScanError, :Date, :DateTime, :YAML, :Base64, :TSort, :Rails, :BigDecimal, :BigMath, :TZInfo, :ThreadSafe, :Threadsafe, :SynchronizedDelegator, :JSON, :OpenStruct, :Singleton, :Mutex_m, :ActionPack, :Rack, :ActionDispatch, :Mime]
</code>```

As you see, this also comes with a lot of new stuff that is required (but not provided) by Rails, like Date, OpenSSL, etc.pp.
Actually, requirements can happen at runtime, too, such that this lists grows as you use the code.
Hope that helps a bit.

Body:
Let us take Rails gem for example

Before require 'rails'

irb(main):001:0> Rails
NameError: uninitialized constant Rails

irb(main):002:0> ActionPack
NameError: uninitialized constant ActionPack

After require 'rails'

irb(main):005:0> require 'rails'
true
irb(main):007:0> Rails.constants
[:Railtie, :Rack, :Initializable, :Configuration, :WelcomeController, :InfoController, :VERSION, :Paths, :Info, :MailersController, :Application, :Engine]

irb(main):009:0> ActionPack.methods-Object.methods
[:gem_version, :version, :initialize_copy]

So now the ActionPack module is available in the console, what other modules or class (if any) are available and how to know about those modules?

Body:
Thats up to the gem developer. To see how your Name- and Objectspace changed there should be many clever ways.

I answer shortly how to find out which new Module (-Constants) there are:

  initial_modules = Module.constants
  # -> [:Object, :Module, :Class, :BasicObject, :Kernel, :NilClass, ...]

  require 'rails'

  Module.constants - initial_modules # all NEW constants
  # -> [:Pathname, :OpenSSL, :Digest, :SecureRandom, :Concurrent, :I18n, :CGI, :ActiveSupport, :Set, :SortedSet, :Timeout, :TimeoutError, :Logger, :LoggerSilence, :DateAndTime, :Psych, :StringScanner, :ScanError, :Date, :DateTime, :YAML, :Base64, :TSort, :Rails, :BigDecimal, :BigMath, :TZInfo, :ThreadSafe, :Threadsafe, :SynchronizedDelegator, :JSON, :OpenStruct, :Singleton, :Mutex_m, :ActionPack, :Rack, :ActionDispatch, :Mime]

As you see, this also comes with a lot of new stuff that is required (but not provided) by Rails, like Date, OpenSSL, etc.pp.
Actually, requirements can happen at runtime, too, such that this lists grows as you use the code.
Hope that helps a bit.


问:
How to create a custom arrow with two colors?
I would like to create a custom shape like this image

My HTML :

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

            aaaaa

                mmm

                nnnn

```

答:
Use HTML5 canvas tag and java script to draw you own image in
you can read about it in below link
https://www.w3schools.com/html/html5_canvas.asp


问:
Android 7 buttons are not showing in XML
I have a App with Login Layout So I have added 2 Buttons Save,Cancel

this is my XML Layout

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

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#303F9F"
        android:layout_alignParentTop="true"
        android:gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="My App Login"
            android:id="@+id/ota"
            android:textColor="#FFF"
            android:textStyle="bold"
            android:layout_gravity="center_horizontal"/>
    </RelativeLayout>

    <ScrollView
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/footer"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:layout_below="@id/header">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical">

            <TextView android:textAppearance="?android:textAppearanceSmall"
                android:gravity="bottom|left|center"
                android:id="@+id/tt5"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="@string/ui"
                android:textSize="14sp"
                android:layout_below="@+id/et3"
                android:layout_weight="0.1"
                android:layout_marginTop="10dp"/>

            <EditText android:id="@+id/et4"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_marginLeft="5.0dip"
                android:layout_marginBottom="5.0dip"
                android:maxLines="1"
                android:hint="Enter User Name"
                android:layout_weight="0.1"
                android:layout_below="@+id/tt5"
                android:inputType="text"/>

            <TextView android:textAppearance="?android:textAppearanceSmall"
                android:gravity="bottom|left|center"
                android:id="@+id/tt6"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="@string/pw"
                android:textSize="14sp"
                android:layout_below="@+id/et4"
                android:layout_weight="0.1"
                android:layout_marginTop="10dp"/>

            <EditText android:id="@+id/et5"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_marginLeft="5.0dip"
                android:layout_marginBottom="5.0dip"
                android:maxLines="1"
                android:hint="Enter Password"
                android:layout_weight="0.1"
                android:layout_below="@+id/tt6"
                android:inputType="textPassword"/>

            <Button android:id="@+id/save"
                android:layout_width="fill_parent"
                android:layout_height="0.0dip"
                android:layout_marginBottom="5.0dip"
                android:text="@string/save"
                android:textAlignment="center"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:background="@drawable/selector_btn"
                android:drawableLeft="@android:drawable/ic_menu_save"
                android:layout_weight="0.1"
                android:layout_marginTop="50dp"
                android:textColor="@color/text_white"/>

            <Button android:id="@+id/cancel"
                android:layout_width="fill_parent"
                android:layout_height="0.0dip"
                android:text="@string/cancel"
                android:textAlignment="center"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:background="@drawable/c_selector_btn"
                android:drawableLeft="@android:drawable/ic_menu_close_clear_cancel"
                android:layout_weight="0.1"
                android:textColor="@color/text_white"/>

        </LinearLayout>

    </ScrollView>

</RelativeLayout>
</code>```

Here its working fine for android 5,6 but in android 7 buttons are not showing in emulator,xml,Real Device

But its not working in android 7

its showing like this

can any one suggest me what I am missing for android 7 in android XML.. I am using same in android 5,6 its worked but its not showing in 7

答:
You can try bellow like..</p>

```<code>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

   <!--Header Hear-->

   <!-- Content Here -->

  <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:layout_weight=".1"
      android:background="#FFFFFF"
      android:orientation="vertical" >

     <TextView
        android:id="@+id/tv_message_reset_new_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp" />

      <ScrollView
          android:id="@+id/scrollView1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical">

            <TextView android:textAppearance="?android:textAppearanceSmall"
                android:gravity="bottom|left|center"
                android:id="@+id/tt5"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="User Id"
                android:textSize="14sp"
                android:layout_below="@+id/et3"
                android:layout_weight="0.1"
                android:layout_marginTop="10dp"/>

            <EditText android:id="@+id/et4"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_marginLeft="5.0dip"
                android:layout_marginBottom="5.0dip"
                android:maxLines="1"
                android:hint="Enter User Name"
                android:layout_weight="0.1"
                android:layout_below="@+id/tt5"
                android:inputType="text"/>

             <TextView android:textAppearance="?android:textAppearanceSmall"
                android:gravity="bottom|left|center"
                android:id="@+id/tt6"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="password"
                android:textSize="14sp"
                android:layout_below="@+id/et4"
                android:layout_weight="0.1"
                android:layout_marginTop="10dp"/>

            <EditText android:id="@+id/et5"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_marginLeft="5.0dip"
                android:layout_marginBottom="5.0dip"
                android:maxLines="1"
                android:hint="Enter Password"
                android:layout_weight="0.1"
                android:layout_below="@+id/tt6"
                android:inputType="textPassword"/>

            <Button android:id="@+id/save"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5.0dip"
                android:text="save"
                android:textAlignment="center"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:background="#97d1ea"
                android:drawableLeft="@android:drawable/ic_menu_save"
                android:layout_weight="0.1"
                android:layout_marginTop="50dp"
                android:textColor="#ffffff"/>

            <Button android:id="@+id/cancel"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="cancel"
                android:textAlignment="center"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:background="#97d1ea"
                android:drawableLeft="@android:drawable/ic_menu_close_clear_cancel"
                android:layout_weight="0.1"
                android:textColor="#ffffff"/>

            </LinearLayout>
          </ScrollView>
       </LinearLayout>

       <!--Footer Hear-->
   </LinearLayout>
</code>```

Body:
I have a App with Login Layout So I have added 2 Buttons Save,Cancel

this is my XML Layout

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

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#303F9F"
        android:layout_alignParentTop="true"
        android:gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="My App Login"
            android:id="@+id/ota"
            android:textColor="#FFF"
            android:textStyle="bold"
            android:layout_gravity="center_horizontal"/>
    </RelativeLayout>

    <ScrollView
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/footer"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:layout_below="@id/header">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical">

            <TextView android:textAppearance="?android:textAppearanceSmall"
                android:gravity="bottom|left|center"
                android:id="@+id/tt5"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="@string/ui"
                android:textSize="14sp"
                android:layout_below="@+id/et3"
                android:layout_weight="0.1"
                android:layout_marginTop="10dp"/>

            <EditText android:id="@+id/et4"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_marginLeft="5.0dip"
                android:layout_marginBottom="5.0dip"
                android:maxLines="1"
                android:hint="Enter User Name"
                android:layout_weight="0.1"
                android:layout_below="@+id/tt5"
                android:inputType="text"/>

            <TextView android:textAppearance="?android:textAppearanceSmall"
                android:gravity="bottom|left|center"
                android:id="@+id/tt6"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="@string/pw"
                android:textSize="14sp"
                android:layout_below="@+id/et4"
                android:layout_weight="0.1"
                android:layout_marginTop="10dp"/>

            <EditText android:id="@+id/et5"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_marginLeft="5.0dip"
                android:layout_marginBottom="5.0dip"
                android:maxLines="1"
                android:hint="Enter Password"
                android:layout_weight="0.1"
                android:layout_below="@+id/tt6"
                android:inputType="textPassword"/>

            <Button android:id="@+id/save"
                android:layout_width="fill_parent"
                android:layout_height="0.0dip"
                android:layout_marginBottom="5.0dip"
                android:text="@string/save"
                android:textAlignment="center"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:background="@drawable/selector_btn"
                android:drawableLeft="@android:drawable/ic_menu_save"
                android:layout_weight="0.1"
                android:layout_marginTop="50dp"
                android:textColor="@color/text_white"/>

            <Button android:id="@+id/cancel"
                android:layout_width="fill_parent"
                android:layout_height="0.0dip"
                android:text="@string/cancel"
                android:textAlignment="center"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:background="@drawable/c_selector_btn"
                android:drawableLeft="@android:drawable/ic_menu_close_clear_cancel"
                android:layout_weight="0.1"
                android:textColor="@color/text_white"/>

        </LinearLayout>

    </ScrollView>

</RelativeLayout>

Here its working fine for android 5,6 but in android 7 buttons are not showing in emulator,xml,Real Device

But its not working in android 7

its showing like this

can any one suggest me what I am missing for android 7 in android XML.. I am using same in android 5,6 its worked but its not showing in 7

Body:
You can try bellow like..

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

   <!--Header Hear-->

   <!-- Content Here -->

  <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:layout_weight=".1"
      android:background="#FFFFFF"
      android:orientation="vertical" >

     <TextView
        android:id="@+id/tv_message_reset_new_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp" />

      <ScrollView
          android:id="@+id/scrollView1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical">

            <TextView android:textAppearance="?android:textAppearanceSmall"
                android:gravity="bottom|left|center"
                android:id="@+id/tt5"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="User Id"
                android:textSize="14sp"
                android:layout_below="@+id/et3"
                android:layout_weight="0.1"
                android:layout_marginTop="10dp"/>

            <EditText android:id="@+id/et4"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_marginLeft="5.0dip"
                android:layout_marginBottom="5.0dip"
                android:maxLines="1"
                android:hint="Enter User Name"
                android:layout_weight="0.1"
                android:layout_below="@+id/tt5"
                android:inputType="text"/>

             <TextView android:textAppearance="?android:textAppearanceSmall"
                android:gravity="bottom|left|center"
                android:id="@+id/tt6"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="password"
                android:textSize="14sp"
                android:layout_below="@+id/et4"
                android:layout_weight="0.1"
                android:layout_marginTop="10dp"/>

            <EditText android:id="@+id/et5"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_marginLeft="5.0dip"
                android:layout_marginBottom="5.0dip"
                android:maxLines="1"
                android:hint="Enter Password"
                android:layout_weight="0.1"
                android:layout_below="@+id/tt6"
                android:inputType="textPassword"/>

            <Button android:id="@+id/save"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5.0dip"
                android:text="save"
                android:textAlignment="center"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:background="#97d1ea"
                android:drawableLeft="@android:drawable/ic_menu_save"
                android:layout_weight="0.1"
                android:layout_marginTop="50dp"
                android:textColor="#ffffff"/>

            <Button android:id="@+id/cancel"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="cancel"
                android:textAlignment="center"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:background="#97d1ea"
                android:drawableLeft="@android:drawable/ic_menu_close_clear_cancel"
                android:layout_weight="0.1"
                android:textColor="#ffffff"/>

            </LinearLayout>
          </ScrollView>
       </LinearLayout>

       <!--Footer Hear-->
   </LinearLayout>


问:
NV12 Format Image Show in UWP
I got image pixel from the IoT camera and used SoftwareBitmap class to store my NV12 pixel buffer data.

But the SoftwareBitmap displayed in a XAML app must be in BGRA pixel format with pre-multiplied alpha values.

Do I have to convert NV12 to BGRA?

How can I directly show NV12 Or BGR24 pixel format in UWP C# Code？

答:
Do I have to convert NV12 to BGRA?

Yes. UWP doesn't support displaying NV12 format image directly. You would have to convert it.

I saw that Xin has submitted a feature request on UWP User Voice. You could vote it up. MS might think about adding this feature in the later version base on the energy value for this feature request.

Title: NV12 Format Image Show in UWP