问:
Send an array with objects to php
i tried here a lot of options to send data from jQuery to php but without success, i'm trying to send an array of objects like here:

```<code>$.ajax({
            type: "POST",
            contentType: 'application/json',
            url: "sendCartDetails.php",
            data: {
                'details': prod
            }
    });
</code>```

where prod has this structure:

```<code>prod: [{name: 'Some Name'}, {name: 'Other Name'}]
</code>```

and my php file:

```<code>$data = json_decode($_POST['details']);

$to = "email@email.com";
$subject = "New Order";
$headers = "From: Some ";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>" . $data . "</td></tr>"
$message .= "</table>";
$message .= "</body></html>";

mail($to,$subject,$message,$headers);
</code>```

and data here it's undefined also had the 500 (Internal Server Error) when trying to send it. How to get the data correctly here? Thanks a lot

答:
I believe that solution for your problem lies on server side, not on client. Also you should send data to server properly like (something like this):

```<code>data: {
    'details': JSON.Stringify(prod)
}
</code>```

And check is data properly sent, you can do that in browser's development tools (on most of them is key F12) and look in Network tab.

After that, I suggest that you try to debug your PHP code, e.g.

```<code>die(var_dump($_POST['details']));
</code>```

On start of your script. If this turns to undefined index notice, there is problem with sending/receiving data.

Title: Send an array with objects to php

Body:
i tried here a lot of options to send data from jQuery to php but without success, i'm trying to send an array of objects like here:

$.ajax({
            type: "POST",
            contentType: 'application/json',
            url: "sendCartDetails.php",
            data: {
                'details': prod
            }
    });

where prod has this structure:

prod: [{name: 'Some Name'}, {name: 'Other Name'}]

and my php file:

$data = json_decode($_POST['details']);

$to = "email@email.com";
$subject = "New Order";
$headers = "From: Some ";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '';
$message .= '
';
$message .= "
Name: 	" . $data . "
"
$message .= "
";
$message .= "";

mail($to,$subject,$message,$headers);

and data here it's undefined also had the 500 (Internal Server Error) when trying to send it. How to get the data correctly here? Thanks a lot

Body:
I believe that solution for your problem lies on server side, not on client. Also you should send data to server properly like (something like this):

data: {
    'details': JSON.Stringify(prod)
}

And check is data properly sent, you can do that in browser's development tools (on most of them is key F12) and look in Network tab.

After that, I suggest that you try to debug your PHP code, e.g.

die(var_dump($_POST['details']));

On start of your script. If this turns to undefined index notice, there is problem with sending/receiving data.


来源: stackexchange

问:
Get data for month wise in mongodb
I want to get data to each month. in my table data is stored like this:-

```<code>   "patient" : [
    {
        "status" : 'arrived',
         start_time: '2017-08-17T09:17:00.000Z

    },
    {
        "status" : 'arraived',
         start_time: '2017-08-16T07:17:00.000Z
    },
   {
        "status" : 'arrived',
         start_time: '2017-07-12T09:17:00.000Z

    },
    {
        "status" : 'arraived',
         start_time: '2017-07-05T08:10:00.000Z
    },
    {
        "status" : 'arrived',
         start_time: '2017-06-02T09:17:00.000Z

    },
    {
        "status" : 'arraived',
         start_time: '2017-05-05T08:16:00.000Z
    }
    ]
</code>```

etc,
and I want to sum of patient of each month (jan to des), like  this :-

```<code>    {
      "month" : 8,
      "count" : 2
   }and like this month 1 to 12
</code>```

答:
This is my code:-

```<code>  db.appointments.aggregate( [
   {
     $project:
     {
       "patient_id": 1,
       "start_time": 1,
        "status": 1
     }
    },
            {
            $match: {
                'start_time' : { $gte: startdate.toISOString() },

                'status': { $eq: 'arrived' }
            } ,

            },
            { $group: {
                _id: {id: "$_id", start_time: {$month: "$appointments.start_time"}},
                count: { $sum: 1}
            }}
            ])
</code>```

When I used this :-

```<code>   { $group: {
        _id: {id: "$_id", start_time: {$month: "$start_time"}},
        count: { $sum: 1}
        }
    }
</code>```

its showing error message:-
     {"name":"MongoError","message":"can't convert from BSON type missing to Date","ok":0,"errmsg":"can't convert from BSON type missing to Date","code":16006,"codeName":"Location16006"}

And when I comment this its showing  this :-

Out Put here:-

```<code>   :[{"count":{"_id":"595b6f95ab43ec1f6c92b898","patient_id":"595649904dbe9525c0e036ef","start_time":"2017-07-04T10:35:00.000Z","status":"arrived"}},
</code>```

{"count":{"_id":"595dff870960d425d4f14633","patient_id":"5956478b4dbe9525c0e036ea","start_time":"2017-03-08T09:14:00.000Z","status":"arrived"}},{"count":{"_id":"595dffaa0960d425d4f14634","patient_id":"595649904dbe9525c0e036ef","start_time":"2017-03-17T09:15:00.000Z","status":"arrived"}},{"count":{"_id":"595dffcf0960d425d4f14635","patient_id":"595648394dbe9525c0e036ec","start_time":"2017-06-08T09:15:00.000Z","status":"arrived"}},{"count":{"_id":"595dfffb0960d425d4f14636","patient_id":"5956478b4dbe9525c0e036ea","start_time":"2017-06-20T09:16:00.000Z","status":"arrived"}},{"count":{"_id":"595e00160960d425d4f14637","patient_id":"5959ea7f80388b19e0b57817","start_time":"2017-08-17T09:17:00.000Z","status":"arrived"}}]}

ContentLicense: CC BY-SA 3.0

Title: Get data for month wise in mongodb

Body:
I want to get data to each month. in my table data is stored like this:-

   "patient" : [
    {
        "status" : 'arrived',
         start_time: '2017-08-17T09:17:00.000Z

    },
    {
        "status" : 'arraived',
         start_time: '2017-08-16T07:17:00.000Z
    },
   {
        "status" : 'arrived',
         start_time: '2017-07-12T09:17:00.000Z

    },
    {
        "status" : 'arraived',
         start_time: '2017-07-05T08:10:00.000Z
    },
    {
        "status" : 'arrived',
         start_time: '2017-06-02T09:17:00.000Z

    },
    {
        "status" : 'arraived',
         start_time: '2017-05-05T08:16:00.000Z
    }
    ]

etc,
and I want to sum of patient of each month (jan to des), like  this :-

    {
      "month" : 8,
      "count" : 2
   }and like this month 1 to 12

Body:
This is my code:-

  db.appointments.aggregate( [
   {
     $project:
     {
       "patient_id": 1,
       "start_time": 1,
        "status": 1
     }
    },
            {
            $match: {
                'start_time' : { $gte: startdate.toISOString() },

                'status': { $eq: 'arrived' }
            } ,

            },
            { $group: {
                _id: {id: "$_id", start_time: {$month: "$appointments.start_time"}},
                count: { $sum: 1}
            }}
            ])

When I used this :-

   { $group: {
        _id: {id: "$_id", start_time: {$month: "$start_time"}},
        count: { $sum: 1}
        }
    }

its showing error message:-
     {"name":"MongoError","message":"can't convert from BSON type missing to Date","ok":0,"errmsg":"can't convert from BSON type missing to Date","code":16006,"codeName":"Location16006"}

And when I comment this its showing  this :-

Out Put here:-

   :[{"count":{"_id":"595b6f95ab43ec1f6c92b898","patient_id":"595649904dbe9525c0e036ef","start_time":"2017-07-04T10:35:00.000Z","status":"arrived"}},

{"count":{"_id":"595dff870960d425d4f14633","patient_id":"5956478b4dbe9525c0e036ea","start_time":"2017-03-08T09:14:00.000Z","status":"arrived"}},{"count":{"_id":"595dffaa0960d425d4f14634","patient_id":"595649904dbe9525c0e036ef","start_time":"2017-03-17T09:15:00.000Z","status":"arrived"}},{"count":{"_id":"595dffcf0960d425d4f14635","patient_id":"595648394dbe9525c0e036ec","start_time":"2017-06-08T09:15:00.000Z","status":"arrived"}},{"count":{"_id":"595dfffb0960d425d4f14636","patient_id":"5956478b4dbe9525c0e036ea","start_time":"2017-06-20T09:16:00.000Z","status":"arrived"}},{"count":{"_id":"595e00160960d425d4f14637","patient_id":"5959ea7f80388b19e0b57817","start_time":"2017-08-17T09:17:00.000Z","status":"arrived"}}]}


OwnerDisplayName: Warz

Title: Compute custom function nth row using dplyr

Body:
Given the following data frame:

A   B        C       D
1   92.44   14261   13183
2   92.43   14244   13166
3   94.24   14730   13882
4   97.42   12149   11836
5   94.75   14431   13674
6   95.91   11038   10587
7   95.66   14886   14240
8   94.94   12587   11950
9   94.27   13251   12492
10  94.89   12789   12135

I am trying to using R create rowwise computation that allows me to summarize() the first 4 rows in columns C and D, divide them accordingly and replace it with the next row.

replace(nth row + 1) = SUM(C) / SUM(D)

Here is what I have tried

df %>% mutate(B=replace(mpB, nrow(4)=summarise(C/D), NA))

Desired Output

A   B        C      D
1   92.44   14261   13183
2   92.43   14244   13166
3   94.24   14730   13882
4   97.42   12149   11836
5   94.01   14431   13674
6   95.91   11038   10587
7   95.66   14886   14240
8   94.94   12587   11950
9   94.27   13251   12492
10  95.18   12789   12135

*Update the 5th row and 10th row with desired calculation

Body:
Modified Scarabee's answer

d %>%
    mutate(g1 = (A - 1)%/%5,
           g2 = A%%5 == 0) %>%
    group_by(g1) %>%
    mutate(V = 100 * sum(D[!g2]/sum(C[!g2]))) %>%
    ungroup() %>%
    mutate(B = if_else(g2, round(V, 2), B)) %>%
    select(-g1, -g2)

#>        A     B     C     D
#>    <int> <dbl> <int> <int>
#>  1     1 92.44 14261 13183
#>  2     2 92.43 14244 13166
#>  3     3 94.24 14730 13882
#>  4     4 97.42 12149 11836
#>  5     5 94.01 14431 13674
#>  6     6 95.91 11038 10587
#>  7     7 95.66 14886 14240
#>  8     8 94.94 12587 11950
#>  9     9 94.27 13251 12492
#> 10    10 95.18 12789 12135


问:
include() and require_once() Issue
I have this situation:

