问:
How do I reference a specific cell in kendo grid with javascript?
Right now I have a kendo grid with 2 rows and 6 columns. I need some logic to highlight a specific cell but I don't know how to reference a cell. I used this example but I don't know what to pass in as the id.

```<code>myHub.client.highlightRow = function (id) {
    var data = $("#MyGrid").data("kendoGrid").dataSource.data();
    for (var i = 0; i < data.length; i++) {
        var dataItem = data[i];
        if (dataItem.id == id) {
            //alert(dataItem.uid);
            $("#MyGrid").data("kendoGrid").tbody.find("tr[data-uid=" + dataItem.uid + "]").effect("highlight", { color: "#f35800" }, 3000);
        }
    }
};
</code>```

Here is a sample of my grid.

```<code>function loadGaugeTable(siteId, dashboardId, endDate, planType) {
    var today = new Date();
    var metricTitle = "Metric, as of " + monthNames[today.getMonth()] + " " + today.getDate();
    var containerSize = $("#gaugeMetricTableContainer").width();
    var apiPath = "/" + getAppPath() + "/Analytics/api/DashboardApi/getAllMetricTDData" + "?siteId=" + siteId +
                                                                                "&dashboardId=" + dashboardId +
                                                                                "&endDate=" + escape(endDate) +
                                                                                "&planType=" + planType

    $("#gaugeMetricTable").kendoGrid({

        attributes: {
            "class": "table-cell",
            style: "font-size: 10px"
        },
        height: 250,
        selectable: "row",
        scrollable: true,
        sortable: true,
        filterable: true,
        columns: [
            { field: "MetricName", title: metricTitle, width: containerSize / 4 + "px" },
            { field: "DailyActual", title: "Daily Actual", format: decimalPrecisionFormat },
            { field: "DailyTarget", title: "Daily Target", format: decimalPrecisionFormat },
            { field: "MTDActual", title: "MTD Actual", format: decimalPrecisionFormat },
            { field: "MTDTarget", title: "MTD Target", format: decimalPrecisionFormat },
            { field: "YTDActual", title: "YTD Actual", format: decimalPrecisionFormat },
            { field: "YTDTarget", title: "YTD Target", format: decimalPrecisionFormat }

        ],
        dataSource: {
            transport: {
                read: {
                    dataType: "json", url: apiPath
                }
            }
        },

    });
}
</code>```

How would I go about referencing say row 1, column 2.

```<code>var data = $("#gaugeMetricTable").data("kendoGrid").dataSource.data();
data[0];
</code>```

Returns the data for the row but I can't reference the column with data[0].columns[1].

答:
You can apply try using the following steps:

First, get a specific row from which you want apply CSS to specific column by name. In my requirement found row using row's UID with specific column class name.

```<code>var grid = $("#grid").data("kendoGrid");

var row = grid.dataSource.getByUid("your-row-uid");
</code>```

And at last, get your selected row specific cell value by its class name.

```<code>$(row).find("td.className").css("background-color", "lightblue");
</code>```

Body:
Right now I have a kendo grid with 2 rows and 6 columns. I need some logic to highlight a specific cell but I don't know how to reference a cell. I used this example but I don't know what to pass in as the id.

myHub.client.highlightRow = function (id) {
    var data = $("#MyGrid").data("kendoGrid").dataSource.data();
    for (var i = 0; i < data.length; i++) {
        var dataItem = data[i];
        if (dataItem.id == id) {
            //alert(dataItem.uid);
            $("#MyGrid").data("kendoGrid").tbody.find("tr[data-uid=" + dataItem.uid + "]").effect("highlight", { color: "#f35800" }, 3000);
        }
    }
};

Here is a sample of my grid.

function loadGaugeTable(siteId, dashboardId, endDate, planType) {
    var today = new Date();
    var metricTitle = "Metric, as of " + monthNames[today.getMonth()] + " " + today.getDate();
    var containerSize = $("#gaugeMetricTableContainer").width();
    var apiPath = "/" + getAppPath() + "/Analytics/api/DashboardApi/getAllMetricTDData" + "?siteId=" + siteId +
                                                                                "&dashboardId=" + dashboardId +
                                                                                "&endDate=" + escape(endDate) +
                                                                                "&planType=" + planType

    $("#gaugeMetricTable").kendoGrid({

        attributes: {
            "class": "table-cell",
            style: "font-size: 10px"
        },
        height: 250,
        selectable: "row",
        scrollable: true,
        sortable: true,
        filterable: true,
        columns: [
            { field: "MetricName", title: metricTitle, width: containerSize / 4 + "px" },
            { field: "DailyActual", title: "Daily Actual", format: decimalPrecisionFormat },
            { field: "DailyTarget", title: "Daily Target", format: decimalPrecisionFormat },
            { field: "MTDActual", title: "MTD Actual", format: decimalPrecisionFormat },
            { field: "MTDTarget", title: "MTD Target", format: decimalPrecisionFormat },
            { field: "YTDActual", title: "YTD Actual", format: decimalPrecisionFormat },
            { field: "YTDTarget", title: "YTD Target", format: decimalPrecisionFormat }

        ],
        dataSource: {
            transport: {
                read: {
                    dataType: "json", url: apiPath
                }
            }
        },

    });
}

How would I go about referencing say row 1, column 2.

var data = $("#gaugeMetricTable").data("kendoGrid").dataSource.data();
data[0];

Returns the data for the row but I can't reference the column with data[0].columns[1].

Body:
You can apply try using the following steps:

First, get a specific row from which you want apply CSS to specific column by name. In my requirement found row using row's UID with specific column class name.

var grid = $("#grid").data("kendoGrid");

var row = grid.dataSource.getByUid("your-row-uid");

And at last, get your selected row specific cell value by its class name.

$(row).find("td.className").css("background-color", "lightblue");


来源: stackexchange

问:
Error: Type Queue Does Not Take Parameter - What's the difference between Queues and Priority Queues?
I get the error message Type Queue does not Take Parameters. When I replace alter the Queue line to a PriorityQueue this error disappears and it compiles fine. What is the difference and how can I change it to compile and a regular queue? </p>

```<code>import java.util.*;

public class StackOneTwoMultiply {

    public static void main(String[] args) {

        int first, second;

        Stack<Integer> s = new Stack<Integer>();  //stack called s
        PriorityQueue<Integer> q = new PriorityQueue<Integer>();

        for (int i = 10; i > 0; i--) {      //filling the stack (what order to fill was not specifified)
            s.push(i);
        }

        while (!s.isEmpty()) {
            first = s.pop();
            second = s.pop();
            q.offer(first * second);
            System.out.println(q.peek());
        }

        System.out.print(q);
    }
}
</code>```

答:
If you want to use Queue instead of PriorityQueue create and object of LinkedList class with Queue interface.

```<code>import java.util.*;
.....
Queue<Integer> q = new LinkedList<Integer>();
.....
</code>```

and if it doesn't work even after this then try using specified import statements :

```<code>import java.util.LinkedList;
import java.util.Queue;
</code>```

Sometimes it happens that it won't accept parameters with java.util.*

code snippet of error due to java.util.*

ContentLicense: CC BY-SA 3.0

Body:
I get the error message Type Queue does not Take Parameters. When I replace alter the Queue line to a PriorityQueue this error disappears and it compiles fine. What is the difference and how can I change it to compile and a regular queue?

import java.util.*;

public class StackOneTwoMultiply {

    public static void main(String[] args) {

        int first, second;

        Stack<Integer> s = new Stack<Integer>();  //stack called s
        PriorityQueue<Integer> q = new PriorityQueue<Integer>();

        for (int i = 10; i > 0; i--) {      //filling the stack (what order to fill was not specifified)
            s.push(i);
        }

        while (!s.isEmpty()) {
            first = s.pop();
            second = s.pop();
            q.offer(first * second);
            System.out.println(q.peek());
        }

        System.out.print(q);
    }
}

Body:
If you want to use Queue instead of PriorityQueue create and object of LinkedList class with Queue interface.

import java.util.*;
.....
Queue<Integer> q = new LinkedList<Integer>();
.....

and if it doesn't work even after this then try using specified import statements :

import java.util.LinkedList;
import java.util.Queue;

Sometimes it happens that it won't accept parameters with java.util.*

code snippet of error due to java.util.*

ContentLicense: CC BY-SA 4.0


问:
TypeError: Cannot read property 'forEach' of undefined Javascript
Following is the code in which I am getting Cannot read property 'forEach' of undefined.

const print2 = function(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )```
</div>
</div>
</p>

<p>Let me know what I am doing wrong here, though if I do -</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function print2(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )</code>```

this is working fine.

答:
You need a semicolon at the end of the variable declaration.

const print2 = function(x, y) {
  console.log(x*y)
};

[1,2,3,4].forEach( x => print2(x, 20) )```
</div>
</div>
</p>

<p>Without the semicolon, it's being treated as</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const print2 = function(x, y) {
  console.log(x*y)
}[1,2,3,4].forEach( x => print2(x, 20) )</code>```

[1,2,3,4] is being interpreted as an property accessor, not an array, and the comma operator returns the last value 4. Since the function doesn't have a 4 property, that returns undefined, and then you try to call .forEach() on that.

Body:
Following is the code in which I am getting Cannot read property 'forEach' of undefined.

const print2 = function(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )

Let me know what I am doing wrong here, though if I do -

function print2(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )

this is working fine.

Body:
You need a semicolon at the end of the variable declaration.

const print2 = function(x, y) {
  console.log(x*y)
};

[1,2,3,4].forEach( x => print2(x, 20) )

Without the semicolon, it's being treated as

const print2 = function(x, y) {
  console.log(x*y)
}[1,2,3,4].forEach( x => print2(x, 20) )

[1,2,3,4] is being interpreted as an property accessor, not an array, and the comma operator returns the last value 4. Since the function doesn't have a 4 property, that returns undefined, and then you try to call .forEach() on that.


问:
Colorbar next to seaborn pairplot
```<code>from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
from pandas import DataFrame

# generate 2d classification dataset
X, y = make_blobs(n_samples=100, centers=3, n_features=2)
# scatter plot, dots colored by class value
df1 = DataFrame(dict(x=X[:,0], y=X[:,1], label=y))

norm = plt.Normalize(df1.x.min(), df1.x.max())
sm = plt.cm.ScalarMappable(cmap=sns.cubehelix_palette(df1['x'].max(), start=.5, rot=-.75,as_cmap=True), norm=norm)
sm.set_array([])

ax=sns.pairplot(df1,vars=['x','y'],
            hue='label',
            palette=sns.cubehelix_palette(df1['x'].max(), start=.5, rot=-.75),
            diag_kind=None,plot_kws={"s": 50})

ax._legend.remove()

# ax.set_ylabel('WT04: Pairplot for features')
cbar=ax.fig.colorbar(sm)
m0=int(np.floor(df1.x.min()))            # colorbar min value
m4=int(np.ceil(df1.x.max()))             # colorbar max value
m1=int(1*(m4-m0)/4.0 + m0)               # colorbar mid value 1
m2=int(2*(m4-m0)/4.0 + m0)               # colorbar mid value 2
m3=int(3*(m4-m0)/4.0 + m0)               # colorbar mid value 3
cbar.set_ticks([m0,m1,m2,m3,m4])
cbar.set_ticklabels([m0,m1,m2,m3,m4])

ax.fig.suptitle('WT04: Pairplot for features',y=0.99)
plt.subplots_adjust(top=0.94)
plt.show()

plt.savefig('result.png')
</code>```

