问:
JavaFX FilteredList, filtering based on property of items in the list
I have a case where I need to filter a ObservableList<Item> based on some properties of the items (i.e. the condition is internal and not external). I found out that javafx has FilteredList so I tried it. I could set the predicate and filtering works, until the property value that determines the filtering changes. Setting the predicate is done now like following:

```<code>list.setPredicate(t -> !t.filteredProperty().get())
</code>```

Since the predicate returns boolean and not BooleanProperty, the changes to that property are not reflected on the list.

Is there any easy solution to this? I could try to do some workarounds, e.g. create a separate list and sync that, or reset the predicate every time the property changes in one item hopefully retriggering the filtering, but I first wanted to ask in case someone knows a pretty solution as those workarounds certainly are not.

答:
If you are using database loading function plus need to filter multiple fields, this solution will help.</p>

```<code> ObservableList<PurchaseOrder> poData = FXCollections.observableArrayList();
 FilteredList<PurchaseOrder> filteredData;
  private void load()  {
        PurchaseOrder po = new PurchaseOrder();
        try {
            poData = po.loadTable("purchase_orders", beanFields); // Database loading data
        } catch (SQLException ex) {
            Logger.getLogger(PurchaseOrdersController.class.getName()).log(Level.SEVERE, null, ex);
        }

        filteredData = new FilteredList<>(poData, t -> true); //Encapsulate data with filter

        poTable.setItems(filteredData); //Load filtered data into table

        //Set event trigger for all filter textboxes
        txtFilter.textProperty().addListener(obs->{
            filter(filteredData);
        });
        txtFilter2.textProperty().addListener(obs->{
            filter(filteredData);
        });
  }

   private void filter(FilteredList<PurchaseOrder> filteredData)
    {
            filteredData.setPredicate(PurchaseOrder -> {
                // If all filters are empty then display all Purchase Orders
                if ((txtFilter.getText() == null || txtFilter.getText().isEmpty())
                        && (txtFilter2.getText() == null || txtFilter2.getText().isEmpty())) {
                    return true;
                }

                // Convert filters to lower case
                String lowerCaseFilter = txtFilter.getText().toLowerCase();
                String lowerCaseFilter2 = txtFilter2.getText().toLowerCase();

                //If fails any given criteria, fail completely
                if(txtFilter.getText().length()>0)
                    if (PurchaseOrder.get("vendor_name").toLowerCase().contains(lowerCaseFilter) == false)
                        return false;
                if(txtFilter2.getText().length()>0)
                    if (PurchaseOrder.get("PONumber").toLowerCase().contains(lowerCaseFilter2) == false)
                        return false;

                return true; // Matches given criteria
            });
    }
</code>```

Body:
I have a case where I need to filter a ObservableList<Item> based on some properties of the items (i.e. the condition is internal and not external). I found out that javafx has FilteredList so I tried it. I could set the predicate and filtering works, until the property value that determines the filtering changes. Setting the predicate is done now like following:

list.setPredicate(t -> !t.filteredProperty().get())

Since the predicate returns boolean and not BooleanProperty, the changes to that property are not reflected on the list.

Is there any easy solution to this? I could try to do some workarounds, e.g. create a separate list and sync that, or reset the predicate every time the property changes in one item hopefully retriggering the filtering, but I first wanted to ask in case someone knows a pretty solution as those workarounds certainly are not.

Body:
If you are using database loading function plus need to filter multiple fields, this solution will help.

 ObservableList<PurchaseOrder> poData = FXCollections.observableArrayList();
 FilteredList<PurchaseOrder> filteredData;
  private void load()  {
        PurchaseOrder po = new PurchaseOrder();
        try {
            poData = po.loadTable("purchase_orders", beanFields); // Database loading data
        } catch (SQLException ex) {
            Logger.getLogger(PurchaseOrdersController.class.getName()).log(Level.SEVERE, null, ex);
        }

        filteredData = new FilteredList<>(poData, t -> true); //Encapsulate data with filter

        poTable.setItems(filteredData); //Load filtered data into table

        //Set event trigger for all filter textboxes
        txtFilter.textProperty().addListener(obs->{
            filter(filteredData);
        });
        txtFilter2.textProperty().addListener(obs->{
            filter(filteredData);
        });
  }

   private void filter(FilteredList<PurchaseOrder> filteredData)
    {
            filteredData.setPredicate(PurchaseOrder -> {
                // If all filters are empty then display all Purchase Orders
                if ((txtFilter.getText() == null || txtFilter.getText().isEmpty())
                        && (txtFilter2.getText() == null || txtFilter2.getText().isEmpty())) {
                    return true;
                }

                // Convert filters to lower case
                String lowerCaseFilter = txtFilter.getText().toLowerCase();
                String lowerCaseFilter2 = txtFilter2.getText().toLowerCase();

                //If fails any given criteria, fail completely
                if(txtFilter.getText().length()>0)
                    if (PurchaseOrder.get("vendor_name").toLowerCase().contains(lowerCaseFilter) == false)
                        return false;
                if(txtFilter2.getText().length()>0)
                    if (PurchaseOrder.get("PONumber").toLowerCase().contains(lowerCaseFilter2) == false)
                        return false;

                return true; // Matches given criteria
            });
    }


来源: stackexchange

问:
Can't load 'mnist-original' dataset using sklearn
This question is similar to what asked here and here. Unfortunately, in my case the suggested solution didn't fix the problem.

I need to work with the MNIST dataset but I can't fetch it, even if I specify the address of the scikit_learn_data/mldata/ folder (see below). How can I fix this?

In case it might help, I'm using Anaconda.

Code:

```<code>from sklearn.datasets.mldata import fetch_mldata

dataset = fetch_mldata('mnist-original', data_home='/Users/michelangelo/scikit_learn_data/mldata/')
mnist = fetch_mldata('MNIST original')
</code>```

Error:

```<code>---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-5-dc4d45bc928e> in <module>()
----> 1 mnist = fetch_mldata('MNIST original')

/Users/michelangelo/anaconda2/lib/python2.7/site-packages/sklearn/datasets/mldata.pyc in fetch_mldata(dataname, target_name, data_name, transpose_data, data_home)
    168     # load dataset matlab file
    169     with open(filename, 'rb') as matlab_file:
--> 170         matlab_dict = io.loadmat(matlab_file, struct_as_record=True)
    171
    172     # -- extract data from matlab_dict

/Users/michelangelo/anaconda2/lib/python2.7/site-packages/scipy/io/matlab/mio.pyc in loadmat(file_name, mdict, appendmat, **kwargs)
    134     variable_names = kwargs.pop('variable_names', None)
    135     MR = mat_reader_factory(file_name, appendmat, **kwargs)
--> 136     matfile_dict = MR.get_variables(variable_names)
    137     if mdict is not None:
    138         mdict.update(matfile_dict)

/Users/michelangelo/anaconda2/lib/python2.7/site-packages/scipy/io/matlab/mio5.pyc in get_variables(self, variable_names)
    290                 continue
    291             try:
--> 292                 res = self.read_var_array(hdr, process)
    293             except MatReadError as err:
    294                 warnings.warn(

/Users/michelangelo/anaconda2/lib/python2.7/site-packages/scipy/io/matlab/mio5.pyc in read_var_array(self, header, process)
    250            `process`.
    251         '''
--> 252         return self._matrix_reader.array_from_header(header, process)
    253
    254     def get_variables(self, variable_names=None):

mio5_utils.pyx in scipy.io.matlab.mio5_utils.VarReader5.array_from_header()

mio5_utils.pyx in scipy.io.matlab.mio5_utils.VarReader5.array_from_header()

mio5_utils.pyx in scipy.io.matlab.mio5_utils.VarReader5.read_real_complex()

mio5_utils.pyx in scipy.io.matlab.mio5_utils.VarReader5.read_numeric()

mio5_utils.pyx in scipy.io.matlab.mio5_utils.VarReader5.read_element()

streams.pyx in scipy.io.matlab.streams.FileStream.read_string()

IOError: could not read bytes
</code>```

答:
Instead of :

```<code>from sklearn.datasets.mldata import fetch_mldata
</code>```

use:

```<code>from sklearn.datasets import fetch_mldata
</code>```

And then:

```<code>mnist = fetch_mldata('MNIST original')
X = mnist.data.astype('float64')
y = mnist.target
</code>```

Please see this example:

http://scikit-learn.org/stable/auto_examples/linear_model/plot_sparse_logistic_regression_mnist.html#sphx-glr-auto-examples-linear-model-plot-sparse-logistic-regression-mnist-py

ContentLicense: CC BY-SA 3.0

Body:
This question is similar to what asked here and here. Unfortunately, in my case the suggested solution didn't fix the problem.