```<code>/

index.php

/init (folder)

      init.php (of course inside this file i use require_once for db/function/and whatever you want to put inside)

/layout_parts (folder)

     header.php (and others common parts are inside this folder)

/my_space (folder inside layout parts)

      my_file.php

      another_file.php

/your_space (folder inside layout parts)

      your_file.php

      another_file.php

/third_space (folder inside layout parts)

      third_file.php

      another_file.php
</code>```

For the index i have no problem it all works fine, but if i include header.php in one of the subfolder files my require_once(init/init.php); that is on the top of header.php won't work.

(Warning message says no such file in the directory (OF COURSE THE FILE EXIST) and it write down the subfolder directory that is not the path i expected).

I tried echo $SERVER['DOCUMENT_ROOT]; to see the whole path, echo __DIR__; to see wich is the right path to the directory, no way out.

I know is such a dummy question but if some kind heart could help me it would be great. Thanks :)

答:
The best way to handle this would be to use absolute paths instead of relative ones. When you use relative paths, you have to worry each time about how many levels deep you are and then have that many ../ etc. This is messy and difficult to manage, for eg, if you move a file to a different location, you have to update the includes again, based on where you are now. This is why absolute paths are helpful.

So create something like this:

```<code>$appRoot = "/path/to/root/folder/";
</code>```

This is the path where the index.php file is located. It is the "application root", if you will.

Now, in ANY file where you want to include init.php add the following line:

```<code>include_once($appRoot."init/init.php");
</code>```

Ideally the $appRoot should be created in a global config located in root. If you do not have a structure where a univeral config can be added, it can still be messy and you might need to add absolute paths into individual files (which is not a good idea)

Title: include() and require_once() Issue

Body:
I have this situation:

/

index.php

/init (folder)

      init.php (of course inside this file i use require_once for db/function/and whatever you want to put inside)

/layout_parts (folder)

     header.php (and others common parts are inside this folder)

/my_space (folder inside layout parts)

      my_file.php

      another_file.php

/your_space (folder inside layout parts)

      your_file.php

      another_file.php

/third_space (folder inside layout parts)

      third_file.php

      another_file.php

For the index i have no problem it all works fine, but if i include header.php in one of the subfolder files my require_once(init/init.php); that is on the top of header.php won't work.

(Warning message says no such file in the directory (OF COURSE THE FILE EXIST) and it write down the subfolder directory that is not the path i expected).

I tried echo $SERVER['DOCUMENT_ROOT]; to see the whole path, echo __DIR__; to see wich is the right path to the directory, no way out.

I know is such a dummy question but if some kind heart could help me it would be great. Thanks :)

Body:
The best way to handle this would be to use absolute paths instead of relative ones. When you use relative paths, you have to worry each time about how many levels deep you are and then have that many ../ etc. This is messy and difficult to manage, for eg, if you move a file to a different location, you have to update the includes again, based on where you are now. This is why absolute paths are helpful.

So create something like this:

$appRoot = "/path/to/root/folder/";

This is the path where the index.php file is located. It is the "application root", if you will.

Now, in ANY file where you want to include init.php add the following line:

include_once($appRoot."init/init.php");

Ideally the $appRoot should be created in a global config located in root. If you do not have a structure where a univeral config can be added, it can still be messy and you might need to add absolute paths into individual files (which is not a good idea)


问:
How to add DocumentBlockExtension in uima ruta
When I try to use DocumentBlock it shows not define in script block. How I need to add it in additional Engine? Can anyone explain in detail about the usage of DocumentBlock.</p>

答:
It depends on how you call/execute the RutaEngine. You need to add org.apache.uima.ruta.block.DocumentBlockExtension to the value of the configuration parameter additionalExtensions.

Using uimaFIT, this would look like:

```<code>AnalysisEngineFactory.createEngineDescription(RutaEngine.class, ...,
    RutaEngine.PARAM_ADDITIONAL_EXTENSIONS, new String[] {
    DocumentBlockExtension.class.getName() });
</code>```

In a simple Ruta project, the value needs to be set in descriptor/BasicEngine.xml which is used as a template for the generated descriptors which are used in the launch configuration, if it is not automatically set in the generated descriptor.

DISCLAIMER: I am a developer of UIMA Ruta

Body:
It depends on how you call/execute the RutaEngine. You need to add org.apache.uima.ruta.block.DocumentBlockExtension to the value of the configuration parameter additionalExtensions.

Using uimaFIT, this would look like:

AnalysisEngineFactory.createEngineDescription(RutaEngine.class, ...,
    RutaEngine.PARAM_ADDITIONAL_EXTENSIONS, new String[] {
    DocumentBlockExtension.class.getName() });

In a simple Ruta project, the value needs to be set in descriptor/BasicEngine.xml which is used as a template for the generated descriptors which are used in the launch configuration, if it is not automatically set in the generated descriptor.

DISCLAIMER: I am a developer of UIMA Ruta


问:
Is it possible to get the name of a select list from an item that has just been removed from that list
I am attempting to update the values in an array after an item has been removed from a selectize list. To do this I need the attr('name') for the list. On the event of an item_remove the $item can get the select list, but it cannot find the attr('name') that I need.

The solution below is how I am doing this for an item_add event. You'll see that the var thisSelect gets the select list and from that, I can populate the values array with the actual list values.

```<code>/**
 * Add callback behaviour once a select element has been selected.
 */
    $('[data-type="select"]').each(function(i, v) {
        v.selectize.on('item_add', function (value, $item) {
            var thisSelect = $item.parents('.controls').find('select'),
                name = thisSelect.attr('name'),
                values = [],
                exclusiveSelected = thisSelect.find('option[data-exclusive="true"]:selected');

            if (exclusiveSelected.length) {
                values.push({
                    "value": exclusiveSelected.val(),
                    "label": exclusiveSelected.text().trim(),
                    "label-key": exclusiveSelected.attr("label-key")
                });

                thisSelect.val(exclusiveSelected.val()).trigger('change');

            } else {
                thisSelect.siblings('.selectize-control').find('.item').each(function(i, v) {
                    values.push({
                        "value": $(v).data('value'),
                        "label": $(v).text().trim(),
                        "label-key": $(v).attr("label-key")
                    });
                });
            }

            setMultipleFieldValues(name, values);
            validate(documentId, name, fields);
        });
    });
</code>```

Below is my current solution for an item_remove event. A Cannot set property 'values' of undefined error occurs in the console because the values array cannot be populated due to the name of the list returning as undefined.

```<code>/**
 * Add callback behaviour once a select element has been unselected.
 */
    $('[data-type="select"]').each(function(i, v) {
        v.selectize.on('item_remove', function (value, $item) {
            var thisSelect = $item.parents('.controls').find('select'),
                name = thisSelect.attr('name'),
                values = [];

            thisSelect.siblings('.selectize-control').find('.item').each(function(i, v) {
                values.push({
                    "value": $(v).data('value'),
                    "label": $(v).text().trim(),
                    "label-key": $(v).attr("label-key")
                });
            });

            setMultipleFieldValues(name, values);
            validate(documentId, name, fields);
        });
    });
</code>```

Attached is the select element I am trying to get the name "additionalWork" from

答:
Thanks for your responses, the solution I managed to come up with involved getting the $input instead of the $item. For this, I could get the values in the list.</p>

```<code>/**
 * Add callback behaviour once a select element has been unselected.
 */
    $('[data-type="select"]').each(function(i, v) {
        v.selectize.on('item_remove', function (value, $item) {
            var thisSelect = this.$input,
                name = thisSelect.attr('name'),
                values = [],
                exclusiveSelected = thisSelect.find('option[data-exclusive="true"]:selected');

            if (exclusiveSelected.length) {
                values.push({
                    "value": exclusiveSelected.val(),
                    "label": exclusiveSelected.text().trim(),
                    "label-key": exclusiveSelected.attr("label-key")
                });

                thisSelect.val(exclusiveSelected.val()).trigger('change');

            } else {
                thisSelect.siblings('.selectize-control').find('.item').each(function(i, v) {
                    values.push({
                        "value": $(v).data('value'),
                        "label": $(v).text().trim(),
                        "label-key": $(v).attr("label-key")
                    });
                });
            }

            setMultipleFieldValues(name, values);
            validate(documentId, name, fields);
        });
    });
</code>```

Body:
I am attempting to update the values in an array after an item has been removed from a selectize list. To do this I need the attr('name') for the list. On the event of an item_remove the $item can get the select list, but it cannot find the attr('name') that I need.

The solution below is how I am doing this for an item_add event. You'll see that the var thisSelect gets the select list and from that, I can populate the values array with the actual list values.

/**
 * Add callback behaviour once a select element has been selected.
 */
    $('[data-type="select"]').each(function(i, v) {
        v.selectize.on('item_add', function (value, $item) {
            var thisSelect = $item.parents('.controls').find('select'),
                name = thisSelect.attr('name'),
                values = [],
                exclusiveSelected = thisSelect.find('option[data-exclusive="true"]:selected');

            if (exclusiveSelected.length) {
                values.push({
                    "value": exclusiveSelected.val(),
                    "label": exclusiveSelected.text().trim(),
                    "label-key": exclusiveSelected.attr("label-key")
                });

                thisSelect.val(exclusiveSelected.val()).trigger('change');

            } else {
                thisSelect.siblings('.selectize-control').find('.item').each(function(i, v) {
                    values.push({
                        "value": $(v).data('value'),
                        "label": $(v).text().trim(),
                        "label-key": $(v).attr("label-key")
                    });
                });
            }

            setMultipleFieldValues(name, values);
            validate(documentId, name, fields);
        });
    });

Below is my current solution for an item_remove event. A Cannot set property 'values' of undefined error occurs in the console because the values array cannot be populated due to the name of the list returning as undefined.

/**
 * Add callback behaviour once a select element has been unselected.
 */
    $('[data-type="select"]').each(function(i, v) {
        v.selectize.on('item_remove', function (value, $item) {
            var thisSelect = $item.parents('.controls').find('select'),
                name = thisSelect.attr('name'),
                values = [];

            thisSelect.siblings('.selectize-control').find('.item').each(function(i, v) {
                values.push({
                    "value": $(v).data('value'),
                    "label": $(v).text().trim(),
                    "label-key": $(v).attr("label-key")
                });
            });

            setMultipleFieldValues(name, values);
            validate(documentId, name, fields);
        });
    });

Attached is the select element I am trying to get the name "additionalWork" from

Body:
Thanks for your responses, the solution I managed to come up with involved getting the $input instead of the $item. For this, I could get the values in the list.