Generates this plot

However, I would like to have the colorbar to the right of the pairplot, and not the bottom right. How can this be done? Some of my pairplots have other dimensions, so something scalable would be nice.

答:
You can try adding the colorbar with plt:

```<code>ax._legend.remove()

# remove this colorbar
# cbar=ax.fig.colorbar(sm)

m0=int(np.floor(df1.x.min()))            # colorbar min value
m4=int(np.ceil(df1.x.max()))             # colorbar max value
m1=int(1*(m4-m0)/4.0 + m0)               # colorbar mid value 1
m2=int(2*(m4-m0)/4.0 + m0)               # colorbar mid value 2
m3=int(3*(m4-m0)/4.0 + m0)               # colorbar mid value 3

ax.fig.suptitle('WT04: Pairplot for features',y=0.99)

# use this colorbar
cbar = plt.colorbar(sm, ax=ax.axes)

cbar.set_ticks([m0,m1,m2,m3,m4])
cbar.set_ticklabels([m0,m1,m2,m3,m4])
</code>```

Output:

Title: Colorbar next to seaborn pairplot

Body:
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
from pandas import DataFrame

# generate 2d classification dataset
X, y = make_blobs(n_samples=100, centers=3, n_features=2)
# scatter plot, dots colored by class value
df1 = DataFrame(dict(x=X[:,0], y=X[:,1], label=y))

norm = plt.Normalize(df1.x.min(), df1.x.max())
sm = plt.cm.ScalarMappable(cmap=sns.cubehelix_palette(df1['x'].max(), start=.5, rot=-.75,as_cmap=True), norm=norm)
sm.set_array([])

ax=sns.pairplot(df1,vars=['x','y'],
            hue='label',
            palette=sns.cubehelix_palette(df1['x'].max(), start=.5, rot=-.75),
            diag_kind=None,plot_kws={"s": 50})

ax._legend.remove()

# ax.set_ylabel('WT04: Pairplot for features')
cbar=ax.fig.colorbar(sm)
m0=int(np.floor(df1.x.min()))            # colorbar min value
m4=int(np.ceil(df1.x.max()))             # colorbar max value
m1=int(1*(m4-m0)/4.0 + m0)               # colorbar mid value 1
m2=int(2*(m4-m0)/4.0 + m0)               # colorbar mid value 2
m3=int(3*(m4-m0)/4.0 + m0)               # colorbar mid value 3
cbar.set_ticks([m0,m1,m2,m3,m4])
cbar.set_ticklabels([m0,m1,m2,m3,m4])

ax.fig.suptitle('WT04: Pairplot for features',y=0.99)
plt.subplots_adjust(top=0.94)
plt.show()

plt.savefig('result.png')

Generates this plot

However, I would like to have the colorbar to the right of the pairplot, and not the bottom right. How can this be done? Some of my pairplots have other dimensions, so something scalable would be nice.

Body:
You can try adding the colorbar with plt:

ax._legend.remove()

# remove this colorbar
# cbar=ax.fig.colorbar(sm)

m0=int(np.floor(df1.x.min()))            # colorbar min value
m4=int(np.ceil(df1.x.max()))             # colorbar max value
m1=int(1*(m4-m0)/4.0 + m0)               # colorbar mid value 1
m2=int(2*(m4-m0)/4.0 + m0)               # colorbar mid value 2
m3=int(3*(m4-m0)/4.0 + m0)               # colorbar mid value 3

ax.fig.suptitle('WT04: Pairplot for features',y=0.99)

# use this colorbar
cbar = plt.colorbar(sm, ax=ax.axes)

cbar.set_ticks([m0,m1,m2,m3,m4])
cbar.set_ticklabels([m0,m1,m2,m3,m4])

Output:


问:
how to centre the image inside a view in react native
I have a grid view, inside each cell I have added a view and then an image , the image isn't centered the code is as follows

<ImageBackground
                source={require('./images/marble.jpg')}
                style={styles.backgroundImage}>

                <GridView
                    itemDimension={130}
                    items={items}
                    style={styles.gridView}
                    renderItem={item => (
                        <View style={[styles.itemContainer, { backgroundColor: item.code }]}>
                            <View style={styles.CircleShapeView}>
                            <Image style={styles.iconItem} source={item.name}/>
                            </View>
                        </View>
                    )}
                />

            </ImageBackground>```
</div>
</div>
</p>

<p>and styles are </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>const styles = StyleSheet.create({
    backgroundImage: {
        flex: 1,
        resizeMode: 'cover', // or 'stretch'
    },
    CircleShapeView: {
        width: 100,
        height: 100,
        borderRadius: 100,
        backgroundColor: '#00BCD4'
    },
    gridView: {
        paddingTop: 50,
        flex: 1,

    },
    itemContainer: {
        justifyContent: 'center',
        alignItems:'center',
        height:130
    },
    iconItem: {
        alignItems:'center',
        justifyContent: 'center'
    }
});</code>```

the output looks like this

Image should be at the centre of the circle, but its not.

答:
set in view</p>

```<code>justifycontent:center
alignitems:center
</code>```

Body:
I have a grid view, inside each cell I have added a view and then an image , the image isn't centered the code is as follows

<ImageBackground
                source={require('./images/marble.jpg')}
                style={styles.backgroundImage}>

                <GridView
                    itemDimension={130}
                    items={items}
                    style={styles.gridView}
                    renderItem={item => (
                        <View style={[styles.itemContainer, { backgroundColor: item.code }]}>
                            <View style={styles.CircleShapeView}>
                            <Image style={styles.iconItem} source={item.name}/>
                            </View>
                        </View>
                    )}
                />

            </ImageBackground>

and styles are

const styles = StyleSheet.create({
    backgroundImage: {
        flex: 1,
        resizeMode: 'cover', // or 'stretch'
    },
    CircleShapeView: {
        width: 100,
        height: 100,
        borderRadius: 100,
        backgroundColor: '#00BCD4'
    },
    gridView: {
        paddingTop: 50,
        flex: 1,

    },
    itemContainer: {
        justifyContent: 'center',
        alignItems:'center',
        height:130
    },
    iconItem: {
        alignItems:'center',
        justifyContent: 'center'
    }
});

the output looks like this

Image should be at the centre of the circle, but its not.

Body:
set in view

justifycontent:center
alignitems:center


问:
How to override the parents padding while adding a border bottom
I am building a dropdown such that there is a line below the first option like:

This is what my HTML looks like right now:

               <svg aria-label="magnifier" class="icon_n7qd0i" fill="#8796A6" width="14" height="14" data-component-id="Icon">
                  <use xlink:href="#sprite_magnifier"></use>
               </svg>

            <input class="input_h63q7t-o_O-bodyM_1n94ib9-o_O-iconInput_1oxe2z4" id="input-5" type="text" maxlength="127" min="" max="" placeholder="Find a Field" value="">

 Select All multiselect

               <input id="toggle-input-0" class="checkbox_1u9fru1" type="checkbox">

 No

               <input id="toggle-input-2" class="checkbox_1u9fru1" type="checkbox">

```

Now I tried adding a border-bottom: 1px solid black on the div with fields class eg:  i.e each of the optios.

But because the parent adds a padding it is not able to match full widt.
How can I override it

答:
You can use negative margins on the child.

div {
  color: #aaa;
}

.parent {
  padding: 2rem;
  outline: 1px solid red;
}

.child {
  /* negative margin to negate parent padding */
  margin: 0 -2rem;
  padding: 2rem;
  outline: 1px solid dodgerBlue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  .parent
  <div class="child">
    .child
  </div>
</div></code>```

Body:
I am building a dropdown such that there is a line below the first option like:

This is what my HTML looks like right now:

               <svg aria-label="magnifier" class="icon_n7qd0i" fill="#8796A6" width="14" height="14" data-component-id="Icon">
                  <use xlink:href="#sprite_magnifier"></use>
               </svg>

            <input class="input_h63q7t-o_O-bodyM_1n94ib9-o_O-iconInput_1oxe2z4" id="input-5" type="text" maxlength="127" min="" max="" placeholder="Find a Field" value="">

 Select All multiselect

               <input id="toggle-input-0" class="checkbox_1u9fru1" type="checkbox">

 No

               <input id="toggle-input-2" class="checkbox_1u9fru1" type="checkbox">

Now I tried adding a border-bottom: 1px solid black on the div with fields class eg:  i.e each of the optios.

But because the parent adds a padding it is not able to match full widt.
How can I override it

Body:
You can use negative margins on the child.

div {
  color: #aaa;
}

.parent {
  padding: 2rem;
  outline: 1px solid red;
}

.child {
  /* negative margin to negate parent padding */
  margin: 0 -2rem;
  padding: 2rem;
  outline: 1px solid dodgerBlue;
}

<div class="parent">
  .parent
  <div class="child">
    .child
  </div>
</div>


问:
Why is the MySQL integer comparison is slower than datetime null comparison?
I'm using MySQL 5.7.

There is a table called transactions with over 3 million records. The table schema is as follows:

id - INT (autoincrements)

deleted_at (DATETIME, NULL allowed)

record_status (TINYINT, DEFAULT value is 1)

Other columns pertaining to this table...

The record_status is an integer version of the deleted_at. When a record is deleted, the value is set to 0. An index is also created for this column.

The null based DATETIME query takes 740 ms to execute:

select transactions.id from transactions where transactions.deleted_at is null

The TINYINT based query takes 15.1 s to execute:

select transactions.id from transactions where transactions.record_status = 1

Isn't the check on the TINYINT column (with index) supposed to be faster? Why is this happening?

[EDIT]

Added information about the table's performance

To take the experiment further, all unnecessary columns were removed from the table. Only the following persist.

id - INT (autoincrements)

deleted_at (DATETIME, NULL allowed)

record_status (TINYINT, DEFAULT value is 1)

transaction_time (DATETIME)

Query 1: Takes 2.3ms

```<code>select transactions.id from transactions
where transactions.record_status = 1 limit 1000000;
</code>```

Query 2: Takes 2.1ms

```<code>select transactions.id from transactions
where transactions.deleted_at is null limit 1000000;
</code>```

Query 3: Takes 20 seconds

```<code>select transactions.id from transactions
where transactions.record_status = 1
and transaction_time > '2020-04-01' limit 1000;
</code>```

Query 4: Takes 500ms

```<code>select transactions.id from transactions
where transactions.deleted_at is null
and transaction_time > '2020-04-01' limit 1000;
</code>```

Query 5: 394ms

```<code>select transactions.id from transactions
where transaction_time > '2020-04-01' limit 1000000;
</code>```

I'm unable to figure out why Query 3 is taking this long.

答:
The issue was addressed by adding a composite index.

Both the following now result in fast performance.

Composite key on transaction_time and deleted_at.

Composite key on transaction_time and record_status.

Thanks to @Gordon Linoff and @jarlh. Their suggestions led to this finding.

Body:
I'm using MySQL 5.7.

There is a table called transactions with over 3 million records. The table schema is as follows:

id - INT (autoincrements)

deleted_at (DATETIME, NULL allowed)

