问:
NetBeans HQL editor wrong translation to SQL
I'm trying to access a MySQL database from a Java webservice. I'm using the NetBeans IDE and am following the tutorial Using Hibernate in a Web Application

Now when I try to test the HQL query: from calls I get:

```<code>org.hibernate.exception.SQLGrammarException: could not execute query
    blablabla
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from limit 100' at line 1
    bla, bla, bla
</code>```

And the translated SQL is also wrong:

```<code>select  from
</code>```

I created the calls.java class using Hibernate Reverse Engineering.

This is the Hibernate.cfg.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/datacheck</property>
        <property name="hibernate.connection.username">admin</property>
        <property name="hibernate.connection.password">####</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
    </session-factory>
</hibernate-configuration>
</code>```

I can't seem to find the error, and I searched the whole Internet :p

A similar thread is HQL Editor not appending table name in query.

答:
I typed the HQL query

```<code>from call
</code>```

while it should be:

```<code>from Call
</code>```

with a capital first letter.

Dumb mistake, I thought it was the database table, but apparently it's the POJO name that you have to specify.

Body:
I'm trying to access a MySQL database from a Java webservice. I'm using the NetBeans IDE and am following the tutorial Using Hibernate in a Web Application

Now when I try to test the HQL query: from calls I get:

org.hibernate.exception.SQLGrammarException: could not execute query
    blablabla
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from limit 100' at line 1
    bla, bla, bla

And the translated SQL is also wrong:

select  from

I created the calls.java class using Hibernate Reverse Engineering.

This is the Hibernate.cfg.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/datacheck</property>
        <property name="hibernate.connection.username">admin</property>
        <property name="hibernate.connection.password">####</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
    </session-factory>
</hibernate-configuration>

I can't seem to find the error, and I searched the whole Internet :p

A similar thread is HQL Editor not appending table name in query.

Body:
I typed the HQL query

from call

while it should be:

from Call

with a capital first letter.

Dumb mistake, I thought it was the database table, but apparently it's the POJO name that you have to specify.


来源: stackexchange

问:
How to split expressJS server code into different files
This is just a part of my express server. I would like to split the code to different files.

```<code>import express from 'express'
const app = express()

app.get('/import', async (req, res) => {
  var fs = require('fs')

  fs.createReadStream('./src/data.csv')
    .pipe(parse({
      delimiter: ',',
      skip_lines_with_error: true
    }))
    .on('error', function (err) { console.log(err) })
    .on('data', async function (row) {
      // do a lot of stuff here
    })

  res.status(200)
})
</code>```

In this case the import should be imported from another file, but I don't know how to do that.

helper/import.js

```<code>export const import = (req, res) => {
  var fs = require('fs')

  fs.createReadStream('./src/data.csv')
    .pipe(parse({
      delimiter: ',',
      skip_lines_with_error: true
    }))
    .on('error', function (err) { console.log(err) })
    .on('data', async function (row) {
      // do a lot of stuff here
    })

  res.status(200)
}
</code>```

server.js

```<code>import express from 'express'
const app = express()

app.get('/import') // <-- ??
</code>```

How do I get the async function here?

答:
So you basically want to put routes in a different file.

I tend to create a folder with all my 'routes' in.

Let's use import.js as an example.. here's what the file would look like:

```<code>const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  var fs = require('fs')

  fs.createReadStream('./src/data.csv')
    .pipe(parse({
      delimiter: ',',
      skip_lines_with_error: true
    }))
    .on('error', function (err) { console.log(err) })
    .on('data', async function (row) {
      // do a lot of stuff here
    })

  res.status(200)
});

module.exports = router;
</code>```

Your server.js would then implement that...

```<code>const importRouter = require("./helper/import.js");

app.use('/import', importRouter);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is just a part of my express server. I would like to split the code to different files.

import express from 'express'
const app = express()

app.get('/import', async (req, res) => {
  var fs = require('fs')

  fs.createReadStream('./src/data.csv')
    .pipe(parse({
      delimiter: ',',
      skip_lines_with_error: true
    }))
    .on('error', function (err) { console.log(err) })
    .on('data', async function (row) {
      // do a lot of stuff here
    })

  res.status(200)
})

In this case the import should be imported from another file, but I don't know how to do that.

helper/import.js

export const import = (req, res) => {
  var fs = require('fs')

  fs.createReadStream('./src/data.csv')
    .pipe(parse({
      delimiter: ',',
      skip_lines_with_error: true
    }))
    .on('error', function (err) { console.log(err) })
    .on('data', async function (row) {
      // do a lot of stuff here
    })

  res.status(200)
}

server.js

import express from 'express'
const app = express()

app.get('/import') // <-- ??

How do I get the async function here?

Body:
So you basically want to put routes in a different file.

I tend to create a folder with all my 'routes' in.

Let's use import.js as an example.. here's what the file would look like:

const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  var fs = require('fs')

  fs.createReadStream('./src/data.csv')
    .pipe(parse({
      delimiter: ',',
      skip_lines_with_error: true
    }))
    .on('error', function (err) { console.log(err) })
    .on('data', async function (row) {
      // do a lot of stuff here
    })

  res.status(200)
});

module.exports = router;

Your server.js would then implement that...

const importRouter = require("./helper/import.js");

app.use('/import', importRouter);


问:
Removing duplicates from List<double[]>
I am trying to remove the duplicates from a list of double arrays. I would like to keep the first instance of the duplicate but remove any found after.

Here is my code:

```<code>private static List<double[]> RemoveDupes(List<double[]> locData)
    {
        List<double[]> list = locData;
        while (ContainsDupes(list))
            for (int a = 0; a < list.Count; a++)
                for (int b = 0; b < list.Count; b++)
                    if (a != b && list[a][0] == list[b][0] && list[a][1] == list[b][1])
                        list.RemoveAt(b);

        return list;
    }
private static bool ContainsDupes(List<double[]> list)
    {
        for (int a = 0; a < list.Count; a++)
            for (int b = 0; b < list.Count; b++)
                if (a != b && list[a][0] == list[b][0] && list[a][1] == list[b][1])
                    return true;
        return false;
    }
</code>```

This method works almost all of the time but it's slow and in edge cases (1 out of a few thousand) it crashes my program with an index exception on line 6. I can't think of any other way to do this so any help would be appreciated.

Input:

```<code>{{45.5, 23.6}, {34.54, 98.34}, {45.5, 23.6}}
</code>```

Desired output:

```<code>{{45.5, 23.6}, {34.54, 98.34}}
</code>```

(length of the double[] is always 2)

答:
Since you've stated that array will always be size of 2, I suggest you to use different data type. For example, tuple would be more appropriate, because these are actually pairs of values.

For example, you could define a collection of pairs:

List<(double, double)> pairs = new List<(double, double)>(); //C# 7.1+

List<Tuple<double, double>> pairsCollection = new List<Tuple<double, double>>(); // C# 7 or less

Seed it in this manner:

```<code>pairs.Add((45.5, 23.6));
pairs.Add((34.54, 98.34));
pairs.Add((45.5, 23.6));
</code>```

And than, just use Distinct method, to remove duplicates:

```<code>pairs.Distinct();
</code>```

This would output:

{{45.5, 23.6}, {34.54, 98.34}}

In addition, if you are not able to change the data type, you can project the collection into collection of pairs, and than distinct it:

```<code>List<double[]> collection = new List<double[]>()
{
    new double[]{45.5, 23.6},
    new double[]{34.54, 98.34},
    new double[]{45.5, 23.6}
};
var pairs = collection.Select(pa => (pa[0], pa[1]));
var distinctPairs = pairs.Distinct();
</code>```

Title: Removing duplicates from List<double[]>

Body:
I am trying to remove the duplicates from a list of double arrays. I would like to keep the first instance of the duplicate but remove any found after.

Here is my code:

private static List<double[]> RemoveDupes(List<double[]> locData)
    {
        List<double[]> list = locData;
        while (ContainsDupes(list))
            for (int a = 0; a < list.Count; a++)
                for (int b = 0; b < list.Count; b++)
                    if (a != b && list[a][0] == list[b][0] && list[a][1] == list[b][1])
                        list.RemoveAt(b);

        return list;
    }
private static bool ContainsDupes(List<double[]> list)
    {
        for (int a = 0; a < list.Count; a++)
            for (int b = 0; b < list.Count; b++)
                if (a != b && list[a][0] == list[b][0] && list[a][1] == list[b][1])
                    return true;
        return false;
    }

This method works almost all of the time but it's slow and in edge cases (1 out of a few thousand) it crashes my program with an index exception on line 6. I can't think of any other way to do this so any help would be appreciated.

Input:

{{45.5, 23.6}, {34.54, 98.34}, {45.5, 23.6}}

Desired output:

{{45.5, 23.6}, {34.54, 98.34}}

(length of the double[] is always 2)

Body:
Since you've stated that array will always be size of 2, I suggest you to use different data type. For example, tuple would be more appropriate, because these are actually pairs of values.

For example, you could define a collection of pairs:

List<(double, double)> pairs = new List<(double, double)>(); //C# 7.1+

List<Tuple<double, double>> pairsCollection = new List<Tuple<double, double>>(); // C# 7 or less

Seed it in this manner:

pairs.Add((45.5, 23.6));
pairs.Add((34.54, 98.34));
pairs.Add((45.5, 23.6));

And than, just use Distinct method, to remove duplicates:

pairs.Distinct();

This would output:

{{45.5, 23.6}, {34.54, 98.34}}

In addition, if you are not able to change the data type, you can project the collection into collection of pairs, and than distinct it:

List<double[]> collection = new List<double[]>()
{
    new double[]{45.5, 23.6},
    new double[]{34.54, 98.34},
    new double[]{45.5, 23.6}
};
var pairs = collection.Select(pa => (pa[0], pa[1]));
var distinctPairs = pairs.Distinct();


问:
React router location only updated in some components
Whether using links or this.props.history.push(), URL in the address bar is updating correctly, as well as this.props.location in a component which is higher up the DOM tree (in this case, my App component).

However, for some reason it is not updating this.props.location in my components which are further down the tree, which is causing my routes to fail.

