问:
How do I concatenate two lists in Python?
How do I concatenate two lists in Python?

Example:

```<code>listone = [1, 2, 3]
listtwo = [4, 5, 6]
</code>```

Expected outcome:

```<code>>>> joinedlist
[1, 2, 3, 4, 5, 6]
</code>```

答:
How do I concatenate two lists in Python?

As of 3.9, these are the most popular stdlib methods for concatenating two (or more) lists in Python.

Version Restrictions
In-Place?
Generalize?*

a + b
-
No
sum(list_of_lists, [])1

list(chain(a, b))2
>=2.3
No
list(chain(*list_of_lists))

[*a, *b]3
>=3.5
No
No

a += b
-
Yes
No

a.extend(b)
-
Yes
No

* A solution will qualify as a generalized solution if it works for an unknown number of lists (say, inside a loop or list comprehension)

Footnotes

This is a slick solution because of its succinctness. But sum performs concatenation in a pairwise fashion, which means this is a
quadratic operation as memory has to be allocated for each step. DO
NOT USE if your lists are large.

See chain
and
chain.from_iterable
from the docs. You will need to from itertools import chain first.
Concatenation is linear in memory, so this is the best in terms of
performance and version compatibility. chain.from_iterable was introduced in 2.6.

This method uses Additional Unpacking Generalizations (PEP 448), but cannot
generalize to N lists unless you manually unpack each one yourself.

a += b and a.extend(b) are more or less equivalent for all practical purposes. += when called on a list will internally call
list.__iadd__, which extends the first list by the second.

Performance

2-List Concatenation1

There's not much difference between these methods but that makes sense given they all have the same order of complexity (linear). There's no particular reason to prefer one over the other except as a matter of style.

N-List Concatenation

Plots have been generated using the perfplot module. Code, for your reference.

1. The iadd (+=) and extend methods operate in-place, so a copy has to be generated each time before testing. To keep things fair, all methods have a pre-copy step for the left-hand list which can be ignored.

Comments on Other Solutions

DO NOT USE THE DUNDER METHOD list.__add__ directly in any way, shape or form. In fact, stay clear of dunder methods, and use the operators and operator functions like they were designed for. Python has careful semantics baked into these which are more complicated than just calling the dunder directly. Here is an example. So, to summarise, a.__add__(b) => BAD; a + b => GOOD.

Some answers here offer reduce(operator.add, [a, b]) for pairwise concatenation -- this is the same as sum([a, b], []) only more wordy.

Any method that uses set will drop duplicates and lose ordering. Use with caution.

for i in b: a.append(i) is more wordy, and slower than a.extend(b), which is single function call and more idiomatic. append is slower because of the semantics with which memory is allocated and grown for lists. See here for a similar discussion.

heapq.merge will work, but its use case is for merging sorted lists in linear time. Using it in any other situation is an anti-pattern.

yielding list elements from a function is an acceptable method, but chain does this faster and better (it has a code path in C, so it is fast).

operator.add(a, b) is an acceptable functional equivalent to a + b. It's use cases are mainly for dynamic method dispatch. Otherwise, prefer a + b which is shorter and more readable, in my opinion. YMMV.

Body:
How do I concatenate two lists in Python?

Example:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

Expected outcome:

>>> joinedlist
[1, 2, 3, 4, 5, 6]


来源: stackexchange

问:
Compiler error: incompatible types when assigning to 'struct' from type 'void *' during malloc
EDIT -- can the down voter explain? I have a clear question, with supporting evidence, and proof of prior investigation. I would like to understand why you are down voting me...?

I am getting this error when I compile with gcc:

error: incompatible types when assigning to type ‘struct cell’ from type ‘void *

The problem lines are:

```<code>    struct cell* cells = NULL;
    cells = malloc(sizeof(struct cell) * length);
    for (i = 0; i < length; i++) {
            cells[i] = malloc(sizeof(struct cell) * width);
</code>```

I believe I have followed the proper protocol, as described here and also here. What am I missing?

答:
malloc() always returns a pointer of type void * you need to type cast

To allocate memory for single element:

struct cell* new = (struct cell*) malloc(sizeof(struct cell)); //This will allocate memory and new is pointer

To access data members :

new->member_name = value; //dot(.) operator doesn't work as new is a pointer and not an identifier

To allocate memory for array :

struct cell* base = (struct cell*) malloc(sizeof(struct cell) * length); //This will allocate memory and base is base of array

To access data members :

base[i].member_name = value; //When accessing elements of array the -> operator doesn't work.

ContentLicense: CC BY-SA 3.0

Body:
EDIT -- can the down voter explain? I have a clear question, with supporting evidence, and proof of prior investigation. I would like to understand why you are down voting me...?

I am getting this error when I compile with gcc:

error: incompatible types when assigning to type ‘struct cell’ from type ‘void *

The problem lines are:

    struct cell* cells = NULL;
    cells = malloc(sizeof(struct cell) * length);
    for (i = 0; i < length; i++) {
            cells[i] = malloc(sizeof(struct cell) * width);

I believe I have followed the proper protocol, as described here and also here. What am I missing?

ContentLicense: CC BY-SA 4.0


问:
How to filter Pandas dataframe using 'in' and 'not in' like in SQL
How can I achieve the equivalents of SQL's IN and NOT IN?

I have a list with the required values. Here's the scenario:

df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
countries_to_keep = ['UK', 'China']

# pseudo-code:
df[df['country'] not in countries_to_keep]
```
<p>My current way of doing this is as follows:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
df2 = pd.DataFrame({'country': ['UK', 'China'], 'matched': True})

# IN
df.merge(df2, how='inner', on='country')

# NOT IN
not_in = df.merge(df2, how='left', on='country')
not_in = not_in[pd.isnull(not_in['matched'])]
</code>```

But this seems like a horrible kludge. Can anyone improve on it?

答:
Collating possible solutions from the answers:

For IN: df[df['A'].isin([3, 6])]

For NOT IN:

df[-df["A"].isin([3, 6])]

df[~df["A"].isin([3, 6])]

df[df["A"].isin([3, 6]) == False]

df[np.logical_not(df["A"].isin([3, 6]))]

Body:
How can I achieve the equivalents of SQL's IN and NOT IN?

I have a list with the required values. Here's the scenario:

df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
countries_to_keep = ['UK', 'China']

# pseudo-code:
df[df['country'] not in countries_to_keep]

My current way of doing this is as follows:

df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
df2 = pd.DataFrame({'country': ['UK', 'China'], 'matched': True})

# IN
df.merge(df2, how='inner', on='country')

# NOT IN
not_in = df.merge(df2, how='left', on='country')
not_in = not_in[pd.isnull(not_in['matched'])]

But this seems like a horrible kludge. Can anyone improve on it?


问:
Can I convert a null pointer of int to a long type by reinterpret_cast
int *pt = 0;

long i = reinterpret_cast<long>(pt);

Is i guaranteed to be 0? Is this well defined or implementation-defined?
I checked the c++ standard, but it only states that

A pointer to a data object or to a function (but not a pointer to member) can be converted to any integer type large enough to contain it.

In this case, pt doesn't point to any data object. Does the rule apply to this case?

答: You want reinterpret_cast(pt) but yes, that will work. reinterpret_cast is the same as the old C style cast (long) and assumes you know what you are doing.</p>


问:
Column Shows 'id' Number Instead of Foreign Key Attribute
When using the select2 field/column type in Laravel Backpack, the list view displays the 'id' of the foreign entity instead of the foreign key required (in this case the 'name' of the Session).

Laravel 5.8.4, Backpack 3.4.  I asked in GitHub and the response was that my relationships were incorrect in my models.  I don't think that's the problem as the name loads in the edit view.

GradeCrudController

        $this->crud->addColumn([
            'label' => "Session",
            'type' => 'select2',
            'name' => 'session_id', // the db column for the foreign key
            'entity' => 'session', // the method that defines the relationship in your Model
            'attribute' => 'name', // foreign key attribute that is shown to user
            'model' => "App\Models\Session" // foreign key model
        ]);
```

<p><b>Grade (Model)</b></p>

<pre class="lang-php prettyprint-override"><code>    public function session()
    {
      return $this->belongsTo('App\Models\Session');
    }
</code>```

Session (Model)

    public function grades()
    {
      return $this->hasMany('App\Models\Grade');
    }
```

答:
As it's been a few days and nobody has responded, I thought I'd post the answer I came up with.  Note that I highly doubt that this is the correct solution, but for my project it will do.

I added a Laravel Observer for the Grade Model. Once a user adds a new record, the observer visits the session table, pulls the name of the session using the key and adds it as a column to the Grades table.

Then in backpack I just display the 'name' column.

There has to be a better way than this... But for now it will do.

Body:
When using the select2 field/column type in Laravel Backpack, the list view displays the 'id' of the foreign entity instead of the foreign key required (in this case the 'name' of the Session).

Laravel 5.8.4, Backpack 3.4.  I asked in GitHub and the response was that my relationships were incorrect in my models.  I don't think that's the problem as the name loads in the edit view.

GradeCrudController

        $this->crud->addColumn([
            'label' => "Session",
            'type' => 'select2',
            'name' => 'session_id', // the db column for the foreign key
            'entity' => 'session', // the method that defines the relationship in your Model
            'attribute' => 'name', // foreign key attribute that is shown to user
            'model' => "App\Models\Session" // foreign key model
        ]);

Grade (Model)

    public function session()
    {
      return $this->belongsTo('App\Models\Session');
    }

Session (Model)

    public function grades()
    {
      return $this->hasMany('App\Models\Grade');
    }


问:
I cannot query if there are duplicate in mysql database//
I have a website that searches for an order id and echoes it on php if it found that id. The problem is if there is a duplicate id it does not query it properly.

I have tried searching the web for answers

```<code><?php
require('connect.php');

$order_id = $_POST['order_id'];

$conn = mysqli_connect("", "", "", "");
$query = "SELECT * FROM `orders` WHERE order_id='$order_id' ";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
$count = mysqli_num_rows($result);

if ($count == 1) {

    $sql = "SELECT `order_id`, `firstname`, `lastname`, `order_name`,
                    `qty`, `price`, `total`, `reg_date`, `status`
            FROM `orders`
            WHERE order_id='$order_id'";
    $result = $conn->query($sql);

    while($row = $result->fetch_assoc()) {

        echo"<div id='orders'>";
            echo "ORDER NUMBER: " . $row["order_id"];
                echo"<br>";
                echo"<br>";
            echo "FIRST NAME: " . $row["firstname"];
                echo"<br>";
                echo"<br>";
            echo "LAST NAME: " . $row["lastname"];
                echo"<br>";
                echo"<br>";
            echo "ORDER: " . $row["order_name"];
                echo"<br>";
                echo"<br>";
            echo "QUANTITY: " . $row["qty"];
                echo"<br>";
                echo"<br>";
            echo "PRICE: " . $row["price"];
                echo"<br>";
                echo"<br>";
            echo "ORDER TOTAL: " . $row["total"];
                echo"<br>";
                echo"<br>";
            echo "STATUS: " . $row["status"];
                echo"<br>";
                echo"<br>";
            echo "DATE ORDERED: " . $row["reg_date"];

            echo"</div>";
        }
    }else{
        echo"<div id='orders'>";
        echo"INVALID ID ENTERED";
        echo"</div>";

}
?>
</code>```

The result returns an "INVALID ID ENTERED" if there are two duplicate results in mysqli data base. I know that I can just simply change the order id so that it does not have to be duplicated but that is not what I wanted.

答:
Don't check if count is 1, check if it's not 0. That way, if there are duplicate orders, you'll show all of them.

There's also no need to do two queries for the same rows. Just do the query that gets the columns you want, and test the count of that.

And use a prepared statement to protect against SQL injection.

```<code><?php
require('connect.php');

$order_id = $_POST['order_id'];

$conn = mysqli_connect("", "", "", "");
$sql = "SELECT `order_id`, `firstname`, `lastname`, `order_name`,
                `qty`, `price`, `total`, `reg_date`, `status`
        FROM `orders`
        WHERE order_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $order_id);
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows;