record_status (TINYINT, DEFAULT value is 1)

Other columns pertaining to this table...

The record_status is an integer version of the deleted_at. When a record is deleted, the value is set to 0. An index is also created for this column.

The null based DATETIME query takes 740 ms to execute:

select transactions.id from transactions where transactions.deleted_at is null

The TINYINT based query takes 15.1 s to execute:

select transactions.id from transactions where transactions.record_status = 1

Isn't the check on the TINYINT column (with index) supposed to be faster? Why is this happening?

[EDIT]

Added information about the table's performance

To take the experiment further, all unnecessary columns were removed from the table. Only the following persist.

id - INT (autoincrements)

deleted_at (DATETIME, NULL allowed)

record_status (TINYINT, DEFAULT value is 1)

transaction_time (DATETIME)

Query 1: Takes 2.3ms

select transactions.id from transactions
where transactions.record_status = 1 limit 1000000;

Query 2: Takes 2.1ms

select transactions.id from transactions
where transactions.deleted_at is null limit 1000000;

Query 3: Takes 20 seconds

select transactions.id from transactions
where transactions.record_status = 1
and transaction_time > '2020-04-01' limit 1000;

Query 4: Takes 500ms

select transactions.id from transactions
where transactions.deleted_at is null
and transaction_time > '2020-04-01' limit 1000;

Query 5: 394ms

select transactions.id from transactions
where transaction_time > '2020-04-01' limit 1000000;

I'm unable to figure out why Query 3 is taking this long.


问:
React form is submitting twice without e.preventDefault() and zero times with e.preventDefault()
below code results in 2 submissions. If I add onSubmit={e => { e.preventDefault();} }, to the form, there will be zero submission:</p>

```<code>export default function SearchBar() {
  return (
    <div>
      <form
        action={BackEnd_ServerName + "/xyz"}
        method="GET"
      >
        <input
          type="text"
          placeholder=""
          name="frontEnd_searchBox"
        />
      </form>
    </div>
  );
}
</code>```

答:
```<code>export default function SearchBar() {
  return (
    <div>
      <form>
        <input
          type="text"
          placeholder=""
          name="frontEnd_searchBox"
        />
      </form>
    </div>
  );
}
</code>```

Try this

Body:
below code results in 2 submissions. If I add onSubmit={e => { e.preventDefault();} }, to the form, there will be zero submission:

export default function SearchBar() {
  return (

      <form
        action={BackEnd_ServerName + "/xyz"}
        method="GET"
      >
        <input
          type="text"
          placeholder=""
          name="frontEnd_searchBox"
        />
      </form>

  );
}

Body:
export default function SearchBar() {
  return (
    <div>
      <form>
        <input
          type="text"
          placeholder=""
          name="frontEnd_searchBox"
        />
      </form>
    </div>
  );
}

Try this


问:
In subversion I want to Revert back to a revison then step through each revision to see where it broke
My project broke somewhere in the past 25 revisions. I need to isolate the file causing the problem, and would like to find the revision where the problem was introduced.

I was thinking of using svn update  -r 404 and then each one after that 405,406 ... etc

Is there a better way?

答: I'd suggest using the git-svn bridge (git is excellent for quick local branching) and using git bisect to quickly find the revision that broke it.</p>


问:
How to create a generator function that produces a specific number of values?
I am trying to create a generator function that accepts 1 or 1+ arguments. It should return an iterable of the left overvalues of the iterable with the most values after the other iterabless no longer produce values.

For example:

```<code> for i in func('dfg', 'dfghjk', [1,2]):
    print(i)

prints -> h
          j
          k
</code>```

because the argument 'dfg', which has the second most values, stop producing values at 3.
  The argument 'dfghjk', which has the most values, then yields 'hjk' (the leftover values).

The catch here is that the iterables may or may not be finite, so I am not able to compute the length of the argument or add it to other data structures.

Any help would be great, thanks!

答:
To solve your problem I'd try to manually exhaust all the iterators until only one remains.

def foo(*iterables):
    iterators = [iter(x) for x in iterables]
    while len(iterators) > 1:
        for idx, it in enumerate(iterators[:]):
            try:
                peek = next(it)
            except StopIteration:
                # remove the iterator when exhausted
                iterators.pop(idx)

    yield peek
    yield from iterators[0]
```

<p>Notice that for it to work you will need to ensure that the iterables are indeed iterators (converting them with <code>iter</code>). You also need to store the last element obtained from the iterator. Notice that because we only use the iterator interface infinite iterators work just fine:</p>

<pre class="lang-py prettyprint-override"><code>>>> it = func([1], itertools.count(), [2,2])
>>> for _ in range(3): print(next(it))
2
3
4
</code>```

Body:
I am trying to create a generator function that accepts 1 or 1+ arguments. It should return an iterable of the left overvalues of the iterable with the most values after the other iterabless no longer produce values.

For example:

 for i in func('dfg', 'dfghjk', [1,2]):
    print(i)

prints -> h
          j
          k

because the argument 'dfg', which has the second most values, stop producing values at 3.
  The argument 'dfghjk', which has the most values, then yields 'hjk' (the leftover values).

The catch here is that the iterables may or may not be finite, so I am not able to compute the length of the argument or add it to other data structures.

Any help would be great, thanks!

Body:
To solve your problem I'd try to manually exhaust all the iterators until only one remains.

def foo(*iterables):
    iterators = [iter(x) for x in iterables]
    while len(iterators) > 1:
        for idx, it in enumerate(iterators[:]):
            try:
                peek = next(it)
            except StopIteration:
                # remove the iterator when exhausted
                iterators.pop(idx)

    yield peek
    yield from iterators[0]

Notice that for it to work you will need to ensure that the iterables are indeed iterators (converting them with iter). You also need to store the last element obtained from the iterator. Notice that because we only use the iterator interface infinite iterators work just fine:

>>> it = func([1], itertools.count(), [2,2])
>>> for _ in range(3): print(next(it))
2
3
4


问:
IndexError: The shape of the mask [1, 1682] at index 0 does not match the shape of the indexed tensor [100, 1682] at index 0
I'm currently doing an DeepLearning course in Udemy.
I am currently designing an Restricted Boltzmann machine in which
my training runs perfectly, but I ended up with this error while testing

IndexError: The shape of the mask [1, 1682] at index 0 does not match the shape of the indexed tensor [100, 1682] at index 0

import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable

# Importing dataset
movies = pd.read_csv('ml-1m/movies.dat',sep='::',header = None,
                     engine='python',encoding='latin-1')
users =  pd.read_csv('ml-1m/users.dat',sep='::',header = None,
                     engine='python',encoding='latin-1')
ratings = pd.read_csv('ml-1m/ratings.dat',sep='::',header = None,
                     engine='python',encoding='latin-1')

# preparing training and test set
training_set = pd.read_csv('ml-100k/u1.base',delimiter='\t')
training_set = np.array(training_set,dtype='int')
test_set = pd.read_csv('ml-100k/u1.test',delimiter='\t')
test_set = np.array(test_set,dtype='int')

#Getting the no of users and movies
nb_users = int(max(max(training_set[:,0]),max(test_set[:,0]))) #max out of both
nb_movies = int(max(max(training_set[:,1]),max(test_set[:,1])))

#Array with users in lines and movies in columns
def convert(data):
    new_data = []
    for id_users in range(1,nb_users+1):
        id_movies = data[:,1][data[:,0]==id_users]
        id_ratings = data[:,2][data[:,0]==id_users]
        ratings = np.zeros(nb_movies)
        ratings[id_movies-1]= id_ratings
        new_data.append(list(ratings))
    return new_data

training_set = convert(training_set)
test_set = convert(test_set)

# COnverting data to torcch tensors
training_set = torch.FloatTensor(training_set)
test_set = torch.FloatTensor(test_set)

# Converting the rating into binary ratings 1 (Liked) or 0 (Not liked)
training_set[training_set == 0] = -1 #taking all zero values in trainingset
training_set[training_set == 1] = 0
training_set[training_set == 2] = 0
training_set[training_set >= 3] = 1
test_set[test_set == 0] = -1 #taking all zero values in trainingset
test_set[test_set == 1] = 0
test_set[test_set == 2] = 0
test_set[test_set >= 3] = 1

# Creating the architecture of the Neural network
class RBM():
    def __init__(self, nv, nh):
        self.W = torch.randn(nh, nv)
        self.a = torch.randn(1, nh)
        self.b = torch.randn(1, nv)
    def sample_h(self, x):
        wx = torch.mm(x, self.W.t())
        activation = wx + self.a.expand_as(wx)
        p_h_given_v = torch.sigmoid(activation)
        return p_h_given_v, torch.bernoulli(p_h_given_v)
    def sample_v(self, y):
        wy = torch.mm(y, self.W)
        activation = wy + self.b.expand_as(wy)
        p_v_given_h = torch.sigmoid(activation)
        return p_v_given_h, torch.bernoulli(p_v_given_h)
    def train(self, v0, vk, ph0, phk):
        self.W += (torch.mm(v0.t(), ph0) - torch.mm(vk.t(), phk)).t()
        self.b += torch.sum((v0 - vk), 0)
        self.a += torch.sum((ph0 - phk), 0)
nv = len(training_set[0])
nh = 100
batch_size = 100
rbm = RBM(nv, nh)

#Training the RBM
nb_epoch = 10
for epoch in range(1, nb_epoch + 1):
    train_loss = 0
    s = 0.
    for id_user in range(0, nb_users - batch_size, batch_size):
        vk = training_set[id_user:id_user+batch_size]
        v0 = training_set[id_user:id_user+batch_size]
        ph0,_ = rbm.sample_h(v0)
        for k in range(10):
            _,hk = rbm.sample_h(vk)
            _,vk = rbm.sample_v(hk)
            vk[v0<0] = v0[v0<0]
        phk,_ = rbm.sample_h(vk)
        rbm.train(v0, vk, ph0, phk)
        train_loss += torch.mean(torch.abs(v0[v0>=0] - vk[v0>=0]))
        s += 1.
    print(f'epoch: {epoch} loss: {train_loss/s}')

# Testing the RBM
test_loss = 0
s = 0.
for id_user in range(nb_users):
    v = training_set[id_user:id_user+1]
    vt = training_set[id_user:id_user+1]
    if len(vt[vt>=0]) > 0:
        _,h = rbm.sample_h(v)
        _,v = rbm.sample_v(hk)
    test_loss += torch.mean(torch.abs(vt[vt>=0] - v[vt>=0]))
    s += 1.
print(f'test_loss: {test_loss/s}')
```

答:
In the test loop, you're re-using a variable of the training phase, which I think (you didn't provide the full stacktrace) is just a typo:

for id_user in range(nb_users):
    v = training_set[id_user:id_user+1]
    vt = training_set[id_user:id_user+1]
    if len(vt[vt>=0]) > 0:
        _,h = rbm.sample_h(v)
        _,v = rbm.sample_v(hk)  # hk should be h, shouldn't it?
```


问:
How to deal with multiple services inside a docker-compose.yml?
I have been using a Microservices architecture for develop my software, and I have running my services using Docker Compose, but my problem is when the new services were created I have to add them into the docker-compose.yml, and then I got about 200+ hundred lines of code inside the docker-compose.yml, and I have around 17 services for now which the services have related each other.