Any guesses on what could be going wrong?

NOTE: I am using redux in this project, but I'm not changing the this.props.history using redux, at least for now. I don't think this should impact anything, but if it is , let me know

edit: Here is the relevant portion of the DOM tree (with my email carefully scratched out) if it's helpful. As you can see, the Authenticated component has an outdated this.props.location (/plans), whereas the App is correct (/posts). Both are wrapped in withRouter. Components further down the tree than Authenticated also have the wrong location.

答:
In my case it was a mistake in js entry point. My code was:

```<code>ReactDOM.render(
    <BrowserRouter>
        <App/>                       // <- missing Route!
    </BrowserRouter>,
    document.getElementById("app")
);
</code>```

And I fixed it by adding <Route/>:

```<code>ReactDOM.render(
    <BrowserRouter>
        <Route component={App}/>
    </BrowserRouter>,
    document.getElementById("app")
);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my case it was a mistake in js entry point. My code was:

ReactDOM.render(
    <BrowserRouter>
        <App/>                       // <- missing Route!
    </BrowserRouter>,
    document.getElementById("app")
);

And I fixed it by adding <Route/>:

ReactDOM.render(
    <BrowserRouter>
        <Route component={App}/>
    </BrowserRouter>,
    document.getElementById("app")
);


问:
Is sed auto in-place substitution?
I have this code, which I do want for replacement of a specific pattern, but not multi in-place replacement.

```<code> echo "ss qq" | sed  "s/ss/qq/g; s/qq/dd/g;"
</code>```

The result is

```<code>dd dd
</code>```

and wish it would be

```<code>qq dd
</code>```

Also via "looping" we get the same result.

```<code>echo "ss qq" | sed  ":loop; s/ss/qq/g; s/qq/dd/g; t loop;"
</code>```

its petty, very disappointing bug !!

Any suggestion why it's happening?

答:
As for "why it's happening": sed takes the input line by line, then applies each command sequentially. This becomes more clear if you look at the debug output of GNU sed (4.6 or newer) for your command:</p>

```<code>$ sed --debug 's/ss/qq/g;s/qq/dd/g' <<< 'ss qq'
SED PROGRAM:
  s/ss/qq/g
  s/qq/dd/g
INPUT:   'STDIN' line 1
PATTERN: ss qq           # Pattern space before first command is applied
COMMAND: s/ss/qq/g
MATCHED REGEX REGISTERS
  regex[0] = 0-2 'ss'
PATTERN: qq qq           # Pattern space before second command is applied
COMMAND: s/qq/dd/g
MATCHED REGEX REGISTERS
  regex[0] = 0-2 'qq'
PATTERN: dd dd
END-OF-CYCLE:
dd dd
</code>```

Title: Is sed auto in-place substitution?

Body:
I have this code, which I do want for replacement of a specific pattern, but not multi in-place replacement.

 echo "ss qq" | sed  "s/ss/qq/g; s/qq/dd/g;"

The result is

dd dd

and wish it would be

qq dd

Also via "looping" we get the same result.

echo "ss qq" | sed  ":loop; s/ss/qq/g; s/qq/dd/g; t loop;"

its petty, very disappointing bug !!

Any suggestion why it's happening?

Body:
As for "why it's happening": sed takes the input line by line, then applies each command sequentially. This becomes more clear if you look at the debug output of GNU sed (4.6 or newer) for your command:

$ sed --debug 's/ss/qq/g;s/qq/dd/g' <<< 'ss qq'
SED PROGRAM:
  s/ss/qq/g
  s/qq/dd/g
INPUT:   'STDIN' line 1
PATTERN: ss qq           # Pattern space before first command is applied
COMMAND: s/ss/qq/g
MATCHED REGEX REGISTERS
  regex[0] = 0-2 'ss'
PATTERN: qq qq           # Pattern space before second command is applied
COMMAND: s/qq/dd/g
MATCHED REGEX REGISTERS
  regex[0] = 0-2 'qq'
PATTERN: dd dd
END-OF-CYCLE:
dd dd


问:
How to create a custom ListView with "extends Activity"?
I am learning android programming, I was able to create a custom ListView
with:

```<code>public class project1 extends ListActivity
{
....
}
</code>```

With a xml file for the custom layout.
i would like to know how to do the same thing but with

```<code>public class project1 extends Activity

    {
    ....
    }
</code>```

All the tutorials I looked at use extends ListActivity, I know that its there to
make things simpler, but for the sake of learning how to do it the hard way???

答:
Have a look at this tutorial. http://techdroid.kbeanie.com/2009/07/custom-listview-for-android.html

Go thru this post. It is advanced some what : Lazy load of images in ListView

Edited According to your comment :

Consider example of displaying list of countries and their abbreviated names

First for Custom ListView you have to create an xml file representing your listview :

```<code> <?xml version="1.0" encoding="utf-8"?>
 <!--main.xml-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffccd0"
>
     <TextView
        android:text="Countries List"
        android:textColor="#b3000d"
        android:gravity="center_vertical|center_horizontal"
        android:textSize="26dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:background="#ffb0b6"
        android:layout_marginBottom="5dip"
        android:typeface="sans"/>
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#570000">
    <TextView android:id="@+id/tv_1"
        android:textColor="#FFFFFF"
        android:gravity="center_vertical|left"
        android:textSize="16dip"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_width="70dip"
        android:paddingLeft="20dip"
        android:text="Abbr">
    </TextView>
    <TextView android:id="@+id/tv_2"
        android:textColor="#FFFFFF"
        android:gravity="center_vertical|left"
        android:textSize="16dip"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_width="200dip"
        android:layout_toRightOf="@+id/tv_1"
        android:text="Countries">
    </TextView>

</RelativeLayout>
<ListView
    android:id="@+id/lv_country"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:cacheColorHint="#00000000">
</ListView>
 </LinearLayout>
</code>```

Now you  have to create an xml file representing a row of list item.
This is my row.xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:gravity="left|center"
android:layout_width="wrap_content"
android:paddingBottom="10px"
android:paddingTop="10px"
android:paddingLeft="3px">
 <TextView
    android:id="@+id/TextView01"
    android:layout_width="70dip"
    android:scrollHorizontally="true"
    android:layout_height="wrap_content"
    android:gravity="left"
    android:layout_weight="1"
    android:singleLine="true"
    android:textSize="15dip"
    android:textStyle="bold"
    android:textColor="#d08021"
    android:paddingLeft="20dip">
 </TextView>
 <TextView
    android:id="@+id/TextView02"
    android:layout_weight="2"
    android:layout_width="200dip"
    android:scrollHorizontally="true"
    android:layout_height="wrap_content"
    android:gravity="left"
    android:singleLine="true"
    android:layout_marginLeft="10dip"
    android:textSize="15dip"
    android:textStyle="bold"
    android:textColor="#7f0000">
 </TextView>
</LinearLayout>
</code>```

As you want to display array of strings in ListView, i have used static Array of Strings and stored in CountriesList.java file.

This is my CountriesList.java file :

```<code>public class CountriesList {
public static String[] countries = { "Afghanistan", "Albania Albania Albania AlbaniaAlbaniaAlbaniaAlbania Albania ", "Algeria",
        "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica",
        "Antigua and Barbuda", "Argentina", "Armenia", "Aruba",
        "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain",
        "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin",
        "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina",
        "Botswana", "Bouvet Island", "Brazil",
        "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria",
        "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada",
        "Cape Verde", "Cayman Islands", "Central African Republic", "Chad",
        "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands",
        "Colombia", "Comoros", "Congo",
        "Congo, the Democratic Republic of the", "Cook Islands",
        "Costa Rica", "Cote D'Ivoire", "Croatia", "Cuba", "Cyprus",
        "Czech Republic", "Denmark", "Djibouti", "Dominica",
        "Dominican Republic", "Ecuador", "Egypt", "El Salvador",
        "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia",
        "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland",
        "France", "French Guiana", "French Polynesia",
        "French Southern Territories", "Gabon", "Gambia", "Georgia",
        "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada",
        "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
        "Guyana", "Haiti", "Heard Island and Mcdonald Islands",
        "Holy See (Vatican City State)", "Honduras", "Hong Kong",
        "Hungary", "Iceland", "India", "Indonesia",
        "Iran, Islamic Republic of", "Iraq", "Ireland", "Israel", "Italy",
        "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati",
        "Korea, Democratic People's Republic of", "Korea, Republic of",
        "Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic",
        "Latvia", "Lebanon", "Lesotho", "Liberia",
        "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania",
        "Luxembourg", "Macao",
        "Macedonia, the Former Yugoslav Republic of", "Madagascar",
        "Malawi", "Malaysia", "Maldives", "Mali", "Malta",
        "Marshall Islands", "Martinique", "Mauritania", "Mauritius",
        "Mayotte", "Mexico", "Micronesia, Federated States of",
        "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat",
        "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal",
        "Netherlands", "Netherlands Antilles", "New Caledonia",
        "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue",
        "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman",
        "Pakistan", "Palau", "Palestinian Territory, Occupied", "Panama",
        "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn",
        "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania",
        "Russian Federation", "Rwanda", "Saint Helena",
        "Saint Kitts and Nevis", "Saint Lucia",
        "Saint Pierre and Miquelon", "Saint Vincent and the Grenadines",
        "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia",
        "Senegal", "Serbia and Montenegro", "Seychelles", "Sierra Leone",
        "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia",
        "South Africa", "South Georgia and the South Sandwich Islands",
        "Spain", "Sri Lanka", "Sudan", "Suriname",
        "Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland",
        "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan",
        "Tanzania, United Republic of", "Thailand", "Timor-Leste", "Togo",
        "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
        "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda",
        "Ukraine", "United Arab Emirates", "United Kingdom",
        "United States", "United States Minor Outlying Islands", "Uruguay",
        "Uzbekistan", "Vanuatu", "Venezuela", "Viet Nam",
        "Virgin Islands, British", "Virgin Islands, U.s.",
        "Wallis and Futuna", "Western Sahara", "Yemen", "Zambia",
        "Zimbabwe" };
public static String[] abbreviations = { "AF Western Sahara Western SaharaWestern Sahara Western SaharaWestern Sahara", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ",
        "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB",
        "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BV", "BR",
        "IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF",
        "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR",
        "CI", "HR", "CU", "CY", "CZ", "DK", "DJ", "DM", "DO", "EC", "EG",
        "SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF",
        "PF", "TF", "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD",
        "GP", "GU", "GT", "GN", "GW", "GY", "HT", "HM", "VA", "HN", "HK",
        "HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IL", "IT", "JM", "JP",
        "JO", "KZ", "KE", "KI", "KP", "KR", "KW", "KG", "LA", "LV", "LB",
        "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MY",
        "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD",
        "MC", "MN", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "AN",
        "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK",
        "PW", "PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR",
        "QA", "RE", "RO", "RU", "RW", "SH", "KN", "LC", "PM", "VC", "WS",
        "SM", "ST", "SA", "SN", "CS", "SC", "SL", "SG", "SK", "SI", "SB",
        "SO", "ZA", "GS", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH",
        "SY", "TW", "TJ", "TZ", "TH", "TL", "TG", "TK", "TO", "TT", "TN",
        "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UM", "UY",
        "UZ", "VU", "VE", "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW" };
 }
</code>```