if ($count == 1) {
    $stmt->bind_result($order_id, $firstname, $lastname, $order_name, $qty, $price, $total, $status, $reg_date);
    while($row = $result->fetch()) {
        echo"<div id='orders'>";
        echo "ORDER NUMBER: " . $order_id;
        echo"<br><br>";
        echo "FIRST NAME: " . $firstname;
        echo"<br><br>";
        echo "LAST NAME: " . $lastname;
        echo"<br><br>";
        echo "ORDER: " . $order_name;
        echo"<br><br>";
        echo "QUANTITY: " . $qty;
        echo"<br><br>";
        echo "PRICE: " . $price;
        echo"<br><br>";
        echo "ORDER TOTAL: " . $total;
        echo"<br><br>";
        echo "STATUS: " . $status;
        echo"<br><br>";
        echo "DATE ORDERED: " . $reg_date;
        echo"</div>";
    }
}else{
    echo"<div id='orders'>";
    echo"INVALID ID ENTERED";
    echo"</div>";
}
?>
</code>```

Body:
I have a website that searches for an order id and echoes it on php if it found that id. The problem is if there is a duplicate id it does not query it properly.

I have tried searching the web for answers

<?php
require('connect.php');

$order_id = $_POST['order_id'];

$conn = mysqli_connect("", "", "", "");
$query = "SELECT * FROM `orders` WHERE order_id='$order_id' ";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
$count = mysqli_num_rows($result);

if ($count == 1) {

    $sql = "SELECT `order_id`, `firstname`, `lastname`, `order_name`,
                    `qty`, `price`, `total`, `reg_date`, `status`
            FROM `orders`
            WHERE order_id='$order_id'";
    $result = $conn->query($sql);

    while($row = $result->fetch_assoc()) {

        echo"
";
            echo "ORDER NUMBER: " . $row["order_id"];
                echo"
";
                echo"
";
            echo "FIRST NAME: " . $row["firstname"];
                echo"
";
                echo"
";
            echo "LAST NAME: " . $row["lastname"];
                echo"
";
                echo"
";
            echo "ORDER: " . $row["order_name"];
                echo"
";
                echo"
";
            echo "QUANTITY: " . $row["qty"];
                echo"
";
                echo"
";
            echo "PRICE: " . $row["price"];
                echo"
";
                echo"
";
            echo "ORDER TOTAL: " . $row["total"];
                echo"
";
                echo"
";
            echo "STATUS: " . $row["status"];
                echo"
";
                echo"
";
            echo "DATE ORDERED: " . $row["reg_date"];

            echo"
";
        }
    }else{
        echo"
";
        echo"INVALID ID ENTERED";
        echo"
";

}
?>

The result returns an "INVALID ID ENTERED" if there are two duplicate results in mysqli data base. I know that I can just simply change the order id so that it does not have to be duplicated but that is not what I wanted.

Body:
Don't check if count is 1, check if it's not 0. That way, if there are duplicate orders, you'll show all of them.

There's also no need to do two queries for the same rows. Just do the query that gets the columns you want, and test the count of that.

And use a prepared statement to protect against SQL injection.

<?php
require('connect.php');

$order_id = $_POST['order_id'];

$conn = mysqli_connect("", "", "", "");
$sql = "SELECT `order_id`, `firstname`, `lastname`, `order_name`,
                `qty`, `price`, `total`, `reg_date`, `status`
        FROM `orders`
        WHERE order_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $order_id);
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows;

if ($count == 1) {
    $stmt->bind_result($order_id, $firstname, $lastname, $order_name, $qty, $price, $total, $status, $reg_date);
    while($row = $result->fetch()) {
        echo"<div id='orders'>";
        echo "ORDER NUMBER: " . $order_id;
        echo"<br><br>";
        echo "FIRST NAME: " . $firstname;
        echo"<br><br>";
        echo "LAST NAME: " . $lastname;
        echo"<br><br>";
        echo "ORDER: " . $order_name;
        echo"<br><br>";
        echo "QUANTITY: " . $qty;
        echo"<br><br>";
        echo "PRICE: " . $price;
        echo"<br><br>";
        echo "ORDER TOTAL: " . $total;
        echo"<br><br>";
        echo "STATUS: " . $status;
        echo"<br><br>";
        echo "DATE ORDERED: " . $reg_date;
        echo"</div>";
    }
}else{
    echo"<div id='orders'>";
    echo"INVALID ID ENTERED";
    echo"</div>";
}
?>


问:
SDTT warning: "The property priceSpecification is not recognized by Google for an object of type Product."
I have the following JSON-LD and am trying to represent a pay monthly product such as a mobile phone contract which consists of an upfront fee and a monthly fee.

When I try to add the unitCode, I get the following warning:

The property priceSpecification is not recognized by Google for an object of type Product.

{
  "@context": "https://schema.org/",
  "@type": "Product",
  "name": "Apple iPhone",
  "image": [
   "https://example.com/photos/1x1/photo.jpg",
   "https://example.com/photos/4x3/photo.jpg",
    "https://example.com/photos/16x9/photo.jpg"
 ],
"description": "Apple iPhone XS ...",
 "sku": "0446310786",
 "mpn": "925872",
 "brand": {
  "@type": "Thing",
  "name": "ACME"
   },
  "review": {
   "@type": "Review",
  "reviewRating": {
  "@type": "Rating",
  "ratingValue": "4",
  "bestRating": "5"
  },
"author": {
  "@type": "Person",
  "name": "Fred Benson"
}
},
"aggregateRating": {
"@type": "AggregateRating",
"ratingValue": "4.4",
"reviewCount": "89"
 },
 "offers": {
"@type": "Offer",
"url": "https://example.com/anvil",
"priceCurrency": "GBP",
"price": "39.99",
"priceValidUntil": "2020-11-05",
"itemCondition": "https://schema.org/UsedCondition",
"availability": "https://schema.org/InStock",
"seller": {
  "@type": "Organization",
  "name": "Executive Objects"
}
},
"priceSpecification": {
    "@type": "UnitPriceSpecification",
    "price": "25",
    "priceCurrency": "GBP",
    "referenceQuantity": {
      "unitCode": "MON"
    }
  }
  }
```

答:
You need to add the priceSpecification property to the Offer, not to the Product.

{
  "@context": "https://schema.org/",
  "@type": "Product",

  "offers": {
    "@type": "Offer",

    "priceSpecification": {
      "@type": "UnitPriceSpecification"
    }

  }

}
```

You can find the expected domain/range of a property on its page. For priceSpecification, it says:

Used on these types

  Demand

  Offer

  TradeAction

So, it’s not expected on Product.

Body:
You need to add the priceSpecification property to the Offer, not to the Product.

{
  "@context": "https://schema.org/",
  "@type": "Product",

  "offers": {
    "@type": "Offer",

    "priceSpecification": {
      "@type": "UnitPriceSpecification"
    }

  }

}

You can find the expected domain/range of a property on its page. For priceSpecification, it says:

Used on these types

  Demand

  Offer

  TradeAction

So, it’s not expected on Product.


问:
How to check application is white list in MI security permission autostart
I am building an android application where I am using some services. My services get close when application is close in some custom android OS like MI.

Then I figure out we have to push our application in white list of security autostart application.

I got some SOF link's where they are suggesting below answer.

```<code>String manufacturer = "xiaomi";
    if(manufacturer.equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
        //this will open auto start screen where user can enable permission for your app
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
        startActivity(intent);
    }
</code>```

This above code used to send user to that particular page.

Now I have to check if my application is disable so I can send user to this page and if it is enable then move to other screen. Is there any way to check this?

答: There is no Android API to check if the the AutoStart is enabled or not. Though you can have your own logic in the App (may be you can use preference to set a Boolean for it) to check this. Also the above way to enabling the AutoStart might not work always. Please have a look here</p>

Body:
I am building an android application where I am using some services. My services get close when application is close in some custom android OS like MI.

Then I figure out we have to push our application in white list of security autostart application.

I got some SOF link's where they are suggesting below answer.

String manufacturer = "xiaomi";
    if(manufacturer.equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
        //this will open auto start screen where user can enable permission for your app
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
        startActivity(intent);
    }

This above code used to send user to that particular page.

Now I have to check if my application is disable so I can send user to this page and if it is enable then move to other screen. Is there any way to check this?


问:
Newbie question: What is the correct way to pass error message from ajax calls?
The theory says:
- if there is no error, return 200
- if there is an error, return 404
but how to pass error messages with the 404 code?

I have built a backend that currently returns code 200 AND in the json response there is a 'success' flag. If the flag is false, another field contains error message.
(There may be several reasons why the operation failed and I want to display the reason to the user).

I am aware that by convention the 404 error should be returned but how can I pass the error message in that case ???

答:
What about handling API results with these two major parts:

HTTP Error Responses:

Not use this for business process errors:

401 and 403 Auth and security - Describing the error cause in header

404 Not found - Only when the request is about downloading file

and the other HTTP error status codes...

Business errors and failed requests:

Responding in 200 (OK) HTTP status code and use a desired response format like this:

status (bool): Is True when the request is successful.

data: The result of API.

message (Object)

code (int [enum]): Defined by an enum describing the message type (for example model state, bad request, unavailable services, business policy, access restriction policy and so on...)

messages ( string[] ): The messages (like invalid fields or message[s] of process and etc...)


问:
Send and process form data
I have a form that I would like to send to saveConfig.php so that the data can be saved into a MySQL database. I would like to pass the selected form options, as well as the total.

```<code><form id="configSave" action="" class="hide-submit">
<div class="btn-configure" id="configSave">
<span class="pcButtonText">
Save
</span>
</div>