/**
 * Add callback behaviour once a select element has been unselected.
 */
    $('[data-type="select"]').each(function(i, v) {
        v.selectize.on('item_remove', function (value, $item) {
            var thisSelect = this.$input,
                name = thisSelect.attr('name'),
                values = [],
                exclusiveSelected = thisSelect.find('option[data-exclusive="true"]:selected');

            if (exclusiveSelected.length) {
                values.push({
                    "value": exclusiveSelected.val(),
                    "label": exclusiveSelected.text().trim(),
                    "label-key": exclusiveSelected.attr("label-key")
                });

                thisSelect.val(exclusiveSelected.val()).trigger('change');

            } else {
                thisSelect.siblings('.selectize-control').find('.item').each(function(i, v) {
                    values.push({
                        "value": $(v).data('value'),
                        "label": $(v).text().trim(),
                        "label-key": $(v).attr("label-key")
                    });
                });
            }

            setMultipleFieldValues(name, values);
            validate(documentId, name, fields);
        });
    });


问:
Can we load Multiple Records into multiple tables into mysql-DB as a single java request?
I have to load multiple records in multiple tables into mysql-DB as a single request using java. (But not with executing multiple insert queries because i have nearly 1L-10L data so i can't run that many insert queries and that many requests). Help me on this atleast like an idea. </p>

答: Normally it is what we do. Update multiple tables in a transaction. If you are using JDBC use multiple insert statements and use batch insert with JDBC transaction management. If you are using a framework like Spring or EJB utilise framework provided transaction management so that either all your sql statements updating multiple tables suceed as a unit or all of them fail.</p>


问:
Recommender System (SVD) with TensorFlow
I'm trying to create a collaborative filtering algorithm to suggest products to certain users.

I started shortly and started working with TensorFlow (I thought it was sufficiently effective and flexible).
I found this code that does what I'm interested in, creates the model and train the user IDs, products, and ratings: https://github.com/songgc/TF-recomm

I launched the code and trained the model.

After training the model I would need to make the predictions, that is, get suggestions for each user so that they can be saved in a DB from which I access with a NODE.js application.

How do I retrieve this list of suggestions for each user when the training is done?

```<code>if __name__ == '__main__':
    df_train, df_test=get_data()
    svd(df_train, df_test)
    print("Done!")
</code>```

答:
You can run </p>

```<code>predict_result = sess.run(inter_op, feed_dict={user_batch:users, item_batch:items})
</code>```

<p>which users means all user ids and items for all item ids, and predict_result is the scores of each user for all items, you can store the predict_result into DB; </p>

Body:
I'm trying to create a collaborative filtering algorithm to suggest products to certain users.

I started shortly and started working with TensorFlow (I thought it was sufficiently effective and flexible).
I found this code that does what I'm interested in, creates the model and train the user IDs, products, and ratings: https://github.com/songgc/TF-recomm

I launched the code and trained the model.

After training the model I would need to make the predictions, that is, get suggestions for each user so that they can be saved in a DB from which I access with a NODE.js application.

How do I retrieve this list of suggestions for each user when the training is done?

if __name__ == '__main__':
    df_train, df_test=get_data()
    svd(df_train, df_test)
    print("Done!")

Body:
You can run

predict_result = sess.run(inter_op, feed_dict={user_batch:users, item_batch:items})

which users means all user ids and items for all item ids, and predict_result is the scores of each user for all items, you can store the predict_result into DB;


问:
Null parameter in controller from ajax
When a user clicks a save button, a JavaScript function uses AJAX to call the Controller and send over JSON data about the objects.

JavaScript Function

```<code>$.ajax({
        url: "/Data/sendFridgeItems?items=" + JSON.stringify($scope.items.data),
        type: "POST",
        data: JSON.stringify($scope.items.data),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            console.log("good!");
        },
        error: function () {
            console.log("error");
        }
    });
</code>```

Controller

```<code>[HttpPost]
    public ActionResult SendFridgeItems(string items)
    {
        fridge[] fridgeItems = JsonConvert.DeserializeObject<fridge[]>(items);
        foreach (fridge item in fridgeItems)
        {
            bool exists = cookDB.fridges.AsEnumerable()
                .Any(x => x.Name == item.Name && x.Purchased == item.Purchased && x.Count == item.Count);
            if (!exists)
            {
                cookDB.fridges.Add(item);
                cookDB.SaveChangesAsync();
            }
        }
        return null;
    }
</code>```

It works, but I don't think the way of sending my data through the url parameter is correct in my situation, because the data will be big enough. I wanted to know if there is a better way to send my data to the controller?

I tried to send it this way, but the controller receives null value.

```<code>$.ajax({
        url: "/Data/sendFridgeItems",
        type: "POST",
        data: JSON.stringify($scope.items.data),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            console.log("good!");
        },
        error: function () {
            console.log("error");
        }
    });
</code>```

JSON of $scope.items.data

```<code>[{"id":2,"name":"Item1","count":2,"type":"pcs.","purchased":"12/09/2017","wasted":"15/10/2017","cam":"Freezer","comment":"no comment","$$hashKey":"object:38"},{"id":3,"name":"Item2","count":30,"type":"g.","purchased":"15/01/1880","wasted":"21/03/1882","cam":"Cooler","comment":"commented","$$hashKey":"object:39"}]
</code>```

$scope.items

```<code>$scope.items = {
    "count": 2,
    "data": [
      {
          "name": "Item1",
          "count": 2,
          "type": "pcs.",
          "purchased": "12/09/2017",
          "wasted": "15/10/2017",
          "cam": "Freezer",
          "comment": "no comment"
      },
  {
          "name": "Item2",
          "count": 30,
          "type": "g.",
          "purchased": "15/01/1880",
          "wasted": "21/03/1882",
          "cam": "Cooler",
          "comment": "Commented"
      }
    ]
};
</code>```

Fixed Controller For N.Ivanov's solution (this controller+ N.Ivanov's ajax = solution)

```<code>public ActionResult SendFridgeItems(fridge[] items)
    {
        fridge[] fridgeItems = JsonConvert.DeserializeObject<fridge[]>(items.ToString());
        foreach (fridge item in items)
        {
            bool exists = cookDB.fridges.AsEnumerable()
                .Any(x => x.Name == item.Name && x.Purchased == item.Purchased && x.Count == item.Count);
            if (!exists)
            {
                cookDB.fridges.Add(item);
                cookDB.SaveChangesAsync();
            }
        }
        return null;
    }
</code>```

答:
Try JSON Parse to parse data as Object and send it to controller</p>

```<code>$.ajax({
    url: "/Data/sendFridgeItems",
    type: "POST",
    data: JSON.parse($scope.items.data),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function () {
        console.log("good!");
    },
    error: function () {
        console.log("error");
    }
});
</code>```

Title: Null parameter in controller from ajax

Body:
When a user clicks a save button, a JavaScript function uses AJAX to call the Controller and send over JSON data about the objects.

JavaScript Function

$.ajax({
        url: "/Data/sendFridgeItems?items=" + JSON.stringify($scope.items.data),
        type: "POST",
        data: JSON.stringify($scope.items.data),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            console.log("good!");
        },
        error: function () {
            console.log("error");
        }
    });

Controller

[HttpPost]
    public ActionResult SendFridgeItems(string items)
    {
        fridge[] fridgeItems = JsonConvert.DeserializeObject<fridge[]>(items);
        foreach (fridge item in fridgeItems)
        {
            bool exists = cookDB.fridges.AsEnumerable()
                .Any(x => x.Name == item.Name && x.Purchased == item.Purchased && x.Count == item.Count);
            if (!exists)
            {
                cookDB.fridges.Add(item);
                cookDB.SaveChangesAsync();
            }
        }
        return null;
    }

It works, but I don't think the way of sending my data through the url parameter is correct in my situation, because the data will be big enough. I wanted to know if there is a better way to send my data to the controller?

I tried to send it this way, but the controller receives null value.

$.ajax({
        url: "/Data/sendFridgeItems",
        type: "POST",
        data: JSON.stringify($scope.items.data),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            console.log("good!");
        },
        error: function () {
            console.log("error");
        }
    });

JSON of $scope.items.data

[{"id":2,"name":"Item1","count":2,"type":"pcs.","purchased":"12/09/2017","wasted":"15/10/2017","cam":"Freezer","comment":"no comment","$$hashKey":"object:38"},{"id":3,"name":"Item2","count":30,"type":"g.","purchased":"15/01/1880","wasted":"21/03/1882","cam":"Cooler","comment":"commented","$$hashKey":"object:39"}]

$scope.items

$scope.items = {
    "count": 2,
    "data": [
      {
          "name": "Item1",
          "count": 2,
          "type": "pcs.",
          "purchased": "12/09/2017",
          "wasted": "15/10/2017",
          "cam": "Freezer",
          "comment": "no comment"
      },
  {
          "name": "Item2",
          "count": 30,
          "type": "g.",
          "purchased": "15/01/1880",
          "wasted": "21/03/1882",
          "cam": "Cooler",
          "comment": "Commented"
      }
    ]
};

Fixed Controller For N.Ivanov's solution (this controller+ N.Ivanov's ajax = solution)

public ActionResult SendFridgeItems(fridge[] items)
    {
        fridge[] fridgeItems = JsonConvert.DeserializeObject<fridge[]>(items.ToString());
        foreach (fridge item in items)
        {
            bool exists = cookDB.fridges.AsEnumerable()
                .Any(x => x.Name == item.Name && x.Purchased == item.Purchased && x.Count == item.Count);
            if (!exists)
            {
                cookDB.fridges.Add(item);
                cookDB.SaveChangesAsync();
            }
        }
        return null;
    }

Body:
Try JSON Parse to parse data as Object and send it to controller

$.ajax({
    url: "/Data/sendFridgeItems",
    type: "POST",
    data: JSON.parse($scope.items.data),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function () {
        console.log("good!");
    },
    error: function () {
        console.log("error");
    }
});


问:
404 Error on Localhost with Twilio + Flask + Ngrok + Python (2.7)
I am following the tutorial from https://www.twilio.com/blog/2016/09/how-to-receive-and-respond-to-a-text-message-with-python-flask-and-twilio.html.

However after starting up my flask app in one terminal window (python textapi.py), starting up ngrok in another terminal(ngrok http 5000), copying and pasting the forwarding http url into the twilio console "a message comes in" field, and then texting the number, I am left with a 404 error.

Both my flask terminal as well as my ngrok terminals register the incoming POST but both respond with a 404 error.

My flask app looks like the following:

```<code>from flask import Flask, request, redirect
import twilio
from twilio.rest import Client
from twilio.twiml.messaging_response import MessagingResponse
import pandas
import os

# Load some background data and credentials

app = Flask(__name__)

# Initiate Twilio Client
client = Client(account_sid, auth_token)

@app.route('/sms', methods=['POST'])
def sms():
    number = request.form['From']
    message_body = request.form['Body']
    # Do stuff to get response_String
    response = response_string
    resp = twiml.Response()
    resp.message(response)
    return str(resp)

if __name__ == '__main__':
    app.run()
</code>```