As you are customizing the ListView, you have create another class extending BaseAdapter, working as a controller of ListView.

So here is my EfficientAdapter.java file :

```<code>private static class EfficientAdapter extends BaseAdapter {
    private LayoutInflater mInflater;

    public EfficientAdapter(Context context) {
        mInflater = LayoutInflater.from(context);
    }

    public int getCount() {
        return CountriesList.abbreviations.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.row, null);
            holder = new ViewHolder();
            holder.text1 = (TextView) convertView
                    .findViewById(R.id.TextView01);
            holder.text2 = (TextView) convertView
                    .findViewById(R.id.TextView02);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.text1.setText(CountriesList.abbreviations[position]);
        holder.text2.setText(CountriesList.countries[position]);

        return convertView;
    }

    static class ViewHolder {
        TextView text1;
        TextView text2;
    }
}
</code>```

Now the last thing remaining is your Activity Class.
Here it is :

```<code>public class MyList extends Activity {
/** Called when the activity is first created. */
ListView listView;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    listView = (ListView) findViewById(R.id.lv_country);
    listView.setAdapter(new EfficientAdapter(this));

            listView.setOnItemClickListener(
            new OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView<?> arg0, View view,int position, long arg3) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getApplicationContext(),"You Selected Item "+Integer.toString(position), Toast.LENGTH_LONG).show();
                }
            }
    );
}
</code>```

Body:
I am learning android programming, I was able to create a custom ListView
with:

public class project1 extends ListActivity
{
....
}

With a xml file for the custom layout.
i would like to know how to do the same thing but with

public class project1 extends Activity

    {
    ....
    }

All the tutorials I looked at use extends ListActivity, I know that its there to
make things simpler, but for the sake of learning how to do it the hard way???

Body:
Have a look at this tutorial. http://techdroid.kbeanie.com/2009/07/custom-listview-for-android.html

Go thru this post. It is advanced some what : Lazy load of images in ListView

Edited According to your comment :

Consider example of displaying list of countries and their abbreviated names

First for Custom ListView you have to create an xml file representing your listview :

 <?xml version="1.0" encoding="utf-8"?>
 <!--main.xml-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffccd0"
>
     <TextView
        android:text="Countries List"
        android:textColor="#b3000d"
        android:gravity="center_vertical|center_horizontal"
        android:textSize="26dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:background="#ffb0b6"
        android:layout_marginBottom="5dip"
        android:typeface="sans"/>
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#570000">
    <TextView android:id="@+id/tv_1"
        android:textColor="#FFFFFF"
        android:gravity="center_vertical|left"
        android:textSize="16dip"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_width="70dip"
        android:paddingLeft="20dip"
        android:text="Abbr">
    </TextView>
    <TextView android:id="@+id/tv_2"
        android:textColor="#FFFFFF"
        android:gravity="center_vertical|left"
        android:textSize="16dip"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_width="200dip"
        android:layout_toRightOf="@+id/tv_1"
        android:text="Countries">
    </TextView>

</RelativeLayout>
<ListView
    android:id="@+id/lv_country"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:cacheColorHint="#00000000">
</ListView>
 </LinearLayout>

Now you  have to create an xml file representing a row of list item.
This is my row.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:gravity="left|center"
android:layout_width="wrap_content"
android:paddingBottom="10px"
android:paddingTop="10px"
android:paddingLeft="3px">
 <TextView
    android:id="@+id/TextView01"
    android:layout_width="70dip"
    android:scrollHorizontally="true"
    android:layout_height="wrap_content"
    android:gravity="left"
    android:layout_weight="1"
    android:singleLine="true"
    android:textSize="15dip"
    android:textStyle="bold"
    android:textColor="#d08021"
    android:paddingLeft="20dip">
 </TextView>
 <TextView
    android:id="@+id/TextView02"
    android:layout_weight="2"
    android:layout_width="200dip"
    android:scrollHorizontally="true"
    android:layout_height="wrap_content"
    android:gravity="left"
    android:singleLine="true"
    android:layout_marginLeft="10dip"
    android:textSize="15dip"
    android:textStyle="bold"
    android:textColor="#7f0000">
 </TextView>
</LinearLayout>

As you want to display array of strings in ListView, i have used static Array of Strings and stored in CountriesList.java file.

This is my CountriesList.java file :

public class CountriesList {
public static String[] countries = { "Afghanistan", "Albania Albania Albania AlbaniaAlbaniaAlbaniaAlbania Albania ", "Algeria",
        "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica",
        "Antigua and Barbuda", "Argentina", "Armenia", "Aruba",
        "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain",
        "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin",
        "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina",
        "Botswana", "Bouvet Island", "Brazil",
        "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria",
        "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada",
        "Cape Verde", "Cayman Islands", "Central African Republic", "Chad",
        "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands",
        "Colombia", "Comoros", "Congo",
        "Congo, the Democratic Republic of the", "Cook Islands",
        "Costa Rica", "Cote D'Ivoire", "Croatia", "Cuba", "Cyprus",
        "Czech Republic", "Denmark", "Djibouti", "Dominica",
        "Dominican Republic", "Ecuador", "Egypt", "El Salvador",
        "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia",
        "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland",
        "France", "French Guiana", "French Polynesia",
        "French Southern Territories", "Gabon", "Gambia", "Georgia",
        "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada",
        "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
        "Guyana", "Haiti", "Heard Island and Mcdonald Islands",
        "Holy See (Vatican City State)", "Honduras", "Hong Kong",
        "Hungary", "Iceland", "India", "Indonesia",
        "Iran, Islamic Republic of", "Iraq", "Ireland", "Israel", "Italy",
        "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati",
        "Korea, Democratic People's Republic of", "Korea, Republic of",
        "Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic",
        "Latvia", "Lebanon", "Lesotho", "Liberia",
        "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania",
        "Luxembourg", "Macao",
        "Macedonia, the Former Yugoslav Republic of", "Madagascar",
        "Malawi", "Malaysia", "Maldives", "Mali", "Malta",
        "Marshall Islands", "Martinique", "Mauritania", "Mauritius",
        "Mayotte", "Mexico", "Micronesia, Federated States of",
        "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat",
        "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal",
        "Netherlands", "Netherlands Antilles", "New Caledonia",
        "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue",
        "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman",
        "Pakistan", "Palau", "Palestinian Territory, Occupied", "Panama",
        "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn",
        "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania",
        "Russian Federation", "Rwanda", "Saint Helena",
        "Saint Kitts and Nevis", "Saint Lucia",
        "Saint Pierre and Miquelon", "Saint Vincent and the Grenadines",
        "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia",
        "Senegal", "Serbia and Montenegro", "Seychelles", "Sierra Leone",
        "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia",
        "South Africa", "South Georgia and the South Sandwich Islands",
        "Spain", "Sri Lanka", "Sudan", "Suriname",
        "Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland",
        "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan",
        "Tanzania, United Republic of", "Thailand", "Timor-Leste", "Togo",
        "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
        "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda",
        "Ukraine", "United Arab Emirates", "United Kingdom",
        "United States", "United States Minor Outlying Islands", "Uruguay",
        "Uzbekistan", "Vanuatu", "Venezuela", "Viet Nam",
        "Virgin Islands, British", "Virgin Islands, U.s.",
        "Wallis and Futuna", "Western Sahara", "Yemen", "Zambia",
        "Zimbabwe" };
public static String[] abbreviations = { "AF Western Sahara Western SaharaWestern Sahara Western SaharaWestern Sahara", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ",
        "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB",
        "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BA", "BW", "BV", "BR",
        "IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF",
        "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR",
        "CI", "HR", "CU", "CY", "CZ", "DK", "DJ", "DM", "DO", "EC", "EG",
        "SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF",
        "PF", "TF", "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD",
        "GP", "GU", "GT", "GN", "GW", "GY", "HT", "HM", "VA", "HN", "HK",
        "HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IL", "IT", "JM", "JP",
        "JO", "KZ", "KE", "KI", "KP", "KR", "KW", "KG", "LA", "LV", "LB",
        "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MY",
        "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD",
        "MC", "MN", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "AN",
        "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK",
        "PW", "PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR",
        "QA", "RE", "RO", "RU", "RW", "SH", "KN", "LC", "PM", "VC", "WS",
        "SM", "ST", "SA", "SN", "CS", "SC", "SL", "SG", "SK", "SI", "SB",
        "SO", "ZA", "GS", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH",
        "SY", "TW", "TJ", "TZ", "TH", "TL", "TG", "TK", "TO", "TT", "TN",
        "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UM", "UY",
        "UZ", "VU", "VE", "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW" };
 }

As you are customizing the ListView, you have create another class extending BaseAdapter, working as a controller of ListView.

So here is my EfficientAdapter.java file :

private static class EfficientAdapter extends BaseAdapter {
    private LayoutInflater mInflater;

    public EfficientAdapter(Context context) {
        mInflater = LayoutInflater.from(context);
    }