<ul id="radio" class="input-list">
  <li>
    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateTotal();">
    <label for="item-1">Item 1</label>
  </li>
  <li>
    <input id="item-2" name="config-prod" value="2.00" type="radio" onchange="updateTotal();">
    <label for="item-2">Item 2</label>
  </li>
  <li>
    <input id="item-3" name="config-prod" value="3.00" type="radio" onchange="updateTotal();">
    <label for="item-3">Item 3</label>
  </li>
</ul>

<select id="plist" name="partlist" onchange="save();">
  <option value="99.99">CPU 1</option>
  <option value="123.00">CPU 2</option>
  <option value="250.54">CPU 3</option>
</select>
</form>
<br>
Total: <input id="total" type="text">

<script>
        $('#configSave').on('click', function () {
            alert("ok");
            $.ajax({
                url: 'saveConfig.php',
                type: "POST",
                data: $('#configSave').serialize(),
                dataType: "JSON",
                contentType: 'application/json;charset=UTF-8',
                success: function (data) {
                    alert('saved');
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            });
        });
    </script>
</code>```

Within the PHP file, how can I access the form data so I can save it into the database?
I get this error message:

```<code>SyntaxError: Unexpected token < in JSON at position 2
</code>```

答:
That error means the JSON string that is arriving at the PHP server is malformed. The reason it is malformed is because you cannot serialize a
. The serialize method is designed to serialize form elements Encode a set of form elements as a string for submission..

Change:

```<code>data: $('#configSave').serialize(),
</code>```

To:

```<code>data: $('#form').serialize(),
</code>```

Title: Send and process form data

Body:
I have a form that I would like to send to saveConfig.php so that the data can be saved into a MySQL database. I would like to pass the selected form options, as well as the total.

<form id="configSave" action="" class="hide-submit">

Save

    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateTotal();">
    Item 1

    <input id="item-2" name="config-prod" value="2.00" type="radio" onchange="updateTotal();">
    Item 2

    <input id="item-3" name="config-prod" value="3.00" type="radio" onchange="updateTotal();">
    Item 3

<select id="plist" name="partlist" onchange="save();">
  <option value="99.99">CPU 1</option>
  <option value="123.00">CPU 2</option>
  <option value="250.54">CPU 3</option>
</select>
</form>

Total: <input id="total" type="text">

Within the PHP file, how can I access the form data so I can save it into the database?
I get this error message:

SyntaxError: Unexpected token < in JSON at position 2

Body:
That error means the JSON string that is arriving at the PHP server is malformed. The reason it is malformed is because you cannot serialize a <div>. The serialize method is designed to serialize form elements Encode a set of form elements as a string for submission..

Change:

data: $('#configSave').serialize(),

To:

data: $('#form').serialize(),


问:
How to trigger a re-render of a plot when a column content of the plotted data changes with the use of reactive element
In the following app the user can select points in the plot by dragging, which should swap their  Selected state between 0 and 1

points will get a shape and color depending on their 0 / 1 state, as a visual support for a user to select/deselect model parameters for the next model run.

in the version of the plots I had in my real app, the plotted data is a reactive variable values$RFImp_FP1 but I found out that the plot does not re-render when the content of column Selected of that data.table (or data.frame)  changes.

Therefore I am trying to change it to a reactive object, but I'm failing to figure out how to change the Selected column of reactive data.table `RFImp

my attempts (comments in the code) so far produce either an assign error, or an infinite loop.

P.S.: Since i'm coding the stuff with lapply as I am using the code block several times in my app (identical "modules" with different serial number and using different data as the app takes the user through sequential stages of processing data), the second approach with values (app 2) has my preference as this allows me to do things like this:

lapply(c('FP1', 'FP2'), function(FP){
values[[paste('RFAcc', FP, sep = '_')]] <- ".... code to select a dataframe from model result list object values[[paste('RFResults', FP, sep = '_']]$Accuracy...."
which as far as I know can't be done with objectname <- reactive({....}) as you can't paste on the left side of the <- here

REACTIVE OBJECT APPROACH:

```<code>library(shiny)
library(plotly)
library(dplyr)
library(data.table)

ui <- fluidPage(
  plotlyOutput('RFAcc_FP1',  width = 450)
)

server <- function(input, output, session) {

  values <- reactiveValues()

  observe({
    if(!is.null(RFImp_FP1()$Selected)) {
      parsToChange <- event_data("plotly_selected", source = 'RFAcc_FP1')$y
      if(!is.null(event_data("plotly_selected", source = 'RFAcc_FP1'))){
        data_df <- RFImp_FP1()
        data_df <- data_df %>% .[, Selected := if_else(Variables %in% parsToChange, 1-Selected, Selected)]
        # how to get the reactive Data frame to update the selected

        # values$Selected <- data_df$Selected    #creates infinite loop.....
        # RFImp_FP1$Selected <- data_df$Selected # throws an error
      }
    }
  })

  RFImp_FP1 <- reactive({
    # in real app the dataframe RFImp_FP1 is a part of a list with randomForest results,
    RFImp_FP1 <- data.table( MeanDecreaseAccuracy =  runif(10, min = 0, max = 1), Variables = letters[1:10])
    RFImp_FP1$Selected <- 1
    # RFImp_FP1$Selected <- if(!is.null(values$Selected)){
    #  values$Selected } else {1 }

    RFImp_FP1
  })

  output$RFAcc_FP1 <- renderPlotly({
    RFImp_FP1()[order(MeanDecreaseAccuracy)]
    RFImp_score <- RFImp_FP1()
    plotheight <- length(RFImp_score$Variables) * 80
    p <- plot_ly(data = RFImp_score,
                 source = 'RFAcc_FP1',
                 height = plotheight,
                 width = 450)  %>%
      add_trace(x = RFImp_score$MeanDecreaseAccuracy,
                y = RFImp_score$Variables,
                type = 'scatter',
                mode = 'markers',
                color = factor(RFImp_score$Selected),
                colors = c('#1b73c1', '#797979'),
                symbol = factor(RFImp_score$Selected),
                symbols = c('circle','x'),
                marker = list(size  = 6),
                hoverinfo = "text",
                text = ~paste ('<br>', 'Parameter: ', RFImp_score$Variables,
                               '<br>',  'Mean decrease accuracy: ', format(round(RFImp_score$MeanDecreaseAccuracy*100, digits = 2), nsmall = 2),'%',
                               sep = '')) %>%
      layout(
        margin = list(l = 160, r= 20, b = 70, t = 50),
        hoverlabel = list(font=list( color = '#1b73c1'), bgcolor='#f7fbff'),
        xaxis =  list(title = 'Mean decrease accuracy index (%)',
                      tickformat = "%",
                      showgrid = F,
                      showline = T,
                      zeroline = F,
                      nticks = 5,
                      font = list(size = 8),
                      ticks = "outside",
                      ticklen = 5,
                      tickwidth = 2,
                      tickcolor = toRGB("black")
        ),
        yaxis =  list(categoryarray = RFImp_score$Variables,
                      autorange = T,
                      showgrid = F,
                      showline = T,
                      autotick = T,
                      font = list(size = 8),
                      ticks = "outside",
                      ticklen = 5,
                      tickwidth = 2,
                      tickcolor = toRGB("black")
        ),
        dragmode =  "select"
      ) %>%  add_annotations(x = 0.5,
                             y = 1.05,
                             textangle = 0,
                             font = list(size = 14,
                                         color = 'black'),
                             text = "Contribution to accuracy",
                             showarrow = F,
                             xref='paper',
                             yref='paper')

    p <- p %>% config(displayModeBar = F)
    p
  })

}
shinyApp(ui, server)
</code>```

PREVIOUS reactiveValues() approach:
as you can see, with this app, the plot does not update when selecting a region in the plot even though the code changes the content of column Selected

```<code>ui <- fluidPage(
  actionButton(inputId = 'Go', label = 'Go'),
  plotlyOutput('RFAcc_FP1',  width = 450)
)

server <- function(input, output, session) {
  values <- reactiveValues()

  observe({
    if(!is.null(values$RFImp_FP1)) {
      parsToChange <- event_data("plotly_selected", source = 'RFAcc_FP1')$y
      if(!is.null(event_data("plotly_selected", source = 'RFAcc_FP1'))){
        data_df <- values$RFImp_FP1
        data_df <- data_df %>% .[, Selected := if_else(Variables %in% parsToChange, 1-Selected, Selected)]
        values$RFImp_FP1 <- data_df
      }
    }
  })

  observeEvent(input$Go, {
      values$RFImp_FP1 <- data.table(MeanDecreaseAccuracy =  runif(10, min = 0, max = 1), Variables = letters[1:10])
      values$RFImp_FP1$Selected <- 1
  })

  output$RFAcc_FP1 <- renderPlotly({
    if(!is.null(values$RFImp_FP1)) {

      RFImp_score <- values$RFImp_FP1[order(MeanDecreaseAccuracy)]
      plotheight <- length(RFImp_score$Variables) * input$testme
      p <- plot_ly(data = RFImp_score,
                   source = 'RFAcc_FP1',
                   height = plotheight,
                   width = 450)  %>%
        add_trace(x = RFImp_score$MeanDecreaseAccuracy,
                  y = RFImp_score$Variables,
                  type = 'scatter',
                  mode = 'markers',
                  color = factor(RFImp_score$Selected),
                  colors = c('#1b73c1', '#797979'),
                  symbol = factor(RFImp_score$Selected),
                  symbols = c('circle','x'),
                  marker = list(size  = 6),
                  hoverinfo = "text",
                  text = ~paste ('<br>', 'Parameter: ', RFImp_score$Variables,
                                 '<br>',  'Mean decrease accuracy: ', format(round(RFImp_score$MeanDecreaseAccuracy*100, digits = 2), nsmall = 2),'%',
                                 sep = '')) %>%
        layout(
          margin = list(l = 160, r= 20, b = 70, t = 50),
          hoverlabel = list(font=list( color = '#1b73c1'), bgcolor='#f7fbff'),
          xaxis =  list(title = 'Mean decrease accuracy index (%)',
                        tickformat = "%",
                        showgrid = F,
                        showline = T,
                        zeroline = F,
                        nticks = 5,
                        font = list(size = 8),
                        ticks = "outside",
                        ticklen = 5,
                        tickwidth = 2,
                        tickcolor = toRGB("black")
          ),
          yaxis =  list(categoryarray = RFImp_score$Variables,
                        autorange = T,
                        showgrid = F,
                        showline = T,
                        autotick = T,
                        font = list(size = 8),
                        ticks = "outside",
                        ticklen = 5,
                        tickwidth = 2,
                        tickcolor = toRGB("black")
          ),
          dragmode =  "select"
        ) %>%  add_annotations(x = 0.5,
                               y = 1.05,
                               textangle = 0,
                               font = list(size = 14,
                                           color = 'black'),
                               text = "Contribution to accuracy",
                               showarrow = F,
                               xref='paper',
                               yref='paper')

      p$elementId <- NULL   ## to surpress warning of widgetid
      p <- p %>% config(displayModeBar = F)
      p

    } else {
      p <- plot_ly( type = 'scatter', mode = 'markers',  height = '400px', width = 450) %>% layout(
        margin = list(l = 160, r= 20, b = 70, t = 50),
        xaxis = list(title = 'Mean decrease accuracy index', range= c(0,1), nticks = 2, showline = TRUE),
        yaxis = list(title = 'Model input variables', range = c(0,1), nticks = 2, showline = TRUE)) %>%
        add_annotations(x = 0.5, y = 1.1, textangle = 0, font = list(size = 14, color = 'black'),
                        text = 'Contribution to accuracy',
                        showarrow = F, xref='paper', yref='paper')
      p$elementId <- NULL
      p <- p %>% config(displayModeBar = F)
      p}
  })

}
shinyApp(ui, server)
</code>```

答:
Not sure if this is what you want (it´s a bit weird that the plot updates with random numbers after selecting points ;-) ), but I hope it helps.

Instead of using a normal observer I use observeEvent that fires when selecting something in the plot. I generally prefer observeEvent to catch an event. This triggers an update ob a reactiveValues value, which will initially be NULL

```<code>library(shiny)
library(plotly)
library(dplyr)
library(data.table)

testDF <- data.table( MeanDecreaseAccuracy =  runif(10, min = 0, max = 1), Variables = letters[1:10])
testDF$Selected <- T

ui <- fluidPage(
    plotlyOutput('RFAcc_FP1',  width = 450)
)

server <- function(input, output, session) {

    values <- reactiveValues(val = NULL)

    observeEvent(event_data("plotly_selected", source = 'RFAcc_FP1')$y, {
        values$val <- runif(1, min = 0, max = 1)
    })

    RFImp_FP1 <- reactive({
        RFImp_FP1 <- testDF
        if(!is.null(values$val)) {
            parsToChange <- event_data("plotly_selected", source = 'RFAcc_FP1')$y
            RFImp_FP1 <- RFImp_FP1 %>% .[, Selected := if_else(Variables %in% parsToChange, 1-Selected, Selected)]
        } else { }
        # in real app the dataframe RFImp_FP1 is a part of a list with randomForest results,
        RFImp_FP1
        # RFImp_FP1$Selected <- if(!is.null(values$Selected)){
        #  values$Selected } else {1 }

    })

    output$RFAcc_FP1 <- renderPlotly({

        RFImp_score <- RFImp_FP1()[order(MeanDecreaseAccuracy)]
        plotheight <- length(RFImp_score$Variables) * 80
        p <- plot_ly(data = RFImp_score,
                     source = 'RFAcc_FP1',
                     height = plotheight,
                     width = 450)  %>%
            add_trace(x = RFImp_score$MeanDecreaseAccuracy,
                      y = RFImp_score$Variables,
                      type = 'scatter',
                      mode = 'markers',
                      color = factor(RFImp_score$Selected),
                      colors = c('#1b73c1', '#797979'),
                      symbol = factor(RFImp_score$Selected),
                      symbols = c('circle','x'),
                      marker = list(size  = 6),
                      hoverinfo = "text",
                      text = ~paste ('<br>', 'Parameter: ', RFImp_score$Variables,
                                     '<br>',  'Mean decrease accuracy: ', format(round(RFImp_score$MeanDecreaseAccuracy*100, digits = 2), nsmall = 2),'%',
                                     sep = '')) %>%
            layout(
                margin = list(l = 160, r= 20, b = 70, t = 50),
                hoverlabel = list(font=list( color = '#1b73c1'), bgcolor='#f7fbff'),
                xaxis =  list(title = 'Mean decrease accuracy index (%)',
                              tickformat = "%",
                              showgrid = F,
                              showline = T,
                              zeroline = F,
                              nticks = 5,
                              font = list(size = 8),
                              ticks = "outside",
                              ticklen = 5,
                              tickwidth = 2,
                              tickcolor = toRGB("black")
                ),
                yaxis =  list(categoryarray = RFImp_score$Variables,
                              autorange = T,
                              showgrid = F,
                              showline = T,
                              autotick = T,
                              font = list(size = 8),
                              ticks = "outside",
                              ticklen = 5,
                              tickwidth = 2,
                              tickcolor = toRGB("black")
                ),
                dragmode =  "select"
            ) %>%  add_annotations(x = 0.5,
                                   y = 1.05,
                                   textangle = 0,
                                   font = list(size = 14,
                                               color = 'black'),
                                   text = "Contribution to accuracy",
                                   showarrow = F,
                                   xref='paper',
                                   yref='paper')

        p <- p %>% config(displayModeBar = F)
        p
    })

}
shinyApp(ui, server)
</code>```

Body:
In the following app the user can select points in the plot by dragging, which should swap their  Selected state between 0 and 1

points will get a shape and color depending on their 0 / 1 state, as a visual support for a user to select/deselect model parameters for the next model run.

in the version of the plots I had in my real app, the plotted data is a reactive variable values$RFImp_FP1 but I found out that the plot does not re-render when the content of column Selected of that data.table (or data.frame)  changes.

Therefore I am trying to change it to a reactive object, but I'm failing to figure out how to change the Selected column of reactive data.table `RFImp

my attempts (comments in the code) so far produce either an assign error, or an infinite loop.

P.S.: Since i'm coding the stuff with lapply as I am using the code block several times in my app (identical "modules" with different serial number and using different data as the app takes the user through sequential stages of processing data), the second approach with values (app 2) has my preference as this allows me to do things like this:

lapply(c('FP1', 'FP2'), function(FP){
values[[paste('RFAcc', FP, sep = '_')]] <- ".... code to select a dataframe from model result list object values[[paste('RFResults', FP, sep = '_']]$Accuracy...."
which as far as I know can't be done with objectname <- reactive({....}) as you can't paste on the left side of the <- here

REACTIVE OBJECT APPROACH:

library(shiny)
library(plotly)
library(dplyr)
library(data.table)

ui <- fluidPage(
  plotlyOutput('RFAcc_FP1',  width = 450)
)

server <- function(input, output, session) {

  values <- reactiveValues()

  observe({
    if(!is.null(RFImp_FP1()$Selected)) {
      parsToChange <- event_data("plotly_selected", source = 'RFAcc_FP1')$y
      if(!is.null(event_data("plotly_selected", source = 'RFAcc_FP1'))){
        data_df <- RFImp_FP1()
        data_df <- data_df %>% .[, Selected := if_else(Variables %in% parsToChange, 1-Selected, Selected)]
        # how to get the reactive Data frame to update the selected

        # values$Selected <- data_df$Selected    #creates infinite loop.....
        # RFImp_FP1$Selected <- data_df$Selected # throws an error
      }
    }
  })

  RFImp_FP1 <- reactive({
    # in real app the dataframe RFImp_FP1 is a part of a list with randomForest results,
    RFImp_FP1 <- data.table( MeanDecreaseAccuracy =  runif(10, min = 0, max = 1), Variables = letters[1:10])
    RFImp_FP1$Selected <- 1
    # RFImp_FP1$Selected <- if(!is.null(values$Selected)){
    #  values$Selected } else {1 }

    RFImp_FP1
  })

  output$RFAcc_FP1 <- renderPlotly({
    RFImp_FP1()[order(MeanDecreaseAccuracy)]
    RFImp_score <- RFImp_FP1()
    plotheight <- length(RFImp_score$Variables) * 80
    p <- plot_ly(data = RFImp_score,
                 source = 'RFAcc_FP1',
                 height = plotheight,
                 width = 450)  %>%
      add_trace(x = RFImp_score$MeanDecreaseAccuracy,
                y = RFImp_score$Variables,
                type = 'scatter',
                mode = 'markers',
                color = factor(RFImp_score$Selected),
                colors = c('#1b73c1', '#797979'),
                symbol = factor(RFImp_score$Selected),
                symbols = c('circle','x'),
                marker = list(size  = 6),
                hoverinfo = "text",
                text = ~paste ('
', 'Parameter: ', RFImp_score$Variables,
                               '
',  'Mean decrease accuracy: ', format(round(RFImp_score$MeanDecreaseAccuracy*100, digits = 2), nsmall = 2),'%',
                               sep = '')) %>%
      layout(
        margin = list(l = 160, r= 20, b = 70, t = 50),
        hoverlabel = list(font=list( color = '#1b73c1'), bgcolor='#f7fbff'),
        xaxis =  list(title = 'Mean decrease accuracy index (%)',
                      tickformat = "%",
                      showgrid = F,
                      showline = T,
                      zeroline = F,
                      nticks = 5,
                      font = list(size = 8),
                      ticks = "outside",
                      ticklen = 5,
                      tickwidth = 2,
                      tickcolor = toRGB("black")
        ),
        yaxis =  list(categoryarray = RFImp_score$Variables,
                      autorange = T,
                      showgrid = F,
                      showline = T,
                      autotick = T,
                      font = list(size = 8),
                      ticks = "outside",
                      ticklen = 5,
                      tickwidth = 2,
                      tickcolor = toRGB("black")
        ),
        dragmode =  "select"
      ) %>%  add_annotations(x = 0.5,
                             y = 1.05,
                             textangle = 0,
                             font = list(size = 14,
                                         color = 'black'),
                             text = "Contribution to accuracy",
                             showarrow = F,
                             xref='paper',
                             yref='paper')

    p <- p %>% config(displayModeBar = F)
    p
  })

}
shinyApp(ui, server)

PREVIOUS reactiveValues() approach:
as you can see, with this app, the plot does not update when selecting a region in the plot even though the code changes the content of column Selected

ui <- fluidPage(
  actionButton(inputId = 'Go', label = 'Go'),
  plotlyOutput('RFAcc_FP1',  width = 450)
)

server <- function(input, output, session) {
  values <- reactiveValues()

  observe({
    if(!is.null(values$RFImp_FP1)) {
      parsToChange <- event_data("plotly_selected", source = 'RFAcc_FP1')$y
      if(!is.null(event_data("plotly_selected", source = 'RFAcc_FP1'))){
        data_df <- values$RFImp_FP1
        data_df <- data_df %>% .[, Selected := if_else(Variables %in% parsToChange, 1-Selected, Selected)]
        values$RFImp_FP1 <- data_df
      }
    }
  })

  observeEvent(input$Go, {
      values$RFImp_FP1 <- data.table(MeanDecreaseAccuracy =  runif(10, min = 0, max = 1), Variables = letters[1:10])
      values$RFImp_FP1$Selected <- 1
  })

  output$RFAcc_FP1 <- renderPlotly({
    if(!is.null(values$RFImp_FP1)) {

      RFImp_score <- values$RFImp_FP1[order(MeanDecreaseAccuracy)]
      plotheight <- length(RFImp_score$Variables) * input$testme
      p <- plot_ly(data = RFImp_score,
                   source = 'RFAcc_FP1',
                   height = plotheight,
                   width = 450)  %>%
        add_trace(x = RFImp_score$MeanDecreaseAccuracy,
                  y = RFImp_score$Variables,
                  type = 'scatter',
                  mode = 'markers',
                  color = factor(RFImp_score$Selected),
                  colors = c('#1b73c1', '#797979'),
                  symbol = factor(RFImp_score$Selected),
                  symbols = c('circle','x'),
                  marker = list(size  = 6),
                  hoverinfo = "text",
                  text = ~paste ('
', 'Parameter: ', RFImp_score$Variables,
                                 '
',  'Mean decrease accuracy: ', format(round(RFImp_score$MeanDecreaseAccuracy*100, digits = 2), nsmall = 2),'%',
                                 sep = '')) %>%
        layout(
          margin = list(l = 160, r= 20, b = 70, t = 50),
          hoverlabel = list(font=list( color = '#1b73c1'), bgcolor='#f7fbff'),
          xaxis =  list(title = 'Mean decrease accuracy index (%)',
                        tickformat = "%",
                        showgrid = F,
                        showline = T,
                        zeroline = F,
                        nticks = 5,
                        font = list(size = 8),
                        ticks = "outside",
                        ticklen = 5,
                        tickwidth = 2,
                        tickcolor = toRGB("black")
          ),
          yaxis =  list(categoryarray = RFImp_score$Variables,
                        autorange = T,
                        showgrid = F,
                        showline = T,
                        autotick = T,
                        font = list(size = 8),
                        ticks = "outside",
                        ticklen = 5,
                        tickwidth = 2,
                        tickcolor = toRGB("black")
          ),
          dragmode =  "select"
        ) %>%  add_annotations(x = 0.5,
                               y = 1.05,
                               textangle = 0,
                               font = list(size = 14,
                                           color = 'black'),
                               text = "Contribution to accuracy",
                               showarrow = F,
                               xref='paper',
                               yref='paper')

      p$elementId <- NULL   ## to surpress warning of widgetid
      p <- p %>% config(displayModeBar = F)
      p

    } else {
      p <- plot_ly( type = 'scatter', mode = 'markers',  height = '400px', width = 450) %>% layout(
        margin = list(l = 160, r= 20, b = 70, t = 50),
        xaxis = list(title = 'Mean decrease accuracy index', range= c(0,1), nticks = 2, showline = TRUE),
        yaxis = list(title = 'Model input variables', range = c(0,1), nticks = 2, showline = TRUE)) %>%
        add_annotations(x = 0.5, y = 1.1, textangle = 0, font = list(size = 14, color = 'black'),
                        text = 'Contribution to accuracy',
                        showarrow = F, xref='paper', yref='paper')
      p$elementId <- NULL
      p <- p %>% config(displayModeBar = F)
      p}
  })

}
shinyApp(ui, server)

Body:
Not sure if this is what you want (it´s a bit weird that the plot updates with random numbers after selecting points ;-) ), but I hope it helps.

Instead of using a normal observer I use observeEvent that fires when selecting something in the plot. I generally prefer observeEvent to catch an event. This triggers an update ob a reactiveValues value, which will initially be NULL

library(shiny)
library(plotly)
library(dplyr)
library(data.table)

testDF <- data.table( MeanDecreaseAccuracy =  runif(10, min = 0, max = 1), Variables = letters[1:10])
testDF$Selected <- T

ui <- fluidPage(
    plotlyOutput('RFAcc_FP1',  width = 450)
)

server <- function(input, output, session) {

    values <- reactiveValues(val = NULL)

    observeEvent(event_data("plotly_selected", source = 'RFAcc_FP1')$y, {
        values$val <- runif(1, min = 0, max = 1)
    })

    RFImp_FP1 <- reactive({
        RFImp_FP1 <- testDF
        if(!is.null(values$val)) {
            parsToChange <- event_data("plotly_selected", source = 'RFAcc_FP1')$y
            RFImp_FP1 <- RFImp_FP1 %>% .[, Selected := if_else(Variables %in% parsToChange, 1-Selected, Selected)]
        } else { }
        # in real app the dataframe RFImp_FP1 is a part of a list with randomForest results,
        RFImp_FP1
        # RFImp_FP1$Selected <- if(!is.null(values$Selected)){
        #  values$Selected } else {1 }

    })

    output$RFAcc_FP1 <- renderPlotly({

        RFImp_score <- RFImp_FP1()[order(MeanDecreaseAccuracy)]
        plotheight <- length(RFImp_score$Variables) * 80
        p <- plot_ly(data = RFImp_score,
                     source = 'RFAcc_FP1',
                     height = plotheight,
                     width = 450)  %>%
            add_trace(x = RFImp_score$MeanDecreaseAccuracy,
                      y = RFImp_score$Variables,
                      type = 'scatter',
                      mode = 'markers',
                      color = factor(RFImp_score$Selected),
                      colors = c('#1b73c1', '#797979'),
                      symbol = factor(RFImp_score$Selected),
                      symbols = c('circle','x'),
                      marker = list(size  = 6),
                      hoverinfo = "text",
                      text = ~paste ('<br>', 'Parameter: ', RFImp_score$Variables,
                                     '<br>',  'Mean decrease accuracy: ', format(round(RFImp_score$MeanDecreaseAccuracy*100, digits = 2), nsmall = 2),'%',
                                     sep = '')) %>%
            layout(
                margin = list(l = 160, r= 20, b = 70, t = 50),
                hoverlabel = list(font=list( color = '#1b73c1'), bgcolor='#f7fbff'),
                xaxis =  list(title = 'Mean decrease accuracy index (%)',
                              tickformat = "%",
                              showgrid = F,
                              showline = T,
                              zeroline = F,
                              nticks = 5,
                              font = list(size = 8),
                              ticks = "outside",
                              ticklen = 5,
                              tickwidth = 2,
                              tickcolor = toRGB("black")
                ),
                yaxis =  list(categoryarray = RFImp_score$Variables,
                              autorange = T,
                              showgrid = F,
                              showline = T,
                              autotick = T,
                              font = list(size = 8),
                              ticks = "outside",
                              ticklen = 5,
                              tickwidth = 2,
                              tickcolor = toRGB("black")
                ),
                dragmode =  "select"
            ) %>%  add_annotations(x = 0.5,
                                   y = 1.05,
                                   textangle = 0,
                                   font = list(size = 14,
                                               color = 'black'),
                                   text = "Contribution to accuracy",
                                   showarrow = F,
                                   xref='paper',
                                   yref='paper')

        p <- p %>% config(displayModeBar = F)
        p
    })

}
shinyApp(ui, server)


问:
Data allocation in the distributed databases
How to optimize a data allocation in the distributed database?

Are there any software products for solving this problem?

For example:

There are some number of connected servers for the distributed database. Each server simultaneously is a client of this database.

The database has many tables.

We have statistic of queries from each client to the particular table.

There is some price of the data storage for each server.
There is some price of transfer, known for each pair of the server and the client.

Objective: To allocate all tables (or parts of tables) on servers in the best possible way.

To solve this problem we can apply a variety of heuristic algorithms: genetic algorithms, evolution strategies, ant algorithms, etc.

But I could not find any ready software tools that would have implemented these algorithms.

Are there any tools to solve this problem for distributed databases (Oracle or others)?

Does anybody care about it?

And maybe somebody has examples of systems with a query statistic with the distributed database that have been optimized in this way?

Thanks!

答:
I think it is a lot easier to just store the data in a centralized database and configure a cache for the various locations. Because the different locations are not likely able to be in the same grid, the cache configuration should be a synchronous cache because in an async cache solution the order of updates in the database might not be the order in which the updates were applied.
The cache will reduce lots of query network traffic and improve performance for the remote locations, compared to when they should access the database directly.
The Oracle In-Memory Cache Database Option could be worth investigating. Works for 10.2.0.4 databases and above, using the 11.2.1.8 version of what was formerly called TimesTen. A great option.
The algorithms you asked for, are effectively caching algorithm. Make sure that often used data is close to the consumer, at the best possible price. If you can spend more on memory, more data fits in. The LRU will take care for cleaning of less often used data from the cache.</p>

ContentLicense: CC BY-SA 2.5


问:
How to sort array by enum value
I have an array and one of its elements uses enum.
I want to sort the array by enum.

```<code>public enum EnumList
    {
        Spring,
        Summer,
        Fall,
        Winter,
        Unknown
    };
</code>```

My array looks like this:

```<code> Class1[] arr = new class1[7];

        arr[0] = new class1(101, "Some string", Class1.EnumList.Spring, 100, DateTime.Parse("10/13/2008"));
 .
 .
 array continues..
</code>```

How do I sort by enum value?

答:
You can use IEnumerable.OrderBy.

If you sort by an enum-value it will look at the underlying type (usually int) and sort by that. This means the best solution would just be like this:

arr.OrderBy(c => c.TheEnumProperty);

This method will return a sorted IEnumerable which you can cast back to an array with IEnumerable.ToArray.

Title: How to sort array by enum value

Body:
I have an array and one of its elements uses enum.
I want to sort the array by enum.

public enum EnumList
    {
        Spring,
        Summer,
        Fall,
        Winter,
        Unknown
    };

My array looks like this:

 Class1[] arr = new class1[7];

        arr[0] = new class1(101, "Some string", Class1.EnumList.Spring, 100, DateTime.Parse("10/13/2008"));
 .
 .
 array continues..

How do I sort by enum value?


问:
make sound loop Alerts every five seconds
I'm trying to write a simple loop sound Alerts every five seconds

How can i add it please

tweak for cydia

Tweak.xm template

```<code>     if (lowenabled) {
      if ([batString isEqualToString:lowbatPercent_String]) {
        if (lowplayer) {
          return;
        }

        if (lowsound == 0)
          soundFilePath = [NSString stringWithFormat:@"%@/Super Mario.mp3", bundlePrefix];
        else if (lowsound == 1)
          soundFilePath = [NSString stringWithFormat:@"%@/Super Mario 1.mp3", bundlePrefix];

        soundFileURL = [NSURL fileURLWithPath:soundFilePath];

        lowplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
        lowplayer.numberOfLoops = 3;
        [lowplayer play];
      } else {
        if (lowplayer) {
          lowplayer = nil;
        }
      }
    }
}
%end
</code>```

答:
Include to fire timer:

```<code>NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(playSound:) userInfo:nil repeats:YES];
[timer fire];
</code>```

Put method in the same class:

```<code>- (void)playSound {
 // the code you included here that plays the sound
}
</code>```

Docs for NSTimer's fire method

Body:
I'm trying to write a simple loop sound Alerts every five seconds

How can i add it please

tweak for cydia

Tweak.xm template

     if (lowenabled) {
      if ([batString isEqualToString:lowbatPercent_String]) {
        if (lowplayer) {
          return;
        }

        if (lowsound == 0)
          soundFilePath = [NSString stringWithFormat:@"%@/Super Mario.mp3", bundlePrefix];
        else if (lowsound == 1)
          soundFilePath = [NSString stringWithFormat:@"%@/Super Mario 1.mp3", bundlePrefix];

        soundFileURL = [NSURL fileURLWithPath:soundFilePath];

        lowplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
        lowplayer.numberOfLoops = 3;
        [lowplayer play];
      } else {
        if (lowplayer) {
          lowplayer = nil;
        }
      }
    }
}
%end

Body:
Include to fire timer:

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(playSound:) userInfo:nil repeats:YES];
[timer fire];

Put method in the same class:

- (void)playSound {
 // the code you included here that plays the sound
}

Docs for NSTimer's fire method


问:
What does a question mark mean in the head of a Nix function definition?
For example in:

```<code>{ nixpkgs ? import <nixpkgs> {}, compiler ? "ghc7102" }:
nixpkgs.pkgs.haskell.packages.${compiler}.callPackage ./foo.nix { }
</code>```

What does compiler ? "ghc7102" indicate? I assume a conditional - but can't find this mentioned under https://nixos.org/nix/manual/#sec-constructs

答: Your example is a function with a set pattern and default values. Everything before : is the pattern and the expressions after ? are default values.

Body:
For example in:

{ nixpkgs ? import <nixpkgs> {}, compiler ? "ghc7102" }:
nixpkgs.pkgs.haskell.packages.${compiler}.callPackage ./foo.nix { }

What does compiler ? "ghc7102" indicate? I assume a conditional - but can't find this mentioned under https://nixos.org/nix/manual/#sec-constructs


问:
How to solve "noHandlerFound" in Spring MVC with Java based configuration?
I am developing Spring MVC application with Java based configuration. I am facing this error org.springframework.web.servlet.DispatcherServlet noHandlerFound and WARNING: No mapping found for HTTP request with URI [/solution/clients/css/form.css] in DispatcherServlet with name 'dispatcher'

AppConfig.java

```<code>@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan(basePackages = "solution")
@PropertySource("classpath:persistence-mysql.properties")
public class AppConfig {
    @Autowired
    private Environment env;

    private Logger logger = Logger.getLogger(getClass().getName());

    @Bean
    public ViewResolver viewResolver() {

        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");

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

SolutionDispatcherServletInitializer.java

```<code>public class SolutionDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { AppConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}
</code>```

Controller class:

```<code>@Controller
@RequestMapping("/clients")
public class ClientsController {

    // Injection of Service Class
    @Autowired
    private ClientService clientService;

    @GetMapping("/list")
    public String listClients(Model theModel) {

        // Getting Clients From SERVICE Class
        List<Clients> theClients = clientService.getClients();

        // Adding Clients to Model(Entity Class)
        theModel.addAttribute("clientsModel", theClients);

        return "list-clients";
    }
}
</code>```

View:

```<code><h3>ALL CLIENTS</h3>
  <div class="addnew-form">

  <table>
     <tr>
        <th class="trtd">First Name</th>
        <th class="trtd">Last Name</th>
        <th class="trtd">Email</th>
        <th class="trtd">Mobile Number</th>
        <th class="trtd">City</th>
        <th class="trtd">Country</th>
        <th class="trtd">Domain</th>
        <th class="trtd">View</th>
        <th class="trtd">Action</th>
     </tr>

     <!-- LOOP -->

     <c:forEach var="tempClients" items="${clientsModel}">
     <tr>
       <td class="trtd">${tempClients.firstName}</td>
       <td class="trtd">${tempClients.lastName}</td>
       <td class="trtd">${tempClients.email}</td>
       <td class="trtd">${tempClients.mobileNumber}</td>
       <td class="trtd">${tempClients.city}</td>
       <td class="trtd">${tempClients.country}</td>
       <td class="trtd">${tempClients.domain}</td>
     </tr>
     </c:forEach>
  </table>
</code>```

Error Messages:

```<code>May 31, 2019 12:40:22 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/solution/clients/css/form.css] in DispatcherServlet with name 'dispatcher'
WARNING: No mapping found for HTTP request with URI [/solution/$%7BpageContext.request.contextPath%7D/clients/list] in DispatcherServlet with name 'dispatcher'
</code>```

The Output on Web browser looks something like this. My Database has connectivity with the application. But still not getting data from MySql. The output displays some JSP code. ${tempClients.firstName}

Image:Click here for Image

Thanks in Advance

答:
I think you need to change @Controller annotation to @RestController.

So your controller will be like

```<code>@RestController
@RequestMapping("/clients")
public class ClientsController {