I need to work with the MNIST dataset but I can't fetch it, even if I specify the address of the scikit_learn_data/mldata/ folder (see below). How can I fix this?

In case it might help, I'm using Anaconda.

Code:

from sklearn.datasets.mldata import fetch_mldata

dataset = fetch_mldata('mnist-original', data_home='/Users/michelangelo/scikit_learn_data/mldata/')
mnist = fetch_mldata('MNIST original')

Error:

---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-5-dc4d45bc928e> in <module>()
----> 1 mnist = fetch_mldata('MNIST original')

/Users/michelangelo/anaconda2/lib/python2.7/site-packages/sklearn/datasets/mldata.pyc in fetch_mldata(dataname, target_name, data_name, transpose_data, data_home)
    168     # load dataset matlab file
    169     with open(filename, 'rb') as matlab_file:
--> 170         matlab_dict = io.loadmat(matlab_file, struct_as_record=True)
    171
    172     # -- extract data from matlab_dict

/Users/michelangelo/anaconda2/lib/python2.7/site-packages/scipy/io/matlab/mio.pyc in loadmat(file_name, mdict, appendmat, **kwargs)
    134     variable_names = kwargs.pop('variable_names', None)
    135     MR = mat_reader_factory(file_name, appendmat, **kwargs)
--> 136     matfile_dict = MR.get_variables(variable_names)
    137     if mdict is not None:
    138         mdict.update(matfile_dict)

/Users/michelangelo/anaconda2/lib/python2.7/site-packages/scipy/io/matlab/mio5.pyc in get_variables(self, variable_names)
    290                 continue
    291             try:
--> 292                 res = self.read_var_array(hdr, process)
    293             except MatReadError as err:
    294                 warnings.warn(

/Users/michelangelo/anaconda2/lib/python2.7/site-packages/scipy/io/matlab/mio5.pyc in read_var_array(self, header, process)
    250            `process`.
    251         '''
--> 252         return self._matrix_reader.array_from_header(header, process)
    253
    254     def get_variables(self, variable_names=None):

mio5_utils.pyx in scipy.io.matlab.mio5_utils.VarReader5.array_from_header()

mio5_utils.pyx in scipy.io.matlab.mio5_utils.VarReader5.array_from_header()

mio5_utils.pyx in scipy.io.matlab.mio5_utils.VarReader5.read_real_complex()

mio5_utils.pyx in scipy.io.matlab.mio5_utils.VarReader5.read_numeric()

mio5_utils.pyx in scipy.io.matlab.mio5_utils.VarReader5.read_element()

streams.pyx in scipy.io.matlab.streams.FileStream.read_string()

IOError: could not read bytes

Body:
Instead of :

from sklearn.datasets.mldata import fetch_mldata

use:

from sklearn.datasets import fetch_mldata

And then:

mnist = fetch_mldata('MNIST original')
X = mnist.data.astype('float64')
y = mnist.target

Please see this example:

http://scikit-learn.org/stable/auto_examples/linear_model/plot_sparse_logistic_regression_mnist.html#sphx-glr-auto-examples-linear-model-plot-sparse-logistic-regression-mnist-py


问:
Get SecurityContext for Dropwizard integration tests
I'm writing integration tests for my Dropwizard + Liquibase + Angular application to test the REST service.
My app has basic authentication with cookies.

So I've created ClassRule:

```<code>@ClassRule
public static final DropwizardAppRule<RESTServerConfiguration> RULE =
            new DropwizardAppRule<>(RESTServer.class, ResourceHelpers.resourceFilePath("serverconfig.yml"));
</code>```

When I test the login method:

```<code>final Response response = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/api/users/login")
    .request(MediaType.APPLICATION_JSON)
    .post(Entity.json("{\"username\": \"admin\", \"password\": \"admin\"}"));
</code>```

everything works fine.

But when I try to test the protected resource, e.g.:

```<code>final TestResponse response = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/api/users/getAllUsers")
    .request()
    .get(TestResponse.class);
</code>```

it fails with 401 error.

How can I get SecurityContext or store the session somewhere?

答:
I finally figured this thing out.

All I needed to do is to extract cookies from login request, such as:

`

```<code>String cookieValue = null;
for (Map.Entry<String, NewCookie> entry : loginResponse.getCookies().entrySet()) {
    String key = entry.getKey();
    if ("sessionToken".equals(key)) {
        cookieValue = entry.getValue().toString();
        cookieValue = cookieValue.substring(0, cookieValue.indexOf(";"));
    }
}
</code>```

`

and then set it as a header to the protected resource request, such as:

.header("Cookie", cookieValue)

ContentLicense: CC BY-SA 4.0

Body:
I'm writing integration tests for my Dropwizard + Liquibase + Angular application to test the REST service.
My app has basic authentication with cookies.

So I've created ClassRule:

@ClassRule
public static final DropwizardAppRule<RESTServerConfiguration> RULE =
            new DropwizardAppRule<>(RESTServer.class, ResourceHelpers.resourceFilePath("serverconfig.yml"));

When I test the login method:

final Response response = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/api/users/login")
    .request(MediaType.APPLICATION_JSON)
    .post(Entity.json("{\"username\": \"admin\", \"password\": \"admin\"}"));

everything works fine.

But when I try to test the protected resource, e.g.:

final TestResponse response = RULE.client().target("http://localhost:" + RULE.getLocalPort() + "/api/users/getAllUsers")
    .request()
    .get(TestResponse.class);

it fails with 401 error.

How can I get SecurityContext or store the session somewhere?

Body:
I finally figured this thing out.

All I needed to do is to extract cookies from login request, such as:

`

String cookieValue = null;
for (Map.Entry<String, NewCookie> entry : loginResponse.getCookies().entrySet()) {
    String key = entry.getKey();
    if ("sessionToken".equals(key)) {
        cookieValue = entry.getValue().toString();
        cookieValue = cookieValue.substring(0, cookieValue.indexOf(";"));
    }
}

`

and then set it as a header to the protected resource request, such as:

.header("Cookie", cookieValue)


问:
Grid with different colours for each cell
I'm new in AngularJS (1.6) and hope you can help me with this question.

I have a grid that grows the number of columns according to the selected date range. This table always has five rows below the header.

I need to create color conditions for each cell depending on the data base value. Something like validate my data before the grid, adding a status for each data, and apply a collor condition based on this status

```<code>Ex:
    10/11   11/11   12/11   13/11
    7%      8%      3%      9%
    3%      2%      1%      4%
    9%      7%      8%      3%
    7%      8%      3%      9%
    3%      2%      1%      4%
</code>```

Controller

```<code> $scope.buscarDados = function (concessionaria, data_inicio, data_fim) {

    $http({
        method: 'POST',
        data: { Concessionaria: concessionaria, DataInicio: data_inicio, DataFim: data_fim },
        url: '/AnaliseDados/GerarJsonCabecalhoGrid'
    })
    .then(function (response) {
        $scope.table_headers = response.data.table_headers;

    }, function (error) {
        console.log(error);
    });

    $http({
        method: 'POST',
        data: { Concessionaria: concessionaria, DataInicio: data_inicio, DataFim: data_fim },
        url: '/AnaliseDados/buscaDadosPI'
    })
    .then(function (response) {
        $scope.items = response.data.items;
    }
)
};
</code>```

View

```<code>    <table class="table table-striped table-condensed table-hover">
        <thead>
            <tr>
                <th ng-repeat="header in table_headers" class="{{header.name}}">
                    {{ header.name }}
                </th>
            </tr>
        </thead>

        <tbody>
            <tr ng-repeat="item in items">
                <td ng-repeat="val in item">{{item[table_headers[$index].name]}}</td>
            </tr>
        </tbody>
    </table>
</code>```

JSON

```<code>$scope.table_headers = [
   { "name": "id"},
   { "name": "01/08" },
   { "name": "02/08" },
   { "name": "03/08" },
   { "name": "04/08" },
   { "name": "05/08" }
];
$scope.items = [
   { "id": 1, "01/08": 10, "02/08": 13, "03/08": 22, "04/08": 26, "05/08": 33 },
   { "id": 2, "01/08": 12, "02/08": 15, "03/08": 24, "04/08": 28, "05/08": 35 },
   { "id": 3, "01/08": 14, "02/08": 17, "03/08": 26, "04/08": 30, "05/08": 37 },
   { "id": 4, "01/08": 16, "02/08": 19, "03/08": 28, "04/08": 32, "05/08": 39 },
   { "id": 5, "01/08": 18, "02/08": 21, "03/08": 30, "04/08": 35, "05/08": 41 },
   { "id": 6, "01/08": 20, "02/08": 23, "03/08": 32, "04/08": 37, "05/08": 43 }
];
</code>```

populated itens

答:
You can create different columns with different styles and change their visibility according to your condition

```<code><th class="style1" ng-show="condition = condition1">
    {{ header.name }}
</th>
<th class="style2" ng-show="condition = condition2">
    {{ header.name }}
</th>
<th class="style3" ng-show="condition = condition3">
    {{ header.name }}
</th>
</code>```

or you can use a custom filter

html

```<code><th ng-repeat="header in table_headers | filter: filterStyle" class="{{header.style}}">
    {{ header.name }}
</th>
</code>```

js

```<code>$scope.filterStyle = function (item) {
    if (item.condition == 'condition1') {
        item.style = 'style1';
    }
    else if (item.condition == 'condition2') {
        item.style = 'style2';
    }
    else if (item.condition == 'condition3') {
        item.style = 'style3';
    }
    else {
        item.style = 'default style';
    }

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

Body:
I'm new in AngularJS (1.6) and hope you can help me with this question.

I have a grid that grows the number of columns according to the selected date range. This table always has five rows below the header.

I need to create color conditions for each cell depending on the data base value. Something like validate my data before the grid, adding a status for each data, and apply a collor condition based on this status

Ex:
    10/11   11/11   12/11   13/11
    7%      8%      3%      9%
    3%      2%      1%      4%
    9%      7%      8%      3%
    7%      8%      3%      9%
    3%      2%      1%      4%

Controller

 $scope.buscarDados = function (concessionaria, data_inicio, data_fim) {

    $http({
        method: 'POST',
        data: { Concessionaria: concessionaria, DataInicio: data_inicio, DataFim: data_fim },
        url: '/AnaliseDados/GerarJsonCabecalhoGrid'
    })
    .then(function (response) {
        $scope.table_headers = response.data.table_headers;

    }, function (error) {
        console.log(error);
    });

    $http({
        method: 'POST',
        data: { Concessionaria: concessionaria, DataInicio: data_inicio, DataFim: data_fim },
        url: '/AnaliseDados/buscaDadosPI'
    })
    .then(function (response) {
        $scope.items = response.data.items;
    }
)
};

View

                    {{ header.name }}

                {{item[table_headers[$index].name]}}

JSON

$scope.table_headers = [
   { "name": "id"},
   { "name": "01/08" },
   { "name": "02/08" },
   { "name": "03/08" },
   { "name": "04/08" },
   { "name": "05/08" }
];
$scope.items = [
   { "id": 1, "01/08": 10, "02/08": 13, "03/08": 22, "04/08": 26, "05/08": 33 },
   { "id": 2, "01/08": 12, "02/08": 15, "03/08": 24, "04/08": 28, "05/08": 35 },
   { "id": 3, "01/08": 14, "02/08": 17, "03/08": 26, "04/08": 30, "05/08": 37 },
   { "id": 4, "01/08": 16, "02/08": 19, "03/08": 28, "04/08": 32, "05/08": 39 },
   { "id": 5, "01/08": 18, "02/08": 21, "03/08": 30, "04/08": 35, "05/08": 41 },
   { "id": 6, "01/08": 20, "02/08": 23, "03/08": 32, "04/08": 37, "05/08": 43 }
];

populated itens

Body:
You can create different columns with different styles and change their visibility according to your condition

<th class="style1" ng-show="condition = condition1">
    {{ header.name }}
</th>
<th class="style2" ng-show="condition = condition2">
    {{ header.name }}
</th>
<th class="style3" ng-show="condition = condition3">
    {{ header.name }}
</th>

or you can use a custom filter

html

<th ng-repeat="header in table_headers | filter: filterStyle" class="{{header.style}}">
    {{ header.name }}
</th>

js

$scope.filterStyle = function (item) {
    if (item.condition == 'condition1') {
        item.style = 'style1';
    }
    else if (item.condition == 'condition2') {
        item.style = 'style2';
    }
    else if (item.condition == 'condition3') {
        item.style = 'style3';
    }
    else {
        item.style = 'default style';
    }

    return true;
};


问:
Value of string was rewritten after read a file which the name is the value of the string
There are 5 txt files, one ("table_of_content.txt") includes the name of other four txt files, in each four successive lines. And in the other four files, each contain one line of sentence.

There is not problem to read the table txt and use array to restore the string(the names of other files).

But after I try to use getline.() to restore the sentences in the other four files, filenames[number], the string which should restore the name of the four files are rewritten, it become the same as words[number], which restore the sentences.

I am really confused, which part is wrong?

```<code>#include <iostream>
#include <fstream>
#include <string>
#include <cstring>

using namespace std;

int main (){
    ifstream content;
    content.open("table_of_content.txt");
    if (content.fail()){
        cout<< "fails";
        return 0;
    }
    int number = 0, i = 0;
    string filenames[number], words[i];
    while (content >> filenames[number]){
        number++;
    }
    content.close();
    cout << number << " students' files are read" << endl;
    // read table_of_content.txt
    ifstream input;
    while (i < number){
        input.open(filenames[i].c_str());
        getline(input, words[i]);
        // after this getline, filenames become words
        input.close();
        i++;
    }
    cout << filenames[2] << endl << words[3] << endl;
    return 0;
}
</code>```

答:
The definition

```<code>string filenames[number]
</code>```

is invalid for two reasons:

C++ doens't have variable-length arrays. The solution is to use std::vector.

At the time of the definition, the value of number is zero. So you attempt to create an array of zero elements, which is not allowed. The solution to this is to do the definition after you get the final value of number.

You have the same problem with words.

Reading the code a little closer, one simple solution for filenames is to read into a temporary string and then push the string into the vector. There are more compact and "C++'ish" solutions, but pushing in a loop is a good start.

That is, you first loop could be something like

```<code>std::vector<std::string> filenames;
std::string filename;
while (content >> filename){
    filenames.push_back(filename)
}
</code>```

Note that number is no longer needed, since the number of elements can be gotten by filenames.size().

You should do something similar with words.

Body:
There are 5 txt files, one ("table_of_content.txt") includes the name of other four txt files, in each four successive lines. And in the other four files, each contain one line of sentence.

There is not problem to read the table txt and use array to restore the string(the names of other files).

But after I try to use getline.() to restore the sentences in the other four files, filenames[number], the string which should restore the name of the four files are rewritten, it become the same as words[number], which restore the sentences.

I am really confused, which part is wrong?

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>

using namespace std;

int main (){
    ifstream content;
    content.open("table_of_content.txt");
    if (content.fail()){
        cout<< "fails";
        return 0;
    }
    int number = 0, i = 0;
    string filenames[number], words[i];
    while (content >> filenames[number]){
        number++;
    }
    content.close();
    cout << number << " students' files are read" << endl;
    // read table_of_content.txt
    ifstream input;
    while (i < number){
        input.open(filenames[i].c_str());
        getline(input, words[i]);
        // after this getline, filenames become words
        input.close();
        i++;
    }
    cout << filenames[2] << endl << words[3] << endl;
    return 0;
}

Body:
The definition

string filenames[number]

is invalid for two reasons:

C++ doens't have variable-length arrays. The solution is to use std::vector.

At the time of the definition, the value of number is zero. So you attempt to create an array of zero elements, which is not allowed. The solution to this is to do the definition after you get the final value of number.

You have the same problem with words.

Reading the code a little closer, one simple solution for filenames is to read into a temporary string and then push the string into the vector. There are more compact and "C++'ish" solutions, but pushing in a loop is a good start.

That is, you first loop could be something like

std::vector<std::string> filenames;
std::string filename;
while (content >> filename){
    filenames.push_back(filename)
}

Note that number is no longer needed, since the number of elements can be gotten by filenames.size().

You should do something similar with words.


问:
Convert UnityEngine.Vector3 to UnityEngine.Touch or mouse input
I want to test my Script in Desktop as well as touch/tablet environment. Therefore I need to convert mouseinputs into Touch in my script. I tried:

```<code>        var screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);

        Touch touchZero = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
</code>```

It says Cannot implicitly convert type UnityEngine.Vector3' toUnityEngine.Touch'

Any chance to convert the type somehow so I do not have to write everything twice?

答:
You can build a touch from mouse input like this:</p>

```<code>Touch fakeTouch = new Touch ();
fakeTouch.fingerId = 10;
fakeTouch.position = Input.mousePosition;
fakeTouch.deltaTime = Time.deltaTime;
fakeTouch.deltaPosition = Input.mousePosition - lastMousePosition;
fakeTouch.phase = (Input.GetMouseButtonDown (0) ? TouchPhase.Began :
                  (fakeTouch.deltaPosition.sqrMagnitude > 1f ?
                  TouchPhase.Moved : TouchPhase.Stationary));
fakeTouch.tapCount = 1;
</code>```

Body:
I want to test my Script in Desktop as well as touch/tablet environment. Therefore I need to convert mouseinputs into Touch in my script. I tried:

        var screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);

        Touch touchZero = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);

It says Cannot implicitly convert type UnityEngine.Vector3' toUnityEngine.Touch'

Any chance to convert the type somehow so I do not have to write everything twice?

Body:
You can build a touch from mouse input like this:

Touch fakeTouch = new Touch ();
fakeTouch.fingerId = 10;
fakeTouch.position = Input.mousePosition;
fakeTouch.deltaTime = Time.deltaTime;
fakeTouch.deltaPosition = Input.mousePosition - lastMousePosition;
fakeTouch.phase = (Input.GetMouseButtonDown (0) ? TouchPhase.Began :
                  (fakeTouch.deltaPosition.sqrMagnitude > 1f ?
                  TouchPhase.Moved : TouchPhase.Stationary));
fakeTouch.tapCount = 1;


问:
How to combine transforms on different classes?
I have two classes where each of them has a transform, how I can to combine them?
I know I can do "transform: transform1, transform", but in this case I have them in different clases and the second replaces the first.

I can't use JavaScript.

Thank you!

Add example: https://codepen.io/anon/pen/BmwrgY

.class1,
.class2 {
  width: 20px;
  height: 20px;
  background-color: blue;
}

.class1 {
  transform: rotate(45deg);
}

.class2 {
  transform: translate3d(50px, 50px, 0);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="class1"></div>

<div class="class2"></div>

<div class="class1 class2"></div></code>```

答:
You have to make a new rule for elements with both classes</p>

```<code>.class1 {
    transform: rotate(45deg);
}

.class2 {
    transform: translate3d(50px, 50px, 0);
}

.class1.class2 {
    transform: rotate(45deg) translate3d(50px, 50px, 0);
}
</code>```

Body:
You have to make a new rule for elements with both classes

.class1 {
    transform: rotate(45deg);
}

.class2 {
    transform: translate3d(50px, 50px, 0);
}

.class1.class2 {
    transform: rotate(45deg) translate3d(50px, 50px, 0);
}


问:
How to write a command line C# program that posts to Twitter
I'd like to write a console program in C# that posts a Tweet to Twitter.  I've never used the Twitter APIs before and don't know anything about how their authentication works.  I found an API library called Twitterizer, but it seems geared towards web applications and wants the user to logon with a web browser.  All the API docs on Twitter's website seems geared around this scenario as well.

Is it possible to access the Twitter APIs using a console app with no web browser access?  I'm perfectly fine hard coding in the name and password for the Twitter user I want to post under as well.  Thanks!

Mike

答:
of course you can use anything to connect to Twitter via RESTful api.

you should use oauth, and set up your application in http://dev.twitter.com, then you should read all articles listed in documents, you must specify your app as Client but not Browser so user input a number to get through authentication.

you can use many libraries so that you can save your time, all are listed in the documents

and be CAREFUL, you should not use Twitter's own api console which is buggy (as i know parameters somtimes can't be parsed), you should use APIgee instead which is powerful and stable.

if you want use basic authentication, you should use api proxy (one famous is twip), if you just need only one single C# apps, you must code by yourself:

you should use given username and password to login twitter, parse cookies passed

use normal oauth to get temporaly access token url.

use cookies got from step 1, emulates form submit to allow your apps, capture PIN code

use pin code to finish oauth.

MOST IMPORTANT, you must store access token in client's machine so next time you can bypass above steps

ContentLicense: CC BY-SA 2.5


问:
"(perhaps it was deleted?)" Spreadsheet Error in Google Scripts
I have a small script that grabs some data from a spreadsheet and displays it on a Google Scripts html page - for testing I'm just displaying the sheet name.

It works fine for me but other users get the error : [Error] ScriptError: Document 1sTltxpKjSqgaFjc9-3EQzgtvyErkut2qETsn7SdThLE is missing (perhaps it was deleted?)

The script and Spreadsheet are both public and the user can access the spreadsheet directly.

Link to Spreadsheet

Link to Script page

Google Scripts Code:

```<code>function getInfo() {
    var ss = SpreadsheetApp.openById("1sTltxpKjSqgaFjc9-3EQzgtvyErkut2qETsn7SdThLE");
    var ssName = ss.getName();
    var sheet = ss.getSheets()[0];

     return 'Doc: ' + ssName + '. Sheet: ' + sheet.getName();
 }
</code>```

The javascript in the html is simply:

```<code>  function getSheetInfo(data) {
      $('p.data').append(data);
  }

  google.script.run.withSuccessHandler(getSheetInfo)
     .getInfo();
</code>```

Can anyone shed any light why this sheet isn;t accessible to other users but they can view the sheet? Both are public.

Thanks
Rob

答:
try your luck with DriveApp instead. </p>

```<code>    var files = DriveApp.getFilesByName(name).next();
</code>```

Body:
I have a small script that grabs some data from a spreadsheet and displays it on a Google Scripts html page - for testing I'm just displaying the sheet name.

It works fine for me but other users get the error : [Error] ScriptError: Document 1sTltxpKjSqgaFjc9-3EQzgtvyErkut2qETsn7SdThLE is missing (perhaps it was deleted?)

The script and Spreadsheet are both public and the user can access the spreadsheet directly.

Link to Spreadsheet

Link to Script page

Google Scripts Code:

function getInfo() {
    var ss = SpreadsheetApp.openById("1sTltxpKjSqgaFjc9-3EQzgtvyErkut2qETsn7SdThLE");
    var ssName = ss.getName();
    var sheet = ss.getSheets()[0];

     return 'Doc: ' + ssName + '. Sheet: ' + sheet.getName();
 }

The javascript in the html is simply:

  function getSheetInfo(data) {
      $('p.data').append(data);
  }

  google.script.run.withSuccessHandler(getSheetInfo)
     .getInfo();

Can anyone shed any light why this sheet isn;t accessible to other users but they can view the sheet? Both are public.

Thanks
Rob

Body:
try your luck with DriveApp instead.

    var files = DriveApp.getFilesByName(name).next();


问:
DrawableBottom Error in Android Sdk 17
I have a Button in my activity's layout like this:

```<code><Button
        android:id="@+id/button_before"
        android:layout_width="45dp"
        android:layout_height="25dp"
        android:layout_gravity="center_vertical|start"
        android:background="@color/transparent"
        android:drawableBottom="@drawable/ic_navigate_before"
        android:textColor="@color/gray_2" />
</code>```

It is ok when I run my app to a device with Android SDK >19 but when I run my app to a device with Android SDK <19 like 17, my activity unfortunately stopped and this error occurs:

```<code>11-16 08:57:41.042 3549-3549/? E/AndroidRuntime: FATAL EXCEPTION: main
                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.app/com.myapp.app.SearchActivity}: android.view.InflateException: Binary XML file line #45: Error inflating class Button
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                 at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                 at android.os.Handler.dispatchMessage(Handler.java:99)
                                                 at android.os.Looper.loop(Looper.java:137)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:511)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: android.view.InflateException: Binary XML file line #45: Error inflating class Button
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.parseInclude(LayoutInflater.java:830)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:736)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                 at com.myapp.app.SearchActivity.onCreate(SearchActivity.java:90)
                                                 at android.app.Activity.performCreate(Activity.java:5104)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                 at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                 at android.os.Handler.dispatchMessage(Handler.java:99)
                                                 at android.os.Looper.loop(Looper.java:137)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:511)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_navigate_before.xml from drawable resource ID #0x7f02007d
                                                 at android.content.res.Resources.loadDrawable(Resources.java:1958)
                                                 at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
                                                 at android.widget.TextView.<init>(TextView.java:769)
                                                 at android.widget.Button.<init>(Button.java:107)
                                                 at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:66)
                                                 at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:62)
                                                 at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:109)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1029)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1087)
                                                 at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:675)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.parseInclude(LayoutInflater.java:830)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:736)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                 at com.myapp.app.SearchActivity.onCreate(SearchActivity.java:90)
                                                 at android.app.Activity.performCreate(Activity.java:5104)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                 at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                 at android.os.Handler.dispatchMessage(Handler.java:99)
                                                 at android.os.Looper.loop(Looper.java:137)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:511)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #1: invalid drawable tag vector
                                                 at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:881)
                                                 at android.graphics.drawable.Drawable.createFromXml(Drawable.java:822)
                                                 at android.content.res.Resources.loadDrawable(Resources.java:1955)
                                                 at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
                                                 at android.widget.TextView.<init>(TextView.java:769)
                                                 at android.widget.Button.<init>(Button.java:107)
                                                 at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:66)
                                                 at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:62)
                                                 at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:109)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1029)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1087)
                                                 at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:675)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.parseInclude(LayoutInflater.java:830)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:736)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                 at com.myapp.app.SearchActivity.onCreate(SearchActivity.java:90)
                                                 at android.app.Activity.performCreate(Activity.java:5104)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                 at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                 at android.os.Handler.dispatchMessage(Handler.java:99)
                                                 at android.os.Looper.loop(Looper.java:137)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:511)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                 at dalvik.system.NativeStart.main(Native Method)
</code>```

When I remove this line from my layout XML activity runs ok in every device:

android:drawableBottom="@drawable/ic_navigate_before"

And ic_navigate_before is an XML file:

```<code><vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
<path
    android:fillColor="@color/gray_2"
    android:pathData="M15.41,7.41L14,6l-6,6 6,6 1.41,-1.41L10.83,12z"/>
</vector>
</code>```

Also, my app min SDK is 16.
What can I do to resolve this problem?

答:
From 23.3.0 version vector drawables can only be loaded via app:srcCompat or setImageResource(). see here.

you can get VectorDrawable to work as drawableLeft (etc.) but it depends on the Support Library version and it comes with a price.the best way to take this issue i found is, remove drawable bottom from xml and add drawable bottom programmatically.

```<code>navigateBefore.setCompoundDrawablesWithIntrinsicBounds( 0, 0, 0, R.drawable. ic_navigate_before);
</code>```

Title: DrawableBottom Error in Android Sdk 17

Body:
I have a Button in my activity's layout like this:

<Button
        android:id="@+id/button_before"
        android:layout_width="45dp"
        android:layout_height="25dp"
        android:layout_gravity="center_vertical|start"
        android:background="@color/transparent"
        android:drawableBottom="@drawable/ic_navigate_before"
        android:textColor="@color/gray_2" />

It is ok when I run my app to a device with Android SDK >19 but when I run my app to a device with Android SDK <19 like 17, my activity unfortunately stopped and this error occurs:

11-16 08:57:41.042 3549-3549/? E/AndroidRuntime: FATAL EXCEPTION: main
                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.app/com.myapp.app.SearchActivity}: android.view.InflateException: Binary XML file line #45: Error inflating class Button
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                 at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                 at android.os.Handler.dispatchMessage(Handler.java:99)
                                                 at android.os.Looper.loop(Looper.java:137)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:511)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: android.view.InflateException: Binary XML file line #45: Error inflating class Button
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.parseInclude(LayoutInflater.java:830)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:736)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                 at com.myapp.app.SearchActivity.onCreate(SearchActivity.java:90)
                                                 at android.app.Activity.performCreate(Activity.java:5104)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                 at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                 at android.os.Handler.dispatchMessage(Handler.java:99)
                                                 at android.os.Looper.loop(Looper.java:137)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:511)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_navigate_before.xml from drawable resource ID #0x7f02007d
                                                 at android.content.res.Resources.loadDrawable(Resources.java:1958)
                                                 at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
                                                 at android.widget.TextView.<init>(TextView.java:769)
                                                 at android.widget.Button.<init>(Button.java:107)
                                                 at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:66)
                                                 at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:62)
                                                 at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:109)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1029)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1087)
                                                 at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:675)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.parseInclude(LayoutInflater.java:830)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:736)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                 at com.myapp.app.SearchActivity.onCreate(SearchActivity.java:90)
                                                 at android.app.Activity.performCreate(Activity.java:5104)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                 at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                 at android.os.Handler.dispatchMessage(Handler.java:99)
                                                 at android.os.Looper.loop(Looper.java:137)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:511)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                 at dalvik.system.NativeStart.main(Native Method)
                                              Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #1: invalid drawable tag vector
                                                 at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:881)
                                                 at android.graphics.drawable.Drawable.createFromXml(Drawable.java:822)
                                                 at android.content.res.Resources.loadDrawable(Resources.java:1955)
                                                 at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
                                                 at android.widget.TextView.<init>(TextView.java:769)
                                                 at android.widget.Button.<init>(Button.java:107)
                                                 at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:66)
                                                 at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:62)
                                                 at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:109)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1029)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1087)
                                                 at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:675)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.parseInclude(LayoutInflater.java:830)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:736)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                 at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                 at com.myapp.app.SearchActivity.onCreate(SearchActivity.java:90)
                                                 at android.app.Activity.performCreate(Activity.java:5104)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
                                                 at android.app.ActivityThread.access$600(ActivityThread.java:141)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
                                                 at android.os.Handler.dispatchMessage(Handler.java:99)
                                                 at android.os.Looper.loop(Looper.java:137)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                 at java.lang.reflect.Method.invokeNative(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:511)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                 at dalvik.system.NativeStart.main(Native Method)

When I remove this line from my layout XML activity runs ok in every device:

android:drawableBottom="@drawable/ic_navigate_before"

And ic_navigate_before is an XML file:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
<path
    android:fillColor="@color/gray_2"
    android:pathData="M15.41,7.41L14,6l-6,6 6,6 1.41,-1.41L10.83,12z"/>
</vector>

Also, my app min SDK is 16.
What can I do to resolve this problem?

Body:
From 23.3.0 version vector drawables can only be loaded via app:srcCompat or setImageResource(). see here.

you can get VectorDrawable to work as drawableLeft (etc.) but it depends on the Support Library version and it comes with a price.the best way to take this issue i found is, remove drawable bottom from xml and add drawable bottom programmatically.

navigateBefore.setCompoundDrawablesWithIntrinsicBounds( 0, 0, 0, R.drawable. ic_navigate_before);


问:
IIS error (possible related to microsoft word interop or windows update 0x80070070 error)
Yesterday I installed office on the production server because my application (C#) is using Microsoft Word Interop. I still got the problem and the part of the application that was using Word Interop (document creation) was not working but the application itself was working fine. In the morning the application was off, and keep throwing "500 error". I uninstalled office but the problem was still there. Finally I performed the windows update and problem solved. Can anyone tell me what could possible go wrong? Here is a part of the windows update log:

03:00:56:161   996    1b54    Handler :::::::::::::
  2017-11-16  03:00:56:161     996    1b54    Handler :: START ::  Handler: MSI Install
  2017-11-16  03:00:56:161     996    1b54    Handler :::::::::
  2017-11-16  03:00:56:161     996    1b54    Handler   : Updates to install = 1
  2017-11-16  03:00:56:161     996    1b54    Handler Extracting MSP file stored in CAB filterpack-x-none.cab
  2017-11-16  03:00:56:176     996    1b54    Handler FATAL: Extraction of CAB filterpack-x-none.cab failed, error = 0x80070070
  2017-11-16  03:00:56:176     996    1b54    Handler   : WARNING: Operation failed at update 0, Exit code = 0x80070070
  2017-11-16  03:00:56:176     996    1b54    Handler :::::::::
  2017-11-16  03:00:56:176     996    1b54    Handler ::  END  ::  Handler: MSI Install
  2017-11-16  03:00:56:176     996    1b54    Handler :::::::::::::
  2017-11-16  03:00:56:176     868    ca4 DnldMgr Regulation: {7971F918-A847-4430-9279-4A52D1EFE18D} - Update D5ACB45E-3FF2-4DD1-AB54-3BA19C4B4440 is "Defaults" regulated and can NOT download. Sequence 2467 vs AcceptRate 0.
  2017-11-16  03:00:56:176     868    ca4 DnldMgr Regulation: {7971F918-A847-4430-9279-4A52D1EFE18D} - Update 6CCF7EC0-EE26-4E69-9700-6F0395CD3E53 is "Defaults" regulated and can NOT download. Sequence 2467 vs AcceptRate 0.

EDIT

I found that error 0x80070070 in windows update log is related to insufficient disk space. Is this possible related with the "500 error" of the iis server? There is 3GB free space in the main hd, the other hds have more than 5GB free space.

答: You should think about changing the way you have coded if you can. Placing office on a backend server to interact behind the scenes for you is notoriously bad. Usually, you let the client deal with document types etc, the only thing that is important is that you ensure IIS has relevant entries in it's MIME Types list to be able to handle the office documents (which I think by default it has anyway).</p>


问:
MFC Classes and C++ style casts
I'm wondering if I haven't fully understood C++ casts versus old C-Style cast. In MFC I have this method:

```<code>CWnd * GetDlgItem(UINT uResId);
</code>```

I'm expecting that a CComboBox (or CEdit), which is derived from CWnd, requires this kind of cast:

```<code>dynamic_cast<CComboBox *>(GetDlgItem(IDC_COMBO1));
// for CEdit:
dynamic_cast<CEdit *>(GetDlgItem(IDC_EDIT1));
</code>```

but this operation causes a crash for using null pointer, that means that cast have failed. Using:

```<code>reinterpret_cast<CComboBox *>(GetDlgItem(IDC_COMBO1));
// for CEdit:
reinterpret_cast<CEdit *>(GetDlgItem(IDC_EDIT1));
</code>```

fixes the problem, but I'm disappointed.
What am I missing?

答:
The problem is that GetDlgItem may return a temporary CWnd* pointer.

If the window is a CWnd derived class and the window is created with CWnd::Create(Ex) or the window is subclassed, RTTI will work.

When the window is created by Windows (due to a dialog template) and the Window isn't subclassed by the MFC (with DDX_Control ow CWnd::SubclassWindow), GetDlgItem just returns a temporary CWnd*, with CWnd::FromHandle. This window handle is always of the base type CWnd.

If you want to check if this window is really a Edit control you can use CWnd::GetClassName. Casting to a CEdit* is safe and convenient because a CEdit control communicates with it's HWND counterpart just via Window messages. So this works for all basic integrated window classes.

Title: MFC Classes and C++ style casts

Body:
I'm wondering if I haven't fully understood C++ casts versus old C-Style cast. In MFC I have this method:

CWnd * GetDlgItem(UINT uResId);

I'm expecting that a CComboBox (or CEdit), which is derived from CWnd, requires this kind of cast:

dynamic_cast<CComboBox *>(GetDlgItem(IDC_COMBO1));
// for CEdit:
dynamic_cast<CEdit *>(GetDlgItem(IDC_EDIT1));

but this operation causes a crash for using null pointer, that means that cast have failed. Using:

reinterpret_cast<CComboBox *>(GetDlgItem(IDC_COMBO1));
// for CEdit:
reinterpret_cast<CEdit *>(GetDlgItem(IDC_EDIT1));

fixes the problem, but I'm disappointed.
What am I missing?


问:
How do I open a new window/tab and dynamically fill it with content?
I am building a website that displays recipes. Each recipe appears as part of a blog entry, and will have a link at the bottom to Print this recipe.

What I want to happen is a click on the link opens a new window and fills it with a print-friendly-styled version of the recipe, which is already inside its own
.

Can I do this with JS/jQuery alone, or do I need to process from the server side? Any ideas how to do this?

EDIT: What would be ideal would be to generate a PDF on the fly, but in lieu of that I'd like a new window, containing only the recipe, for the visitor to print out or save, as they see fit. Print-styles are nice, but most people don't know they exist and can't be bothered to check and see by printing out a page that doesn't look print ready.

答:
If i was you, i'd go for the pdf creating solution. It is fairly simple to create pdf's on the fly in php, and it will almost certainly give a better user experience to your main audience.

If you want to skip that excersise, i'd do it the following way:

1: fetch the data you need as JSON on the original non-printerfriendly page, and use clientside templating to build the ui. Store the JSON for use on the printerfriendly page

2: when you open the new window, use the exact same method, but use another template optimized for printing.


问:
String To C char** Swift 3
I am trying to call a C function in swift

```<code>int getValueFromC(char ** aValue);
</code>```

In swift I see the "Type" is

```<code>UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>
</code>```

So i would call the function i swift using:

```<code>getValueFrom(myStringPointerPointer)
</code>```

where myStringPointerPointer value would be at least initialised

答:
```<code>var aVar:UnsafeMutablePointer<CChar>? = nil
let aIntVar = getValueFromC(&aVar)
</code>```

Title: String To C char** Swift 3

Body:
I am trying to call a C function in swift

int getValueFromC(char ** aValue);

In swift I see the "Type" is

UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>

So i would call the function i swift using:

getValueFrom(myStringPointerPointer)

where myStringPointerPointer value would be at least initialised


问:
How to show popup dialog over lock screen like Android Alarm Clock when getting GCM
I need to show message on top of the lock screen,
like Android Alarm Clock is displaying full screen of the alarm, when it's the time to wake up.

Here is a photo of one of the screen popup when there is alarm:

Screenshot

答:
```<code>Window window = getWindow();

window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
</code>```


问:
Why custom subclass of UIScrollView in Swift have to UIGestureRecognizerDelegate?
Objective-C code:

```<code>#import "CZScrollView.h"

@implementation CZScrollView

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    NSLog(@"it works");
    return false;
}

@end
</code>```

Swift code:

```<code>import UIKit

class CZScrollView: UIScrollView,UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        print("it works")
        return false
    }
}
</code>```

I need to identify other gestures and decide my scrollview's behavior. So I need to create a subclass of UIScrollView and add my code in the method shouldRecognizeSimultaneouslyWith of UIGestureRecognizerDelegate.

First, the Objective-C code and the Swift code can realize my need. But there is something strange in the Swift code. If you don't declare the UIGestureRecognizerDelegate, the method would not be run. Why is this?

答:
Chances are that in the internal swift code of UIScrollView there could be something like this:

```<code>if let gestureRecognizerDelegate = self as? UIGestureRecognizerDelegate {
   // Do whatever
}
</code>```

If you don't explicitly mark your class as conforming to the UIGestureRecognizerDelegate protocol, that check will fail.

Body:
Objective-C code:

#import "CZScrollView.h"

@implementation CZScrollView

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    NSLog(@"it works");
    return false;
}

@end

Swift code:

import UIKit

class CZScrollView: UIScrollView,UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        print("it works")
        return false
    }
}

I need to identify other gestures and decide my scrollview's behavior. So I need to create a subclass of UIScrollView and add my code in the method shouldRecognizeSimultaneouslyWith of UIGestureRecognizerDelegate.

First, the Objective-C code and the Swift code can realize my need. But there is something strange in the Swift code. If you don't declare the UIGestureRecognizerDelegate, the method would not be run. Why is this?

Body:
Chances are that in the internal swift code of UIScrollView there could be something like this:

if let gestureRecognizerDelegate = self as? UIGestureRecognizerDelegate {
   // Do whatever
}

If you don't explicitly mark your class as conforming to the UIGestureRecognizerDelegate protocol, that check will fail.


问:
Git - amending an historical commit
So you're working along like a good little developer: you commit one set of changes, let's call it foundation. Then you finish up the next segment and commit, lets call it framework. You're about to move onto the next step of cleanup when you realize: Oh No! I forgot to add an important change to my foundation commit! (let's call it patch)

But not to fear. Git allows us to edit history*. No one will ever see our mistakes...

to review this is what our commit history looks like

```<code>patch
|
framework
|
foundation
|
everything that came before
...
</code>```

As far as I know there are two basic ways we could go about this. First method, commit the changes of patch and then use git rebase -i to change the order of commits and squash/fixup patch into foundation. Second method, stash the changes in patch then using git rebase -i edit the foundation commit using git commit --amend. That is:

First method

git commit -am 'patch'

git rebase -i

```<code># Originally
# pick foundation
# pick framework
# pick patch

# Now
pick foundation
fixup patch
pick framework
</code>```

Second method

git stash

git rebase -i

```<code># Originally
# pick foundation
# pick framework

# Now
edit foundation
pick framework
</code>```

git stash apply

git commit --amend

git rebase --continue

At the end of both of these methods, we will have the commit history of

```<code>framework
|
foundation+patch
|
everything that came before
...
</code>```

So my question is

Should we prefer one process over another? And if so why? What benefits/risks are involved with one or the other?

*Disclaimer: Time travel is dangerous. Editing your history could destroy your repo, especially if it has been shared with multiple people. Use this power wisely...

答:
The main difference between the two method you listed should be whether use fixup or edit  for git rebase -i command.

Both of the two method are ok. But the second method can make the commit history more clearly, especially if you co-work with others for the same repo/branch, squash commits is not recommended. While if you want the history to be short, you can squash as the first method.

And for the second method, you can also commit patch  first and then rewrite the commit foundation:

```<code>git commit -am 'patch'
git rebase -i
</code>```

In rebase interactive window, change it as:

```<code>edit foundation
pick framework
pick patch
</code>```

Title: Git - amending an historical commit

Body:
So you're working along like a good little developer: you commit one set of changes, let's call it foundation. Then you finish up the next segment and commit, lets call it framework. You're about to move onto the next step of cleanup when you realize: Oh No! I forgot to add an important change to my foundation commit! (let's call it patch)

But not to fear. Git allows us to edit history*. No one will ever see our mistakes...

to review this is what our commit history looks like

patch
|
framework
|
foundation
|
everything that came before
...

As far as I know there are two basic ways we could go about this. First method, commit the changes of patch and then use git rebase -i to change the order of commits and squash/fixup patch into foundation. Second method, stash the changes in patch then using git rebase -i edit the foundation commit using git commit --amend. That is:

First method

git commit -am 'patch'

git rebase -i

# Originally
# pick foundation
# pick framework
# pick patch

# Now
pick foundation
fixup patch
pick framework

Second method

git stash

git rebase -i

# Originally
# pick foundation
# pick framework

# Now
edit foundation
pick framework

git stash apply

git commit --amend

git rebase --continue

At the end of both of these methods, we will have the commit history of

framework
|
foundation+patch
|
everything that came before
...

So my question is

Should we prefer one process over another? And if so why? What benefits/risks are involved with one or the other?

*Disclaimer: Time travel is dangerous. Editing your history could destroy your repo, especially if it has been shared with multiple people. Use this power wisely...

Body:
The main difference between the two method you listed should be whether use fixup or edit  for git rebase -i command.

Both of the two method are ok. But the second method can make the commit history more clearly, especially if you co-work with others for the same repo/branch, squash commits is not recommended. While if you want the history to be short, you can squash as the first method.

And for the second method, you can also commit patch  first and then rewrite the commit foundation:

git commit -am 'patch'
git rebase -i

In rebase interactive window, change it as:

edit foundation
pick framework
pick patch


问:
Open Source (Free) ASP.NET Site Seacrch
Does anybody know of an easy to implement site search engine for asp.net? The less complicated the better.

Probably just needs a crawler and backend to store results. Some sort of API to get the search results back would be handy but I can get it straight from the DB as well.

答:
Dot Lucene (AKA Lucene.net)

You can find a good sample and explanation in CodeProject

OwnerDisplayName: William

Title: Open Source (Free) ASP.NET Site Seacrch

OwnerDisplayName: Eduardo Molteni

LastEditorDisplayName: Eduardo Molteni


问:
Testing iPad applications
Bit of a hardware question here. I am developing iPad applications for a client and am finding that when I send over beta versions for the client to test, he is finding many more crashes on his devices than I am seeing. A lot of these crashes are 'low memory crashes' which I simply am not seeing/able to reproduce.

Am wondering what differences between the 2 devices there may be so that we can work out if it is a hardware issue. Any ideas?

答:
Possibly your client has more stuff running at the same time. Or your own app is background-enabled and is getting killed from time to time...

Always test your own code with the Simulator - it has a feature that allows you to simulate low memory warnings.

Title: Testing iPad applications


问:
GoogleSignIn Account Information
I'm currently able to SignIn in my app with GoogleSignIn, so in my SignInActivity I have the GoogleSignIn button that asks the user to choose a Google account.

In the MainActivity in onStart() method I have GoogleSignIn.getLastSignedInAccount that return a GoogleSignInAccount.

From this object I can get information on account like: name, email or image.

I put all this information in the header of navigation drawer as all Google apps has, but I miss the 'background image' that you see in the Google Plus account.

How can I get this background image? Do I have to change the GoogleSignIn method or the options?

答: Unfortunately, you cannot get the background image from googleSignInAccount object. As you can see, there many methods but none of them can help you get the background image. Using googleSignInAccount can help you only retrieve a signed-in user's basic profile information, such as their name, email address, and profile photo URL.

Title: GoogleSignIn Account Information


问:
Filter table data depending of a url id in vueJS
I want to get data from a JSON API depending of the id in the url page.
First I have the code of my table that have link depending of a url id that go to the second table template:

```<code><table class="table table-condensed">
    <tr style="text-align:left;" v-for="data in metadata">
        <td>{{data.id}}</td>
        <td><router-link :to="{ name: 'mixtapesDetails', params{id : data.id}}">
            {{data.title}}
        </router-link></td>
        <td><router-link :to="{ name: 'mixtapesDetails', params{id : data.id}}">
            {{data.artist}}
        </router-link></td>
    </tr>
</table>
</code>```

There is my second table where I only want to display my data depending of the ID:

```<code>    <div style="margin-left:400px;">
        <div>{{$route.params.id}}</div>
        <table class="table table-condensed">
            <tr>
                <th>ID</th>
            </tr>
            <tr style="text-align:left;" v-for="data in metadata">
                <td>{{data.id}}</td>
                <td>{{data.title}}</td>
                <td>{{data.artist}}</td>
                <td>{{data.cover}}</td>

            </tr>
        </table>
    </div>
</code>```

Then I have my Js function to get all my data :

```<code>export default {
  data(){
    return {
        metadata: null
    }
  },
  methods:{
    httpGet(theUrl){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", theUrl, false); // true for asynchronous request
    xmlHttp.send(null);
    console.log(JSON.parse(xmlHttp.responseText));
    return JSON.parse(xmlHttp.responseText);
    }
  },
  mounted(){
    this.metadata = this.httpGet("urltooJsondata");
  }
}
</code>```

And then I have my routes in JS :

```<code>export default new VueRouter({
    routes: [
      {
        path: '/mixtapeList',
        name: 'mixtapeList',
        component: mixtapeList
      },
    {
        path: '/mixtapesDetails/:id',
        name: 'mixtapesDetails',
        component: mixtapesDetails
    }
    ]
  })
</code>```

The objective is that when I click on a router-link it goes to a single page with a url like this /mixtapesdetails/id, and I want that the the data displayed on that page are the data which correspond to the url id.

I really need help and I don't find the solution on web.

答:
I think that for this purposes is there $route.params object. So if you have route like this,

```<code>{
  path: '/mixtapesDetails/:anything',
  name: 'mixtapesDetails',
  component: mixtapesDetails
}
</code>```

in mixtapesDetails component implementation you can access :anything path segment value with $route.params.anything.

Body:
I want to get data from a JSON API depending of the id in the url page.
First I have the code of my table that have link depending of a url id that go to the second table template:

        {{data.id}}
        <router-link :to="{ name: 'mixtapesDetails', params{id : data.id}}">
            {{data.title}}
        </router-link>
        <router-link :to="{ name: 'mixtapesDetails', params{id : data.id}}">
            {{data.artist}}
        </router-link>

There is my second table where I only want to display my data depending of the ID:

{{$route.params.id}}

                ID

                {{data.id}}
                {{data.title}}
                {{data.artist}}
                {{data.cover}}

Then I have my Js function to get all my data :

export default {
  data(){
    return {
        metadata: null
    }
  },
  methods:{
    httpGet(theUrl){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", theUrl, false); // true for asynchronous request
    xmlHttp.send(null);
    console.log(JSON.parse(xmlHttp.responseText));
    return JSON.parse(xmlHttp.responseText);
    }
  },
  mounted(){
    this.metadata = this.httpGet("urltooJsondata");
  }
}

And then I have my routes in JS :

export default new VueRouter({
    routes: [
      {
        path: '/mixtapeList',
        name: 'mixtapeList',
        component: mixtapeList
      },
    {
        path: '/mixtapesDetails/:id',
        name: 'mixtapesDetails',
        component: mixtapesDetails
    }
    ]
  })

The objective is that when I click on a router-link it goes to a single page with a url like this /mixtapesdetails/id, and I want that the the data displayed on that page are the data which correspond to the url id.

I really need help and I don't find the solution on web.

Body:
I think that for this purposes is there $route.params object. So if you have route like this,

{
  path: '/mixtapesDetails/:anything',
  name: 'mixtapesDetails',
  component: mixtapesDetails
}

in mixtapesDetails component implementation you can access :anything path segment value with $route.params.anything.


问:
notification on data waiting to be read on serial link
I try to add to my g_main_loop a new source that is a file descriptor on a serial line peripheric.

I try this code :

```<code>GError* error;
GIOChannel* channel;
channel=g_io_channel_unix_new(fd_serial_line_dev);
g_io_add_watch(channel, G_IO_IN, cb_1, NULL);
g_io_channel_set_close_on_unref(channel, TRUE);
g_io_channel_set_encoding(channel, NULL, &error);
g_io_channel_set_buffered(channel, FALSE);
</code>```

The callback is :

```<code>gboolean cb_1 (GIOChannel *source, GIOCondition condition, gpointer data)
{
  gchar** line=NULL;
  GIOStatus status;
  GError* error;

  printf("cb\n");

  status=g_io_channel_read_line(source, line, NULL, NULL, &error);

  if(G_IO_STATUS_NORMAL == status)
  {
    printf("callback : data : %s\n", *line);
    g_free(*line);
    //g_io_channel_seek_position(source, 0, G_SEEK_CUR, NULL);
  }

  return TRUE;
}
</code>```

When I send data on the serial line, I obtain an infinite loop that call cb_1 each time.

I don't see where is my mistake, I expected that a read within file descriptor of the serial line will be suffisant to stop call to the callback during the next g main loop iteration...

答:
Try adding g_io_channel_unref(channel) immediatley after g_io_add_watch. Then in your callback add

```<code>if(G_IO_STATUS_EOF == status)
 return FALSE;
</code>```

g_io_channel_*_new() returns a GIOChannel
  object with a reference count of one.  g_io_add_watch() adds a further
  reference count - if you decrement it by 1, the callback will be
  disconnected and the relevant GSource object removed when the callback
  returns FALSE, which it should do when it detects end-of-file, or if
  you call g_source_remove() on the return value of g_io_add_watch()

Body:
I try to add to my g_main_loop a new source that is a file descriptor on a serial line peripheric.

I try this code :

GError* error;
GIOChannel* channel;
channel=g_io_channel_unix_new(fd_serial_line_dev);
g_io_add_watch(channel, G_IO_IN, cb_1, NULL);
g_io_channel_set_close_on_unref(channel, TRUE);
g_io_channel_set_encoding(channel, NULL, &error);
g_io_channel_set_buffered(channel, FALSE);

The callback is :

gboolean cb_1 (GIOChannel *source, GIOCondition condition, gpointer data)
{
  gchar** line=NULL;
  GIOStatus status;
  GError* error;

  printf("cb\n");

  status=g_io_channel_read_line(source, line, NULL, NULL, &error);

  if(G_IO_STATUS_NORMAL == status)
  {
    printf("callback : data : %s\n", *line);
    g_free(*line);
    //g_io_channel_seek_position(source, 0, G_SEEK_CUR, NULL);
  }

  return TRUE;
}

When I send data on the serial line, I obtain an infinite loop that call cb_1 each time.

I don't see where is my mistake, I expected that a read within file descriptor of the serial line will be suffisant to stop call to the callback during the next g main loop iteration...

Body:
Try adding g_io_channel_unref(channel) immediatley after g_io_add_watch. Then in your callback add

if(G_IO_STATUS_EOF == status)
 return FALSE;

g_io_channel_*_new() returns a GIOChannel
  object with a reference count of one.  g_io_add_watch() adds a further
  reference count - if you decrement it by 1, the callback will be
  disconnected and the relevant GSource object removed when the callback
  returns FALSE, which it should do when it detects end-of-file, or if
  you call g_source_remove() on the return value of g_io_add_watch()


问:
How to set .htaccess for 2 type get value on the same page?
For this page test.php

i have to use 2 format url

```<code>www.example.com/test/1234
</code>```

and

```<code>www.example.com/test/1234/abcd
</code>```

My .htaccess is

```<code>RewriteRule ^test/([^-]*)/([^-]*)$ /test.php?one=$1&two=$2 [L]
</code>```

It's work good with www.example.com/test/1234/abcd but redirect internal error with www.example.com/test/1234

I want to know how can i edit .htaccess for work good with my 2 url format on test.php ?

Body:
For this page test.php

i have to use 2 format url

www.example.com/test/1234

and

www.example.com/test/1234/abcd

My .htaccess is

RewriteRule ^test/([^-]*)/([^-]*)$ /test.php?one=$1&two=$2 [L]

It's work good with www.example.com/test/1234/abcd but redirect internal error with www.example.com/test/1234

I want to know how can i edit .htaccess for work good with my 2 url format on test.php ?

Body:
You can use:

RewriteRule ^test/([^/-]+)(?:/([^-]*))?$ /test.php?one=$1&two=$2 [L]


问:
Is possible to select different table cells for different threads in same sampler in JMeter record and play back
I want to load test following scenario.

1.Submit student details in basic data insert page.

Result : Added record just bind into table grid in same page.

2.Click on edit button of particular added record in table.
3.Change student name and click on save again.

My key load test scenario is record edit scenario. I used CSV data config for test parameters. I want to know is it possible to select different table cells with different thread requests in same sampler to test my scenario in same tread group.

Please refer the attachment for sample screen.enter image description here

答:
CSV Data Set Config element has Sharing Mode setting, by default it is All Threads.

This means that CSV file is shared across all JMeter threads and each Thread (virtual user) takes the next line each iteration so default configuration should be fine for your use case, just add more threads and/or loops in Thread Group or Loop Controller and JMeter will pick up the next line for each thread/iteration.

See CSV Data Set Config in Sharing Mode - Made Easy article for more information.


问:
How to access multiple data packet sent from AJAX to nodejs
I wanted to access multiple datapacket that is sent to nodejs
Below is my client code:

```<code>$(document).ready(function() {
 //console.log(newval);
$.ajax({
type: "POST",
url: 'http://localhost:8124/',
timeout: 2000,
data: JSON.stringify({data:newval,data1:newval1}),
});
});
</code>```

Below is my server code:

```<code>http.createServer(function (req, res) {
//console.log('request received');
//util.log(util.inspect(req));
console.log(req,res);

res.writeHead(200, {'Content-Type': 'text/plain'});
req.on('data','data1', function (chunk) {
    console.log(chunk.toString());
    //req.on(function (chunk) {
    var obj = JSON.parse(chunk.toString());
    console.log(obj.data);
    console.log(obj.data1);
    var dataval=obj.data;
</code>```

I wanted to get the data1 value so that I can use it for further needs. Could you please guide me in doing that? Thank you in advance

答:
You have written $(document).ready this is incorrect.

Either do document.ready(<FUNCTION HERE>) OR $(<FUNCTION HERE>);

Your client code sends a HTTP request on port 8124. Your Node.js does not listen for incoming requests on port 8124.

You have incorrectly initialised your server.

You need to do var app = http.createServer(<FUNCTION HERE>)

Then listen on port 8124 app.listen(8124,<FUNCTION HERE>);

In regards to stream handling, I refer you here:

https://medium.freecodecamp.org/node-js-streams-everything-you-need-to-know-c9141306be93

Body:
I wanted to access multiple datapacket that is sent to nodejs
Below is my client code:

$(document).ready(function() {
 //console.log(newval);
$.ajax({
type: "POST",
url: 'http://localhost:8124/',
timeout: 2000,
data: JSON.stringify({data:newval,data1:newval1}),
});
});

Below is my server code:

http.createServer(function (req, res) {
//console.log('request received');
//util.log(util.inspect(req));
console.log(req,res);

res.writeHead(200, {'Content-Type': 'text/plain'});
req.on('data','data1', function (chunk) {
    console.log(chunk.toString());
    //req.on(function (chunk) {
    var obj = JSON.parse(chunk.toString());
    console.log(obj.data);
    console.log(obj.data1);
    var dataval=obj.data;

I wanted to get the data1 value so that I can use it for further needs. Could you please guide me in doing that? Thank you in advance


问:
replace an empty numpy string with 0
I have to numpy string array which look like this:

[['0', '', '12.12', '140.65', '', ''],

  ['3', '', '10.45', '154.45', '', ''],

  ['5', '', '15.65', '184.74', '', '']]

What I need to do is to replace the empty cells with a number in order to convert it into a float array. I can't just delete the columns because in some cases the empty cells are filled. I tried this:

```<code>data = np.char.replace(data, '','0').astype(np.float64)
</code>```

But this will just put a 0 everywhere between all characters which ends up in this:

[[0, 0, 1020.0102, 104000.0605, 0, 0],

  [30, 0, 1000.0405, 105040.0405, 0, 0],

  [50, 0, 1050.0605, 108040.0704, 0, 0]]

I can't figure out why python does that? I searched via google but couldn't find a good explanation for numpy.char.replace. Can anyone explain to me how it works?

Title: replace an empty numpy string with 0

Body:
I have to numpy string array which look like this:

[['0', '', '12.12', '140.65', '', ''],

  ['3', '', '10.45', '154.45', '', ''],

  ['5', '', '15.65', '184.74', '', '']]

What I need to do is to replace the empty cells with a number in order to convert it into a float array. I can't just delete the columns because in some cases the empty cells are filled. I tried this:

data = np.char.replace(data, '','0').astype(np.float64)

But this will just put a 0 everywhere between all characters which ends up in this:

[[0, 0, 1020.0102, 104000.0605, 0, 0],

  [30, 0, 1000.0405, 105040.0405, 0, 0],

  [50, 0, 1050.0605, 108040.0704, 0, 0]]

I can't figure out why python does that? I searched via google but couldn't find a good explanation for numpy.char.replace. Can anyone explain to me how it works?

Body:
>>> a = np.array([['0', '', '12.12', '140.65', '', ''],
... ['3', '', '10.45', '154.45', '', ''],
... ['5', '', '15.65', '184.74', '', '']])
>>> a[a == ''] = 0
>>> a.astype(np.float64)
array([[   0.  ,    0.  ,   12.12,  140.65,    0.  ,    0.  ],
       [   3.  ,    0.  ,   10.45,  154.45,    0.  ,    0.  ],
       [   5.  ,    0.  ,   15.65,  184.74,    0.  ,    0.  ]])