    public int getCount() {
        return CountriesList.abbreviations.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.row, null);
            holder = new ViewHolder();
            holder.text1 = (TextView) convertView
                    .findViewById(R.id.TextView01);
            holder.text2 = (TextView) convertView
                    .findViewById(R.id.TextView02);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.text1.setText(CountriesList.abbreviations[position]);
        holder.text2.setText(CountriesList.countries[position]);

        return convertView;
    }

    static class ViewHolder {
        TextView text1;
        TextView text2;
    }
}

Now the last thing remaining is your Activity Class.
Here it is :

public class MyList extends Activity {
/** Called when the activity is first created. */
ListView listView;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    listView = (ListView) findViewById(R.id.lv_country);
    listView.setAdapter(new EfficientAdapter(this));

            listView.setOnItemClickListener(
            new OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView<?> arg0, View view,int position, long arg3) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getApplicationContext(),"You Selected Item "+Integer.toString(position), Toast.LENGTH_LONG).show();
                }
            }
    );
}


问:
Woocommerce Removing required fields from "Additional Information"
I have a free product in Woocommerce, and used this tutorial from Skyverge to simplify the checkout process: https://www.skyverge.com/blog/how-to-simplify-free-woocommerce-checkout/

The problem is, for all other products we have 3 required fields in the Additional Information tab:

cracha_empresa
cracha_primeironome
cracha_sobrenome

And we removed "order_notes" all together. To achieve this, we are using the Woocommerce Checkout Field Editor.

When we try to go through the checkout process for this free product, the filter add_filter( 'woocommerce_enable_order_notes_field', '__return_false' ); is removing the additional fields (as expected), but when you try to complete the purchase, I get an error saying that the above fields are REQUIERED to fill out, even though they aren't showing.

From what I guess, I need to filter these fields in an array?

/**
 * Remove os cupons, notas, e campos que não são necessários para palestrantes.
 *
 */
function sv_free_checkout_fields() {

```<code>// Se carrinho precisa de pagamento, não fazer nada
if ( WC()->cart && WC()->cart->needs_payment() ) {
    return;
}

// Continuar somente se estamos no checkout
// is_checkout() foi quebrado em WooCommerce 3.2 no ajax, checkar se is_ajax está ativo
if ( function_exists( 'is_checkout' ) && ( is_checkout() || is_ajax() ) ) {

    // Remove cupons para produtos gratuitos
    remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );

    // Remove o campo "Additional Info" nas notas dos pedidos
    add_filter( 'woocommerce_enable_order_notes_field', '__return_false' );

    // Desativa os campos para produtos gratuitos
    function unset_unwanted_checkout_fields( $fields ) {

        // Adiciona aqui o que deseja remover
        // campos: http://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/#section-2
        $billing_keys = array(
            'billing_persontype',
            'billing_cpf',
            'billing_rg',
            'billing_cnpj',
            'billing_company',
            'billing_phone',
            'billing_cellphone',
            'billing_address_1',
            'billing_address_2',
            'billing_neighborhood',
            'billing_city',
            'billing_postcode',
            'billing_country',
            'billing_state',
            'billing_number',
        );

        // unset each of those unwanted fields
        foreach( $billing_keys as $key ) {
            unset( $fields['billing'][ $key ] );
        }

        return $fields;
    }
    add_filter( 'woocommerce_checkout_fields', 'unset_unwanted_checkout_fields' );
}
</code>```

}
add_action( 'wp', 'sv_free_checkout_fields' );

I tried this with no luck:

/**
 * Remove os cupons, notas, e campos que não são necessários para palestrantes.
 *
 */
function sv_free_checkout_fields() {

```<code>// Se carrinho precisa de pagamento, não fazer nada
if ( WC()->cart && WC()->cart->needs_payment() ) {
    return;
}

// Continuar somente se estamos no checkout
// is_checkout() foi quebrado em WooCommerce 3.2 no ajax, checkar se is_ajax está ativo
if ( function_exists( 'is_checkout' ) && ( is_checkout() || is_ajax() ) ) {

    // Remove cupons para produtos gratuitos
    remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );

    // Remove o campo "Additional Info" nas notas dos pedidos
    add_filter( 'woocommerce_enable_order_notes_field', '__return_false' );

    // Desativa os campos para produtos gratuitos
    function unset_unwanted_checkout_fields( $fields ) {

        // Adiciona aqui o que deseja remover
        // campos: http://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/#section-2
        $billing_keys = array(
            'billing_persontype',
            'billing_cpf',
            'billing_rg',
            'billing_cnpj',
            'billing_company',
            'billing_phone',
            'billing_cellphone',
            'billing_address_1',
            'billing_address_2',
            'billing_neighborhood',
            'billing_city',
            'billing_postcode',
            'billing_country',
            'billing_state',
            'billing_number',
        );

        $order_keys = array(
            'cracha_empresa',
            'cracha_primeironome',
            'cracha_sobrenome',
        );

        // unset each of those unwanted fields
        foreach( $billing_keys as $key ) {
            unset( $fields['billing'][ $key ] );
        }

        // unset each of those unwanted fields
        foreach( $order_keys as $key ) {
            unset( $fields['order'][ $key ] );
        }

        return $fields;

    }
    add_filter( 'woocommerce_checkout_fields', 'unset_unwanted_checkout_fields' );
}
</code>```

}
add_action( 'wp', 'sv_free_checkout_fields' );

答:
Just disable Woocommerce Checkout Field Editor and try this.

You can remove the Additional Information and Order Notes fields in WooCommerce checkout page with 2 filters that you add to your themes functions.php file

```<code>// Removes Order Notes Title - Additional Information & Notes Field
add_filter( 'woocommerce_enable_order_notes_field', '__return_false', 9999 );

// Remove Order Notes Field
add_filter( 'woocommerce_checkout_fields' , 'remove_order_notes' );

    enter code here

function remove_order_notes( $fields ) {
     unset($fields['order']['order_comments']);
     return $fields;
}
</code>```

The first filter woocommerce_enable_order_notes_field is returning false and will not display the ‘Additional Information’ heading and also the order notes field,
I have found it needs to be run with a high priority sometimes, that’s why I have added in the ‘9999’.

The second filter woocommerce_checkout_fields is removing the order notes field.

Body:
I have a free product in Woocommerce, and used this tutorial from Skyverge to simplify the checkout process: https://www.skyverge.com/blog/how-to-simplify-free-woocommerce-checkout/

The problem is, for all other products we have 3 required fields in the Additional Information tab:

cracha_empresa
cracha_primeironome
cracha_sobrenome

And we removed "order_notes" all together. To achieve this, we are using the Woocommerce Checkout Field Editor.

When we try to go through the checkout process for this free product, the filter add_filter( 'woocommerce_enable_order_notes_field', '__return_false' ); is removing the additional fields (as expected), but when you try to complete the purchase, I get an error saying that the above fields are REQUIERED to fill out, even though they aren't showing.

From what I guess, I need to filter these fields in an array?

/**
 * Remove os cupons, notas, e campos que não são necessários para palestrantes.
 *
 */
function sv_free_checkout_fields() {

// Se carrinho precisa de pagamento, não fazer nada
if ( WC()->cart && WC()->cart->needs_payment() ) {
    return;
}

// Continuar somente se estamos no checkout
// is_checkout() foi quebrado em WooCommerce 3.2 no ajax, checkar se is_ajax está ativo
if ( function_exists( 'is_checkout' ) && ( is_checkout() || is_ajax() ) ) {

    // Remove cupons para produtos gratuitos
    remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );

    // Remove o campo "Additional Info" nas notas dos pedidos
    add_filter( 'woocommerce_enable_order_notes_field', '__return_false' );

    // Desativa os campos para produtos gratuitos
    function unset_unwanted_checkout_fields( $fields ) {

        // Adiciona aqui o que deseja remover
        // campos: http://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/#section-2
        $billing_keys = array(
            'billing_persontype',
            'billing_cpf',
            'billing_rg',
            'billing_cnpj',
            'billing_company',
            'billing_phone',
            'billing_cellphone',
            'billing_address_1',
            'billing_address_2',
            'billing_neighborhood',
            'billing_city',
            'billing_postcode',
            'billing_country',
            'billing_state',
            'billing_number',
        );

        // unset each of those unwanted fields
        foreach( $billing_keys as $key ) {
            unset( $fields['billing'][ $key ] );
        }

        return $fields;
    }
    add_filter( 'woocommerce_checkout_fields', 'unset_unwanted_checkout_fields' );
}

}
add_action( 'wp', 'sv_free_checkout_fields' );

I tried this with no luck:

/**
 * Remove os cupons, notas, e campos que não são necessários para palestrantes.
 *
 */
function sv_free_checkout_fields() {

// Se carrinho precisa de pagamento, não fazer nada
if ( WC()->cart && WC()->cart->needs_payment() ) {
    return;
}

// Continuar somente se estamos no checkout
// is_checkout() foi quebrado em WooCommerce 3.2 no ajax, checkar se is_ajax está ativo
if ( function_exists( 'is_checkout' ) && ( is_checkout() || is_ajax() ) ) {

    // Remove cupons para produtos gratuitos
    remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );

    // Remove o campo "Additional Info" nas notas dos pedidos
    add_filter( 'woocommerce_enable_order_notes_field', '__return_false' );

    // Desativa os campos para produtos gratuitos
    function unset_unwanted_checkout_fields( $fields ) {

        // Adiciona aqui o que deseja remover
        // campos: http://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/#section-2
        $billing_keys = array(
            'billing_persontype',
            'billing_cpf',
            'billing_rg',
            'billing_cnpj',
            'billing_company',
            'billing_phone',
            'billing_cellphone',
            'billing_address_1',
            'billing_address_2',
            'billing_neighborhood',
            'billing_city',
            'billing_postcode',
            'billing_country',
            'billing_state',
            'billing_number',
        );

        $order_keys = array(
            'cracha_empresa',
            'cracha_primeironome',
            'cracha_sobrenome',
        );

        // unset each of those unwanted fields
        foreach( $billing_keys as $key ) {
            unset( $fields['billing'][ $key ] );
        }

        // unset each of those unwanted fields
        foreach( $order_keys as $key ) {
            unset( $fields['order'][ $key ] );
        }

        return $fields;

    }
    add_filter( 'woocommerce_checkout_fields', 'unset_unwanted_checkout_fields' );
}

}
add_action( 'wp', 'sv_free_checkout_fields' );