    // Injection of Service Class
    @Autowired
    private ClientService clientService;

    @GetMapping("/list")
    public String listClients(Model theModel) {

        // Getting Clients From SERVICE Class
        List<Clients> theClients = clientService.getClients();

        // Adding Clients to Model(Entity Class)
        theModel.addAttribute("clientsModel", theClients);

        return "list-clients";
    }
}
</code>```

Body:
I am developing Spring MVC application with Java based configuration. I am facing this error org.springframework.web.servlet.DispatcherServlet noHandlerFound and WARNING: No mapping found for HTTP request with URI [/solution/clients/css/form.css] in DispatcherServlet with name 'dispatcher'

AppConfig.java

@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan(basePackages = "solution")
@PropertySource("classpath:persistence-mysql.properties")
public class AppConfig {
    @Autowired
    private Environment env;

    private Logger logger = Logger.getLogger(getClass().getName());

    @Bean
    public ViewResolver viewResolver() {

        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");

        return viewResolver;
    }
}

SolutionDispatcherServletInitializer.java

public class SolutionDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { AppConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

Controller class:

@Controller
@RequestMapping("/clients")
public class ClientsController {

    // Injection of Service Class
    @Autowired
    private ClientService clientService;

    @GetMapping("/list")
    public String listClients(Model theModel) {

        // Getting Clients From SERVICE Class
        List<Clients> theClients = clientService.getClients();

        // Adding Clients to Model(Entity Class)
        theModel.addAttribute("clientsModel", theClients);

        return "list-clients";
    }
}

View:

ALL CLIENTS

        First Name
        Last Name
        Email
        Mobile Number
        City
        Country
        Domain
        View
        Action

     <c:forEach var="tempClients" items="${clientsModel}">

       ${tempClients.firstName}
       ${tempClients.lastName}
       ${tempClients.email}
       ${tempClients.mobileNumber}
       ${tempClients.city}
       ${tempClients.country}
       ${tempClients.domain}

     </c:forEach>

Error Messages:

May 31, 2019 12:40:22 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/solution/clients/css/form.css] in DispatcherServlet with name 'dispatcher'
WARNING: No mapping found for HTTP request with URI [/solution/$%7BpageContext.request.contextPath%7D/clients/list] in DispatcherServlet with name 'dispatcher'

The Output on Web browser looks something like this. My Database has connectivity with the application. But still not getting data from MySql. The output displays some JSP code. ${tempClients.firstName}

Image:Click here for Image

Thanks in Advance

Body:
I think you need to change @Controller annotation to @RestController.

So your controller will be like

@RestController
@RequestMapping("/clients")
public class ClientsController {

    // Injection of Service Class
    @Autowired
    private ClientService clientService;

    @GetMapping("/list")
    public String listClients(Model theModel) {

        // Getting Clients From SERVICE Class
        List<Clients> theClients = clientService.getClients();

        // Adding Clients to Model(Entity Class)
        theModel.addAttribute("clientsModel", theClients);

        return "list-clients";
    }
}


答:
Something like</p>

```<code>var sortedByEnum = arr.GroupBy(x => x.enum).OrderBy(group => group);
</code>```

Title: How to sort array by enum value

Body:
Something like

var sortedByEnum = arr.GroupBy(x => x.enum).OrderBy(group => group);


问:
Using the number of statements in a function as a constant for memory allocation
I have a function which executes a bunch of tests. Whenever a new test is created, the function gets one or two more lines. And - the result is pushed back into an array. So it goes something like this (simplified):

```<code>void foo(int *results) {
    auto index { 0 };

    results[i++] = test_1(some, args, here);
    results[i++] = test_1(some, other_args, here);

    results[i++] = test_2(some, args, here);

    results[i++] = test_3(some, args, here);

    // etc. etc.
}