Can someone explain where the 404 error is coming from and why it cannot locate "localhost:5000/sms"?

Also this: Flask server returns 404 on localhost:5000 w/ Twilio doesn't seem to solve my issue.

UPDATE 1: part of the issue was not having "/sms" at the end of my ngrok url that I pasted into Twilio's console.

Now I'm having an error that twiml has no attribute Response.

答:
Twilio developer evangelist here.

You imported MessagingResponse which is what you need to use instead of twiml.Response(). So, your code should be:

```<code>@app.route('/sms', methods=['POST'])
def sms():
    number = request.form['From']
    message_body = request.form['Body']
    # Do stuff to get response_String
    response = response_string
    resp = MessagingResponse()
    resp.message(response)
    return str(resp)
</code>```

Edit

Just wanted to apologise, the blog post you are referring to was using the version 5 Python library, which did use twiml.Response. We've since released version 6 which has the MessagingResponse module. There is a migration document for upgrading from version 5 which you might find useful.

Body:
I am following the tutorial from https://www.twilio.com/blog/2016/09/how-to-receive-and-respond-to-a-text-message-with-python-flask-and-twilio.html.

However after starting up my flask app in one terminal window (python textapi.py), starting up ngrok in another terminal(ngrok http 5000), copying and pasting the forwarding http url into the twilio console "a message comes in" field, and then texting the number, I am left with a 404 error.

Both my flask terminal as well as my ngrok terminals register the incoming POST but both respond with a 404 error.

My flask app looks like the following:

from flask import Flask, request, redirect
import twilio
from twilio.rest import Client
from twilio.twiml.messaging_response import MessagingResponse
import pandas
import os

# Load some background data and credentials

app = Flask(__name__)

# Initiate Twilio Client
client = Client(account_sid, auth_token)

@app.route('/sms', methods=['POST'])
def sms():
    number = request.form['From']
    message_body = request.form['Body']
    # Do stuff to get response_String
    response = response_string
    resp = twiml.Response()
    resp.message(response)
    return str(resp)

if __name__ == '__main__':
    app.run()

Can someone explain where the 404 error is coming from and why it cannot locate "localhost:5000/sms"?

Also this: Flask server returns 404 on localhost:5000 w/ Twilio doesn't seem to solve my issue.

UPDATE 1: part of the issue was not having "/sms" at the end of my ngrok url that I pasted into Twilio's console.

Now I'm having an error that twiml has no attribute Response.

Body:
Twilio developer evangelist here.

You imported MessagingResponse which is what you need to use instead of twiml.Response(). So, your code should be:

@app.route('/sms', methods=['POST'])
def sms():
    number = request.form['From']
    message_body = request.form['Body']
    # Do stuff to get response_String
    response = response_string
    resp = MessagingResponse()
    resp.message(response)
    return str(resp)

Edit

Just wanted to apologise, the blog post you are referring to was using the version 5 Python library, which did use twiml.Response. We've since released version 6 which has the MessagingResponse module. There is a migration document for upgrading from version 5 which you might find useful.


问:
Using jq to compare two fields from same json and printing some other field as a result
I have json data in following format

```<code>{
  "body": [
    {
      "username": "name1",
      "id": "4444"
    },
    {
      "username": "name2",
      "id": "5555"
    }
  ],
  "meta": {
    "input": "name1"
  }}
</code>```

Given this data I want to match the "username"s in the body with "meta.input" and if there is a match return/print related id.

答:
This should be as simple as that:

var data = {
  "body": [{
    "username": "name1",
    "id": "4444"
  }, {
    "username": "name2",
    "id": "5555"
  }],
  "meta": {
    "input": "name1"
  }
};

function getID(data) {
  var username = data.meta.input;
  var userID;

  for (i in data.body) {

    if (data.body[i].username === username) {
      userID = data.body[i].id;
      break;
    }
  }

  return userID;
}

var id = getID(data);
alert(id);```

Body:
I have json data in following format

{
  "body": [
    {
      "username": "name1",
      "id": "4444"
    },
    {
      "username": "name2",
      "id": "5555"
    }
  ],
  "meta": {
    "input": "name1"
  }}

Given this data I want to match the "username"s in the body with "meta.input" and if there is a match return/print related id.


问:
'Debug.apk' installed through cordova,I can not remove it
Goodmorning everyone,
I'd better explain what I meant in the title,i've created an app through ionic/cordova. I used the command: " ionic cordova run android --device --verbose" to launch debug.apk on the device, connected to the pc.

Now the problem:

When I try to uninstall it, it is deleted, but going into 'Application management' i still see the app with the phrase: "not installed"(=Non installato).

device: samsung sm-t335 galaxy tab 4

I am going crazy,can someone help me ?

Sorry for my English

thank you all :)

The image with the phrase "not installed" (=Non installato)

答:
If you have multiple users for your device, the app may be installed for all users and the entry may be persistent.
Try this

Settings -> Apps -> select your app tap on menu button (3 dots) -> Uninstall for all users

Or  this

Open each account and uninstall the app from there.


问:
How to return Java 'java.time.Instant' property as json value in Restful API body response?
I have a Spring Boot restful API service that returns a Java object in its response which is translated into json.

One of the Java object properties is a 'Java.time.Instant'.  How should I translate this for the json object being returned?

update

I've tried using @JsonFormat but this doesn't work...

The Java object being returned has an 'Instant' property...

```<code> @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ",timezone = "UTC")
 public Instant getRequested() {
     return Requested;
}
</code>```

This is coming back in the json response body as...

```<code>"requested": {
    "epochSecond": 1499342121,
    "nano": 868000000
},
</code>```

I'm using Spring Boot 1.5.4

The controller method is...

```<code>@RequestMapping(value="/", method= RequestMethod.POST)
public AcceptedAccountRequest newRequest(@RequestBody NewAccountRequest aRequest) {
AcceptedAccountRequest anAcceptedRequest = createAccepted(aRequest);
return anAcceptedRequest;
}
</code>```

答:
You can simply use the java.time.Instant to their representation using .toString()
If you are using Spring, you might have to add @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) to your RestMethod in order to make sure it is converted correctly

Body:
I have a Spring Boot restful API service that returns a Java object in its response which is translated into json.

One of the Java object properties is a 'Java.time.Instant'.  How should I translate this for the json object being returned?

update

I've tried using @JsonFormat but this doesn't work...

The Java object being returned has an 'Instant' property...

 @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ",timezone = "UTC")
 public Instant getRequested() {
     return Requested;
}

This is coming back in the json response body as...

"requested": {
    "epochSecond": 1499342121,
    "nano": 868000000
},

I'm using Spring Boot 1.5.4

The controller method is...

@RequestMapping(value="/", method= RequestMethod.POST)
public AcceptedAccountRequest newRequest(@RequestBody NewAccountRequest aRequest) {
AcceptedAccountRequest anAcceptedRequest = createAccepted(aRequest);
return anAcceptedRequest;
}


问:
How can I configure a Flask API to allow for token-protected user-specific responses?
If I have a server end point that say does a simple task like initializes an API with a token that I generate client side, and then print the users account info.

Can I initialize() the API globally so the user can do other tasks after printing account info?

and

How does that affect other users initializing() and printing info if they do it at the same time?

I don't understand how this server works and any help would be great. Thank you!

答:
Nathan's answer points you in the right direction, but I'll make a comment about state and scope because you asked about multiple users.

Firstly, the normal way to do this would be for the server to generate the random token and send it back to the user.

```<code>client request 1 > init > create token > store along with init data > return token to user
client request 2 > something(token) > find data related to token > return data to user
</code>```

When you run Flask (and most webapps) you try to make it so that each request is independent. In your case, the user calls an endpoint and identifies themselves by passing a token. If you make a record of that token somewhere (normally in a database) then you can identify that user's data by looking up the same token they pass on subsequent requests.

Where you choose to store that information is important. As I say a database is the normal recommended approach as it's built to be accessed safely by multiple people at the same time.

You might be tempted to not do the database thing and actually store the token / data information in a global variable inside python. Here's the reason why that's (probably) not going to work:

Flask is a wsgi server, and how it behaves when up and running depends on how it's configured. I generally use uwsgi with several different processes. Each process will have its own state that can't see one another. In this (standard / common) configuration, you don't know which process is going to receive any given request.

```<code>request 1 > init(token) > process 1 > store token in global vars
request 2 > other(token) >  process 2 > can't find token in global vars
</code>```

That's why we use a database to store all shared information:

```<code>request 1 > init(token) > process 1 > store token in db
request 2 > other(token) >  process 2 > can find token db
</code>```

Body:
Nathan's answer points you in the right direction, but I'll make a comment about state and scope because you asked about multiple users.

Firstly, the normal way to do this would be for the server to generate the random token and send it back to the user.

client request 1 > init > create token > store along with init data > return token to user
client request 2 > something(token) > find data related to token > return data to user

When you run Flask (and most webapps) you try to make it so that each request is independent. In your case, the user calls an endpoint and identifies themselves by passing a token. If you make a record of that token somewhere (normally in a database) then you can identify that user's data by looking up the same token they pass on subsequent requests.

Where you choose to store that information is important. As I say a database is the normal recommended approach as it's built to be accessed safely by multiple people at the same time.

You might be tempted to not do the database thing and actually store the token / data information in a global variable inside python. Here's the reason why that's (probably) not going to work:

Flask is a wsgi server, and how it behaves when up and running depends on how it's configured. I generally use uwsgi with several different processes. Each process will have its own state that can't see one another. In this (standard / common) configuration, you don't know which process is going to receive any given request.

request 1 > init(token) > process 1 > store token in global vars
request 2 > other(token) >  process 2 > can't find token in global vars

That's why we use a database to store all shared information:

request 1 > init(token) > process 1 > store token in db
request 2 > other(token) >  process 2 > can find token db


问:
Symfony findOneBy: column type array returns null
I have an entity with a column type array

```<code>/**
 * Report entity
 *
 * @ORM\Table(name="report")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ReportRepository")
 */
class Report
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var array
     *
     * @ORM\Column(name="selectedCountries", type="array", nullable=true)
     */
    private $selectedCountries;