Body:
Just disable Woocommerce Checkout Field Editor and try this.

You can remove the Additional Information and Order Notes fields in WooCommerce checkout page with 2 filters that you add to your themes functions.php file

// Removes Order Notes Title - Additional Information & Notes Field
add_filter( 'woocommerce_enable_order_notes_field', '__return_false', 9999 );

// Remove Order Notes Field
add_filter( 'woocommerce_checkout_fields' , 'remove_order_notes' );

    enter code here

function remove_order_notes( $fields ) {
     unset($fields['order']['order_comments']);
     return $fields;
}

The first filter woocommerce_enable_order_notes_field is returning false and will not display the ‘Additional Information’ heading and also the order notes field,
I have found it needs to be run with a high priority sometimes, that’s why I have added in the ‘9999’.

The second filter woocommerce_checkout_fields is removing the order notes field.


问:
flextable: How to merge rows with duplicate values for some columns
I'm making a table using flextable(). I would like to merge cells with duplicated srdr_id.

Given these data:

```<code>test <- structure(list(srdr_id = c("175124", "175124", "172545", "172545",
"172609", "172609", "172609"), full_name = c("TAU", "MI", "TAU",
"MI", "TAU", "MI", "MI"), article_arm_name = c("Control", "WISEteens",
"Assessed control", "Intervention", "Control", "Computer BI",
"Therapist BI"), arm_number = c(1L, 2L, 1L, 2L, 1L, 2L, 3L)), row.names = c(NA,
-7L), class = c("tbl_df", "tbl", "data.frame"))

  srdr_id full_name article_arm_name arm_number
  <chr>   <chr>     <chr>                 <int>
1 175124  TAU       Control                   1
2 175124  MI        WISEteens                 2
3 172545  TAU       Assessed control          1
4 172545  MI        Intervention              2
5 172609  TAU       Control                   1
6 172609  MI        Computer BI               2
7 172609  MI        Therapist BI              3
</code>```

I can do it with the following code - but would like to simplify the multiple merge_at() statements.

```<code>flextable(test) %>% theme_box() %>%
           merge_at(i = 1:2, j = 1) %>%
           merge_at(i = 3:4, j = 1) %>%
           merge_at(i = 5:7, j = 1)
</code>```

<img src="https://i.stack.imgur.com/EyUXu.png" alt="enter image description here">

Unfortunately, the simple solution, merge_v(j = ~srdr_id), no longer is sufficient when I add another column which is duplicated across common srdr_id's.

```<code>test_2 <- structure(list(srdr_id = c("175124", "175124", "172525", "172525",
"172545", "172545", "172609", "172609", "172609"), substances = c("alcohol",
"alcohol", "alcohol", "alcohol", "cannabis", "cannabis", "alcohol\n cannabis\n other drugs",
"alcohol\n cannabis\n other drugs", "alcohol\n cannabis\n other drugs"
), full_name = c("TAU", "MI", "TAU", "MI (parent)", "TAU", "MI",
"TAU", "MI", "MI"), article_arm_name = c("Control", "WISEteens",
"Treatment as usual", "Brief MI (b-MI)", "Assessed control",
"Intervention", "Control", "Computer BI", "Therapist BI")), row.names = c(NA,
-9L), class = c("tbl_df", "tbl", "data.frame"))

# A tibble: 9 x 4
  srdr_id substances                         full_name   article_arm_name
  <chr>   <chr>                              <chr>       <chr>
1 175124  alcohol                            TAU         Control
2 175124  alcohol                            MI          WISEteens
3 172525  alcohol                            TAU         Treatment as usual
4 172525  alcohol                            MI (parent) Brief MI (b-MI)
5 172545  cannabis                           TAU         Assessed control
6 172545  cannabis                           MI          Intervention
7 172609  "alcohol\n cannabis\n other drugs" TAU         Control
8 172609  "alcohol\n cannabis\n other drugs" MI          Computer BI
9 172609  "alcohol\n cannabis\n other drugs" MI          Therapist BI
</code>```

答:
Wow - I missed the obvious solution for the simple case. Question has been edited with a more realistic (nested) dataset.</p>

```<code>test_ft <- flextable(test) %>% theme_box() %>%  merge_v(j = ~srdr_id)
</code>```

Body:
I'm making a table using flextable(). I would like to merge cells with duplicated srdr_id.

Given these data:

test <- structure(list(srdr_id = c("175124", "175124", "172545", "172545",
"172609", "172609", "172609"), full_name = c("TAU", "MI", "TAU",
"MI", "TAU", "MI", "MI"), article_arm_name = c("Control", "WISEteens",
"Assessed control", "Intervention", "Control", "Computer BI",
"Therapist BI"), arm_number = c(1L, 2L, 1L, 2L, 1L, 2L, 3L)), row.names = c(NA,
-7L), class = c("tbl_df", "tbl", "data.frame"))

  srdr_id full_name article_arm_name arm_number
  <chr>   <chr>     <chr>                 <int>
1 175124  TAU       Control                   1
2 175124  MI        WISEteens                 2
3 172545  TAU       Assessed control          1
4 172545  MI        Intervention              2
5 172609  TAU       Control                   1
6 172609  MI        Computer BI               2
7 172609  MI        Therapist BI              3

I can do it with the following code - but would like to simplify the multiple merge_at() statements.

flextable(test) %>% theme_box() %>%
           merge_at(i = 1:2, j = 1) %>%
           merge_at(i = 3:4, j = 1) %>%
           merge_at(i = 5:7, j = 1)

<img src="https://i.stack.imgur.com/EyUXu.png" alt="enter image description here">

Unfortunately, the simple solution, merge_v(j = ~srdr_id), no longer is sufficient when I add another column which is duplicated across common srdr_id's.

test_2 <- structure(list(srdr_id = c("175124", "175124", "172525", "172525",
"172545", "172545", "172609", "172609", "172609"), substances = c("alcohol",
"alcohol", "alcohol", "alcohol", "cannabis", "cannabis", "alcohol\n cannabis\n other drugs",
"alcohol\n cannabis\n other drugs", "alcohol\n cannabis\n other drugs"
), full_name = c("TAU", "MI", "TAU", "MI (parent)", "TAU", "MI",
"TAU", "MI", "MI"), article_arm_name = c("Control", "WISEteens",
"Treatment as usual", "Brief MI (b-MI)", "Assessed control",
"Intervention", "Control", "Computer BI", "Therapist BI")), row.names = c(NA,
-9L), class = c("tbl_df", "tbl", "data.frame"))

# A tibble: 9 x 4
  srdr_id substances                         full_name   article_arm_name
  <chr>   <chr>                              <chr>       <chr>
1 175124  alcohol                            TAU         Control
2 175124  alcohol                            MI          WISEteens
3 172525  alcohol                            TAU         Treatment as usual
4 172525  alcohol                            MI (parent) Brief MI (b-MI)
5 172545  cannabis                           TAU         Assessed control
6 172545  cannabis                           MI          Intervention
7 172609  "alcohol\n cannabis\n other drugs" TAU         Control
8 172609  "alcohol\n cannabis\n other drugs" MI          Computer BI
9 172609  "alcohol\n cannabis\n other drugs" MI          Therapist BI

Body:
Wow - I missed the obvious solution for the simple case. Question has been edited with a more realistic (nested) dataset.

test_ft <- flextable(test) %>% theme_box() %>%  merge_v(j = ~srdr_id)


问:
VS Code HTML formatting wrong
I have a HTML file where the formatting is completely messed up. Hopefully you can the the problem in this picture below:

This is just an example from the file (other parts are messed up too). You can see that the
 start tag and end tag don't have the same indentation. Also, I would expect everything inside the tag to be indented farther. This is how it looks after using the Shift + Alt + F code formatting shortcut. What could the problem be and how can I solve it?

答: I had the same problem! I opened a issue in vscode's github https://github.com/microsoft/vscode/issues/74139#issuecomment-495578264. The older versions used to work I just got it solved rolling back to the version 1.17...</p>

Title: VS Code HTML formatting wrong


问:
Angular can not render generated HTML with Button dynamically
I am facing a problem, I want to render generated HTML code, into material table with Pipe, but it is not working.

the code looks like this:

pipe.ts

```<code>import { Pipe, PipeTransform } from "@angular/core";
import * as _ from "underscore";

@Pipe({ name: "customPipeChecks" })
export class CustomPipeChecks implements PipeTransform {
  transform(
    elementValue: {},
    elementProperty: string,
    object: {},
    customPipeFunction: any,
    defaultValue: string
  ) {
    if (customPipeFunction != null && _.isFunction(customPipeFunction)) {
      console.log(customPipeFunction(elementValue, elementProperty, object));
      return customPipeFunction(elementValue, elementProperty, object);
    } else {
      if (defaultValue) {
        return defaultValue;
      }
      return elementValue;
    }
  }
}
</code>```

the generated function

```<code>  private setCustomValueFunction() {
    this.customValueFunction = (
      elemValue: string,
      elemKey: string,
      elem: {}
    ) => {
      if (elemKey === "vin") {
        elemValue = "<button>zrdzdrz</button>";
      }
      return elemValue;
    };
  }
</code>```

this function generates a HTML string.

the HTML code looks like this :

```<code>
<td
     mat-cell
     *matCellDef="let cellData"
     class="{{
              cellData[colName]
                | customPipeChecks: colName:cellData:customCssFunction:' '
            }}"
     innerHtml="{{
              cellData[colName]
                | customPipeChecks: colName:cellData:customValueFunction
       }}">
</td>

</code>```

When the app is loaded, it will shown only 'zrdzdrz' only the text (inner HTML of the desired button), without the button (that is suppoused to wrap the text).

Any suggestion?

Best Regards,

Leo

答:
Very interesting question.

Here is a demo at StackBlitz that will fix your problem.