Then my question is "How to manage the docker-compose.yml to be easy to maintain and clean?"

My docker-compose.yml:

```<code>version: '2'
services:
   mongo:
     container_name: mongodb
     image: mongo:3.4.7
     volumes:
       - ./mongo/data:/data/db
     ports:
       - 54321:27017
     networks:
       - zensorium_backend
     restart: always
     command: mongod --smallfiles

   golang_oauth:
     container_name: golang_oauth
     build: .
     volumes:
        - ./oauth:/go/src/oauth
     working_dir: /go/src/oauth
     ports:
        - 8080:8082
     depends_on:
        - mongo
     env_file:
       - ./.api.env
     networks:
       - zensorium_backend
     command: realize start --run
     restart: always

   golang_account:
     container_name: golang_account
     build: .
     volumes:
        - ./account:/go/src/account
     working_dir: /go/src/account
     ports:
        - 8081:8082
     depends_on:
        - mongo
     env_file:
       - ./.api.env
     networks:
       - zensorium_backend
     command: realize start --run
     restart: always

   golang_client:
     container_name: golang_client
     build: .
     volumes:
        - ./client:/go/src/client
     working_dir: /go/src/client
     ports:
        - 8082:8082
     depends_on:
        - mongo
     env_file:
       - ./.api.env
     networks:
       - zensorium_backend
     command: realize start --run
     restart: always

   golang_mail:
     container_name: golang_mail
     build: .
     volumes:
        - ./mail:/go/src/mail
     working_dir: /go/src/mail
     expose:
        - 8082
     depends_on:
        - mongo
     env_file:
        - ./.api.env
     networks:
        - zensorium_backend
     command: realize start --run
     restart: always

   golang_user:
     container_name: golang_user
     build: .
     volumes:
        - ./user:/go/src/user
     working_dir: /go/src/user
     ports:
        - 8083:8082
     depends_on:
        - mongo
     env_file:
        - ./.api.env
     networks:
        - zensorium_backend
     command: realize start --run
     restart: always

   golang_gateway2:
     container_name: golang_gateway2
     build: .
     volumes:
        - ./gateway2:/go/src/gateway
     working_dir: /go/src/gateway
     ports:
        - 8084:8082
     depends_on:
        - mongo
     env_file:
       - ./.api.env
     networks:
        - zensorium_backend
     command: realize start --run
     restart: always

   golang_measurement:
     container_name: golang_measurement
     build: .
     volumes:
        - ./measurement:/go/src/measurement
     working_dir: /go/src/measurement
     ports:
        - 8085:8082
     depends_on:
        - mongo
     env_file:
        - ./.api.env
     networks:
        - zensorium_backend
     command: realize start --run
     restart: always

   golang_app:
     container_name: golang_app
     build: .
     volumes:
        - ./app:/go/src/app
     working_dir: /go/src/app
     ports:
        - 8086:8082
     depends_on:
        - mongo
     env_file:
        - ./.api.env
     networks:
        - zensorium_backend
     command: realize start --run
     restart: always

   golang_logging:
     container_name: golang_logging
     build: .
     volumes:
        - ./logging:/go/src/logging
     working_dir: /go/src/logging
     ports:
        - 8087:8082

     networks:
        - zensorium_backend
     command: realize start --run
     restart: always

   golang_notify:
     container_name: golang_notify
     build: .
     volumes:
        - ./notify:/go/src/notify
     working_dir: /go/src/notify
     ports:
        - 8088:8082
     env_file:
        - ./.api.env
     networks:
        - zensorium_backend
     command: realize start --run
     restart: always

   golang_routine:
     container_name: golang_routine
     build: .
     volumes:
       - ./routine:/go/src/routine
     working_dir: /go/src/routine
     ports:
       - 8089:8082
     env_file:
       - ./.api.env
     networks:
       - zensorium_backend
     command: realize start --run
     restart: always

   angular_cli:
     container_name: angular_cli
     build: ./angular-cli
     ports:
       - "4200:4200"
     networks:
       - zensorium_frontend
     working_dir: /home/node/webPortal
     volumes:
       - ./angular-cli/webPortal:/home/node/webPortal
       - /home/node/webPortal/node_modules
     restart: always
     command: npm start

   golang_dev:
       container_name: golang_dev
       build: .
       volumes:
          - ./dev:/go/src/dev
       working_dir: /go/src/dev
       ports:
         - 8090:8082
       env_file:
         - ./.api.env
       networks:
         - zensorium_backend
       command: realize start --run
       restart: always

networks:
  zensorium_backend:
    driver: bridge
  zensorium_frontend:
    driver: bridge
</code>```

答:
Also you can use the possibilities of yaml to write repeated strings in shorter way. For example :

```
---
version: '3.4'
x-command: &command bash -c "ls &&  sleep infinity"

services:

  service1:
    command: *command

  service2:
    command: *command

```

And man can use templates:
https://matthiasnoback.nl/2018/03/defining-multiple-similar-services-with-docker-compose/

Body:
I have been using a Microservices architecture for develop my software, and I have running my services using Docker Compose, but my problem is when the new services were created I have to add them into the docker-compose.yml, and then I got about 200+ hundred lines of code inside the docker-compose.yml, and I have around 17 services for now which the services have related each other.

Then my question is "How to manage the docker-compose.yml to be easy to maintain and clean?"

My docker-compose.yml:

version: '2'
services:
   mongo:
     container_name: mongodb
     image: mongo:3.4.7
     volumes:
       - ./mongo/data:/data/db
     ports:
       - 54321:27017
     networks:
       - zensorium_backend
     restart: always
     command: mongod --smallfiles

   golang_oauth:
     container_name: golang_oauth
     build: .
     volumes:
        - ./oauth:/go/src/oauth
     working_dir: /go/src/oauth
     ports:
        - 8080:8082
     depends_on:
        - mongo
     env_file:
       - ./.api.env
     networks:
       - zensorium_backend
     command: realize start --run
     restart: always

   golang_account:
     container_name: golang_account
     build: .
     volumes:
        - ./account:/go/src/account
     working_dir: /go/src/account
     ports:
        - 8081:8082
     depends_on:
        - mongo
     env_file:
       - ./.api.env
     networks:
       - zensorium_backend
     command: realize start --run
     restart: always

   golang_client:
     container_name: golang_client
     build: .
     volumes:
        - ./client:/go/src/client
     working_dir: /go/src/client
     ports:
        - 8082:8082
     depends_on:
        - mongo
     env_file:
       - ./.api.env
     networks:
       - zensorium_backend
     command: realize start --run
     restart: always

   golang_mail:
     container_name: golang_mail
     build: .
     volumes:
        - ./mail:/go/src/mail
     working_dir: /go/src/mail
     expose:
        - 8082
     depends_on:
        - mongo
     env_file:
        - ./.api.env
     networks:
        - zensorium_backend
     command: realize start --run
     restart: always

   golang_user:
     container_name: golang_user
     build: .
     volumes:
        - ./user:/go/src/user
     working_dir: /go/src/user
     ports:
        - 8083:8082
     depends_on:
        - mongo
     env_file:
        - ./.api.env
     networks:
        - zensorium_backend
     command: realize start --run
     restart: always

   golang_gateway2:
     container_name: golang_gateway2
     build: .
     volumes:
        - ./gateway2:/go/src/gateway
     working_dir: /go/src/gateway
     ports:
        - 8084:8082
     depends_on:
        - mongo
     env_file:
       - ./.api.env
     networks:
        - zensorium_backend
     command: realize start --run
     restart: always

   golang_measurement:
     container_name: golang_measurement
     build: .
     volumes:
        - ./measurement:/go/src/measurement
     working_dir: /go/src/measurement
     ports:
        - 8085:8082
     depends_on:
        - mongo
     env_file:
        - ./.api.env
     networks:
        - zensorium_backend
     command: realize start --run
     restart: always

   golang_app:
     container_name: golang_app
     build: .
     volumes:
        - ./app:/go/src/app
     working_dir: /go/src/app
     ports:
        - 8086:8082
     depends_on:
        - mongo
     env_file:
        - ./.api.env
     networks:
        - zensorium_backend
     command: realize start --run
     restart: always

   golang_logging:
     container_name: golang_logging
     build: .
     volumes:
        - ./logging:/go/src/logging
     working_dir: /go/src/logging
     ports:
        - 8087:8082

     networks:
        - zensorium_backend
     command: realize start --run
     restart: always

   golang_notify:
     container_name: golang_notify
     build: .
     volumes:
        - ./notify:/go/src/notify
     working_dir: /go/src/notify
     ports:
        - 8088:8082
     env_file:
        - ./.api.env
     networks:
        - zensorium_backend
     command: realize start --run
     restart: always

   golang_routine:
     container_name: golang_routine
     build: .
     volumes:
       - ./routine:/go/src/routine
     working_dir: /go/src/routine
     ports:
       - 8089:8082
     env_file:
       - ./.api.env
     networks:
       - zensorium_backend
     command: realize start --run
     restart: always

   angular_cli:
     container_name: angular_cli
     build: ./angular-cli
     ports:
       - "4200:4200"
     networks:
       - zensorium_frontend
     working_dir: /home/node/webPortal
     volumes:
       - ./angular-cli/webPortal:/home/node/webPortal
       - /home/node/webPortal/node_modules
     restart: always
     command: npm start

   golang_dev:
       container_name: golang_dev
       build: .
       volumes:
          - ./dev:/go/src/dev
       working_dir: /go/src/dev
       ports:
         - 8090:8082
       env_file:
         - ./.api.env
       networks:
         - zensorium_backend
       command: realize start --run
       restart: always

networks:
  zensorium_backend:
    driver: bridge
  zensorium_frontend:
    driver: bridge

Body:
Also you can use the possibilities of yaml to write repeated strings in shorter way. For example :

---
version: '3.4'
x-command: &command bash -c "ls &&  sleep infinity"

services:

  service1:
    command: *command

  service2:
    command: *command

And man can use templates:
https://matthiasnoback.nl/2018/03/defining-multiple-similar-services-with-docker-compose/


问:
Can I set Tomcat SSL port other then 443 or 8443
I have Plesk on my server that is using both ports as:

```<code>#netstat -lnp | grep 443
tcp        0      0 0.0.0.0:8443            0.0.0.0:*               LISTEN      5513/sw-cp-server:
tcp6       0      0 :::443                  :::*                    LISTEN      32660/httpd
tcp6       0      0 :::8443                 :::*                    LISTEN      5513/sw-cp-server:
unix  2      [ ACC ]     STREAM     LISTENING     110443   31339/dovecot        /var/run/dovecot/stats
</code>```

Best regards

答: Yes, you can. http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html (First Google hit, incidentally)</p>

Body:
I have Plesk on my server that is using both ports as:

#netstat -lnp | grep 443
tcp        0      0 0.0.0.0:8443            0.0.0.0:*               LISTEN      5513/sw-cp-server:
tcp6       0      0 :::443                  :::*                    LISTEN      32660/httpd
tcp6       0      0 :::8443                 :::*                    LISTEN      5513/sw-cp-server:
unix  2      [ ACC ]     STREAM     LISTENING     110443   31339/dovecot        /var/run/dovecot/stats

Best regards