void bar() {
    auto results = new int/* magic */];
    foo(results);
}
</code>```

I want to use the number of statements in this function to allocate space for the results (the line in bar()). I cannot use a dynamically-reallocated structure like an std::vector or a list etc. - since I am precluded from allocating any memory due to hardware restrictions.

Now, I could just manually count the lines - and this would work. But then whenever I add another test I would have to remember to update the magical constant.

Is there some way to do the counting with the result usable for the "magic" expression?

Note: Since I'm a scrupulous man with no dignity, I am willing to stoop to the use of macros.

答:
As you haven't specified any language version, though, did tag it with constexpr, I've solved this making use of C++17. This without any dirty macros. Instead, I'm relying on CTAD (Constructor template argument deduction).

First of all, I've assumed your functions are constexpr. That way, everything can be done at compile-time. (In the resulting code, you don't even see memory being used for the array.

```<code>constexpr int test_1(int a, int b, int c)
{
    return a + b + c;
}

constexpr int test_2(int a, int b, int c)
{
    return a * b * c;
}
</code>```

This isn't strictly needed, however, it can move unneeded calculations to compile time. It also allows propagating constexpr upto the final variable. That way, you could guarantee that none of the calculations will happen at run-time.

```<code>static constexpr auto myArr = createFilledArray();
</code>```

However, the most important part is CTAD. A new C++17 feature that allows deducing the template arguments of your class based on the values that are passed at the constructor.
Instead of first creating an array, I create the array directly with all the different values that you pass to it. Since you haven't provided any arguments in your example, I assume they are known at compile time, which is again required for the constexpr waterfall. However, more importantly, I assume the number of elements is known at compile time.

By constructing all arguments when calling the constructor of std::array, there is no need for specifying its template arguments (note also the auto as return type). This gets deduced as std::array<int, 3> for this example.

```<code>constexpr auto createFilledArray(){
    std::array a
        {
            test_1(1, 2, 3),
            test_1(4, 5, 6),
            test_2(7, 8, 9),
        };
    return a;
}