The reason why your implementation doesn't work is because angular is sanitizing the injected HTMl, in order to bypass this, your custom pipe should look like the snippet bellow, where the important part is the usage of DomSanitizer which will "tell" the framework in explicit manner that you want to inject HTML that must be rendered.

import { Pipe, PipeTransform } from "@angular/core";
import {
  DomSanitizer,
  SafeHtml
} from '@angular/platform-browser';

@Pipe({ name: "customPipeChecks" })
export class CustomPipeChecks implements PipeTransform {

  constructor(
    public sanitizer: DomSanitizer,
  ) { }
  transform() {
    return this.sanitizer.bypassSecurityTrustHtml('<button>Button content</button>')
  }
}```
</div>
</div>
</p>
<h1>Update</h1>
<p>One more notable point is that in the template you must inject the <code>innerHTML</code> in the following manner,  <strong>[innerHTML]</strong></p>
```

```

Body:
I am facing a problem, I want to render generated HTML code, into material table with Pipe, but it is not working.

the code looks like this:

pipe.ts

import { Pipe, PipeTransform } from "@angular/core";
import * as _ from "underscore";

@Pipe({ name: "customPipeChecks" })
export class CustomPipeChecks implements PipeTransform {
  transform(
    elementValue: {},
    elementProperty: string,
    object: {},
    customPipeFunction: any,
    defaultValue: string
  ) {
    if (customPipeFunction != null && _.isFunction(customPipeFunction)) {
      console.log(customPipeFunction(elementValue, elementProperty, object));
      return customPipeFunction(elementValue, elementProperty, object);
    } else {
      if (defaultValue) {
        return defaultValue;
      }
      return elementValue;
    }
  }
}

the generated function

  private setCustomValueFunction() {
    this.customValueFunction = (
      elemValue: string,
      elemKey: string,
      elem: {}
    ) => {
      if (elemKey === "vin") {
        elemValue = "<button>zrdzdrz</button>";
      }
      return elemValue;
    };
  }

this function generates a HTML string.

the HTML code looks like this :

When the app is loaded, it will shown only 'zrdzdrz' only the text (inner HTML of the desired button), without the button (that is suppoused to wrap the text).

Any suggestion?

Best Regards,

Leo

Body:
Very interesting question.

Here is a demo at StackBlitz that will fix your problem.

The reason why your implementation doesn't work is because angular is sanitizing the injected HTMl, in order to bypass this, your custom pipe should look like the snippet bellow, where the important part is the usage of DomSanitizer which will "tell" the framework in explicit manner that you want to inject HTML that must be rendered.

import { Pipe, PipeTransform } from "@angular/core";
import {
  DomSanitizer,
  SafeHtml
} from '@angular/platform-browser';

@Pipe({ name: "customPipeChecks" })
export class CustomPipeChecks implements PipeTransform {

  constructor(
    public sanitizer: DomSanitizer,
  ) { }
  transform() {
    return this.sanitizer.bypassSecurityTrustHtml('<button>Button content</button>')
  }
}

Update

One more notable point is that in the template you must inject the innerHTML in the following manner,  [innerHTML]

<td mat-cell *matCellDef="let element" [innerHtml]="'someString' | customPipeChecks">
    </td>


问:
What to watch out for when converting a std::string to a char* for C function?
I have read many posts asking the question on how to convert a C++ std::string or const std::string& to a char* to pass it to a C function and it seems there is quite a few caveat's in regards to doing this.  One has to beware about the string being contiguous and a lot of other things.  The point is that I've never really understood all the points one needs to be aware of and why?

I wondered if someone could sum up the caveats and downfalls about doing a conversion from a std::string to a char* that is needed to pass to a C function?

This when the std::string is a const reference and when it's just a non-const reference, and when the C function will alter the char* and when it will not alter it.

答:
First, whether const reference or value doesn't change anything.

You then have to consider what the function is expecting.  There
are different things which a function can do with a char* or
a char const*---the original versions of memcpy, for
example, used these types, and it's possible that there is still
such code around.  It is, hopefully, rare, and in the following,
I will assume that the char* in the C function refer to '\0'
terminated strings.

If the C function takes a char const*, you can pass it the
results of std::string::c_str(); if it takes a char*, it
depends.  If it takes a char* simply because it dates from the
pre-const days of C, and in fact, it modifies nothing,
std::string::c_str() followed by a const_cast is
appropriate.  If the C function is using the char* as an out
parameter, however, things become more difficult.  I personally
prefer declaring a char[] buffer, passing this, and then
converting the results to std::string, but all known
implementations of std::string use a contiguous buffer, and
the next version of the standard will require it, so correctly
dimensioning the std::string first (using
std::string::resize(), then passing &s[0], and afterwards
redimensionning the string to the resulting length (determined
using strlen(s.c_str()), if necessary) can also be used.

Finally (but this is also an issue for C programs using
char[]), you have to consider any lifetime issues.  Most
functions taking char* or char const* simply use the
pointer, and forget it, but if the function saves the pointer
somewhere, for later use, the string object must live at least
as long, and its size should not be modified during that period.
(Again, in such cases, I prefer using a char[].)


问:
how to map inside another map in React.js
Using the map function in React.js to get what's inside Mp3 from this json:

```<code>{
  "175": {
    "label": "Pub Radio",
    "icone": "",
    "Mp3": {
      "33278": {
        "id": 33278,
        "titre": "Ricardo Villalobos - Caminando",
        "intention1": "Doux",
        "intention2": "Doux",
        "intention3": "Doux",
        "langue": "Allemand",
        "visibilite": 1
      }
    }
  },
  "176": {
    "label": "Pub Cd/Dvd",
    "icone": "",
    "Mp3": {
      "33277": {
        "id": 33277,
        "titre": "Mano lo taugh - Primative People",
        "intention1": "Chaleureux, rassurant",
        "intention2": "Joyeux",
        "intention3": "Souriant",
        "langue": "Allemand",
        "visibilite": 1
      },
      "33279": {
        "id": 33279,
        "titre": "Foals - Late Night (Solomun Remix).mp3",
        "intention1": "Amical, complice",
        "intention2": "Amical, complice",
        "intention3": "Amical, complice",
        "langue": "Allemand",
        "visibilite": 1
      }
    }
  },
  "245": {
    "label": "Billboard",
    "icone": "",
    "Mp3": {
      "33280": {
        "id": 33280,
        "titre": "Techno",
        "intention1": "Posé, calme",
        "intention2": "Amical, complice",
        "intention3": "Souriant",
        "langue": "Americain",
        "visibilite": 1
      }
    }
  }
}
</code>```

this is my map function :

```<code>  {Object.keys(extraitMP3).map((label, i) => (
    <li key={i}>
        <span >key: {i} Name: {extraitMP3[label]}</span>
            {Object.keys(extraitMP3[label]).map((Mp3, i) => (
        <li key={i}>
            <span >key: {i} Name: {extraitMP3[label][Mp3]}</span>

            {Object.keys(extraitMP3[label][Mp3]).map((idSon, i) => (
        <li key={i}>
            <span >key: {i} Name: {extraitMP3[label][Mp3][idSon]}</span>
            {console.log('Titre',extraitMP3[label][Mp3][idSon].titre)}
            {console.log('Intention 1',extraitMP3[label][Mp3][idSon].intention1)}
            {console.log('Intention 2',extraitMP3[label][Mp3][idSon].intention2)}
            {console.log('Intention 3',extraitMP3[label][Mp3][idSon].intention3)}
            {console.log('Langue',extraitMP3[label][Mp3][idSon].langue)}
            {console.log('Visibilite',extraitMP3[label][Mp3][idSon].visibilite)}
        </li>
    ))}
        </li>
    ))}
        </li>
    ))}
</code>```

Results are shown in the console as expected but also I receive a lot of other results as undefined. I think it's a problem of looping with map but I don't where is my problem exactly :

This is what I found in the console :

答:
Short answer :

extraitMP3[label][Mp3] should be extraitMP3[label].Mp3 (or alternatively extraitMP3[label]['Mp3'] though not recommended by most linter)

But there are several things wrong

You got duplicate keys which will mess up your React performances. Instead of
 put an unique identifier such as the song id (for the last nested loop)

As pointed by HRK44 you should use a unique iterator in each of the loop.

Personal preference, I would use Object.entries to avoid this kind of problem in the future. This way you'll never get lost in long concatenated strings and it will be easier to debug...

Body:
Using the map function in React.js to get what's inside Mp3 from this json:

{
  "175": {
    "label": "Pub Radio",
    "icone": "",
    "Mp3": {
      "33278": {
        "id": 33278,
        "titre": "Ricardo Villalobos - Caminando",
        "intention1": "Doux",
        "intention2": "Doux",
        "intention3": "Doux",
        "langue": "Allemand",
        "visibilite": 1
      }
    }
  },
  "176": {
    "label": "Pub Cd/Dvd",
    "icone": "",
    "Mp3": {
      "33277": {
        "id": 33277,
        "titre": "Mano lo taugh - Primative People",
        "intention1": "Chaleureux, rassurant",
        "intention2": "Joyeux",
        "intention3": "Souriant",
        "langue": "Allemand",
        "visibilite": 1
      },
      "33279": {
        "id": 33279,
        "titre": "Foals - Late Night (Solomun Remix).mp3",
        "intention1": "Amical, complice",
        "intention2": "Amical, complice",
        "intention3": "Amical, complice",
        "langue": "Allemand",
        "visibilite": 1
      }
    }
  },
  "245": {
    "label": "Billboard",
    "icone": "",
    "Mp3": {
      "33280": {
        "id": 33280,
        "titre": "Techno",
        "intention1": "Posé, calme",
        "intention2": "Amical, complice",
        "intention3": "Souriant",
        "langue": "Americain",
        "visibilite": 1
      }
    }
  }
}

this is my map function :

  {Object.keys(extraitMP3).map((label, i) => (

        key: {i} Name: {extraitMP3[label]}
            {Object.keys(extraitMP3[label]).map((Mp3, i) => (

            key: {i} Name: {extraitMP3[label][Mp3]}

            {Object.keys(extraitMP3[label][Mp3]).map((idSon, i) => (

            key: {i} Name: {extraitMP3[label][Mp3][idSon]}
            {console.log('Titre',extraitMP3[label][Mp3][idSon].titre)}
            {console.log('Intention 1',extraitMP3[label][Mp3][idSon].intention1)}
            {console.log('Intention 2',extraitMP3[label][Mp3][idSon].intention2)}
            {console.log('Intention 3',extraitMP3[label][Mp3][idSon].intention3)}
            {console.log('Langue',extraitMP3[label][Mp3][idSon].langue)}
            {console.log('Visibilite',extraitMP3[label][Mp3][idSon].visibilite)}

    ))}

    ))}

    ))}

Results are shown in the console as expected but also I receive a lot of other results as undefined. I think it's a problem of looping with map but I don't where is my problem exactly :

This is what I found in the console :

Body:
Short answer :

extraitMP3[label][Mp3] should be extraitMP3[label].Mp3 (or alternatively extraitMP3[label]['Mp3'] though not recommended by most linter)

But there are several things wrong

You got duplicate keys which will mess up your React performances. Instead of <li key={i}> put an unique identifier such as the song id (for the last nested loop)

As pointed by HRK44 you should use a unique iterator in each of the loop.

Personal preference, I would use Object.entries to avoid this kind of problem in the future. This way you'll never get lost in long concatenated strings and it will be easier to debug...


问:
Acessing base class property when overriding
Considering the following basic Python classes:

```<code>class Foo(object):

    def __init__(self, a1):
        self._att1 = a1

    @property
    def att1(self):
        return self._att1

    @att1.setter
    def att1(self, a):
        try:
            self._att1 = a
        except TypeError:
            # handle exception
            print("Not allowed")