</code>```

In the database I have a a record which is stored as:

```<code>+-------------------------+
|    selectedCountries    |
+-------------------------+
|         a:0:{}          |
+-------------------------+
</code>```

When I do:

```<code>$report = $this->reportRepository->findOneBy(array('selectedCountries' => []));
</code>```

I get null and I have no idea why.

The db connection, entity, repository etc.. is working fine: just when I include this array in the findOneBy() it does not find the result.

答:
With the help of the Symfony profiler, I debugged the queries doctrine makes and found that I need to use simple_array instead of array for the @ORM\Column type.

When I use array as a column type: doctrine serializes this array whenever it saves data to the database like a:0:{}. The problem with this approach is when I try to run a findby:

If I use an array as a parameter, doctrine querie looks like this: ..AND t0.selectedCountries IN ('de')..

If I use a serialized array, doctrine escapes it like this: ..AND
t0.selectedCountries = 's:19:\"a:1:{i:0;s:2:\"de\";}\";' ..

So in both cases the record will not be found!

But by using simple_array doctrine query looks like: .. AND t0.selectedCountries IN ('de') .. which is perfect since the data in the table is saved now as:

```<code>+-------------------------+
|    selectedCountries    |
+-------------------------+
|         de              |
+-------------------------+
</code>```

The only issue with this approach is when you have more elements in the array: selectedCountries    => de,fr,uk and want to search by this. For this to work you should do extra work:

Add @ORM\HasLifecycleCallbacks() to your entity and sort the array before inserting

```<code>/**
 * @ORM\PrePersist
 */
public function setSelectedCountriesValue()
{
    sort($this->selectedCountries);
}
</code>```

In your entity's repository use Query Builder and sort the array when trying to find results.

```<code> $qb = $this->getEntityManager()->createQueryBuilder();

        $qb->select('r')
            ->from('AppBundle:Report', 'r')
            ...

        if ($creteria['selectedCountries']) {
            sort($creteria['selectedCountries']);
            $qb->andWhere('r.selectedCountries= :selectedCountries')
                ->setParameter('selectedCountries', implode(',', $creteria['selectedCountries']));
        }
</code>```

Body:
I have an entity with a column type array

/**
 * Report entity
 *
 * @ORM\Table(name="report")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ReportRepository")
 */
class Report
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var array
     *
     * @ORM\Column(name="selectedCountries", type="array", nullable=true)
     */
    private $selectedCountries;

In the database I have a a record which is stored as:

+-------------------------+
|    selectedCountries    |
+-------------------------+
|         a:0:{}          |
+-------------------------+

When I do:

$report = $this->reportRepository->findOneBy(array('selectedCountries' => []));

I get null and I have no idea why.

The db connection, entity, repository etc.. is working fine: just when I include this array in the findOneBy() it does not find the result.

Body:
With the help of the Symfony profiler, I debugged the queries doctrine makes and found that I need to use simple_array instead of array for the @ORM\Column type.

When I use array as a column type: doctrine serializes this array whenever it saves data to the database like a:0:{}. The problem with this approach is when I try to run a findby:

If I use an array as a parameter, doctrine querie looks like this: ..AND t0.selectedCountries IN ('de')..

If I use a serialized array, doctrine escapes it like this: ..AND
t0.selectedCountries = 's:19:\"a:1:{i:0;s:2:\"de\";}\";' ..

So in both cases the record will not be found!

But by using simple_array doctrine query looks like: .. AND t0.selectedCountries IN ('de') .. which is perfect since the data in the table is saved now as:

+-------------------------+
|    selectedCountries    |
+-------------------------+
|         de              |
+-------------------------+

The only issue with this approach is when you have more elements in the array: selectedCountries    => de,fr,uk and want to search by this. For this to work you should do extra work:

Add @ORM\HasLifecycleCallbacks() to your entity and sort the array before inserting

/**
 * @ORM\PrePersist
 */
public function setSelectedCountriesValue()
{
    sort($this->selectedCountries);
}

In your entity's repository use Query Builder and sort the array when trying to find results.

 $qb = $this->getEntityManager()->createQueryBuilder();

        $qb->select('r')
            ->from('AppBundle:Report', 'r')
            ...

        if ($creteria['selectedCountries']) {
            sort($creteria['selectedCountries']);
            $qb->andWhere('r.selectedCountries= :selectedCountries')
                ->setParameter('selectedCountries', implode(',', $creteria['selectedCountries']));
        }


问:
Unknown column in WHERE clause in subquery
I have pages table which I'm trying to truncate.
I need to leave last 10 versions of each page (page is identified by uid).

```<code>id----|----uid----|----version

1 ----|---- 1 ----|---- 1

2 ----|---- 1 ----|---- 2

3 ----|---- 1 ----|---- 3

4 ----|---- 1 ----|---- 4

5 ----|---- 2 ----|---- 1

6 ----|---- 2 ----|---- 2

...........

55 ----|---- 1 ----|---- 23

56 ----|---- 2 ----|---- 14

57 ----|---- 2 ----|---- 15
</code>```

I've tried with this MySQL query:

```<code>DELETE FROM pages AS p WHERE p.id IN (
    SELECT Versions.id FROM
        (SELECT q.id FROM pages AS q WHERE p.uid = q.uid ORDER BY q.version DESC LIMIT 10)
    AS Versions
)
</code>```

but above SQL returns:

Unknown column 'p.uid' in 'where clause'

On Stackoverflow is loads of answers for similar questions like mine but as I'm not SQL ninja I wasn't able to convert any of these to fit my problem.
I don't want to overkill my query as well.
There must be some simple answer to this.

I can achieve needed truncation in MSSQL Server with query below:

```<code>DELETE FROM pages WHERE id NOT IN (
    SELECT Versions.id FROM
        (SELECT TOP (10) q.id FROM pages AS q WHERE pages.uid = q.uid ORDER BY q.version DESC)
    AS Versions
)
</code>```

Thanks

答:
```<code>DELETE p FROM pages AS p WHERE p.id IN (
    SELECT Versions.id FROM
        (SELECT q.id FROM pages AS q WHERE p.uid = q.uid ORDER BY q.version DESC LIMIT 10)
    AS Versions
)
</code>```

Check if this works..

Body:
I have pages table which I'm trying to truncate.
I need to leave last 10 versions of each page (page is identified by uid).

id----|----uid----|----version

1 ----|---- 1 ----|---- 1

2 ----|---- 1 ----|---- 2

3 ----|---- 1 ----|---- 3

4 ----|---- 1 ----|---- 4

5 ----|---- 2 ----|---- 1

6 ----|---- 2 ----|---- 2

...........

55 ----|---- 1 ----|---- 23

56 ----|---- 2 ----|---- 14

57 ----|---- 2 ----|---- 15

I've tried with this MySQL query:

DELETE FROM pages AS p WHERE p.id IN (
    SELECT Versions.id FROM
        (SELECT q.id FROM pages AS q WHERE p.uid = q.uid ORDER BY q.version DESC LIMIT 10)
    AS Versions
)

but above SQL returns:

Unknown column 'p.uid' in 'where clause'

On Stackoverflow is loads of answers for similar questions like mine but as I'm not SQL ninja I wasn't able to convert any of these to fit my problem.
I don't want to overkill my query as well.
There must be some simple answer to this.

I can achieve needed truncation in MSSQL Server with query below:

DELETE FROM pages WHERE id NOT IN (
    SELECT Versions.id FROM
        (SELECT TOP (10) q.id FROM pages AS q WHERE pages.uid = q.uid ORDER BY q.version DESC)
    AS Versions
)

Thanks

Body:
DELETE p FROM pages AS p WHERE p.id IN (
    SELECT Versions.id FROM
        (SELECT q.id FROM pages AS q WHERE p.uid = q.uid ORDER BY q.version DESC LIMIT 10)
    AS Versions
)

Check if this works..


问:
Generate a UNIQUE string made out of numeric / ALPHABET

My Problem

I don't know any VBA

Need to generate a string of 12 chars (ALPHA +  numbers , 0-9 , A-Z) IN VBA...

Sample output :

```<code>"ADF3V3224K1WQ"
</code>```

(12 characters long , Higher caps Alphabetical letters , and Numeric values aswell).

Story

I'm having a hard time figuring out how to create a string generator (didn't say it has to be random, but it 100% has to be unique, meaning it has to check for duplications or store existing values), I have no experience with VBA. I already found a similar post here, but it is different then mine, as it does not specifically ask for the string to be 100% unique. (I don't need a very low chance, I need 100% across the board).

Syntax-wise I'm pretty confused, I managed to find where the code behind events are, ie Button presses, so I know where I need to write it, but I have no idea how to check for duplications. (even relying on a time seed that can ensure it will be 100% unique is great).

Link to the similar post: MS Access Visual Basic - generate random string in text field

答:
Well, I guess if it really needs to be alphanumeric and unique, this is the way to go:

This code generates a random string of characters based on the current time (like the answer by @paul-bica), only it encodes them alphanumerically and uses the timer to get fractions of a second to reach 12 characters). This way you should be able to generate multiple random strings per second.

Just call UniqueTimeBasedString() to get the string.
(Note that if you use this function in a query, Access will cache the result and it won't be unique at all).

```<code>Public Function UniqueTimeBasedString() As String
    Dim alphanumericCharacters As String
    alphanumericCharacters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Dim timeString As String
    timeString = Format(Now, "yymmddhhmmss") & Getmtimestring(6)
    Dim c As Integer
    Dim intTimepart As Integer
    c = 1
    Do While c < Len(timeString)
        intTimepart = CInt(Mid(timeString, c, 3))
        c = c + 3
        UniqueTimeBasedString = UniqueTimeBasedString & Mid(alphanumericCharacters, Int(intTimepart / 61) + 1, 1) & Mid(alphanumericCharacters, intTimepart Mod 61 + 1, 1)
    Loop
End Function

Public Function Getmtimestring(length As Integer) As String
    Dim mtime As Double
    mtime = Timer()
    Dim mtimeLng As Long
    mtimeLng = Int((mtime - Int(mtime)) * (10 ^ length))
    Getmtimestring = CStr(mtimeLng)
    Do While Len(Getmtimestring) < length
        Getmtimestring = "0" & Getmtimestring
    Loop