问:
JavaScript Fetch API can you access headers as well as JSON in a `.then ` callback?
I need to make a POST request and then depending on the response as well as the headers, I need to update saved state, I know the headers are available via response.header.get('SOME-KEY') and I can access JSON part of the response in a .then callback like so: .then(response => response.json()).then(json =>())

what I want to know is, is there a way to get both in the block which has the parsed JSON response data?

答:
Well I don't know how I missed this, the solution was extremely simple, .json() returns a Promise, so we can just call .then on it inside the current context and do what we want with the headers and the response body:

fetch('/url')
  .then(response => response.json().then(json => ({...json, token: response.headers.get('TOKEN')})))
  .then(json => props.updateUser(json));
```

In this way we can get the desired object which contains the header values as well as the response data. Sometimes all you need to solve your problem is a bit of sleep.

Body:
Well I don't know how I missed this, the solution was extremely simple, .json() returns a Promise, so we can just call .then on it inside the current context and do what we want with the headers and the response body:

fetch('/url')
  .then(response => response.json().then(json => ({...json, token: response.headers.get('TOKEN')})))
  .then(json => props.updateUser(json));

In this way we can get the desired object which contains the header values as well as the response data. Sometimes all you need to solve your problem is a bit of sleep.


问:
What is the best way to add two numbers without using the + operator?
A friend and I are going back and forth with brain-teasers and I have no idea how to solve this one.  My assumption is that it's possible with some bitwise operators, but not sure.</p>

答:
Here is the solution in C++, you can find it on my github here: https://github.com/CrispenGari/Add-Without-Integers-without-operators/blob/master/main.cpp</p>

```<code>int add(int a, int b){
   while(b!=0){
      int sum = a^b; // add without carrying
      int carry = (a&b)<<1; // carrying without adding
      a= sum;
      b= carry;
    }
   return a;
 }
 // the function can be writen as follows :
 int add(int a, int b){
     if(b==0){
        return a; // any number plus 0 = that number simple!
    }
    int sum = a ^ b;// adding without carrying;
    int carry = (a & b)<<1; // carry, without adding
    return add(sum, carry);
  }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here is the solution in C++, you can find it on my github here: https://github.com/CrispenGari/Add-Without-Integers-without-operators/blob/master/main.cpp

int add(int a, int b){
   while(b!=0){
      int sum = a^b; // add without carrying
      int carry = (a&b)<<1; // carrying without adding
      a= sum;
      b= carry;
    }
   return a;
 }
 // the function can be writen as follows :
 int add(int a, int b){
     if(b==0){
        return a; // any number plus 0 = that number simple!
    }
    int sum = a ^ b;// adding without carrying;
    int carry = (a & b)<<1; // carry, without adding
    return add(sum, carry);
  }


问:
How to print TextInput value entered in .kv (kivy), to be printed in .py file?
I am new to kivy and Python.
This is a snippet of my code:
.py file:

```<code>    from kivy.app import App
    from kivy.lang import Builder
    from kivy.uix.screenmanager import ScreenManager, Screen
    from kivy.properties import ObjectProperty, StringProperty
    from kivy.uix.popup import Popup
    from kivy.uix.label import Label
    from database import DataBase

class IpickupWindow(Screen):
n = ObjectProperty(None)
start1 = StringProperty('Test')
current = ""
pop = StringProperty("")
def on_enter(self, *args):
    name = db.curr_user(self.current)
    self.n.text = "Hi, " + name
    print(self.start1)

def on_leave(self, *args):
    print(self.start1)
    #print(self.start1.text)

def btn(self):
    popup = CustomPopup()
    print(self.pop)
    popup.open()
</code>```

.kv file:

```<code><IpickupWindow>:
name:"Ipick"
n:n
start1: str(start)

FloatLayout:
    cols: 1

    FloatLayout:
        size: root.width, root.height/2

        Label:
            id: n
            pos_hint:{"x": 0.0, "top":1.0}
            size_hint:0.8, 0.2

        Label:
            pos_hint:{"x": 0.1, "top":0.9}
            size_hint:0.8, 0.2
            text: "Please provide the below details to find the best ride for you: "
        Label:
            pos_hint:{"x": 0.0, "top":0.75}
            size_hint:0.4, 0.2
            text: "Start Location: "
        TextInput:
            id: start
            font_size: (root.width**2 + root.height**2) / 13**4
            multiline: False
            pos_hint: {"x": 0.4 , "top":0.7}
            size_hint: 0.3, 0.1

        Label:

            pos_hint:{"x": 0.0, "top":0.55}
            size_hint:0.4, 0.2
            text: "End Location: "
        TextInput:
            id: end
            font_size: (root.width**2 + root.height**2) / 13**4
            multiline: False
            pos_hint: {"x": 0.4 , "top":0.5}
            size_hint: 0.3, 0.1

        Label:
            pos_hint:{"x": 0.0, "top":0.35}
            size_hint:0.4, 0.2
            text: "Time frame: "
        TextInput:
            id: time
            font_size: (root.width**2 + root.height**2) / 13**4
            multiline: False
            pos_hint: {"x": 0.4 , "top":0.3}
            size_hint: 0.3, 0.1

    Button:
        pos_hint:{"x":0.4, "top": 0.1}
        size_hint:0.2,0.1
        text: "Submit"
        on_press: root.btn()
</code>```

so the following are the 2 problems:

When trying to print start1 in on_enter function, it is printing
this in the console:

-<--kivy.uix.textinput.TextInput object at 0x00000240AC1E0208-->-
I want to print the kivy textbox value

When trying to print start1 in on_leave function, null value is
    being printed.I want to print the kivy textbox value.

答:
You are having start1 defined as StringProperty('Test') and in .kv file you are using start1: str(start) which does not create a reference to TextInput object rather start1 refers to string representation of TextInput object.

To print the kivy textbox value, you need to define start1 as ObjectProperty(None) and in .kv file start1: start. Then you can simply refer to TextInput value in corresponding .py file using self.start1.text.

So in .py file use:

```<code>class IpickupWindow(Screen):
    n = ObjectProperty(None)
    start1 = ObjectProperty(None)
    current = ""
    pop = StringProperty("")
    def on_enter(self, *args):
        name = db.curr_user(self.current)
        self.n.text = "Hi, " + name
        print(self.start1.text)
</code>```

In .kv file use:

```<code><IpickupWindow>:
    name:"Ipick"
    n:n
    start1: start
</code>```

Rest of the code snippet remains same and please take care of indentation.

Body:
I am new to kivy and Python.
This is a snippet of my code:
.py file:

    from kivy.app import App
    from kivy.lang import Builder
    from kivy.uix.screenmanager import ScreenManager, Screen
    from kivy.properties import ObjectProperty, StringProperty
    from kivy.uix.popup import Popup
    from kivy.uix.label import Label
    from database import DataBase

class IpickupWindow(Screen):
n = ObjectProperty(None)
start1 = StringProperty('Test')
current = ""
pop = StringProperty("")
def on_enter(self, *args):
    name = db.curr_user(self.current)
    self.n.text = "Hi, " + name
    print(self.start1)

def on_leave(self, *args):
    print(self.start1)
    #print(self.start1.text)

def btn(self):
    popup = CustomPopup()
    print(self.pop)
    popup.open()

.kv file:

<IpickupWindow>:
name:"Ipick"
n:n
start1: str(start)

FloatLayout:
    cols: 1

    FloatLayout:
        size: root.width, root.height/2

        Label:
            id: n
            pos_hint:{"x": 0.0, "top":1.0}
            size_hint:0.8, 0.2

        Label:
            pos_hint:{"x": 0.1, "top":0.9}
            size_hint:0.8, 0.2
            text: "Please provide the below details to find the best ride for you: "
        Label:
            pos_hint:{"x": 0.0, "top":0.75}
            size_hint:0.4, 0.2
            text: "Start Location: "
        TextInput:
            id: start
            font_size: (root.width**2 + root.height**2) / 13**4
            multiline: False
            pos_hint: {"x": 0.4 , "top":0.7}
            size_hint: 0.3, 0.1

        Label:

            pos_hint:{"x": 0.0, "top":0.55}
            size_hint:0.4, 0.2
            text: "End Location: "
        TextInput:
            id: end
            font_size: (root.width**2 + root.height**2) / 13**4
            multiline: False
            pos_hint: {"x": 0.4 , "top":0.5}
            size_hint: 0.3, 0.1

        Label:
            pos_hint:{"x": 0.0, "top":0.35}
            size_hint:0.4, 0.2
            text: "Time frame: "
        TextInput:
            id: time
            font_size: (root.width**2 + root.height**2) / 13**4
            multiline: False
            pos_hint: {"x": 0.4 , "top":0.3}
            size_hint: 0.3, 0.1

    Button:
        pos_hint:{"x":0.4, "top": 0.1}
        size_hint:0.2,0.1
        text: "Submit"
        on_press: root.btn()

so the following are the 2 problems:

When trying to print start1 in on_enter function, it is printing
this in the console:

-<--kivy.uix.textinput.TextInput object at 0x00000240AC1E0208-->-
I want to print the kivy textbox value

When trying to print start1 in on_leave function, null value is
    being printed.I want to print the kivy textbox value.

Body:
You are having start1 defined as StringProperty('Test') and in .kv file you are using start1: str(start) which does not create a reference to TextInput object rather start1 refers to string representation of TextInput object.

To print the kivy textbox value, you need to define start1 as ObjectProperty(None) and in .kv file start1: start. Then you can simply refer to TextInput value in corresponding .py file using self.start1.text.

So in .py file use:

class IpickupWindow(Screen):
    n = ObjectProperty(None)
    start1 = ObjectProperty(None)
    current = ""
    pop = StringProperty("")
    def on_enter(self, *args):
        name = db.curr_user(self.current)
        self.n.text = "Hi, " + name
        print(self.start1.text)

In .kv file use:

<IpickupWindow>:
    name:"Ipick"
    n:n
    start1: start

Rest of the code snippet remains same and please take care of indentation.


问:
Renaming columns in Pandas Data Frame by rename method
Have been trying to change column names in a Pandas DataFrame.

```<code>In [1]: import pandas as pd
   ...: df=pd.read_csv('winequality-red.csv',sep=';')
   ...: df.head()
Out[1]:
   fixed acidity  volatile acidity  citric acid  residual sugar  chlorides  \
0            7.4              0.70         0.00             1.9      0.076
1            7.8              0.88         0.00             2.6      0.098
2            7.8              0.76         0.04             2.3      0.092
3           11.2              0.28         0.56             1.9      0.075
4            7.4              0.70         0.00             1.9      0.076

   free sulfur dioxide  total sulfur dioxide  density    pH  sulphates  \
0                 11.0                  34.0   0.9978  3.51       0.56
1                 25.0                  67.0   0.9968  3.20       0.68
2                 15.0                  54.0   0.9970  3.26       0.65
3                 17.0                  60.0   0.9980  3.16       0.58
4                 11.0                  34.0   0.9978  3.51       0.56

   alcohol  quality
0      9.4        5
1      9.8        5
2      9.8        5
3      9.8        6
4      9.4        5
</code>```

While using the replace method inside rename, received the following error message:

```<code>In [2]: df.rename(str.replace(' ', '_'),axis='columns',inplace=True)
   ...: df.head()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-3bf0bb1685ed> in <module>
----> 1 df.rename(str.replace(' ', '_'),axis='columns',inplace=True)
      2 df.head()

**TypeError: replace() takes at least 2 arguments (1 given)**
</code>```

However, if changing str.replace for str.title, str.upper or str.lower, it works.

```<code>In [3]: df.rename(str.title,axis='columns',inplace=True)
   ...: df.head()
Out[3]:
   Fixed Acidity  Volatile Acidity  Citric Acid  Residual Sugar  Chlorides  \
0            7.4              0.70         0.00             1.9      0.076
1            7.8              0.88         0.00             2.6      0.098
2            7.8              0.76         0.04             2.3      0.092
3           11.2              0.28         0.56             1.9      0.075
4            7.4              0.70         0.00             1.9      0.076

   Free Sulfur Dioxide  Total Sulfur Dioxide  Density    Ph  Sulphates  \
0                 11.0                  34.0   0.9978  3.51       0.56
1                 25.0                  67.0   0.9968  3.20       0.68
2                 15.0                  54.0   0.9970  3.26       0.65
3                 17.0                  60.0   0.9980  3.16       0.58
4                 11.0                  34.0   0.9978  3.51       0.56

   Alcohol  Quality
0      9.4        5
1      9.8        5
2      9.8        5
3      9.8        6
4      9.4        5

In [4]: df.rename(str.upper,axis='columns',inplace=True)
   ...: df.head()
Out[4]:
   FIXED ACIDITY  VOLATILE ACIDITY  CITRIC ACID  RESIDUAL SUGAR  CHLORIDES  \
0            7.4              0.70         0.00             1.9      0.076
1            7.8              0.88         0.00             2.6      0.098
2            7.8              0.76         0.04             2.3      0.092
3           11.2              0.28         0.56             1.9      0.075
4            7.4              0.70         0.00             1.9      0.076

   FREE SULFUR DIOXIDE  TOTAL SULFUR DIOXIDE  DENSITY    PH  SULPHATES  \
0                 11.0                  34.0   0.9978  3.51       0.56
1                 25.0                  67.0   0.9968  3.20       0.68
2                 15.0                  54.0   0.9970  3.26       0.65
3                 17.0                  60.0   0.9980  3.16       0.58
4                 11.0                  34.0   0.9978  3.51       0.56

   ALCOHOL  QUALITY
0      9.4        5
1      9.8        5
2      9.8        5
3      9.8        6
4      9.4        5

In [5]: df.rename(str.lower,axis='columns',inplace=True)
   ...: df.head()
Out[5]:
   fixed acidity  volatile acidity  citric acid  residual sugar  chlorides  \
0            7.4              0.70         0.00             1.9      0.076
1            7.8              0.88         0.00             2.6      0.098
2            7.8              0.76         0.04             2.3      0.092
3           11.2              0.28         0.56             1.9      0.075
4            7.4              0.70         0.00             1.9      0.076

   free sulfur dioxide  total sulfur dioxide  density    ph  sulphates  \
0                 11.0                  34.0   0.9978  3.51       0.56
1                 25.0                  67.0   0.9968  3.20       0.68
2                 15.0                  54.0   0.9970  3.26       0.65
3                 17.0                  60.0   0.9980  3.16       0.58
4                 11.0                  34.0   0.9978  3.51       0.56

   alcohol  quality
0      9.4        5
1      9.8        5
2      9.8        5
3      9.8        6
4      9.4        5
</code>```

Any clues why the "TypeError: replace() takes at least 2 arguments (1 given)" when using str.replace?

P.S. By the way, I managed to solve using list comprehensions

```<code>In [6]: df.columns=[col.replace(' ', '_') for col in df.columns]
   ...: df.head()
Out[6]:
   fixed_acidity  volatile_acidity  citric_acid  residual_sugar  chlorides  \
0            7.4              0.70         0.00             1.9      0.076
1            7.8              0.88         0.00             2.6      0.098
2            7.8              0.76         0.04             2.3      0.092
3           11.2              0.28         0.56             1.9      0.075
4            7.4              0.70         0.00             1.9      0.076

   free_sulfur_dioxide  total_sulfur_dioxide  density    ph  sulphates  \
0                 11.0                  34.0   0.9978  3.51       0.56
1                 25.0                  67.0   0.9968  3.20       0.68
2                 15.0                  54.0   0.9970  3.26       0.65
3                 17.0                  60.0   0.9980  3.16       0.58
4                 11.0                  34.0   0.9978  3.51       0.56

   alcohol  quality
0      9.4        5
1      9.8        5
2      9.8        5
3      9.8        6
4      9.4        5
</code>```

But I'm still confused why the replace method is returning a TypeError message when used inside pd.rename.

答:
Did you try this:

```<code>df.columns = df.columns.str.replace(' ', '_')
</code>```

Inside rename you can do a lambda:

```<code>df.rename(columns=lambda x: x.replace(' ', '_'), inplace=True)
</code>```

Body:
Have been trying to change column names in a Pandas DataFrame.

In [1]: import pandas as pd
   ...: df=pd.read_csv('winequality-red.csv',sep=';')
   ...: df.head()
Out[1]:
   fixed acidity  volatile acidity  citric acid  residual sugar  chlorides  \
0            7.4              0.70         0.00             1.9      0.076
1            7.8              0.88         0.00             2.6      0.098
2            7.8              0.76         0.04             2.3      0.092
3           11.2              0.28         0.56             1.9      0.075
4            7.4              0.70         0.00             1.9      0.076

   free sulfur dioxide  total sulfur dioxide  density    pH  sulphates  \
0                 11.0                  34.0   0.9978  3.51       0.56
1                 25.0                  67.0   0.9968  3.20       0.68
2                 15.0                  54.0   0.9970  3.26       0.65
3                 17.0                  60.0   0.9980  3.16       0.58
4                 11.0                  34.0   0.9978  3.51       0.56

   alcohol  quality
0      9.4        5
1      9.8        5
2      9.8        5
3      9.8        6
4      9.4        5

While using the replace method inside rename, received the following error message:

In [2]: df.rename(str.replace(' ', '_'),axis='columns',inplace=True)
   ...: df.head()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-3bf0bb1685ed> in <module>
----> 1 df.rename(str.replace(' ', '_'),axis='columns',inplace=True)
      2 df.head()

**TypeError: replace() takes at least 2 arguments (1 given)**

However, if changing str.replace for str.title, str.upper or str.lower, it works.

In [3]: df.rename(str.title,axis='columns',inplace=True)
   ...: df.head()
Out[3]:
   Fixed Acidity  Volatile Acidity  Citric Acid  Residual Sugar  Chlorides  \
0            7.4              0.70         0.00             1.9      0.076
1            7.8              0.88         0.00             2.6      0.098
2            7.8              0.76         0.04             2.3      0.092
3           11.2              0.28         0.56             1.9      0.075
4            7.4              0.70         0.00             1.9      0.076

   Free Sulfur Dioxide  Total Sulfur Dioxide  Density    Ph  Sulphates  \
0                 11.0                  34.0   0.9978  3.51       0.56
1                 25.0                  67.0   0.9968  3.20       0.68
2                 15.0                  54.0   0.9970  3.26       0.65
3                 17.0                  60.0   0.9980  3.16       0.58
4                 11.0                  34.0   0.9978  3.51       0.56

   Alcohol  Quality
0      9.4        5
1      9.8        5
2      9.8        5
3      9.8        6
4      9.4        5

In [4]: df.rename(str.upper,axis='columns',inplace=True)
   ...: df.head()
Out[4]:
   FIXED ACIDITY  VOLATILE ACIDITY  CITRIC ACID  RESIDUAL SUGAR  CHLORIDES  \
0            7.4              0.70         0.00             1.9      0.076
1            7.8              0.88         0.00             2.6      0.098
2            7.8              0.76         0.04             2.3      0.092
3           11.2              0.28         0.56             1.9      0.075
4            7.4              0.70         0.00             1.9      0.076

   FREE SULFUR DIOXIDE  TOTAL SULFUR DIOXIDE  DENSITY    PH  SULPHATES  \
0                 11.0                  34.0   0.9978  3.51       0.56
1                 25.0                  67.0   0.9968  3.20       0.68
2                 15.0                  54.0   0.9970  3.26       0.65
3                 17.0                  60.0   0.9980  3.16       0.58
4                 11.0                  34.0   0.9978  3.51       0.56

   ALCOHOL  QUALITY
0      9.4        5
1      9.8        5
2      9.8        5
3      9.8        6
4      9.4        5

In [5]: df.rename(str.lower,axis='columns',inplace=True)
   ...: df.head()
Out[5]:
   fixed acidity  volatile acidity  citric acid  residual sugar  chlorides  \
0            7.4              0.70         0.00             1.9      0.076
1            7.8              0.88         0.00             2.6      0.098
2            7.8              0.76         0.04             2.3      0.092
3           11.2              0.28         0.56             1.9      0.075
4            7.4              0.70         0.00             1.9      0.076

   free sulfur dioxide  total sulfur dioxide  density    ph  sulphates  \
0                 11.0                  34.0   0.9978  3.51       0.56
1                 25.0                  67.0   0.9968  3.20       0.68
2                 15.0                  54.0   0.9970  3.26       0.65
3                 17.0                  60.0   0.9980  3.16       0.58
4                 11.0                  34.0   0.9978  3.51       0.56

   alcohol  quality
0      9.4        5
1      9.8        5
2      9.8        5
3      9.8        6
4      9.4        5

Any clues why the "TypeError: replace() takes at least 2 arguments (1 given)" when using str.replace?

P.S. By the way, I managed to solve using list comprehensions

In [6]: df.columns=[col.replace(' ', '_') for col in df.columns]
   ...: df.head()
Out[6]:
   fixed_acidity  volatile_acidity  citric_acid  residual_sugar  chlorides  \
0            7.4              0.70         0.00             1.9      0.076
1            7.8              0.88         0.00             2.6      0.098
2            7.8              0.76         0.04             2.3      0.092
3           11.2              0.28         0.56             1.9      0.075
4            7.4              0.70         0.00             1.9      0.076

   free_sulfur_dioxide  total_sulfur_dioxide  density    ph  sulphates  \
0                 11.0                  34.0   0.9978  3.51       0.56
1                 25.0                  67.0   0.9968  3.20       0.68
2                 15.0                  54.0   0.9970  3.26       0.65
3                 17.0                  60.0   0.9980  3.16       0.58
4                 11.0                  34.0   0.9978  3.51       0.56

   alcohol  quality
0      9.4        5
1      9.8        5
2      9.8        5
3      9.8        6
4      9.4        5

But I'm still confused why the replace method is returning a TypeError message when used inside pd.rename.

Body:
Did you try this:

df.columns = df.columns.str.replace(' ', '_')

Inside rename you can do a lambda:

df.rename(columns=lambda x: x.replace(' ', '_'), inplace=True)


问:
The timeout period elapsed prior to obtaining a connection from the pool - but the pool is not full
I hate even bringing this up b/c there are so many hundreds of pages talking about this error dating back 7-8  years...  However, I cant quite figure this out.

I have a report service running on server A which connects to SQL Server 2008 R2 on Server B.  Both servers are running Windows Server 2008.  The report service is multi-threaded and runs up to 10 reports at a time each on its own thread.