class Bar(Foo):
    def __init__(self):
        Foo.__init__(self, 100)

    @Foo.att1.setter
    def att1(self, a):
        # self.att1 = a * 0.5  # RecursionError: maximum recursion depth exceeded
        # Foo.att1 = a * 0.5  # attribute is not changed (base instances are though (?))
        # Foo.att1(self,a)  # TypeError: 'property' object is not callable
        super().att1.__set__(a * 0.5)   # AttributeError: 'int' object has no attribute '__set__'
        # ... some other additional code ...

a = Foo(5)
b = Bar()
b.att1 = 700

print(a.att1)
print(b.att1)
</code>```

What would be syntax for calling base property setter from within its override on the child class? I understand I could set self._att1 directly, but I would like to avoid that because I would then need to repeat exception handling code. This but a simple example, and I have more complex cases where the base class implements some additional operations on the attribute, and I would like to avoid repeating the same code on the derived class property setter.

答:
Code:

```<code>class Foo:
    def __init__(self, a1):
        self._att1 = a1

    @property
    def att1(self):
        return self._att1

    @att1.setter
    def att1(self, a):
        if not isinstance(a, int):
            print("Not allowed")
        else:
            self._att1 = a

class Bar(Foo):
    def __init__(self):
        Foo.__init__(self, 100)

    @Foo.att1.setter
    def att1(self, a):
        Foo.att1.fset(self, a * 2)

c = Bar()
print(c.att1)
c.att1 = 10
print(c.att1)
c.att1 = "some string"
</code>```

Output:

```<code>100
20
Not allowed
</code>```

UPD.

Following @chepner advice, I've decided to add some explanation.

When you're using decorator @Foo.att1.setter it doesn't work like you expected.

In docs you can see 2 examples of declaring properties: assign class variable using property() function and use @property decorator. Both this methods are equialent, but I find first much more obvious in case of demonstration how does provided code works.

Let's rewrite class declarations using property() function instead decorators:

```<code>class Foo:
    def __init__(self, a1):
        self._att1 = a1

    def getatt1(self):
        return self._att1

    def setatt1(self, a):
        if not isinstance(a, int):
            print("Not allowed")
        else:
            self._att1 = a

    att1 = property(getatt1, setatt1)

class Bar(Foo):
    def __init__(self):
        super().__init__(100)

    def setatt1(self, a):
        Foo.att1.fset(self, a * 2)

    att1 = property(Foo.getatt1, setatt1)
</code>```

As you see, you don't override property, you're creating new with same name, which shadow base class property. You can prove it using this code:

```<code>print(f"Foo.att1 is Bar.att1: {Foo.att1 is Bar.att1}")
</code>```

In both declarations it'll return False, which means that property objects of this classes aren't same.

Body:
Considering the following basic Python classes:

class Foo(object):

    def __init__(self, a1):
        self._att1 = a1

    @property
    def att1(self):
        return self._att1

    @att1.setter
    def att1(self, a):
        try:
            self._att1 = a
        except TypeError:
            # handle exception
            print("Not allowed")

class Bar(Foo):
    def __init__(self):
        Foo.__init__(self, 100)

    @Foo.att1.setter
    def att1(self, a):
        # self.att1 = a * 0.5  # RecursionError: maximum recursion depth exceeded
        # Foo.att1 = a * 0.5  # attribute is not changed (base instances are though (?))
        # Foo.att1(self,a)  # TypeError: 'property' object is not callable
        super().att1.__set__(a * 0.5)   # AttributeError: 'int' object has no attribute '__set__'
        # ... some other additional code ...

a = Foo(5)
b = Bar()
b.att1 = 700

print(a.att1)
print(b.att1)

What would be syntax for calling base property setter from within its override on the child class? I understand I could set self._att1 directly, but I would like to avoid that because I would then need to repeat exception handling code. This but a simple example, and I have more complex cases where the base class implements some additional operations on the attribute, and I would like to avoid repeating the same code on the derived class property setter.

Body:
Code:

class Foo:
    def __init__(self, a1):
        self._att1 = a1

    @property
    def att1(self):
        return self._att1

    @att1.setter
    def att1(self, a):
        if not isinstance(a, int):
            print("Not allowed")
        else:
            self._att1 = a

class Bar(Foo):
    def __init__(self):
        Foo.__init__(self, 100)

    @Foo.att1.setter
    def att1(self, a):
        Foo.att1.fset(self, a * 2)

c = Bar()
print(c.att1)
c.att1 = 10
print(c.att1)
c.att1 = "some string"

Output:

100
20
Not allowed

UPD.

Following @chepner advice, I've decided to add some explanation.

When you're using decorator @Foo.att1.setter it doesn't work like you expected.

In docs you can see 2 examples of declaring properties: assign class variable using property() function and use @property decorator. Both this methods are equialent, but I find first much more obvious in case of demonstration how does provided code works.

Let's rewrite class declarations using property() function instead decorators:

class Foo:
    def __init__(self, a1):
        self._att1 = a1

    def getatt1(self):
        return self._att1

    def setatt1(self, a):
        if not isinstance(a, int):
            print("Not allowed")
        else:
            self._att1 = a

    att1 = property(getatt1, setatt1)

class Bar(Foo):
    def __init__(self):
        super().__init__(100)

    def setatt1(self, a):
        Foo.att1.fset(self, a * 2)

    att1 = property(Foo.getatt1, setatt1)

As you see, you don't override property, you're creating new with same name, which shadow base class property. You can prove it using this code:

print(f"Foo.att1 is Bar.att1: {Foo.att1 is Bar.att1}")

In both declarations it'll return False, which means that property objects of this classes aren't same.


问:
How to handle images with webpack encore & assets
so I seem to be a bit confused on how to work with images in webpack encore + assets.

I store all JS & CSS like this

```<code>/assets/js
/assets/css
...
</code>```

With encore I can access them later from my /public/build folder - no issues there.

Now I want to store some images (e.g. file upload).

First idea was to store them inside a folder like /assets/images. But with the current settings & using assets I can only access files inside /public/build folder.

So I tried to use to copyFiles to copy everything from /assets/images to /public/build/images.

But this does not automatically copy my files (e.g. file upload to /assets/images/ does not copy it to /public/build - which is in order not accessible in my project). So I would need to run manually encore - which I don't want.

Second idea was to store the uploaded images directly inside /public/build/images but those files would be deleted when I run encore.

Next I disabled the webpack option cleanupOutputBeforeBuild, so images would not be deleted. But without this option the folder will be flooded by new JS & CSS Files everytime I run encore.

What do I need?

A solution to store my images either way in /assets folder & make them available for my project.

or

store the images directly in /public/build folder without encore deleting them nor flooding the folder with JS/CSS by disabling cleanupOutput Option.

Thanks in advance ~Syllz

答:
Solution to my problem:
Store the images into /public/images and not into the build folder - which will be deleted when running encore.

Body:
so I seem to be a bit confused on how to work with images in webpack encore + assets.

I store all JS & CSS like this

/assets/js
/assets/css
...

With encore I can access them later from my /public/build folder - no issues there.

Now I want to store some images (e.g. file upload).

First idea was to store them inside a folder like /assets/images. But with the current settings & using assets I can only access files inside /public/build folder.

So I tried to use to copyFiles to copy everything from /assets/images to /public/build/images.

But this does not automatically copy my files (e.g. file upload to /assets/images/ does not copy it to /public/build - which is in order not accessible in my project). So I would need to run manually encore - which I don't want.

Second idea was to store the uploaded images directly inside /public/build/images but those files would be deleted when I run encore.

Next I disabled the webpack option cleanupOutputBeforeBuild, so images would not be deleted. But without this option the folder will be flooded by new JS & CSS Files everytime I run encore.

What do I need?

A solution to store my images either way in /assets folder & make them available for my project.

or

store the images directly in /public/build folder without encore deleting them nor flooding the folder with JS/CSS by disabling cleanupOutput Option.

Thanks in advance ~Syllz


问:
Run a command but stay in the shell vs exit
I know that in vim I can type

```<code>:terminal <command> %
</code>```

to run a command on the file in the current edit buffer. For example and to simplify what I want to do let's take a simple ls command:

```<code>:terminal ls %
</code>```

which will split the window, run the command and exit the shell while leaving the output on the screen.  that's not what I want.  I want it to run the command but leave me in the shell  so I can run more bash commands potentially related to the current file/operation, then exit manually when I'm done.

If I simply type

```<code>:terminal
</code>```

it brings me to a bash shell which allows me to type as many commands as I want which is great.  BUT I then lose the ability to use the expansion facility of %, and the ease of spawning the terminal from the file I'm editing.  ie. I lose the automation of the context provided by spawning from the original file/buffer which means I have to manually type in the current file name including potentially long path and or scroll previous bash history to rerun the original command.  this is a waste of keystrokes.

Basically, I'm trying to find a way to create a vim map that lets me use % filename expansion in a bash command via :term withOUT ending the job after the command is run (i prefer to be left in at a prompt in a shell to continue the session!)

I actually don't care if a solution just starts the :term shell and echos my command with % filename expansion at the bash prompt without entering it.. that would allow me to still stay in bash after the command is executed by me with a manual carriage return.

I'm not sure if what I want to do is possible? note, I'm not looking to suspend my current edit session and fg back as it ties up the current editing session.  I'm not sure if tmux - vim integration might provide a way to do what I want though I'd prefer to find a solution using straight-up :term since it's a built-in feature and works well except for what I'm trying to achieve :)

答:
You can do this with a mapping.

This mapping works for expanding '%' and leaving the new terminal active:

```<code>:nmap <F12> :let $MYFILE=expand('%')<CR>:terminal<CR>echo $MYFILE<CR>
</code>```

You might need to map to a different key but otherwise this should work.

Body:
I know that in vim I can type

:terminal <command> %

to run a command on the file in the current edit buffer. For example and to simplify what I want to do let's take a simple ls command:

:terminal ls %

which will split the window, run the command and exit the shell while leaving the output on the screen.  that's not what I want.  I want it to run the command but leave me in the shell  so I can run more bash commands potentially related to the current file/operation, then exit manually when I'm done.

If I simply type

:terminal

it brings me to a bash shell which allows me to type as many commands as I want which is great.  BUT I then lose the ability to use the expansion facility of %, and the ease of spawning the terminal from the file I'm editing.  ie. I lose the automation of the context provided by spawning from the original file/buffer which means I have to manually type in the current file name including potentially long path and or scroll previous bash history to rerun the original command.  this is a waste of keystrokes.

Basically, I'm trying to find a way to create a vim map that lets me use % filename expansion in a bash command via :term withOUT ending the job after the command is run (i prefer to be left in at a prompt in a shell to continue the session!)

I actually don't care if a solution just starts the :term shell and echos my command with % filename expansion at the bash prompt without entering it.. that would allow me to still stay in bash after the command is executed by me with a manual carriage return.

I'm not sure if what I want to do is possible? note, I'm not looking to suspend my current edit session and fg back as it ties up the current editing session.  I'm not sure if tmux - vim integration might provide a way to do what I want though I'd prefer to find a solution using straight-up :term since it's a built-in feature and works well except for what I'm trying to achieve :)

Body:
You can do this with a mapping.

This mapping works for expanding '%' and leaving the new terminal active:

:nmap <F12> :let $MYFILE=expand('%')<CR>:terminal<CR>echo $MYFILE<CR>

You might need to map to a different key but otherwise this should work.


问:
Handling dead actors in Akka Typed
I have some actors that kill themselves when idle or other system constraints require them to. The actors that have ActorRefs to them are watching for their Terminated(ref), but there is a race condition of messages meant for the actors being sent before the termination arrives and I'm trying to figure out a clean way to handle that.

I was considering subscribing to DeadLetter and using that to signal the sender that their ref is stale and that they need to get or spawn a new target ActorRef.

However, in Akka Typed, I cannot find any way to get to dead letters other than using the untyped co-existence path, so I figure I'm likely approaching this wrong.

Is there a better pattern for dealing dead downstream refs and re-directing messages to a new downstream refs, short of requiring some kind of ack hand-shake for every message?

答:
Consider dead letters as a debugging tool rather something to use to implement delivery guarantees with (true for both Akka typed and untyped).

If an actor needs to be certain that a message was delivered the message protocol will need to include an an ack. To do resending the actor will also need to keep a buffer for in-flight/not yet acknowledged messages to be able to resend.

We have some ideas on an abstraction for different levels of reliability for message delivery, we'll see if that fits in Akka 2.6 or happens later though, prototyped in: https://github.com/akka/akka/pull/25099

Title: Handling dead actors in Akka Typed


答:
You can use GroupBy.diff:

```<code>stack['timestamp'] = pd.to_datetime(stack['timestamp'])
stack['timestamp']= (stack.sort_values(['id','timestamp'])
                            .groupby('id')
                            .diff()['timestamp']
                            .dt.total_seconds()
                            .round().fillna(0))