int main(int, char**)
{
    return myArr.size(); // Returns 3
}
</code>```

Code at compiler explorer

From what I'm aware, there is a proposal for C++20 that is intended to make std::vector constexpr. However, none of the compilers I've tested at compiler explorer support this. This will most likely allow you to write code based on std::vector and use that at compile time. In other words, the allocated memory that represents your data, will be part of your executable.

A quick attempt of what your code could look like can be found here at compiler explorer. (However, it ain't compiling at this point)

Body:
I have a function which executes a bunch of tests. Whenever a new test is created, the function gets one or two more lines. And - the result is pushed back into an array. So it goes something like this (simplified):

void foo(int *results) {
    auto index { 0 };

    results[i++] = test_1(some, args, here);
    results[i++] = test_1(some, other_args, here);

    results[i++] = test_2(some, args, here);

    results[i++] = test_3(some, args, here);

    // etc. etc.
}

void bar() {
    auto results = new int/* magic */];
    foo(results);
}

I want to use the number of statements in this function to allocate space for the results (the line in bar()). I cannot use a dynamically-reallocated structure like an std::vector or a list etc. - since I am precluded from allocating any memory due to hardware restrictions.

Now, I could just manually count the lines - and this would work. But then whenever I add another test I would have to remember to update the magical constant.

Is there some way to do the counting with the result usable for the "magic" expression?

Note: Since I'm a scrupulous man with no dignity, I am willing to stoop to the use of macros.

Body:
As you haven't specified any language version, though, did tag it with constexpr, I've solved this making use of C++17. This without any dirty macros. Instead, I'm relying on CTAD (Constructor template argument deduction).

First of all, I've assumed your functions are constexpr. That way, everything can be done at compile-time. (In the resulting code, you don't even see memory being used for the array.

constexpr int test_1(int a, int b, int c)
{
    return a + b + c;
}

constexpr int test_2(int a, int b, int c)
{
    return a * b * c;
}

This isn't strictly needed, however, it can move unneeded calculations to compile time. It also allows propagating constexpr upto the final variable. That way, you could guarantee that none of the calculations will happen at run-time.

static constexpr auto myArr = createFilledArray();

However, the most important part is CTAD. A new C++17 feature that allows deducing the template arguments of your class based on the values that are passed at the constructor.
Instead of first creating an array, I create the array directly with all the different values that you pass to it. Since you haven't provided any arguments in your example, I assume they are known at compile time, which is again required for the constexpr waterfall. However, more importantly, I assume the number of elements is known at compile time.

By constructing all arguments when calling the constructor of std::array, there is no need for specifying its template arguments (note also the auto as return type). This gets deduced as std::array<int, 3> for this example.

constexpr auto createFilledArray(){
    std::array a
        {
            test_1(1, 2, 3),
            test_1(4, 5, 6),
            test_2(7, 8, 9),
        };
    return a;
}

int main(int, char**)
{
    return myArr.size(); // Returns 3
}

Code at compiler explorer

From what I'm aware, there is a proposal for C++20 that is intended to make std::vector constexpr. However, none of the compilers I've tested at compiler explorer support this. This will most likely allow you to write code based on std::vector and use that at compile time. In other words, the allocated memory that represents your data, will be part of your executable.

A quick attempt of what your code could look like can be found here at compiler explorer. (However, it ain't compiling at this point)


问:
have gdb read automatically ./.gdbinit
With the pristine gdb (Debian 8.2.1-2) while debugging RefPerSys (GPLv3+, on gitlab) commit ec4ab756d302056cace0b on my Linux/x86-64/Debian Sid AMD2970WX desktop, I am reproducibly getting

```<code>rimski.x86_64 ~/refpersys 14:39 .0 % gdb --args ./refpersys --object-tinybenchmark1
GNU gdb (Debian 8.2.1-2) 8.2.1
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./refpersys...done.
warning: File "/home/basile/refpersys/.gdbinit" auto-loading has been declined by your `auto-load safe-path' set to "$debugdir:$datadir/auto-load".
To enable execution of this file add
    add-auto-load-safe-path /home/basile/refpersys/.gdbinit
line to your configuration file "/home/basile/.gdbinit".
To completely disable this security protection add
    set auto-load safe-path /
line to your configuration file "/home/basile/.gdbinit".
For more information about this security protection see the
"Auto-loading safe path" section in the GDB manual.  E.g., run from the shell:
    info "(gdb)Auto-loading safe path"
</code>```