My connection string is as follows:

```<code>Data Source=ServerB;Initial Catalog=DBName;trusted_connection=YES;Connection Timeout=0;Max Pool Size=500;
</code>```

As you see, I have set the connect timeout to 0 to wait for a connection until its available, and max pool size to 500 b/c I wanted to make sure the pool was not too small for my multi-threaded service.  The error typically only shows up when the service starts and there is a queue of reports waiting to be processed.

So obviously, the first thing to do is look for leaking connections..  there have to be connections that are not being closed that are causing the pool to fill up, right?  Nope -looks like the pool never fills up.

I have spent the last several hours running Performance Monitor on the server watching ".NET Data Provider for SqlServer" and the NumberOfPooledConnections never gets above 20 or  so.  I also have perfmon running on the SQL server watching "SQLServer:General Statistics" and UserConnections never goes above 50.  During this time, I have caused this error to be reported 2 or 3 times by manually restarting the service.

What else can I look for?  What else would cause this error?
Full error message is:

```<code>System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
</code>```

Thanks,
Stephen

答:
This is known bug as shown here

Posted by Microsoft on 8/15/2008 at 11:31 AM
  Thanks for your feedback. The fix was submitted to the source branch of the next major .Net release.

Body:
I hate even bringing this up b/c there are so many hundreds of pages talking about this error dating back 7-8  years...  However, I cant quite figure this out.

I have a report service running on server A which connects to SQL Server 2008 R2 on Server B.  Both servers are running Windows Server 2008.  The report service is multi-threaded and runs up to 10 reports at a time each on its own thread.

My connection string is as follows:

Data Source=ServerB;Initial Catalog=DBName;trusted_connection=YES;Connection Timeout=0;Max Pool Size=500;

As you see, I have set the connect timeout to 0 to wait for a connection until its available, and max pool size to 500 b/c I wanted to make sure the pool was not too small for my multi-threaded service.  The error typically only shows up when the service starts and there is a queue of reports waiting to be processed.

So obviously, the first thing to do is look for leaking connections..  there have to be connections that are not being closed that are causing the pool to fill up, right?  Nope -looks like the pool never fills up.

I have spent the last several hours running Performance Monitor on the server watching ".NET Data Provider for SqlServer" and the NumberOfPooledConnections never gets above 20 or  so.  I also have perfmon running on the SQL server watching "SQLServer:General Statistics" and UserConnections never goes above 50.  During this time, I have caused this error to be reported 2 or 3 times by manually restarting the service.

What else can I look for?  What else would cause this error?
Full error message is:

System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()

Thanks,
Stephen


问:
How to convert string hhmm to time in python
How could I convert the below column Time 1 from string to time eg: Time2

Time1

438

448

1815

1758

Time2

04:38

04:48

18:15

17:58

Body:
Try the datetime library

>>> Time1 = ['438','448','1815','1758']
>>> Time2 = []
>>> import datetime
>>> for t in Time1:
...     Time2.append(datetime.datetime.strptime(t,'%H%M').strftime('%H:%M'))
>>> print (Time2)
['04:38', '04:48', '18:15', '17:58']


问:
sort numbers numerically and strings alphabetically in an array of hashes perl
It's a very easy problem but can't get my way around it. I have an array of hashes. The data structure as follows:

```<code>my @unsorted = (
    {
        'key_5' => '14.271 text',
        # ...
    },
    {
        'key_5' => 'text',
        # ...
    },
    {
        'key_5' => '13.271 text',
        # ...
    },
    {
        'key_5' => 'etext',
        # ...
    },
);
</code>```

How can I sort the array based on key_5 of the hash. The string part should be sorted alphabetically. and where the key is number string (format is always like this),it should be sorted numerically (ignoring the string part completely). So the output would look like, either:

```<code>my @sorted = (
    {
        'key_5' => 'etext',
        # ...
    },
    {
        'key_5' => 'text',
        # ...
    },
    {
        'key_5' => '13.271 text',
        # ...
    },
    {
        'key_5' => '14.271 text',
        # ...
    },
);
</code>```

So, the array elements are sorted based on key_5 of the hash elements.

Important: Cannot use any perl packages that are not shipped with native perl installation. Using perl 5.18

答:
Using Sort::Key::Natural:

```<code>use Sort::Key::Natural qw( natkeysort );

my @sorted = natkeysort { $_->{key_5} } @unsorted;
</code>```

The above produces the following from your input:

```<code>[
    {
        'key_5' => '13.271 text'
        # ...
    },
    {
        'key_5' => '14.271 text'
        # ...
    },
    {
        'key_5' => 'etext'
        # ...
    },
    {
        'key_5' => 'text'
        # ...
    },
]
</code>```

If that's not good enough, you can use the following:

```<code>use Sort::Key::Multi qw( unskeysort );   # uns = (u)nsigned int, (n)umber, (s)tring

my @sorted =
   unskeysort {
      $_->{key_5} =~ /^([0-9.]+)\s+(.*)/s
         ? ( 1, $1, $2 )
         : ( 0, 0, $_->{key_5} )
   }
      @unsorted;
</code>```

Body:
It's a very easy problem but can't get my way around it. I have an array of hashes. The data structure as follows:

my @unsorted = (
    {
        'key_5' => '14.271 text',
        # ...
    },
    {
        'key_5' => 'text',
        # ...
    },
    {
        'key_5' => '13.271 text',
        # ...
    },
    {
        'key_5' => 'etext',
        # ...
    },
);

How can I sort the array based on key_5 of the hash. The string part should be sorted alphabetically. and where the key is number string (format is always like this),it should be sorted numerically (ignoring the string part completely). So the output would look like, either:

my @sorted = (
    {
        'key_5' => 'etext',
        # ...
    },
    {
        'key_5' => 'text',
        # ...
    },
    {
        'key_5' => '13.271 text',
        # ...
    },
    {
        'key_5' => '14.271 text',
        # ...
    },
);

So, the array elements are sorted based on key_5 of the hash elements.

Important: Cannot use any perl packages that are not shipped with native perl installation. Using perl 5.18

Body:
Using Sort::Key::Natural:

use Sort::Key::Natural qw( natkeysort );

my @sorted = natkeysort { $_->{key_5} } @unsorted;

The above produces the following from your input:

[
    {
        'key_5' => '13.271 text'
        # ...
    },
    {
        'key_5' => '14.271 text'
        # ...
    },
    {
        'key_5' => 'etext'
        # ...
    },
    {
        'key_5' => 'text'
        # ...
    },
]

If that's not good enough, you can use the following:

use Sort::Key::Multi qw( unskeysort );   # uns = (u)nsigned int, (n)umber, (s)tring

my @sorted =
   unskeysort {
      $_->{key_5} =~ /^([0-9.]+)\s+(.*)/s
         ? ( 1, $1, $2 )
         : ( 0, 0, $_->{key_5} )
   }
      @unsorted;


问:
Flutter DropdownMenuItem in separate widget file
I have an issue with refactoring my code of DropdownButton widget in Flutter. I have simple DropdownButton.

```<code>DropdownButton(
  items: [
    DropdownMenuItem(
      child: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text('Ascending'),
            if (widget.currentDateSortOrder == SortOrderType.Ascending)
              Icon(Icons.check)
          ],
        ),
      ),
      value: 'Asc',
    ),
    DropdownMenuItem(
      child: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text('Descending'),
            if (widget.currentDateSortOrder == SortOrderType.Descending)
              Icon(Icons.check)
          ],
        ),
      ),
      value: 'Desc',
    )
  ],
  onChanged: (itemIdentifier) {
    ...
  },
)
</code>```

I want to move DropdownMenuItem to separate widget to make my widget tree leaner. So I then moved it.

```<code>import 'package:flutter/material.dart';

class FileListDropdownMenuItem extends StatelessWidget {
  final String labelText;
  final bool showSelectedMark;
  final String itemValue;

  FileListDropdownMenuItem(this.labelText, this.showSelectedMark, this.itemValue);

  @override
  Widget build(BuildContext context) {
    return DropdownMenuItem(
      child: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(labelText),
            if (showSelectedMark)
              Icon(Icons.check)
          ],
        ),
      ),
      value: itemValue,
    );
  }
}
</code>```

And when I'm trying to use it in DropdownButton like this:

```<code>...
items: [
  FileListDropdownMenuItem(
      'Ascending',
      widget.currentDateSortOrder == SortOrderType.Ascending,
      'Asc')
],
...
</code>```

I get this error:

```<code>The argument type 'List<FileListDropdownMenuItem>' can't be assigned to the parameter type 'List<DropdownMenuItem<dynamic>>'.
</code>```

Is there a way to make such approach work? I know that I can leave DropdownMenuItem in DropdownButton and move only 'child' property of it to the separate widget. However then I would have to manage 'value' and other properties of DropdownMenuItem in the main file.

答:
DropdownButton requires its items to be List<DropdownMenuItem>. But your class, FileListDropdownMenuItem, extends just StatelessWidget. If you want to use it as replacement for DropdownMenuItem, you should extend it:

class FileListDropdownMenuItem extends DropdownMenuItem {
  FileListDropdownMenuItem(
    String labelText,
    bool showSelectedMark,
    String itemValue,
  ) : super(
    child: Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(labelText),
          if (showSelectedMark)
            Icon(Icons.check)
        ],
      ),
    ),
    value: itemValue,
  );
}
```

Body:
I have an issue with refactoring my code of DropdownButton widget in Flutter. I have simple DropdownButton.

DropdownButton(
  items: [
    DropdownMenuItem(
      child: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text('Ascending'),
            if (widget.currentDateSortOrder == SortOrderType.Ascending)
              Icon(Icons.check)
          ],
        ),
      ),
      value: 'Asc',
    ),
    DropdownMenuItem(
      child: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text('Descending'),
            if (widget.currentDateSortOrder == SortOrderType.Descending)
              Icon(Icons.check)
          ],
        ),
      ),
      value: 'Desc',
    )
  ],
  onChanged: (itemIdentifier) {
    ...
  },
)

I want to move DropdownMenuItem to separate widget to make my widget tree leaner. So I then moved it.

import 'package:flutter/material.dart';

class FileListDropdownMenuItem extends StatelessWidget {
  final String labelText;
  final bool showSelectedMark;
  final String itemValue;

  FileListDropdownMenuItem(this.labelText, this.showSelectedMark, this.itemValue);

  @override
  Widget build(BuildContext context) {
    return DropdownMenuItem(
      child: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(labelText),
            if (showSelectedMark)
              Icon(Icons.check)
          ],
        ),
      ),
      value: itemValue,
    );
  }
}

And when I'm trying to use it in DropdownButton like this:

...
items: [
  FileListDropdownMenuItem(
      'Ascending',
      widget.currentDateSortOrder == SortOrderType.Ascending,
      'Asc')
],
...

I get this error:

The argument type 'List<FileListDropdownMenuItem>' can't be assigned to the parameter type 'List<DropdownMenuItem<dynamic>>'.

Is there a way to make such approach work? I know that I can leave DropdownMenuItem in DropdownButton and move only 'child' property of it to the separate widget. However then I would have to manage 'value' and other properties of DropdownMenuItem in the main file.


问:
Is it possible to avoid this loop using numpy?
Suppose you have two numpy matrices:

```<code>import numpy as np