End Function
</code>```

Notes:

Timer() isn't really accurate, and this can theoretically cause
problems

This code is incompatible with OS X, but that won't be a problem if you stay limited to Access (Getmtimestring will just return zeroes)

You really should have a talk with your boss. Asking you to do something you aren't really qualified for with a tight deadline no options to use a slightly other solution isn't healthy workplace behaviour.

The string contains encoded time, and can be decoded. Don't report it if you want the time of creation of the string to be secret.

Body:
My Problem

I don't know any VBA

Need to generate a string of 12 chars (ALPHA +  numbers , 0-9 , A-Z) IN VBA...

Sample output :

"ADF3V3224K1WQ"

(12 characters long , Higher caps Alphabetical letters , and Numeric values aswell).

Story

I'm having a hard time figuring out how to create a string generator (didn't say it has to be random, but it 100% has to be unique, meaning it has to check for duplications or store existing values), I have no experience with VBA. I already found a similar post here, but it is different then mine, as it does not specifically ask for the string to be 100% unique. (I don't need a very low chance, I need 100% across the board).

Syntax-wise I'm pretty confused, I managed to find where the code behind events are, ie Button presses, so I know where I need to write it, but I have no idea how to check for duplications. (even relying on a time seed that can ensure it will be 100% unique is great).

Link to the similar post: MS Access Visual Basic - generate random string in text field

Body:
Well, I guess if it really needs to be alphanumeric and unique, this is the way to go:

This code generates a random string of characters based on the current time (like the answer by @paul-bica), only it encodes them alphanumerically and uses the timer to get fractions of a second to reach 12 characters). This way you should be able to generate multiple random strings per second.

Just call UniqueTimeBasedString() to get the string.
(Note that if you use this function in a query, Access will cache the result and it won't be unique at all).

Public Function UniqueTimeBasedString() As String
    Dim alphanumericCharacters As String
    alphanumericCharacters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Dim timeString As String
    timeString = Format(Now, "yymmddhhmmss") & Getmtimestring(6)
    Dim c As Integer
    Dim intTimepart As Integer
    c = 1
    Do While c < Len(timeString)
        intTimepart = CInt(Mid(timeString, c, 3))
        c = c + 3
        UniqueTimeBasedString = UniqueTimeBasedString & Mid(alphanumericCharacters, Int(intTimepart / 61) + 1, 1) & Mid(alphanumericCharacters, intTimepart Mod 61 + 1, 1)
    Loop
End Function

Public Function Getmtimestring(length As Integer) As String
    Dim mtime As Double
    mtime = Timer()
    Dim mtimeLng As Long
    mtimeLng = Int((mtime - Int(mtime)) * (10 ^ length))
    Getmtimestring = CStr(mtimeLng)
    Do While Len(Getmtimestring) < length
        Getmtimestring = "0" & Getmtimestring
    Loop
End Function

Notes:

Timer() isn't really accurate, and this can theoretically cause
problems

This code is incompatible with OS X, but that won't be a problem if you stay limited to Access (Getmtimestring will just return zeroes)

You really should have a talk with your boss. Asking you to do something you aren't really qualified for with a tight deadline no options to use a slightly other solution isn't healthy workplace behaviour.

The string contains encoded time, and can be decoded. Don't report it if you want the time of creation of the string to be secret.


问:
HttpWebResponse hangs/freezes when running in a WebAPI
I am using a C# WebAPI project which would call an external API based on its URL. However, when I am trying to retrieve the data back, it hangs/freezes.

The code where it stops is:

```<code>var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
</code>```

I don't understand why it is stopping though. Could it be interfering with the API request I am also making? When I run this code as part of a unit test, I would get a response back within seconds. I don't think it is the API service itself, I think it is my code. I have already tried various API URLS. None of them work.

My full code is:

```<code>public static async Task<string> CallWebAPi<T>(string url)
{
    string returnValue;

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.ContentType = "application/json";
    request.Method = "GET";

    var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

    Stream stream = response.GetResponseStream();
    StreamReader strReader = new StreamReader(stream);
    returnValue = await strReader.ReadToEndAsync();

    return returnValue;
}
</code>```

Any help would be appreciated.

答:
As a workaround you can use the synchronous functions, create a Task and await this task:</p>

```<code>var response = await Task.Run(() =>
{
    return (HttpWebResponse)request.GetResponse();
});
</code>```

Body:
I am using a C# WebAPI project which would call an external API based on its URL. However, when I am trying to retrieve the data back, it hangs/freezes.

The code where it stops is:

var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

I don't understand why it is stopping though. Could it be interfering with the API request I am also making? When I run this code as part of a unit test, I would get a response back within seconds. I don't think it is the API service itself, I think it is my code. I have already tried various API URLS. None of them work.

My full code is:

public static async Task<string> CallWebAPi<T>(string url)
{
    string returnValue;

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.ContentType = "application/json";
    request.Method = "GET";

    var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

    Stream stream = response.GetResponseStream();
    StreamReader strReader = new StreamReader(stream);
    returnValue = await strReader.ReadToEndAsync();

    return returnValue;
}

Any help would be appreciated.

Body:
As a workaround you can use the synchronous functions, create a Task and await this task:

var response = await Task.Run(() =>
{
    return (HttpWebResponse)request.GetResponse();
});


问:
Springboot Thymeleaf Cache page
I implement a client application. This application consume a Rest webservice and these service return and html page as a variable in a model.
I take these html page successfully from Rest Service and try to write to a blank html page.
My code to write html page.

```<code>public void writeToHtml(ResponseModel response) {

    FileWriter fWriter = null;
    BufferedWriter writer = null;
    try {
        fWriter = new FileWriter(src/main/resources/templates/test.html);
        writer = new BufferedWriter(fWriter);
        writer.write(response.getHtmlPage());
        writer.newLine();
        writer.close();
    } catch (Exception e) {

    }
}
</code>```

These function can take htmlPage from ResponseModel and write successfully to test.html
Untill there everthing work properly and my controller display it on secreen.

However, if I again call same Rest service, it can again write to "test.html" but, on the screen it shows the first created html page.
Probably it cache the first html and if I rewrite again. I just take cache one.

My Controller

```<code>@RequestMapping(value = "/testPath", method = RequestMethod.POST)
public String payment(RequestModel paymentInfoModel, BindingResult bindingResult, Model model) {
    RestTemplate restTemplate = new RestTemplate();

        ResponseModel response = restTemplate.postForObject(url, request, ResponseModel.class);
        writeToHtml(response);

    return "test";

}
</code>```

Could you help me to solve these issue ?

IDEA : Inteliji

答:
I solved my problem a bit differently:

```<code>@RequestMapping(value = "/testPath", method = RequestMethod.POST, produces = "text/html")
@ResponseBody
public String payment(RequestModel paymentInfoModel, BindingResult bindingResult, Model model) {

   RestTemplate restTemplate = new RestTemplate();
   ResponseModel response = restTemplate.postForObject(url, request, ResponseModel.class);
   writeToHtml(response);

   return response.getHtmlPage();
}
</code>```

So I don't need to create an HTML page.

ContentLicense: CC BY-SA 4.0

Title: Springboot Thymeleaf Cache page

Body:
I implement a client application. This application consume a Rest webservice and these service return and html page as a variable in a model.
I take these html page successfully from Rest Service and try to write to a blank html page.
My code to write html page.

public void writeToHtml(ResponseModel response) {

    FileWriter fWriter = null;
    BufferedWriter writer = null;
    try {
        fWriter = new FileWriter(src/main/resources/templates/test.html);
        writer = new BufferedWriter(fWriter);
        writer.write(response.getHtmlPage());
        writer.newLine();
        writer.close();
    } catch (Exception e) {

    }
}

These function can take htmlPage from ResponseModel and write successfully to test.html
Untill there everthing work properly and my controller display it on secreen.

However, if I again call same Rest service, it can again write to "test.html" but, on the screen it shows the first created html page.
Probably it cache the first html and if I rewrite again. I just take cache one.

My Controller

@RequestMapping(value = "/testPath", method = RequestMethod.POST)
public String payment(RequestModel paymentInfoModel, BindingResult bindingResult, Model model) {
    RestTemplate restTemplate = new RestTemplate();

        ResponseModel response = restTemplate.postForObject(url, request, ResponseModel.class);
        writeToHtml(response);

    return "test";

}

Could you help me to solve these issue ?

IDEA : Inteliji

Body:
I solved my problem a bit differently:

@RequestMapping(value = "/testPath", method = RequestMethod.POST, produces = "text/html")
@ResponseBody
public String payment(RequestModel paymentInfoModel, BindingResult bindingResult, Model model) {

   RestTemplate restTemplate = new RestTemplate();
   ResponseModel response = restTemplate.postForObject(url, request, ResponseModel.class);
   writeToHtml(response);

   return response.getHtmlPage();
}

So I don't need to create an HTML page.


问:
How to create instance of an object?
I am using Json.Net library to convert objects to json and back to objects.

I have an interface:

```<code>public interface IGoods
{
    List<IPen> Pens { get; set; }
    List<IPencil> Pencils{ get; set; }
    void Deserialize(String json);

}
</code>```

implementation:

```<code>new public void Deserialize(String json)
    {
        JsonConvert.DeserializeObject<Goods>(json);
    }
</code>```

The obvious error I got is: Could not create an instance of type Project.IPen. Type is an interface or abstract class and cannot be instantated.

How do I overcome this error?

Thanks!

答: According to the documentation you need to write some logic to tell Json.Net how to do the object creation - http://james.newtonking.com/projects/json/help/CustomCreationConverter.html</p>

ContentLicense: CC BY-SA 2.5

Title: How to create instance of an object?

Body:
I am using Json.Net library to convert objects to json and back to objects.

I have an interface:

public interface IGoods
{
    List<IPen> Pens { get; set; }
    List<IPencil> Pencils{ get; set; }
    void Deserialize(String json);

}

implementation:

new public void Deserialize(String json)
    {
        JsonConvert.DeserializeObject<Goods>(json);
    }

The obvious error I got is: Could not create an instance of type Project.IPen. Type is an interface or abstract class and cannot be instantated.

How do I overcome this error?

Thanks!


问:
How can iterate object value from json object in javascript
I tried to implement small google map. I have a json object that is : {"app_title":"whether","users":{"iv001":{"lat":"17.85","lng":"18.45"}}}  . How can i iterate lat and lng values. please help me.

```<code>{ "app_title":"whether",
  "users": {
     "iv001": {
             "lat":"17.85",
             "lng":"18.45"
       }
   }
 }
</code>```

var latitude = ???; //here we need lat value
var longitude = ???; //here we need lng value

答:
```<code>var testData = {"app_title":"whether","users":{"iv001":{"lat":"17.85","lng":"18.45"},"iv002":{"lat":"14.85","lng":"16.45"}}}

var arr = Object.values(testData.users);

for(i=0; i<arr.length; i++){
console.log('Long : ' + arr[i].lng + ', ' + 'Lat : ' + arr[i].lat);
}
</code>```

https://jsfiddle.net/yr47xgx3/

Body:
I tried to implement small google map. I have a json object that is : {"app_title":"whether","users":{"iv001":{"lat":"17.85","lng":"18.45"}}}  . How can i iterate lat and lng values. please help me.

{ "app_title":"whether",
  "users": {
     "iv001": {
             "lat":"17.85",
             "lng":"18.45"
       }
   }
 }

var latitude = ???; //here we need lat value
var longitude = ???; //here we need lng value

Body:
var testData = {"app_title":"whether","users":{"iv001":{"lat":"17.85","lng":"18.45"},"iv002":{"lat":"14.85","lng":"16.45"}}}

var arr = Object.values(testData.users);

for(i=0; i<arr.length; i++){
console.log('Long : ' + arr[i].lng + ', ' + 'Lat : ' + arr[i].lat);
}

https://jsfiddle.net/yr47xgx3/


问:
Showing error message for invalid input
I want to show error message when user enter invalid input in text field.

Right now I am using:

```<code>Pin:<input type="text" class="form-control input-sm" ng-pattern="numOnlyRegex" name="pin" ng-model="pin" required placeholder="Pin"/>
<span style="color:red" ng-show="myForm.pin.$invalid">Only number are allowed</span>
<input type="Submit" class="form-control btn btn-success" ng-disabled="myForm.$invalid" value="Submit" />
</code>```

Controller:

```<code><script>
            angular.module('myApp', []).controller("numOnlyRegex", function ($scope)
            {
                $scope.numOnlyRegex = /^\d+$/;
            });
        </script>