What is the magic to have my ./.gdbinit digested by such a gdb invocation without diagnostics? That  .gdbinit  contains:

```<code># file refpersys/.gdbinit
# GPLv3+ licensed
add-auto-load-safe-path ./.gdbinit
break abort
break rps_fatal_stop_at
set max-value-size 67108864
</code>```

I could (and did that in the past) rebuild gdb from its source code. But today, I am lame, and prefer focusing on my bugs.

FWIW

```<code>(gdb) show configuration
This GDB was configured as follows:
   configure --host=x86_64-linux-gnu --target=x86_64-linux-gnu
             --with-auto-load-dir=$debugdir:$datadir/auto-load
             --with-auto-load-safe-path=$debugdir:$datadir/auto-load
             --with-expat
             --with-gdb-datadir=/usr/share/gdb (relocatable)
             --with-jit-reader-dir=/usr/lib/gdb (relocatable)
             --without-libunwind-ia64
             --with-lzma
             --with-babeltrace
             --with-intel-pt
             --disable-libmcheck
             --without-mpfr
             --with-python=/usr (relocatable)
             --without-guile
             --with-separate-debug-dir=/usr/lib/debug (relocatable)
             --with-system-gdbinit=/etc/gdb/gdbinit
</code>```

答:
Just as the warning says when you launch gdb:

```<code>To enable execution of this file add
    add-auto-load-safe-path /home/basile/refpersys/.gdbinit
line to your configuration file "/home/basile/.gdbinit".
</code>```

It seems like you've misunderstood and added the line into the .gdbinit file within your repo but it needs to go into your home directory.

If the .gdbinit file doesn't yet exist in your home directory, you can create it and only add the needed line above, and it should work.

Title: have gdb read automatically ./.gdbinit

Body:
With the pristine gdb (Debian 8.2.1-2) while debugging RefPerSys (GPLv3+, on gitlab) commit ec4ab756d302056cace0b on my Linux/x86-64/Debian Sid AMD2970WX desktop, I am reproducibly getting

rimski.x86_64 ~/refpersys 14:39 .0 % gdb --args ./refpersys --object-tinybenchmark1
GNU gdb (Debian 8.2.1-2) 8.2.1
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./refpersys...done.
warning: File "/home/basile/refpersys/.gdbinit" auto-loading has been declined by your `auto-load safe-path' set to "$debugdir:$datadir/auto-load".
To enable execution of this file add
    add-auto-load-safe-path /home/basile/refpersys/.gdbinit
line to your configuration file "/home/basile/.gdbinit".
To completely disable this security protection add
    set auto-load safe-path /
line to your configuration file "/home/basile/.gdbinit".
For more information about this security protection see the
"Auto-loading safe path" section in the GDB manual.  E.g., run from the shell:
    info "(gdb)Auto-loading safe path"

What is the magic to have my ./.gdbinit digested by such a gdb invocation without diagnostics? That  .gdbinit  contains:

# file refpersys/.gdbinit
# GPLv3+ licensed
add-auto-load-safe-path ./.gdbinit
break abort
break rps_fatal_stop_at
set max-value-size 67108864

I could (and did that in the past) rebuild gdb from its source code. But today, I am lame, and prefer focusing on my bugs.

FWIW

(gdb) show configuration
This GDB was configured as follows:
   configure --host=x86_64-linux-gnu --target=x86_64-linux-gnu
             --with-auto-load-dir=$debugdir:$datadir/auto-load
             --with-auto-load-safe-path=$debugdir:$datadir/auto-load
             --with-expat
             --with-gdb-datadir=/usr/share/gdb (relocatable)
             --with-jit-reader-dir=/usr/lib/gdb (relocatable)
             --without-libunwind-ia64
             --with-lzma
             --with-babeltrace
             --with-intel-pt
             --disable-libmcheck
             --without-mpfr
             --with-python=/usr (relocatable)
             --without-guile
             --with-separate-debug-dir=/usr/lib/debug (relocatable)
             --with-system-gdbinit=/etc/gdb/gdbinit

Body:
Just as the warning says when you launch gdb:

To enable execution of this file add
    add-auto-load-safe-path /home/basile/refpersys/.gdbinit
line to your configuration file "/home/basile/.gdbinit".

It seems like you've misunderstood and added the line into the .gdbinit file within your repo but it needs to go into your home directory.

If the .gdbinit file doesn't yet exist in your home directory, you can create it and only add the needed line above, and it should work.


问:
R: Convert Fraction to Decimal within a String
I want to convert some fraction characters in a string to a decimal format, but keep the context of the rest of the string, so that:

becomes:

This answer is similar to what I'm looking to do, but when adjusted to my use case, it doesn't keep the remainder of the string, and seems to break down entirely when used on a data frame.

```<code>library(gsubfn)

calc <- function(s) {
  x <- c(if (length(s) == 2) 0, as.numeric(s), 0:1)
  x[1] + x[2] / x[3]
}

ff <- c('1 1/2', '2 3/4', '2/3', '11 1/4', '5/4')
sapply(strapplyc(ff, "\\d+"), calc)
#1.5000000  2.7500000  0.6666667 11.2500000  1.2500000

ef = c('1 1/2" ant', '2 3/4" apple', '2/3" berry', '11" 1/4 plum', '5/4" orange')
sapply(strapplyc(ef, "\\d+"), calc)
#1.5000000  2.7500000  0.6666667 11.2500000  1.2500000

df <- as.data.frame(ef)
sapply(strapplyc(df$ef, "\\d+"), calc)
#2 3 4 1 5
</code>```

答:
An option would be gsubfn

```<code>gsubfn("(\\d+) (\\d+)", ~ as.numeric(x) + as.numeric(y),
     gsubfn("(\\d+)/(\\d+)", ~ as.numeric(x)/as.numeric(y), ef))
</code>```

Body:
I want to convert some fraction characters in a string to a decimal format, but keep the context of the rest of the string, so that:

becomes:

This answer is similar to what I'm looking to do, but when adjusted to my use case, it doesn't keep the remainder of the string, and seems to break down entirely when used on a data frame.

library(gsubfn)

calc <- function(s) {
  x <- c(if (length(s) == 2) 0, as.numeric(s), 0:1)
  x[1] + x[2] / x[3]
}

ff <- c('1 1/2', '2 3/4', '2/3', '11 1/4', '5/4')
sapply(strapplyc(ff, "\\d+"), calc)
#1.5000000  2.7500000  0.6666667 11.2500000  1.2500000

ef = c('1 1/2" ant', '2 3/4" apple', '2/3" berry', '11" 1/4 plum', '5/4" orange')
sapply(strapplyc(ef, "\\d+"), calc)
#1.5000000  2.7500000  0.6666667 11.2500000  1.2500000

df <- as.data.frame(ef)
sapply(strapplyc(df$ef, "\\d+"), calc)
#2 3 4 1 5

Body:
An option would be gsubfn

gsubfn("(\\d+) (\\d+)", ~ as.numeric(x) + as.numeric(y),
     gsubfn("(\\d+)/(\\d+)", ~ as.numeric(x)/as.numeric(y), ef))


问:
Why it is needed to invoke close after finish in nodejs stream?
Here is a source:

```<code>var http = require('http');
var fs = require('fs');