n = 800
m = 16
A = np.zeros((n, 4)) #np.random.rand(n,4) if you wish
B = np.zeros(m)      #np.random.rand(m) if you wish
</code>```

In my code, I need to substract each value found in B to all values of A, then calculate that square and get the index that give me the minimum of that new matrix. Therefore, I will have m minimums. From those, I need the minimum. To do this now I use a loop such:

```<code>min_C = np.zeros(m)

for j in range(m):
    C = A[:,2]-B[j]
    C = C*C
    min_C[j] = np.where(C == np.amin(C))[0][0]
</code>```

So I have a minimum for each j. Then, I do the minimum of min_C. Can I avoid this loop to obtain the absolute minimum? I cannot imagine now how to code it, if possible. It's just to improve efficency in my code, which I need it, since this calculation is done lots of times with differents A and B, of course.

答:
I'll assume that the fixed index 2 that appears in your sample code will remain fixed, which reduces the problem to the case that A is one-dimensional.
If I understand the question correctly and looking at the output of your sample, you are looking for an index and not the value appearing in one of the C's itself, such that we can replace the square with the absolute value. First, we create this absolute value of all combinations of A[i,2] and B[j] via the broadcasting tip by @yatu, and then we compute the minimum of the argmins along the second axis (of size n)

```<code>c = np.abs(A[:,2]-B[:,None])
answer = np.min(np.argmin(c, axis=1))
</code>```

I hope I got correctly what you asked for, if the fixed index of A is to be varied, extend the broadcasting:

```<code>c = np.abs(A[:,:]-B[:,None,None])
answer = np.min(np.argmin(c, axis=1))
</code>```

The output will be an int, which differs from your sample code.

Body:
Suppose you have two numpy matrices:

import numpy as np

n = 800
m = 16
A = np.zeros((n, 4)) #np.random.rand(n,4) if you wish
B = np.zeros(m)      #np.random.rand(m) if you wish

In my code, I need to substract each value found in B to all values of A, then calculate that square and get the index that give me the minimum of that new matrix. Therefore, I will have m minimums. From those, I need the minimum. To do this now I use a loop such:

min_C = np.zeros(m)

for j in range(m):
    C = A[:,2]-B[j]
    C = C*C
    min_C[j] = np.where(C == np.amin(C))[0][0]

So I have a minimum for each j. Then, I do the minimum of min_C. Can I avoid this loop to obtain the absolute minimum? I cannot imagine now how to code it, if possible. It's just to improve efficency in my code, which I need it, since this calculation is done lots of times with differents A and B, of course.

Body:
I'll assume that the fixed index 2 that appears in your sample code will remain fixed, which reduces the problem to the case that A is one-dimensional.
If I understand the question correctly and looking at the output of your sample, you are looking for an index and not the value appearing in one of the C's itself, such that we can replace the square with the absolute value. First, we create this absolute value of all combinations of A[i,2] and B[j] via the broadcasting tip by @yatu, and then we compute the minimum of the argmins along the second axis (of size n)

c = np.abs(A[:,2]-B[:,None])
answer = np.min(np.argmin(c, axis=1))

I hope I got correctly what you asked for, if the fixed index of A is to be varied, extend the broadcasting:

c = np.abs(A[:,:]-B[:,None,None])
answer = np.min(np.argmin(c, axis=1))

The output will be an int, which differs from your sample code.


问:
AjaxControlToolkit - Extenders - Whats the "current" approach?
Currently, I have a ASP.net 3.5 web application for which I currently am working on the UI.I have been out of touch of doing web ui's for a while.

When i last did UI related work (way back in 2007), i used the Ajax Control Toolkit - specially the extenders like MaskedEdit Extender etc for implementing a lot of the UI functionality i.e restricting the user from entering incorrect data / formatting etc.

Question 1:-
Is there a newer / better / easier way of implementing the functionality similar to the extenders provided by AjaxToolkit that someone would recommend?

Question 2
Also, my current application needs to support multiple cultures in terms of the number / date formatting. In my experience with Ajax extenders, for eg in MaskedEditExtender, I would have to specify the Mask explicitly which defeats the whole purpose of it being able to switch formats depending on the currently selected culture. Is anyone aware of the latest / greatest way in terms of controls etc that I can achieve this?

Note: I am open to lightweight 3rd party controls that could help me do this but would prefer not to touch heavycontrols like infragistics / telerik kinds mainly due to their  learning curve / cost.

答:
A combination of:

web services (asmx or mvc)

jQuery ajax

jQuery UI

Along with the plethora of jQuery plug-ins available would be my recommendation for both light weight, and a good abundance of supporting help as well as plug-ins and very active development.

IF you need a bit more you should look a the http://www.obout.com/ controls as an option.


问:
issue with calling function inside the other function
I am getting a response as  "Cannot read property 'addEventListener' of undefined " error  while calling deleteButtons() function inside displayCart() function. Can anyone help me with this issue?

```<code>  function displayCart() {
let cartItems = localStorage.getItem('productsInCart');
cartItems = JSON.parse(cartItems);

let productContainer = document.querySelector(".products");
let cartCost = localStorage.getItem('totalCost');
</code>```

//  console.log(cartItems);---pulling data from localstorage

```<code>console.log(cartItems);

if(cartItems && productContainer) {

    productContainer.innerHTML ='';
    Object.values(cartItems).map(item => {
    productContainer.innerHTML +=
        `
        <div class="products">
        <ion-icon name="close-circle-outline"></ion-icon>

         <span>${item.name}</span>

    <div class="price">$${item.price},00</div>
    <div class="quantity">
        <ion-icon name="caret-back-circle-outline">Remove</ion-icon>

        <span>${item.incart}</span>
        <ion-icon name="caret-forward-circle-outline"></ion-icon>
    </div>
    <div class="total">
    $${item.incart * item.price},00
    </div>
    </div>
        `
    ;
    });

    productContainer.innerHTML +=
        `
        <div class="basketTotalContainer">
        <h4 class="basketTotalTitle"> Basket Total </h4>
        <h4 class ="basketTotal">
            $${cartCost},00
        </h4>
    </div>

        `;
 }
</code>```

deleteButtons();
    }

function deleteButtons() {

```<code>let deleteButtons = document.querySelectorAll('.product ion-icon');
let productName;
let productNumbers = localStorage.getItem('cartNumbers')
let cartItems = localStorage.getItem('productsInCart');
cartItems = JSON.parse(cartItems);
let cartCost = localStorage.getItem('totalCost');
console.log(cartItems);

for(let i=0; i < 10; i++)
{

    deleteButtons[i].addEventListener('click', () => {
    productName = deleteButtons[i].parentElement.textContent.trim().toLowerCase().replace(/ /g, '');
console.log(productName);
console.log(cartItems[productName].price + " " + cartItems[productName].incart);
localStorage.setItem('cartNumbers',productNumbers - cartItems[productName].incart);
localStorage.setItem('totalCost', cartCost - (cartItems[productName].price * cartItems[productName].incart));
delete cartItems[productName];
localStorage.setItem('productsInCart', JSON.stringify(cartItems));
    });
}
}
</code>```

答:
I see 2 things to consider:

The class name mismatch .product when it should be .products

You are using an arbitrary fixed number (10) to iterate over a dynamically allocated collection of elements.

Since the collection is dynamic you should use the size of it in order to know when to stop your loop, in this case by using deleteButtons.length

Se the runnable example below:

let deleteButtons = document.querySelectorAll('.products ion-icon')

for(let i=0; i < deleteButtons.length; i++) {
  console.log(i)
  deleteButtons[i].addEventListener('click', () => {
    console.log(`This is the deleteButtons #${i}`);
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { font-family: sans-serif; }
ion-icon { cursor: pointer; padding 1em; margin: 1em 0; border: 1px solid #333 }</code>```

  <ion-icon name="close-circle-outline">A</ion-icon>
  ${item.name}

$${item.price},00

    <ion-icon name="caret-back-circle-outline">Remove</ion-icon>
    ${item.incart}
    <ion-icon name="caret-forward-circle-outline">X</ion-icon>

  $${item.incart * item.price},00

```

Body:
I am getting a response as  "Cannot read property 'addEventListener' of undefined " error  while calling deleteButtons() function inside displayCart() function. Can anyone help me with this issue?

  function displayCart() {
let cartItems = localStorage.getItem('productsInCart');
cartItems = JSON.parse(cartItems);

let productContainer = document.querySelector(".products");
let cartCost = localStorage.getItem('totalCost');

//  console.log(cartItems);---pulling data from localstorage

console.log(cartItems);

if(cartItems && productContainer) {

    productContainer.innerHTML ='';
    Object.values(cartItems).map(item => {
    productContainer.innerHTML +=
        `

        <ion-icon name="close-circle-outline"></ion-icon>

         ${item.name}

$${item.price},00

        <ion-icon name="caret-back-circle-outline">Remove</ion-icon>

        ${item.incart}
        <ion-icon name="caret-forward-circle-outline"></ion-icon>

    $${item.incart * item.price},00

        `
    ;
    });

    productContainer.innerHTML +=
        `

 Basket Total

            $${cartCost},00

        `;
 }

deleteButtons();
    }

function deleteButtons() {

let deleteButtons = document.querySelectorAll('.product ion-icon');
let productName;
let productNumbers = localStorage.getItem('cartNumbers')
let cartItems = localStorage.getItem('productsInCart');
cartItems = JSON.parse(cartItems);
let cartCost = localStorage.getItem('totalCost');
console.log(cartItems);

for(let i=0; i < 10; i++)
{

    deleteButtons[i].addEventListener('click', () => {
    productName = deleteButtons[i].parentElement.textContent.trim().toLowerCase().replace(/ /g, '');
console.log(productName);
console.log(cartItems[productName].price + " " + cartItems[productName].incart);
localStorage.setItem('cartNumbers',productNumbers - cartItems[productName].incart);
localStorage.setItem('totalCost', cartCost - (cartItems[productName].price * cartItems[productName].incart));
delete cartItems[productName];
localStorage.setItem('productsInCart', JSON.stringify(cartItems));
    });
}
}

Body:
I see 2 things to consider:

The class name mismatch .product when it should be .products

You are using an arbitrary fixed number (10) to iterate over a dynamically allocated collection of elements.

Since the collection is dynamic you should use the size of it in order to know when to stop your loop, in this case by using deleteButtons.length

Se the runnable example below:

let deleteButtons = document.querySelectorAll('.products ion-icon')

for(let i=0; i < deleteButtons.length; i++) {
  console.log(i)
  deleteButtons[i].addEventListener('click', () => {
    console.log(`This is the deleteButtons #${i}`);
  });
}

body { font-family: sans-serif; }
ion-icon { cursor: pointer; padding 1em; margin: 1em 0; border: 1px solid #333 }

<hr/>
<div class="products">
  <ion-icon name="close-circle-outline">A</ion-icon>
  <span>${item.name}</span>
  <div class="price">$${item.price},00</div>
  <div class="quantity">
    <ion-icon name="caret-back-circle-outline">Remove</ion-icon>
    <span>${item.incart}</span>
    <ion-icon name="caret-forward-circle-outline">X</ion-icon>
  </div>
  <div class="total">
  $${item.incart * item.price},00
</div>