</code>```

But the above way I am trying shows a static message below the input text-field. What I want is when the user enters letters instead of numbers it should show error message like "only numbers are allowed" else there it should not show any error message.

ng-show method shows static message when the input is empty but I want to show error only when there is error(more realistic way)

答:
angular.module('myApp',[]).controller('myFormController',['$scope',function($scope){
  $scope.myInputVal='';
}])```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<html>
  <body ng-app="myApp">
  <div ng-controller="myFormController">
     <form name="myForm" >
     <input type="text" ng-model="myInputVal" ng-pattern="/^[0-9]*$/" name="myInputVal"/>
     <span ng-show="myForm.myInputVal.$error.pattern">Only Numbers are allowed</span>
     <span ng-show="!myForm.myInputVal.$error.pattern">{{myInputVal}}</span>
     <button type="submit" ng-disabled="myForm.$invalid">Submit</button>
     </form>
     </div>
  </body>
  </code>```

Title: Showing error message for invalid input

Body:
I want to show error message when user enter invalid input in text field.

Right now I am using:

Pin:<input type="text" class="form-control input-sm" ng-pattern="numOnlyRegex" name="pin" ng-model="pin" required placeholder="Pin"/>
Only number are allowed
<input type="Submit" class="form-control btn btn-success" ng-disabled="myForm.$invalid" value="Submit" />

Controller:

But the above way I am trying shows a static message below the input text-field. What I want is when the user enters letters instead of numbers it should show error message like "only numbers are allowed" else there it should not show any error message.

ng-show method shows static message when the input is empty but I want to show error only when there is error(more realistic way)

Body:
angular.module('myApp',[]).controller('myFormController',['$scope',function($scope){
  $scope.myInputVal='';
}])

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<html>
  <body ng-app="myApp">
  <div ng-controller="myFormController">
     <form name="myForm" >
     <input type="text" ng-model="myInputVal" ng-pattern="/^[0-9]*$/" name="myInputVal"/>
     <span ng-show="myForm.myInputVal.$error.pattern">Only Numbers are allowed</span>
     <span ng-show="!myForm.myInputVal.$error.pattern">{{myInputVal}}</span>
     <button type="submit" ng-disabled="myForm.$invalid">Submit</button>
     </form>
     </div>
  </body>


问:
How to autofocus Android camera automatically?
I want to autofocus Android camera as soon as camera holds still. Im looking for tutorials or samples how to do it or at least small sample that shows what classes I can use to hook on such events.</p>

答:
This works perfectly for preview callback:</p>

```<code>Camera.Parameters parameters = camera.getParameters();
if (parameters.getSupportedFocusModes().contains(
        Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
    parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
camera.setParameters(parameters);
</code>```

Body:
This works perfectly for preview callback:

Camera.Parameters parameters = camera.getParameters();
if (parameters.getSupportedFocusModes().contains(
        Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
    parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
camera.setParameters(parameters);


问:
android - how to change the fb logo size on facebook login button
so I have an Android application and I want to do a Facebook login. For that purpose I implemented the Facebook Login button in my layout. It's the following code now:

```<code><com.facebook.login.widget.LoginButton
    android:id="@+id/login_button"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="20dp"
    android:textSize="25dp"
    />
</code>```

The problem is, that the Facebook logo is too small:

fb logo too small

Is there a way to make it bigger?

Thanks for your help!

答:
give your width and height on dp value

```<code>android:layout_width="600dp"
android:layout_height="wrap_content"
</code>```

or you have to create more large size image
Note: i believe that you have already added all the screen sizes of drawables

cheerz

Body:
so I have an Android application and I want to do a Facebook login. For that purpose I implemented the Facebook Login button in my layout. It's the following code now:

<com.facebook.login.widget.LoginButton
    android:id="@+id/login_button"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="20dp"
    android:textSize="25dp"
    />

The problem is, that the Facebook logo is too small:

fb logo too small

Is there a way to make it bigger?

Thanks for your help!

Body:
give your width and height on dp value

android:layout_width="600dp"
android:layout_height="wrap_content"

or you have to create more large size image
Note: i believe that you have already added all the screen sizes of drawables

cheerz


问:
Display loader before whole page gets load
Code is simple but page gets load along with loader.</p>

```<code><script>
$(window).load(function() {
$(".loader").delay(2000).fadeOut("slow");
})
</script>

<body>
<header>
<div class="loader"><img src="img/loader.gif"></div>
</header>
</body>
</code>```

答:
```<code><body>
  <header>
    <div class="loader"><img src="img/loader.gif"></div>
    <script>
      $(".loader").fadeOut("slow");
    </script>
  </header>
</body>
</code>```

Should make it show the loader immediately after it's rendered, and then slowly fade out. This  section and then the script should be the first items in the .

Body:
<body>
  <header>
    <div class="loader"><img src="img/loader.gif"></div>
    <script>
      $(".loader").fadeOut("slow");
    </script>
  </header>
</body>

Should make it show the loader immediately after it's rendered, and then slowly fade out. This <header> section and then the script should be the first items in the <body>.


问:
Java Static
Duplicate: What does the 'static' keyword do in a class?

I've read this post already.

What does the "static" keyword in a method do?

I remember being told that static != clingy...but that is pretty much all I know about this keyword.

答:
a static method is one that's established for the class.  It doesn't need (and doesn't have) a this pointer, and can't access instance data.  So you can write something ike

```<code>public class Hello {

    void instanceHello() {
         System,out.println("Hello from the instance.");
    }

    public static void main(int argc, String[] argv){
         // The main method is defined even though there are no instances
         System.out.println("Hello from main.");
         instanceHello();  // but this is a syntax error;
         Hello h = new Hello();
         h.instanceHello();  // this isn't though
    }
}
</code>```

OwnerDisplayName: koldfyre

Title: Java Static

LastEditorDisplayName: nemo

Body:
a static method is one that's established for the class.  It doesn't need (and doesn't have) a this pointer, and can't access instance data.  So you can write something ike

public class Hello {

    void instanceHello() {
         System,out.println("Hello from the instance.");
    }

    public static void main(int argc, String[] argv){
         // The main method is defined even though there are no instances
         System.out.println("Hello from main.");
         instanceHello();  // but this is a syntax error;
         Hello h = new Hello();
         h.instanceHello();  // this isn't though
    }
}

OwnerDisplayName: Charlie Martin


问:
Flex - scroll wheel ok using IE, but not on FF or Chrome?
Flex - scroll wheel ok using IE, but not on FF or Chrome?

Switching between browsers during debugging and noticed the scroll wheel does not work in Firefox or Chrome, but is fine in Internet Explorer. Anyone else notice this? Suppose I could use a scroll listener and manually do it, but would much rather not!

答: I'm not sure if this is the cause of problem or not . but sometimes in flex when you run a project in your default testing browser . the recent changes doesn't show themselves . but when you copy the address of that file and paste it to another browser , it just works fine . if you're default browser doesn't show your project properly , the cause of problem is probably that . </p>


问:
Should I convert methods which doesn’t use this to static ones in React?
I start using ESlint, and
when I create a method like that in React component:

```<code>getWholeQUantityProducts(obj) {
    return Object.keys(obj)
      .reduce((sum, key) => sum + parseFloat(obj[key]), 0);
  }
</code>```

it warns me that "If a class method does not use this, it can safely be made a static function".

then I made it static  and put it before a constructor:

```<code>  static getWholeQUantityProducts(obj) {
    return Object.keys(obj)
      .reduce((sum, key) => sum + parseFloat(obj[key]), 0);
  }
</code>```

Now to call this method inside my component I write this.constructor.methodName.

I haven't seen yet that anyone recommends or uses such stuff in react tutorials.

So should I turning off this eslint rule? or write static method if doesn't contains this.

答:
The ESLint rules are best-practices authored by the creator. In this case it looks more like a utility method and not class dependent so it would make sense to export it into a utility class as a static method.

But to call it with this.constructor.methodName is weird. E.g. should look like this

```<code>export class Utils {

    public static getWholeQUantityProducts(obj) {
    return Object.keys(obj)
      .reduce((sum, key) => sum + parseFloat(obj[key]), 0);
  }
}
</code>```

And you would call it with Utils.getWholeQUantityProducts(obj).

Body:
I start using ESlint, and
when I create a method like that in React component:

getWholeQUantityProducts(obj) {
    return Object.keys(obj)
      .reduce((sum, key) => sum + parseFloat(obj[key]), 0);
  }

it warns me that "If a class method does not use this, it can safely be made a static function".

then I made it static  and put it before a constructor:

  static getWholeQUantityProducts(obj) {
    return Object.keys(obj)
      .reduce((sum, key) => sum + parseFloat(obj[key]), 0);
  }

Now to call this method inside my component I write this.constructor.methodName.

I haven't seen yet that anyone recommends or uses such stuff in react tutorials.

So should I turning off this eslint rule? or write static method if doesn't contains this.

Body:
The ESLint rules are best-practices authored by the creator. In this case it looks more like a utility method and not class dependent so it would make sense to export it into a utility class as a static method.

But to call it with this.constructor.methodName is weird. E.g. should look like this

export class Utils {

    public static getWholeQUantityProducts(obj) {
    return Object.keys(obj)
      .reduce((sum, key) => sum + parseFloat(obj[key]), 0);
  }
}

And you would call it with Utils.getWholeQUantityProducts(obj).


问:
Python/Pandas - How to assign value for each row which depends on cells values
I have data frame like this:

```<code>  x  y   z
0 AA BB  CC
1 BB NaN CC
2 BB AA  NaN
</code>```

and dictionary:

```<code>d = {'AA': 1, 'BB': 2, 'CC': 3}
</code>```

I want to compare values from each cell with values from dictionary and add another new column with sum of these values for each row. In result I need something like this:

```<code>  x  y   z   sum
0 AA BB  CC   6
1 BB NaN CC   5
2 BB AA  NaN  3
</code>```

I need the most efficient solution, any ideas?

答:
Use replace with sum per row by axis=1, last convert to int by astype:

```<code>print (df.replace(d))
   x    y    z
0  1  2.0  3.0
1  2  NaN  3.0
2  2  1.0  NaN

df['sum'] = df.replace(d).sum(axis=1).astype(int)
print (df)
    x    y    z  sum
0  AA   BB   CC    6
1  BB  NaN   CC    5
2  BB   AA  NaN    3
</code>```

Body:
I have data frame like this:

  x  y   z
0 AA BB  CC
1 BB NaN CC
2 BB AA  NaN

and dictionary:

d = {'AA': 1, 'BB': 2, 'CC': 3}

I want to compare values from each cell with values from dictionary and add another new column with sum of these values for each row. In result I need something like this:

  x  y   z   sum
0 AA BB  CC   6
1 BB NaN CC   5
2 BB AA  NaN  3

I need the most efficient solution, any ideas?

Body:
Use replace with sum per row by axis=1, last convert to int by astype:

print (df.replace(d))
   x    y    z
0  1  2.0  3.0
1  2  NaN  3.0
2  2  1.0  NaN

df['sum'] = df.replace(d).sum(axis=1).astype(int)
print (df)
    x    y    z  sum
0  AA   BB   CC    6
1  BB  NaN   CC    5
2  BB   AA  NaN    3


问:
Paste Special in Excel as standard
Is there a way where I can make an Excel file where whenever you copy something from it then it will automatically use paste special formatted as values? Even if you paste in another Excel file.</p>

答:
I've found a solution where I run a on-key event macro which looks like this:

```<code>Sub Paste_Special()
  On Error Resume Next

If Err = 1004 Then
  Exit Sub
Else
  Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
  Application.CutCopyMode = False
End If

Err.Clear
On Error GoTo 0
End Sub
</code>```

And it works between Excel files as long as the file where the macro originate from is open.

Title: Paste Special in Excel as standard

Body:
I've found a solution where I run a on-key event macro which looks like this:

Sub Paste_Special()
  On Error Resume Next

If Err = 1004 Then
  Exit Sub
Else
  Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
  Application.CutCopyMode = False
End If

Err.Clear
On Error GoTo 0
End Sub

And it works between Excel files as long as the file where the macro originate from is open.


问:
How do I output leaflet map from R into format where I can edit using Leaflet commands?
I have some experience with using R for data manipulation and making maps with GIS software, so I just tried to make my first Leaflet map using the Leaflet for R package. Working off of tutorials I've been able to do this just fine, but there are a few tweaks I would like to make to my final map that appear to be possible using 'regular Leaflet', but not the R package (using a tile layer of labels only in a custom map pane so that the geography labels appear above my polygons, etc.). This is fine, except I cannot figure out where in the output files for my map I can make the necessary edits using the Leaflet syntax.

I am exporting my map using the following code, based off this example:

```<code>saveWidget(myMap, 'myMap.html', selfcontained = FALSE)
</code>```

I am not very familiar with the HTML output; I've made maps in QGIS that were exported to HTML files, but I never needed to edit the source code. I'm looking for a file in which I can add Leaflet commands. The index.html file appears to be the only file that contains information specific to my map, with the other files containing code that the index.html file references in order to display the map. I thought that this would be the place to edit the code with Leaflet commands, but it doesn't look anything like the examples of Leaflet map code that I've seen at all. I'm not including my full index.html file here because it's too long, but it looks nothing like the Leaflet script here. No var = or L.tileLayer, L.polygon, etc. I don't see map objects, simply coordinates.

What I assume is happening is that when I output the Leaflet map using HTML widgets, the R is translated into Leaflet, which is then translated into base Javascript, which I see in my index.html file. So first of all, I'm wondering if this is accurate.

If it is accurate, my question is: Is there a way to output the map from R into Leaflet commands instead of just Javascript?

If it is not accurate, my question is: Can I edit the files I have right now in my map output folder using Leaflet? (I may be misunderstanding Leaflet-It's a library of custom commands that are different than typical Javascript, right?)

My apologies in advance if this is a very basic question, I'm definitely a novice here.

EDIT: Here is an image of the HTML file for my map. I'm assuming this is all base Javascript (or maybe even simplified Javascript?) and that if I want to tweak the map further, I have to do it here by referencing the Leaflet source code. Unless there is a way to reference the Leaflet library within the htmlwidgets::onRender command mentioned in the first reply, where I can then write in Leaflet.

HTML file for map

答:
In effect, the leaflet htmlwidget does what you have described under the hood.
 Instead of direct leaflet commands, it uses methods defined here to manipulate the map as seen in the screenshot below.

Calls from R

The calls from R are stored on map$x$calls.  Let's use some code from ?leaflet to make a quick map, so we can see what is happening.

```<code># from ?leaflet
library(leaflet)

rand_lng = function(n = 10) rnorm(n, -93.65, .01)
rand_lat = function(n = 10) rnorm(n, 42.0285, .01)

m = leaflet() %>%
  addTiles() %>%
  fitBounds(0, 40, 10, 50) %>%
  setView(-93.65, 42.0285, zoom = 17) %>%
  addPopups(
    -93.65, 42.0285, 'Here is the <b>Department of Statistics</b>, ISU'
  ) %>%
  clearBounds()

m$x$calls
</code>```

Or more graphically looks like this (see here for live example).

These calls are sent as JSON when the leaflet widget is created.  This approach provides lots of helpers for working with leaflet and is especially helpful for a R user unfamiliar with leaflet or JavaScript.  However this intermediate step might make what you are trying to accomplish slightly more difficult.

onRender

If I understand correctly, htmlwidgets::onRender() might do exactly what you want.  Let's see it in action.

```<code>htmlwidgets::onRender(
  m,
  "
  function(el, x, data) {
    // our leaflet map is available as this
    console.log(this);
  }
  "
)
</code>```

If you open the map in browser and inspect with developer tools (ctrl + shift + i), you will see that the leaflet map is available for further manipulation.

Follow up

I hope this helped.  Please let me know if you have more questions, and I will be happy to help answer.

Body:
I have some experience with using R for data manipulation and making maps with GIS software, so I just tried to make my first Leaflet map using the Leaflet for R package. Working off of tutorials I've been able to do this just fine, but there are a few tweaks I would like to make to my final map that appear to be possible using 'regular Leaflet', but not the R package (using a tile layer of labels only in a custom map pane so that the geography labels appear above my polygons, etc.). This is fine, except I cannot figure out where in the output files for my map I can make the necessary edits using the Leaflet syntax.

I am exporting my map using the following code, based off this example:

saveWidget(myMap, 'myMap.html', selfcontained = FALSE)

I am not very familiar with the HTML output; I've made maps in QGIS that were exported to HTML files, but I never needed to edit the source code. I'm looking for a file in which I can add Leaflet commands. The index.html file appears to be the only file that contains information specific to my map, with the other files containing code that the index.html file references in order to display the map. I thought that this would be the place to edit the code with Leaflet commands, but it doesn't look anything like the examples of Leaflet map code that I've seen at all. I'm not including my full index.html file here because it's too long, but it looks nothing like the Leaflet script here. No var = or L.tileLayer, L.polygon, etc. I don't see map objects, simply coordinates.

What I assume is happening is that when I output the Leaflet map using HTML widgets, the R is translated into Leaflet, which is then translated into base Javascript, which I see in my index.html file. So first of all, I'm wondering if this is accurate.

If it is accurate, my question is: Is there a way to output the map from R into Leaflet commands instead of just Javascript?

If it is not accurate, my question is: Can I edit the files I have right now in my map output folder using Leaflet? (I may be misunderstanding Leaflet-It's a library of custom commands that are different than typical Javascript, right?)

My apologies in advance if this is a very basic question, I'm definitely a novice here.

EDIT: Here is an image of the HTML file for my map. I'm assuming this is all base Javascript (or maybe even simplified Javascript?) and that if I want to tweak the map further, I have to do it here by referencing the Leaflet source code. Unless there is a way to reference the Leaflet library within the htmlwidgets::onRender command mentioned in the first reply, where I can then write in Leaflet.

HTML file for map

Body:
In effect, the leaflet htmlwidget does what you have described under the hood.
 Instead of direct leaflet commands, it uses methods defined here to manipulate the map as seen in the screenshot below.

Calls from R

The calls from R are stored on map$x$calls.  Let's use some code from ?leaflet to make a quick map, so we can see what is happening.

# from ?leaflet
library(leaflet)

rand_lng = function(n = 10) rnorm(n, -93.65, .01)
rand_lat = function(n = 10) rnorm(n, 42.0285, .01)

m = leaflet() %>%
  addTiles() %>%
  fitBounds(0, 40, 10, 50) %>%
  setView(-93.65, 42.0285, zoom = 17) %>%
  addPopups(
    -93.65, 42.0285, 'Here is the <b>Department of Statistics</b>, ISU'
  ) %>%
  clearBounds()

m$x$calls

Or more graphically looks like this (see here for live example).

These calls are sent as JSON when the leaflet widget is created.  This approach provides lots of helpers for working with leaflet and is especially helpful for a R user unfamiliar with leaflet or JavaScript.  However this intermediate step might make what you are trying to accomplish slightly more difficult.

onRender

If I understand correctly, htmlwidgets::onRender() might do exactly what you want.  Let's see it in action.

htmlwidgets::onRender(
  m,
  "
  function(el, x, data) {
    // our leaflet map is available as this
    console.log(this);
  }
  "
)

If you open the map in browser and inspect with developer tools (ctrl + shift + i), you will see that the leaflet map is available for further manipulation.

Follow up

I hope this helped.  Please let me know if you have more questions, and I will be happy to help answer.


问:
Get cucumber scenario step name
I try to get step's name in hooks file:

```<code>AfterStep do |scenario|
  step = scenario.steps.find { |s| s.status == :failed }
  if step.name.include?("failed step")
    puts "Failed step is: #{step}"
  end
end
</code>```

But when I run a scenario I'm getting  next error:
NoMethodError: undefined method 'steps' for #<Cucumber::Core::Test::Result::Passed:0x42a58b8>

I use Cucumber 2.4.0. Is another way to get scenario step name?

答:
Answer is next:</p>

```<code>AfterStep do |result, step|
  puts step.name
end
</code>```

Title: Get cucumber scenario step name

Body:
I try to get step's name in hooks file:

AfterStep do |scenario|
  step = scenario.steps.find { |s| s.status == :failed }
  if step.name.include?("failed step")
    puts "Failed step is: #{step}"
  end
end

But when I run a scenario I'm getting  next error:
NoMethodError: undefined method 'steps' for #<Cucumber::Core::Test::Result::Passed:0x42a58b8>

I use Cucumber 2.4.0. Is another way to get scenario step name?

Body:
Answer is next:

AfterStep do |result, step|
  puts step.name
end