print(stack['time_taken'])
0         0.0
1       260.0
2      3276.0
3         0.0
4         0.0
5      1196.0
6     13306.0
7         4.0
8         0.0
9         0.0
10      370.0
11     2872.0
...
</code>```

If you want the resulting dataframe to be ordered by date, instead do:

```<code>stack['timestamp'] = pd.to_datetime(stack['timestamp'])
stack = stack.sort_values(['id','timestamp'])
stack['time_taken'] = (stack.groupby('id')
                            .diff()['timestamp']
                            .dt.total_seconds()
                            .round()
                            .fillna(0))
</code>```

Title: How to perform functions that reference previous row on subset of data in a dataframe using groupby

Body:
I have some log data that represents an item (id) and a timestamp that an action was a started and I want to determine the time between actions on each item.

for example, I have some data that looks like this:

data = [{"timestamp":"2019-05-21T14:17:29.265Z","id":"ff9dad92-e7c1-47a5-93a7-6e49533a6e25"},{"timestamp":"2019-05-21T14:21:49.722Z","id":"ff9dad92-e7c1-47a5-93a7-6e49533a6e25"},{"timestamp":"2019-05-21T15:16:25.695Z","id":"ff9dad92-e7c1-47a5-93a7-6e49533a6e25"},{"timestamp":"2019-05-21T15:16:25.696Z","id":"ff9dad92-e7c1-47a5-93a7-6e49533a6e25"},{"timestamp":"2019-05-22T07:51:17.49Z","id":"ff12891e-5786-438b-891c-abd4244723b4"},{"timestamp":"2019-05-22T08:11:13.948Z","id":"ff12891e-5786-438b-891c-abd4244723b4"},{"timestamp":"2019-05-22T11:52:59.897Z","id":"ff12891e-5786-438b-891c-abd4244723b4"},{"timestamp":"2019-05-22T11:53:03.406Z","id":"ff12891e-5786-438b-891c-abd4244723b4"},{"timestamp":"2019-05-22T11:53:03.481Z","id":"ff12891e-5786-438b-891c-abd4244723b4"},{"timestamp":"2019-05-21T14:23:08.147Z","id":"fe55bb22-fe5b-4b12-8aaf-d5f0320ac7fa"},{"timestamp":"2019-05-21T14:29:18.228Z","id":"fe55bb22-fe5b-4b12-8aaf-d5f0320ac7fa"},{"timestamp":"2019-05-21T15:17:09.831Z","id":"fe55bb22-fe5b-4b12-8aaf-d5f0320ac7fa"},{"timestamp":"2019-05-21T15:17:09.834Z","id":"fe55bb22-fe5b-4b12-8aaf-d5f0320ac7fa"},{"timestamp":"2019-05-21T14:02:19.072Z","id":"fd3554cd-b83d-49af-a8e6-7bf41c741cd0"},{"timestamp":"2019-05-21T14:02:34.867Z","id":"fd3554cd-b83d-49af-a8e6-7bf41c741cd0"},{"timestamp":"2019-05-21T14:12:28.877Z","id":"fd3554cd-b83d-49af-a8e6-7bf41c741cd0"},{"timestamp":"2019-05-21T15:19:19.567Z","id":"fd3554cd-b83d-49af-a8e6-7bf41c741cd0"},{"timestamp":"2019-05-21T15:19:19.582Z","id":"fd3554cd-b83d-49af-a8e6-7bf41c741cd0"},{"timestamp":"2019-05-21T09:58:02.185Z","id":"f89c2e3e-06dc-467b-813b-dc92f2692f63"},{"timestamp":"2019-05-21T10:07:24.044Z","id":"f89c2e3e-06dc-467b-813b-dc92f2692f63"}]
stack = pd.DataFrame(data)
stack.head()

I have tried getting all the unique ids to split the data frame and then getting the time taken with the index to recombine with the original set like, but the function is extremely slow on large data-sets and messes up both the index
 and timestamp order resulting in results getting miss matched.

import ciso8601 as time
records = []
for i in list(stack.id.unique()):
    dff = stack[stack.id == i]
    time_taken = []
    times = []
    i = 0
    for _, row in dff.iterrows():
        if bool(times):
            print(_)
            current_time = time.parse_datetime(row.timestamp)
            prev_time = times[i]
            time_taken = current_time - prev_time
            times.append(current_time)
            i+=1
            records.append(dict(index = _, time_taken = time_taken.seconds))
        else:
            records.append(dict(index = _, time_taken = 0))
            times.append(time.parse_datetime(row.timestamp))

x = pd.DataFrame(records).set_index('index')
stack.merge(x, left_index=True, right_index=True, how='inner')

Is there a neat pandas groupby and apply way of doing this so that I don't have to split the frame and store it in memory so that can reference the previous row in the subset?

Thanks

Body:
You can use GroupBy.diff:

stack['timestamp'] = pd.to_datetime(stack['timestamp'])
stack['timestamp']= (stack.sort_values(['id','timestamp'])
                            .groupby('id')
                            .diff()['timestamp']
                            .dt.total_seconds()
                            .round().fillna(0))

print(stack['time_taken'])
0         0.0
1       260.0
2      3276.0
3         0.0
4         0.0
5      1196.0
6     13306.0
7         4.0
8         0.0
9         0.0
10      370.0
11     2872.0
...

If you want the resulting dataframe to be ordered by date, instead do:

stack['timestamp'] = pd.to_datetime(stack['timestamp'])
stack = stack.sort_values(['id','timestamp'])
stack['time_taken'] = (stack.groupby('id')
                            .diff()['timestamp']
                            .dt.total_seconds()
                            .round()
                            .fillna(0))