var download = function(url, dest, cb) {
  var file = fs.createWriteStream(dest);
  var request = http.get(url, function(response) {
    response.pipe(file);
    file.on('finish', function() {
      file.close(cb);  // close() is async, call cb after close completes.
    });
  }).on('error', function(err) { // Handle errors
    fs.unlink(dest); // Delete the file async. (But we don't check the result)
    if (cb) cb(err.message);
  });
};
</code>```

Why file.close(cb) is called on finish event? Does not finish close a stream? Look strange.

答:
Before NodeJS version 5.5.0 it was the application's responsibility to close the file descriptor and make sure there's no file descriptor leak.

In v5.5 they introduced the autoClose attribute for the method createWriteStream with a default value of true which means on error or finish the file descriptor will be closed automatically.

The source you're looking at was before v5.5.0 (2016-01-21)

Body:
Here is a source:

var http = require('http');
var fs = require('fs');

var download = function(url, dest, cb) {
  var file = fs.createWriteStream(dest);
  var request = http.get(url, function(response) {
    response.pipe(file);
    file.on('finish', function() {
      file.close(cb);  // close() is async, call cb after close completes.
    });
  }).on('error', function(err) { // Handle errors
    fs.unlink(dest); // Delete the file async. (But we don't check the result)
    if (cb) cb(err.message);
  });
};

Why file.close(cb) is called on finish event? Does not finish close a stream? Look strange.


问:
Axios params returns data inside an object instead of array
When using axios.get without the params all data is returned inside of array like it is supposed to be, but when I use params all objects are returned inside an object and I'cant map it. How can put all objects inside of array? If I try to put it inside of array it only puts the object that contains all the objects I need.

```<code>axios
  .get("http://api.digiart.lt/items/", { params: { category: "latte" } })
  .then((response) => {
    let coffee = response.data;
    this.props.onLoadData(coffee);
    console.log(response.data);
  });
</code>```

returns like this

```<code>{…}
count: 10,
items: Object { 0: {…}, 2: {…}, 3: {…}, … },
<prototype>: Object { … }
</code>```

supposed to be like this

```<code>Array(41) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
</code>```

答:
That's the default response from the http://api.digiart.lt/items/ API

Use Object.keys to map it to an array.

// Request -> http://api.digiart.lt/items?category=latte
var response = {
  "items": {
    "0": {
      "title": "Abbey's White Chocolate Latte",
      "description": "I created this recipe for my little sister, Abbey, who`s a latte fanatic. She was blown away, and drained it to the last drop! This makes one VERY large, indulgent latte, and could probably serve two. Enjoy!\n\nIngredients:\n1 1\/2 cups milk\n1 tablespoon heavy cream\n1\/8 teaspoon vanilla extract\n1 tablespoon white sugar\n1\/2 cup brewed espresso\n1\/4 cup white chocolate chips, chopped",
      "url": "https:\/\/www.allrecipes.com\/recipe\/137332\/abbeys-white-chocolate-latte\/",
      "category": "latte",
      "date": "2018-05-31",
      "img": "https:\/\/images.media-allrecipes.com\/userphotos\/560x315\/2107268.jpg"
    },
    "2": {
      "title": "Brown Sugar-Caramel Latte",
      "description": "Sometimes coffee is a dessert in itself. This is one of my favorite morning treats to make a Monday seem less intimidating. You'll need a battery-powered milk frother or it's just not the same.\n\nIngredients:\n1 tablespoon brown sugar\n1\/4 cup half-and-half\n1 tablespoon caramel ice cream topping\n3\/4 cup hot, brewed coffee",
      "url": "https:\/\/www.allrecipes.com\/recipe\/139119\/brown-sugar-caramel-latte\/",
      "category": "latte",
      "date": "2017-08-22",
      "img": "https:\/\/images.media-allrecipes.com\/userphotos\/560x315\/707064.jpg"
    }
    // .. More items
  }
}

var arr = []
Object.keys(response.items).forEach(key => arr.push(response.items[key]))
console.log(arr)```

Body:
When using axios.get without the params all data is returned inside of array like it is supposed to be, but when I use params all objects are returned inside an object and I'cant map it. How can put all objects inside of array? If I try to put it inside of array it only puts the object that contains all the objects I need.

axios
  .get("http://api.digiart.lt/items/", { params: { category: "latte" } })
  .then((response) => {
    let coffee = response.data;
    this.props.onLoadData(coffee);
    console.log(response.data);
  });

returns like this

{…}
count: 10,
items: Object { 0: {…}, 2: {…}, 3: {…}, … },
<prototype>: Object { … }

supposed to be like this

Array(41) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]


问:
Tkinter GUI disappears when file selection dialog appears
Background:
I am building a GUI for a PDF app. This app requires that the user select the location of the file and provide some additional information so that a cover page can be generated and then appended to a PDF. I have chosen Tkinter to create the GUI for this app. I developing on Mac OS.

Problem:
I am able to generate a file selection dialog upon pressing the form's button, however, the GUI disappears immediately after the file selection dialog appears. Does someone know what is causing this?

```<code>from tkinter import *
from tkinter import filedialog

root = Tk()
Label(root, text='Submittal No. ').grid(row=0)
Label(root, text='Project Name ').grid(row=1)
Label(root, text='Product Name ').grid(row=2)
e1 = Entry(root)
e2 = Entry(root)
e3 = Entry(root)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)

def fileSelector():
    root.withdraw()
    root.fileName = filedialog.askopenfilename()
    print(root.fileName)

Button(root, text='Select PDF file ', command=fileSelector).grid(row=3)

if __name__ == "__main__":
    mainloop()
</code>```

答:
In your fileSelector function, the line root.withdraw is used to make the root window disappear while keeping it alive.

You can either remove that line so the GUI stays visible or if you want to prevent the user from interacting with the GUI until the filedialog.askopenfilename is resolved, you can make the window reappear later with the deiconify function :

```<code>def fileSelector():
    global filename
    root.withdraw()
    root.fileName = filedialog.askopenfilename()
    root.deiconify()
    print(root.fileName)
</code>```

Body:
Background:
I am building a GUI for a PDF app. This app requires that the user select the location of the file and provide some additional information so that a cover page can be generated and then appended to a PDF. I have chosen Tkinter to create the GUI for this app. I developing on Mac OS.

Problem:
I am able to generate a file selection dialog upon pressing the form's button, however, the GUI disappears immediately after the file selection dialog appears. Does someone know what is causing this?

from tkinter import *
from tkinter import filedialog

root = Tk()
Label(root, text='Submittal No. ').grid(row=0)
Label(root, text='Project Name ').grid(row=1)
Label(root, text='Product Name ').grid(row=2)
e1 = Entry(root)
e2 = Entry(root)
e3 = Entry(root)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)

def fileSelector():
    root.withdraw()
    root.fileName = filedialog.askopenfilename()
    print(root.fileName)

Button(root, text='Select PDF file ', command=fileSelector).grid(row=3)

if __name__ == "__main__":
    mainloop()

Body:
In your fileSelector function, the line root.withdraw is used to make the root window disappear while keeping it alive.

You can either remove that line so the GUI stays visible or if you want to prevent the user from interacting with the GUI until the filedialog.askopenfilename is resolved, you can make the window reappear later with the deiconify function :

def fileSelector():
    global filename
    root.withdraw()
    root.fileName = filedialog.askopenfilename()
    root.deiconify()
    print(root.fileName)


问:
yum module not talking to telnet
I've written a playbook using a tag feature so that I can control the execution of the playbook. The Playbook is correct syntax-wise.

ansible-playbook tags.yml --syntax-check

Gives no Error

However, when I run the playbook, I receive the following error

```<code>fatal: [controlnode]: FAILED! => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "msg": "Failure talking to yum: near \"telnet\": syntax error"}
</code>```

Here is the complete playbook

```<code>---
- hosts: RHEL7
  become: yes
  connection: ssh
  gather_facts: no
  tasks:
    - name: Installing packages
      yum: pkg=['telnet','httpd','tree'] state=installed
      tags:
        - packages
    - name: Verifying if those packages are installed properly
      raw: rpm -qa --last | head -5 > /home/packages.log
      tags:
        - verification_packages
</code>```

答:
Try full YAML syntax:</p>

```<code>- name: Ensure packages are installed
  yum:
    state: installed
    name:
      - telnet
      - httpd
      - tree
</code>```

Title: yum module not talking to telnet

Body:
I've written a playbook using a tag feature so that I can control the execution of the playbook. The Playbook is correct syntax-wise.

ansible-playbook tags.yml --syntax-check

Gives no Error

However, when I run the playbook, I receive the following error

fatal: [controlnode]: FAILED! => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "msg": "Failure talking to yum: near \"telnet\": syntax error"}

Here is the complete playbook

---
- hosts: RHEL7
  become: yes
  connection: ssh
  gather_facts: no
  tasks:
    - name: Installing packages
      yum: pkg=['telnet','httpd','tree'] state=installed
      tags:
        - packages
    - name: Verifying if those packages are installed properly
      raw: rpm -qa --last | head -5 > /home/packages.log
      tags:
        - verification_packages

Body:
Try full YAML syntax:

- name: Ensure packages are installed
  yum:
    state: installed
    name:
      - telnet
      - httpd
      - tree


问:
Automatically checking for a new version of my application
Trying to honor a feature request from our customers, I'd like that my application, when Internet is available, check on our website if a new version is available.

The problem is that I have no idea about what have to be done on the server side.

I can imagine that my application (developped in C++ using Qt) has to send a request (HTTP ?) to the server, but what is going to respond to this request ? In order to go through firewalls, I guess I'll have to use port 80 ? Is this correct ?

Or, for such a feature, do I have to ask our network admin to open a specific port number through which I'll communicate ?

@pilif : thanks for your detailed answer. There is still something which is unclear for me :

like

http://www.example.com/update?version=1.2.4

Then you can return what ever you want, probably also the download-URL of the installer of the new version.

How do I return something ? Will it be a php or asp page (I know nothing about PHP nor ASP, I have to confess) ? How can I decode the ?version=1.2.4 part in order to return something accordingly ?

答: On the server you could just have a simple file "latestversion.txt" which contains the version number (and maybe download URL) of the latest version. The client then just needs to read this file using a simple HTTP request (yes, to port 80) to retrieve http://your.web.site/latestversion.txt, which you can then parse to get the version number. This way you don't need any fancy server code --- you just need to add a simple file to your existing website.</p>

OwnerDisplayName: Jérôme

LastEditorDisplayName: Jérôme

OwnerDisplayName: Anthony Williams


问:
How to program shortcut for website with j2me and netbeans?
I want make application for my blackberry ..

the application is .. shortcut for my website .. like when I'm click he go to my website .

答: The BlackBerry knowledge center has a guide "How To - Create a web icon" that provides the code to do it.</p>