问:
push_back keeps rewriting all entries in the vector to the item pushed_back?
I am currently trying to make a light copy of a vector. A light copy meaning that the content of the copy, is a vector of pointer of the original vector.  I am for some reasons having problems doing so... Each time I push_back a new entry into the copy vector, I seem to overwrite all the entries in the vector, to the element I just push_back, why is this happening:

MWE:

```<code>// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
#include <experimental/filesystem>
#include <vector>
#include <algorithm>

struct abstract_data_structure
{
    int x;
    int y;
    std::vector<int> points;
    std::string name;

    abstract_data_structure(int x, int y , std::vector<int> points, std::string name)
    {
        this->x= x;
        this->y = y;
        this->points = points;
        this->name = name;
    }
};

int main()
{
     std::vector<abstract_data_structure> storage;
     std::vector<abstract_data_structure*> copy_of_storage;

     std::srand(std::time(0));
     for (int i = 0; i< 5 ; i++)
     {
        int x = std::rand();
        int y = std::rand();
        std::vector<int> vecOfRandomNums(10);
        std::generate(vecOfRandomNums.begin(), vecOfRandomNums.end(), []() {
           return rand() % 100;
        });
        std::string name = "something"+std::to_string(i);
        abstract_data_structure something(x,y,vecOfRandomNums,name);
        storage.push_back(something);

     }

    std::cout << storage.size() << std::endl;
    std::cout << "Make the copy" << std::endl;

    for (auto element : storage)
    {
        std::cout << "in storage" << std::endl;
        std::cout << element.name << std::endl;
        copy_of_storage.push_back(&(element));
        std::cout << "in copy storage" << std::endl;

        for (auto copy_element: copy_of_storage)
        {
            std::cout << copy_element->name << std::endl;
        }
    }

}
</code>```

https://wandbox.org/permlink/Xn96xbIshd6RXTRa

which outputs this:

```<code>5
Make the copy
in storage
something0
in copy storage
something0
in storage
something1
in copy storage
something1
something1
in storage
something2
in copy storage
something2
something2
something2
in storage
something3
in copy storage
something3
something3
something3
something3
in storage
something4
in copy storage
something4
something4
something4
something4
something4
0
</code>```

As one might see are all the entries in the copy vector, modified to point to last element inserted? why?

答:
The problem is a bit deeper than you may suspect. In

```<code>std::vector<abstract_data_structure> storage;
std::vector<abstract_data_structure*> copy_of_storage;
</code>```

copy_of_storage cannot be a copy of storage without a lot of extra effort and probably dynamic allocation of abstract_data_structures.

copy_of_storage contains pointers and those pointers have to point to abstract_data_structures. These abstract_data_structures may or may not be copies.

The naive fix, swapping

```<code>for (auto element : storage)
</code>```

for

```<code>for (auto & element : storage)
</code>```

makes element a reference to an abstract_data_structure stored within storage. This means that element references a variable that has longer life than a single iteration of the for loop, but

```<code>copy_of_storage.push_back(&(element));
</code>```

doesn't make a copy. It just points to the original abstract_data_structure inside storage. Sometimes this is useful, but when one list is supposed to be a copy of the other, it probably should directly refer to the other list.

For example, adding another abstract_data_structure to storage will invalidate the pointers. The contents of storage can be moved in the existing storage. The storage may be replaced with a larger block and the pointers left pointing to invalid memory. All sorts of nasty things can happen.

Instead, I recommend

```<code>std::vector<abstract_data_structure> storage;
std::vector<abstract_data_structure> copy_of_storage;
</code>```

and later

```<code>for (auto & element : storage)
</code>```

and

```<code>copy_of_storage.push_back(element);
</code>```

Now you have a copy.

But... there are easier ways. std::vector is a very smart beast. You can

```<code>copy_of_storage = storage;
</code>```

and storage will copy itself.

Recommended extra reading: What is The Rule of Three? This is not required for your example, but very very important to learn early in a programming career.

Body:
I am currently trying to make a light copy of a vector. A light copy meaning that the content of the copy, is a vector of pointer of the original vector.  I am for some reasons having problems doing so... Each time I push_back a new entry into the copy vector, I seem to overwrite all the entries in the vector, to the element I just push_back, why is this happening:

MWE:

// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
#include <experimental/filesystem>
#include <vector>
#include <algorithm>

struct abstract_data_structure
{
    int x;
    int y;
    std::vector<int> points;
    std::string name;

    abstract_data_structure(int x, int y , std::vector<int> points, std::string name)
    {
        this->x= x;
        this->y = y;
        this->points = points;
        this->name = name;
    }
};

int main()
{
     std::vector<abstract_data_structure> storage;
     std::vector<abstract_data_structure*> copy_of_storage;

     std::srand(std::time(0));
     for (int i = 0; i< 5 ; i++)
     {
        int x = std::rand();
        int y = std::rand();
        std::vector<int> vecOfRandomNums(10);
        std::generate(vecOfRandomNums.begin(), vecOfRandomNums.end(), []() {
           return rand() % 100;
        });
        std::string name = "something"+std::to_string(i);
        abstract_data_structure something(x,y,vecOfRandomNums,name);
        storage.push_back(something);

     }

    std::cout << storage.size() << std::endl;
    std::cout << "Make the copy" << std::endl;

    for (auto element : storage)
    {
        std::cout << "in storage" << std::endl;
        std::cout << element.name << std::endl;
        copy_of_storage.push_back(&(element));
        std::cout << "in copy storage" << std::endl;

        for (auto copy_element: copy_of_storage)
        {
            std::cout << copy_element->name << std::endl;
        }
    }

}

https://wandbox.org/permlink/Xn96xbIshd6RXTRa

which outputs this:

5
Make the copy
in storage
something0
in copy storage
something0
in storage
something1
in copy storage
something1
something1
in storage
something2
in copy storage
something2
something2
something2
in storage
something3
in copy storage
something3
something3
something3
something3
in storage
something4
in copy storage
something4
something4
something4
something4
something4
0

As one might see are all the entries in the copy vector, modified to point to last element inserted? why?

Body:
The problem is a bit deeper than you may suspect. In

std::vector<abstract_data_structure> storage;
std::vector<abstract_data_structure*> copy_of_storage;

copy_of_storage cannot be a copy of storage without a lot of extra effort and probably dynamic allocation of abstract_data_structures.

copy_of_storage contains pointers and those pointers have to point to abstract_data_structures. These abstract_data_structures may or may not be copies.

The naive fix, swapping

for (auto element : storage)

for

for (auto & element : storage)

makes element a reference to an abstract_data_structure stored within storage. This means that element references a variable that has longer life than a single iteration of the for loop, but

copy_of_storage.push_back(&(element));

doesn't make a copy. It just points to the original abstract_data_structure inside storage. Sometimes this is useful, but when one list is supposed to be a copy of the other, it probably should directly refer to the other list.

For example, adding another abstract_data_structure to storage will invalidate the pointers. The contents of storage can be moved in the existing storage. The storage may be replaced with a larger block and the pointers left pointing to invalid memory. All sorts of nasty things can happen.

Instead, I recommend

std::vector<abstract_data_structure> storage;
std::vector<abstract_data_structure> copy_of_storage;

and later

for (auto & element : storage)

and

copy_of_storage.push_back(element);

Now you have a copy.

But... there are easier ways. std::vector is a very smart beast. You can

copy_of_storage = storage;

and storage will copy itself.

Recommended extra reading: What is The Rule of Three? This is not required for your example, but very very important to learn early in a programming career.


来源: stackexchange

问:
Mapping slope of an area and returning percent above and below a threshold in R
I am trying to figure our the proportion of an area that has a slope of 0, +/- 5 degrees. Another way of saying it is anything above 5 degrees and below 5 degrees are bad. I am trying to find the actual number, and a graphic.

To achieve this I turned to R and using the Raster package.
Let's use a generic country, in this case, the Philippines

```<code>{list.of.packages <- c("sp","raster","rasterVis","maptools","rgeos")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)}

library(sp)  # classes for spatial data
library(raster)  # grids, rasters
library(rasterVis)  # raster visualisation
library(maptools)
library(rgeos)
</code>```

Now let's get the altitude information and plot the slopes.

```<code>elevation <- getData("alt", country = "PHL")
x <- terrain(elevation, opt = c("slope", "aspect"), unit = "degrees")
plot(x$slope)
</code>```

Not very helpful due to the scale, so let's simply look at the Island of Palawan

```<code>e <- drawExtent(show=TRUE) #to crop out Palawan (it's the long skinny island that is roughly midway on the left and is oriented between 2 and 8 O'clock)
gewataSub <- crop(x,e)
plot(gewataSub, 1)## Now visualize the new cropped object
</code>```

A little bit better to visualize. I get a sense of the magnitude of the slopes and that with a 5 degree restriction, I am mostly confined to the coast. But I need a little bit more for analysis.

I would like Results to be something to be in two parts:
1. " 35 % (made up) of the selected area has a slope exceeding +/- 5 degrees" or " 65 % of the selected area is within +/- 5 degrees". (with the code to get it)
2. A picture where everything within +/- 5 degrees is one color, call it good or green, and everything else is in another color, call it bad or red.

Thanks

答:
There are no negative slopes, so I assume you want those that are less than 5 degrees

```<code>library(raster)
elevation <- getData('alt', country='CHE')
x <- terrain(elevation, opt='slope', unit='degrees')

z <- x <= 5
</code>```

Now you can count cells with freq

```<code>f <- freq(z)
</code>```

If you have a planar coordinate reference system (that is, with units in meters or similar) you can do

```<code>f <- cbind(f, area=f[,2] * prod(res(z)))
</code>```

to get areas. But for lon/lat data, you would need to correct for different sized cells and do

```<code>a <- area(z)
zonal(a, z, fun=sum)
</code>```

And there are different ways to plot, but the most basic one

```<code>plot(z)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to figure our the proportion of an area that has a slope of 0, +/- 5 degrees. Another way of saying it is anything above 5 degrees and below 5 degrees are bad. I am trying to find the actual number, and a graphic.

To achieve this I turned to R and using the Raster package.
Let's use a generic country, in this case, the Philippines

{list.of.packages <- c("sp","raster","rasterVis","maptools","rgeos")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)}

library(sp)  # classes for spatial data
library(raster)  # grids, rasters
library(rasterVis)  # raster visualisation
library(maptools)
library(rgeos)

Now let's get the altitude information and plot the slopes.

elevation <- getData("alt", country = "PHL")
x <- terrain(elevation, opt = c("slope", "aspect"), unit = "degrees")
plot(x$slope)

Not very helpful due to the scale, so let's simply look at the Island of Palawan

e <- drawExtent(show=TRUE) #to crop out Palawan (it's the long skinny island that is roughly midway on the left and is oriented between 2 and 8 O'clock)
gewataSub <- crop(x,e)
plot(gewataSub, 1)## Now visualize the new cropped object

A little bit better to visualize. I get a sense of the magnitude of the slopes and that with a 5 degree restriction, I am mostly confined to the coast. But I need a little bit more for analysis.

I would like Results to be something to be in two parts:
1. " 35 % (made up) of the selected area has a slope exceeding +/- 5 degrees" or " 65 % of the selected area is within +/- 5 degrees". (with the code to get it)
2. A picture where everything within +/- 5 degrees is one color, call it good or green, and everything else is in another color, call it bad or red.

Thanks

Body:
There are no negative slopes, so I assume you want those that are less than 5 degrees

library(raster)
elevation <- getData('alt', country='CHE')
x <- terrain(elevation, opt='slope', unit='degrees')

z <- x <= 5

Now you can count cells with freq

f <- freq(z)

If you have a planar coordinate reference system (that is, with units in meters or similar) you can do

f <- cbind(f, area=f[,2] * prod(res(z)))

to get areas. But for lon/lat data, you would need to correct for different sized cells and do

a <- area(z)
zonal(a, z, fun=sum)

And there are different ways to plot, but the most basic one

plot(z)


问:
How can I input an integer in a textbox and get a specific IF or ELSE-IF result?
I want to input a numerical value in a text box ranging from 0 to 100, then press a button and display the corresponding grade. So far, I have this:

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnIF_Click(object sender, EventArgs e)
    {
        int[] i = new int[1];
        txtNumK.Text = i[0].ToString();
        {
            Console.WriteLine("Please enter test " + i);
            bool result = int.TryParse(Console.ReadLine(), out i[0]);
            if (!result)
            {
                Console.WriteLine("This program only accept numbers.");
            }

            if (i[0] >= 90)
            {
                Console.WriteLine("note is A");
            }
            if (i[0] >= 80)
            {
                Console.WriteLine("note is B");
            }
            if (i[0] >= 70)
            {
                Console.WriteLine("note is C");
            }
            if (i[0] >= 60)
            {
                Console.WriteLine("note is D");
            }
            if (i[0] >= 0)
            {
                Console.WriteLine("note is F");
            }
            else if (i[0] > 0 || i[0] < 100)
            {
                Console.WriteLine("I'm sorry, the number MUST be between 0 and 100");
            }
            Console.WriteLine("Your result is:" + i[0]);
        }
    }

    private void txtNumK_TextChanged(object sender, EventArgs e)
    {

    }
}
}
</code>```

Every time I input a number in the text box, the value within it is turned back into a 0.

答:
You have your assignment backwards.  You want:</p>

```<code>i[0] = Int32.parse(txtNumk.text);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to input a numerical value in a text box ranging from 0 to 100, then press a button and display the corresponding grade. So far, I have this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnIF_Click(object sender, EventArgs e)
    {
        int[] i = new int[1];
        txtNumK.Text = i[0].ToString();
        {
            Console.WriteLine("Please enter test " + i);
            bool result = int.TryParse(Console.ReadLine(), out i[0]);
            if (!result)
            {
                Console.WriteLine("This program only accept numbers.");
            }

            if (i[0] >= 90)
            {
                Console.WriteLine("note is A");
            }
            if (i[0] >= 80)
            {
                Console.WriteLine("note is B");
            }
            if (i[0] >= 70)
            {
                Console.WriteLine("note is C");
            }
            if (i[0] >= 60)
            {
                Console.WriteLine("note is D");
            }
            if (i[0] >= 0)
            {
                Console.WriteLine("note is F");
            }
            else if (i[0] > 0 || i[0] < 100)
            {
                Console.WriteLine("I'm sorry, the number MUST be between 0 and 100");
            }
            Console.WriteLine("Your result is:" + i[0]);
        }
    }

    private void txtNumK_TextChanged(object sender, EventArgs e)
    {

    }
}
}

Every time I input a number in the text box, the value within it is turned back into a 0.

Body:
You have your assignment backwards.  You want:

i[0] = Int32.parse(txtNumk.text);


问:
how to avoid record fetching issues after deleting a user account
Hey I'm trying to find a way to avoid record fetching issues when a user has been deleted.

I got a posts table and a comments table, both referencing to a user_id. If I delete the user it gives me an error page when the each-method is fetching data from either the posts or the comments table.

Thanks for advise!

答:
If you add lines like this

```<code>has_many :posts, :dependent => :destroy
has_many :comments, :dependent => :destroy
</code>```

to User model, all posts and comments will be removed with the removed user.  If you want to keep the posts you can either instead of removing user record set some inactive flag, or create a special 'removed user' and pin all orphaned posts and comments to that user.

ContentLicense: CC BY-SA 2.5

Body:
If you add lines like this

has_many :posts, :dependent => :destroy
has_many :comments, :dependent => :destroy

to User model, all posts and comments will be removed with the removed user.  If you want to keep the posts you can either instead of removing user record set some inactive flag, or create a special 'removed user' and pin all orphaned posts and comments to that user.


问:
Shuffle Error: Exceeded MAX_FAILED_UNIQUE_FETCHES; bailing-out
I am trying to run mapreduce job on two node cluster. I am getting the following error
Shuffle Error: Exceeded MAX_FAILED_UNIQUE_FETCHES; bailing-out.

I read through some posts which say it is due to problem in /etc/hosts

my /etc/hosts in master looks like this.( Also, master itself is a slave):

127.0.0.1   localhost

127.0.1.1   xyz

10.140.169.41 master

10.140.169.38 slave

/etc/hosts in slave looks like this

127.0.0.1     localhost

127.0.1.1      abc

10.140.169.41 master

10.140.169.38 slave

I have turned off the firewall

Any help will be greatly appreciated

答:
Shuffling is the phase when intermediate data is being transferred from mapper to reducer. You have not mentioned what Map Reduce properties you have set for your code to run, but I can suggest you to try out setting following properties:

```<code><property>
    <name>mapreduce.reduce.shuffle.input.buffer.percent</name>
    <value>0.20</value>
</property>
<property>
    <name>mapreduce.reduce.shuffle.parallelcopies</name>
    <value>4</value>
</property>
</code>```

If you need the description about how can we calculate the buffer input percentage have a look at this : https://issues.apache.org/jira/browse/MAPREDUCE-6447/

Thanks.

Body:
Shuffling is the phase when intermediate data is being transferred from mapper to reducer. You have not mentioned what Map Reduce properties you have set for your code to run, but I can suggest you to try out setting following properties:

<property>
    <name>mapreduce.reduce.shuffle.input.buffer.percent</name>
    <value>0.20</value>
</property>
<property>
    <name>mapreduce.reduce.shuffle.parallelcopies</name>
    <value>4</value>
</property>

If you need the description about how can we calculate the buffer input percentage have a look at this : https://issues.apache.org/jira/browse/MAPREDUCE-6447/

Thanks.


问:
how to remove this error in Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner
```<code>import java.sql.*;
import java.util.*;
import java.text.*;

public class DataInsertDemo1{

    public static void main(String kl[]) throws SQLException,Exception{
        String url="jdbc:oracle:thin:@localhost:1521:orcl";
        String driver="oracle.jdbc.OracleDriver";
        Class.forName(driver);
        Connection con=DriverManager.getConnection(url,"System","System1996");

        Scanner sc=new Scanner("System.in");
        System.out.println("enter person name");
        String name=sc.next();

        System.out.println("Enter DOP(dd-mm-yyyy):");
        String dop=sc.next();

        SimpleDateFormat sdf=new SimpleDateFormat("dd-mm-yyyy");
        java.util.Date udate=sdf.parse(dop);
        long l=udate.getTime();
        java.sql.Date sdate=new java.sql.Date(l);

        String sql="insert into userdate values(?,?)";

        PreparedStatement  ps=con.prepareStatement(sql);
        ps.setString(1,name);
        ps.setDate(2,sdate);

        int rc=ps.executeUpdate();

            if(rc == 0){
                System.out.println("Record not inserted");
            }
            else{
                System.out.println("record is inserted");
            }

    con.close();

    }
}
</code>```

答:
The problem is in

```<code>Scanner sc=new Scanner("System.in");
</code>```

You don't need to pass the String to the constructor in this case, because "System.in" is not the path.

```<code>Scanner sc=new Scanner(System.in);
</code>```

will work.
Also, it's a good practice to check if scanner has next token

```<code>if (sc.hasNext()) {
    sc.next()
}
</code>```

Body:
The problem is in

Scanner sc=new Scanner("System.in");

You don't need to pass the String to the constructor in this case, because "System.in" is not the path.

Scanner sc=new Scanner(System.in);

will work.
Also, it's a good practice to check if scanner has next token

if (sc.hasNext()) {
    sc.next()
}


问:
App crashes with OnClickListener in Fragment
I have an app with 3 tabs and one of them has a todo-function. Everything works fine when I want to add a new note. Now I wanted to implement a delete function for the notes and since I can't access the button from the .xml file I tried it with public class Tab2 extends Fragment implements View.OnClickListener and public void onClick(View v) but now my App crashes completly when I start it. What do I do wrong?
Here the Fragment:

```<code>public class Tab2 extends Fragment implements View.OnClickListener {

ImageButton btn_ok;
EditText edit_task;
private TaskDbHelper mHelper;
public ListView mTaskListView;
private ArrayAdapter<String> mAdapter;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab2, container, false);

    setHasOptionsMenu(true);
    mHelper = new TaskDbHelper(getActivity());
    mTaskListView = view.findViewById(R.id.list_todo);
    updateUI();

    Button b = view.findViewById(R.id.btn_delete);
    b.setOnClickListener(this);

    return view;
}

public void updateUI() {
    ArrayList<String> taskList = new ArrayList<>();
    SQLiteDatabase db = mHelper.getReadableDatabase();
    Cursor cursor = db.query(TaskContract.TaskEntry.TABLE, new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE},
            null, null, null, null, null, null);
    while (cursor.moveToNext()) {
        int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
        taskList.add(cursor.getString(idx));
    }

    if (mAdapter == null) {
        mAdapter = new ArrayAdapter<String>(getActivity(), R.layout.item_todo, R.id.task_title, taskList);
        mTaskListView.setAdapter(mAdapter);
    } else {
        mAdapter.clear();
        mAdapter.addAll(taskList);
        mAdapter.notifyDataSetChanged();
    }

    cursor.close();
    db.close();
}

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.main_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_add_task:
            final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
            View mView = getLayoutInflater().inflate(R.layout.dialog_add_task, null);
            btn_ok = mView.findViewById(R.id.btn_ok5);
            edit_task = mView.findViewById(R.id.edit_task);
            mBuilder.setView(mView);
            final AlertDialog dialog = mBuilder.create();
            dialog.show();

            btn_ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String task = String.valueOf(edit_task.getText());
                    SQLiteDatabase db = mHelper.getWritableDatabase();
                    ContentValues values = new ContentValues();
                    values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
                    db.insertWithOnConflict(TaskContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
                    db.close();

                    updateUI();

                    dialog.cancel();
                }
            });

            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_delete:
            View parent = (View) v.getParent();
            TextView taskTextView = parent.findViewById(R.id.task_title);
            String task = String.valueOf(taskTextView.getText());
            SQLiteDatabase db = mHelper.getWritableDatabase();
            db.delete(TaskContract.TaskEntry.TABLE, TaskContract.TaskEntry.COL_TASK_TITLE + " = ?", new String[]{task});
            db.close();

            updateUI();

            break;
    }
} }
</code>```

Logcat:

```<code>    12-06 19:35:58.710 20306-20306/com.example.rike1.final_logbuch E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.rike1.final_logbuch, PID: 20306
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                                at com.example.rike1.final_logbuch.Tab2.onCreateView(Tab2.java:49)
                                                                                at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
                                                                                at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
                                                                                at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
                                                                                at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2199)
                                                                                at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:651)
                                                                                at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:145)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1236)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1084)
                                                                                at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1614)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:714)
                                                                                at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:91)
                                                                                at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1361)
                                                                                at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:784)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1485)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:775)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:657)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1485)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:775)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:657)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at com.android.internal.policy.DecorView.onMeasure(DecorView.java:729)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2436)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1482)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1741)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1366)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6768)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:926)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:735)
12-06 19:35:58.710 20306-20306/com.example.rike1.final_logbuch E/AndroidRuntime:     at android.view.Choreographer.doFrame(Choreographer.java:667)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:912)
                                                                                at android.os.Handler.handleCallback(Handler.java:761)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:156)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6523)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
</code>```

XML item_todo where the Button is I want to access:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_vertical">
    <TextView
        android:id="@+id/task_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:text="Hello"
        android:textSize="20sp" />
    <Button
        android:id="@+id/btn_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="Done"
        android:backgroundTint="@color/colorAccent"/>
</RelativeLayout>
</code>```

tab2 XML:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">
    <ListView
        android:id="@+id/list_todo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </ListView>
</RelativeLayout>
</code>```

答:
You are inflating tab2.xml like this

```<code>View view = inflater.inflate(R.layout.tab2, container, false);
</code>```

But you can't get your button from it

```<code>Button b = view.findViewById(R.id.btn_delete);
</code>```

since the view you inflated doesn't contain btn_delete. That is why you are getting Null exception from the above line.

Body:
I have an app with 3 tabs and one of them has a todo-function. Everything works fine when I want to add a new note. Now I wanted to implement a delete function for the notes and since I can't access the button from the .xml file I tried it with public class Tab2 extends Fragment implements View.OnClickListener and public void onClick(View v) but now my App crashes completly when I start it. What do I do wrong?
Here the Fragment:

public class Tab2 extends Fragment implements View.OnClickListener {

ImageButton btn_ok;
EditText edit_task;
private TaskDbHelper mHelper;
public ListView mTaskListView;
private ArrayAdapter<String> mAdapter;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab2, container, false);

    setHasOptionsMenu(true);
    mHelper = new TaskDbHelper(getActivity());
    mTaskListView = view.findViewById(R.id.list_todo);
    updateUI();

    Button b = view.findViewById(R.id.btn_delete);
    b.setOnClickListener(this);

    return view;
}

public void updateUI() {
    ArrayList<String> taskList = new ArrayList<>();
    SQLiteDatabase db = mHelper.getReadableDatabase();
    Cursor cursor = db.query(TaskContract.TaskEntry.TABLE, new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE},
            null, null, null, null, null, null);
    while (cursor.moveToNext()) {
        int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
        taskList.add(cursor.getString(idx));
    }

    if (mAdapter == null) {
        mAdapter = new ArrayAdapter<String>(getActivity(), R.layout.item_todo, R.id.task_title, taskList);
        mTaskListView.setAdapter(mAdapter);
    } else {
        mAdapter.clear();
        mAdapter.addAll(taskList);
        mAdapter.notifyDataSetChanged();
    }

    cursor.close();
    db.close();
}

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.main_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_add_task:
            final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
            View mView = getLayoutInflater().inflate(R.layout.dialog_add_task, null);
            btn_ok = mView.findViewById(R.id.btn_ok5);
            edit_task = mView.findViewById(R.id.edit_task);
            mBuilder.setView(mView);
            final AlertDialog dialog = mBuilder.create();
            dialog.show();

            btn_ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String task = String.valueOf(edit_task.getText());
                    SQLiteDatabase db = mHelper.getWritableDatabase();
                    ContentValues values = new ContentValues();
                    values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
                    db.insertWithOnConflict(TaskContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
                    db.close();

                    updateUI();

                    dialog.cancel();
                }
            });

            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_delete:
            View parent = (View) v.getParent();
            TextView taskTextView = parent.findViewById(R.id.task_title);
            String task = String.valueOf(taskTextView.getText());
            SQLiteDatabase db = mHelper.getWritableDatabase();
            db.delete(TaskContract.TaskEntry.TABLE, TaskContract.TaskEntry.COL_TASK_TITLE + " = ?", new String[]{task});
            db.close();

            updateUI();

            break;
    }
} }

Logcat:

    12-06 19:35:58.710 20306-20306/com.example.rike1.final_logbuch E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.rike1.final_logbuch, PID: 20306
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                                at com.example.rike1.final_logbuch.Tab2.onCreateView(Tab2.java:49)
                                                                                at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
                                                                                at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
                                                                                at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
                                                                                at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2199)
                                                                                at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:651)
                                                                                at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:145)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1236)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1084)
                                                                                at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1614)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:714)
                                                                                at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:91)
                                                                                at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1361)
                                                                                at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:784)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1485)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:775)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:657)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1485)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:775)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:657)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at com.android.internal.policy.DecorView.onMeasure(DecorView.java:729)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2436)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1482)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1741)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1366)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6768)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:926)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:735)
12-06 19:35:58.710 20306-20306/com.example.rike1.final_logbuch E/AndroidRuntime:     at android.view.Choreographer.doFrame(Choreographer.java:667)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:912)
                                                                                at android.os.Handler.handleCallback(Handler.java:761)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:156)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6523)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)

XML item_todo where the Button is I want to access:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_vertical">
    <TextView
        android:id="@+id/task_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:text="Hello"
        android:textSize="20sp" />
    <Button
        android:id="@+id/btn_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="Done"
        android:backgroundTint="@color/colorAccent"/>
</RelativeLayout>

tab2 XML:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">
    <ListView
        android:id="@+id/list_todo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </ListView>
</RelativeLayout>

Body:
You are inflating tab2.xml like this

View view = inflater.inflate(R.layout.tab2, container, false);

But you can't get your button from it

Button b = view.findViewById(R.id.btn_delete);

since the view you inflated doesn't contain btn_delete. That is why you are getting Null exception from the above line.


问:
Unable to start the startxwin cygwin
I was using Cygwin download by some one in our organization and the xterm worked fine, I recently updated the xterm version, since then I lost the ability to use the xwindow/start the xserver. The bash console where I ran the startxwin shows the following and does not open the xterm window. I manually opened the xterm window and it does not open the xwindows when I ssh'd into the remote machine. </p>

```<code>$ startxwin
:0" in "list" command display name "6175
xauth: (stdin):1:  bad "add" command line

Welcome to the XWin X Server
Vendor: The Cygwin/X Project
Release: 1.19.3.0
OS: CYGWIN_NT-6.1 6175 2.8.0(0.309/5/3) 2017-04-01 20:47 x86_64
OS: Windows 7 Service Pack 1 [Windows NT 6.1 build 7601] (Win64)
Package: version 1.19.3-2 built 2017-04-23

XWin was started with the following command line:

/usr/bin/XWin :0 -multiwindow -auth
 /home/usrpao/.serverauth.13204

(II) xorg.conf is not supported
(II) See http://x.cygwin.com/docs/faq/cygwin-x-faq.html for more information
LoadPreferences: /home/usrpao/.XWinrc not found
LoadPreferences: Loading /etc/X11/system.XWinrc
LoadPreferences: Done parsing the configuration file...
winDetectSupportedEngines - RemoteSession: no
winDetectSupportedEngines - DirectDraw4 installed, allowing ShadowDDNL
winDetectSupportedEngines - Returning, supported engines 00000005
winSetEngine - Multi Window or Rootless => ShadowGDI
winScreenInit - Using Windows display depth of 32 bits per pixel
winAllocateFBShadowGDI - Creating DIB with width: 2560 height: 1024 depth: 32
winFinishScreenInitFB - Masks: 00ff0000 0000ff00 000000ff
winInitVisualsShadowGDI - Masks 00ff0000 0000ff00 000000ff BPRGB 8 d 24 bpp 32
MIT-SHM extension disabled due to lack of kernel support
XFree86-Bigfont extension local-client optimization disabled due to lack of shared memory support in                                                                                the kernel
glWinSelectGLimplementation: Loaded 'cygnativeGLthunk.dll'
(II) AIGLX: Testing pixelFormatIndex 1
GL_VERSION:     4.3.0 - Build 10.18.14.4280
GL_VENDOR:      Intel
GL_RENDERER:    Intel(R) HD Graphics 4600
(II) GLX: enabled GLX_SGI_make_current_read
(II) GLX: enabled GLX_SGI_swap_control
(II) GLX: enabled GLX_MESA_swap_control
(II) GLX: enabled GLX_SGIX_pbuffer
(II) GLX: enabled GLX_ARB_multisample
(II) GLX: enabled GLX_SGIS_multisample
(II) GLX: enabled GLX_ARB_fbconfig_float
(II) GLX: enabled GLX_EXT_fbconfig_packed_float
(II) GLX: enabled GLX_ARB_create_context
(II) GLX: enabled GLX_ARB_create_context_profile
(II) GLX: enabled GLX_ARB_create_context_robustness
(II) GLX: enabled GLX_EXT_create_context_es2_profile
(II) GLX: enabled GLX_ARB_framebuffer_sRGB
(II) AIGLX: enabled GLX_MESA_copy_sub_buffer
(II) 80 pixel formats reported by wglGetPixelFormatAttribivARB
(II) 44 fbConfigs
(II) ignored pixel formats: 0 not OpenGL, 0 unknown pixel type, 36 unaccelerated
(II) GLX: Initialized Win32 native WGL GL provider for screen 0
winPointerWarpCursor - Discarding first warp: 1280 512
(--) 8 mouse buttons found
(--) Setting autorepeat to delay=500, rate=31
(--) Windows keyboard layout: "00000409" (00000409) "US", type 4
(--) Found matching XKB configuration "English (USA)"
(--) Model = "pc105" Layout = "us" Variant = "none" Options = "none"
Rules = "base" Model = "pc105" Layout = "us" Variant = "none" Options = "none"
winInitMultiWindowWM - DISPLAY=:0.0
winMultiWindowXMsgProc - DISPLAY=:0.0
winInitMultiWindowWM - xcb_connect () returned and successfully opened the display.
winProcEstablishConnection - winInitClipboard returned.
winClipboardThreadProc - DISPLAY=:0.0
winMultiWindowXMsgProc - xcb_connect() returned and successfully opened the display.
OS maintains clipboard viewer chain: yes
winClipboardProc - XOpenDisplay () returned and successfully opened the display.
Using Composite redirection
</code>```

答:
I had a similar issue and tracked it down to startx misbehaving.  This is what I saw:

```<code>$ ./startx -- :1
:1" in "list" command display name "hostname
xauth: (stdin):1:  bad "add" command line
</code>```

The problem is with the way startx is setting its hostname variable.  It does not strip out the carriage return.  Later, when startx uses the hostname variable, the contained carriage return causes xuath "add" command to terminate prematurely and fail.

The fix for me was to strip out the carriage return.

Find where the variable hostname gets set in /usr/bin/startx, and just below there add this line:

```<code>hostname=$(echo $hostname | sed 's/\x0D//g')
</code>```

Title: Unable to start the startxwin cygwin

Body:
I was using Cygwin download by some one in our organization and the xterm worked fine, I recently updated the xterm version, since then I lost the ability to use the xwindow/start the xserver. The bash console where I ran the startxwin shows the following and does not open the xterm window. I manually opened the xterm window and it does not open the xwindows when I ssh'd into the remote machine.

$ startxwin
:0" in "list" command display name "6175
xauth: (stdin):1:  bad "add" command line

Welcome to the XWin X Server
Vendor: The Cygwin/X Project
Release: 1.19.3.0
OS: CYGWIN_NT-6.1 6175 2.8.0(0.309/5/3) 2017-04-01 20:47 x86_64
OS: Windows 7 Service Pack 1 [Windows NT 6.1 build 7601] (Win64)
Package: version 1.19.3-2 built 2017-04-23

XWin was started with the following command line:

/usr/bin/XWin :0 -multiwindow -auth
 /home/usrpao/.serverauth.13204

(II) xorg.conf is not supported
(II) See http://x.cygwin.com/docs/faq/cygwin-x-faq.html for more information
LoadPreferences: /home/usrpao/.XWinrc not found
LoadPreferences: Loading /etc/X11/system.XWinrc
LoadPreferences: Done parsing the configuration file...
winDetectSupportedEngines - RemoteSession: no
winDetectSupportedEngines - DirectDraw4 installed, allowing ShadowDDNL
winDetectSupportedEngines - Returning, supported engines 00000005
winSetEngine - Multi Window or Rootless => ShadowGDI
winScreenInit - Using Windows display depth of 32 bits per pixel
winAllocateFBShadowGDI - Creating DIB with width: 2560 height: 1024 depth: 32
winFinishScreenInitFB - Masks: 00ff0000 0000ff00 000000ff
winInitVisualsShadowGDI - Masks 00ff0000 0000ff00 000000ff BPRGB 8 d 24 bpp 32
MIT-SHM extension disabled due to lack of kernel support
XFree86-Bigfont extension local-client optimization disabled due to lack of shared memory support in                                                                                the kernel
glWinSelectGLimplementation: Loaded 'cygnativeGLthunk.dll'
(II) AIGLX: Testing pixelFormatIndex 1
GL_VERSION:     4.3.0 - Build 10.18.14.4280
GL_VENDOR:      Intel
GL_RENDERER:    Intel(R) HD Graphics 4600
(II) GLX: enabled GLX_SGI_make_current_read
(II) GLX: enabled GLX_SGI_swap_control
(II) GLX: enabled GLX_MESA_swap_control
(II) GLX: enabled GLX_SGIX_pbuffer
(II) GLX: enabled GLX_ARB_multisample
(II) GLX: enabled GLX_SGIS_multisample
(II) GLX: enabled GLX_ARB_fbconfig_float
(II) GLX: enabled GLX_EXT_fbconfig_packed_float
(II) GLX: enabled GLX_ARB_create_context
(II) GLX: enabled GLX_ARB_create_context_profile
(II) GLX: enabled GLX_ARB_create_context_robustness
(II) GLX: enabled GLX_EXT_create_context_es2_profile
(II) GLX: enabled GLX_ARB_framebuffer_sRGB
(II) AIGLX: enabled GLX_MESA_copy_sub_buffer
(II) 80 pixel formats reported by wglGetPixelFormatAttribivARB
(II) 44 fbConfigs
(II) ignored pixel formats: 0 not OpenGL, 0 unknown pixel type, 36 unaccelerated
(II) GLX: Initialized Win32 native WGL GL provider for screen 0
winPointerWarpCursor - Discarding first warp: 1280 512
(--) 8 mouse buttons found
(--) Setting autorepeat to delay=500, rate=31
(--) Windows keyboard layout: "00000409" (00000409) "US", type 4
(--) Found matching XKB configuration "English (USA)"
(--) Model = "pc105" Layout = "us" Variant = "none" Options = "none"
Rules = "base" Model = "pc105" Layout = "us" Variant = "none" Options = "none"
winInitMultiWindowWM - DISPLAY=:0.0
winMultiWindowXMsgProc - DISPLAY=:0.0
winInitMultiWindowWM - xcb_connect () returned and successfully opened the display.
winProcEstablishConnection - winInitClipboard returned.
winClipboardThreadProc - DISPLAY=:0.0
winMultiWindowXMsgProc - xcb_connect() returned and successfully opened the display.
OS maintains clipboard viewer chain: yes
winClipboardProc - XOpenDisplay () returned and successfully opened the display.
Using Composite redirection

Body:
I had a similar issue and tracked it down to startx misbehaving.  This is what I saw:

$ ./startx -- :1
:1" in "list" command display name "hostname
xauth: (stdin):1:  bad "add" command line

The problem is with the way startx is setting its hostname variable.  It does not strip out the carriage return.  Later, when startx uses the hostname variable, the contained carriage return causes xuath "add" command to terminate prematurely and fail.

The fix for me was to strip out the carriage return.

Find where the variable hostname gets set in /usr/bin/startx, and just below there add this line:

hostname=$(echo $hostname | sed 's/\x0D//g')


问:
loading local fonts with font face observer - every weight needed in my promise?
I've got 2 local fonts each with 2 styles (normal and bold) that I want to use on a site and I'm trying to set up font face observer to load them. I have listed both fonts with the same name so that the browser can chose normal vs bold without me having to touch every bit of css to set a specific font for bold. I think normally this should work fine but with the addition of font face observer I'm not sure if I now need to specify the weight and then amend my css accordingly. I read on https://github.com/bramstein/fontfaceobserver that font weight is not mandatory but will be set to "normal" if not specified.

So this:

```<code>    var fontHeading = new FontFaceObserver("Oxygen", { weight: 400 });
    var fontMain = new FontFaceObserver("Rubik", { weight: 400 });
    Promise.all([
      fontHeading.load(),
      fontMain.load(),
    ]).then(function() {
    document.documentElement.className += " fonts-loaded";
    });
</code>```

Or this:

```<code>var fontHeading = new FontFaceObserver("Oxygen", { weight: 400 });
var fontHeadingBold = new FontFaceObserver("Oxygen", { weight: 700 });
var fontMain = new FontFaceObserver("Rubik", { weight: 400 });
var fontMainBold = new FontFaceObserver("Rubik", { weight: 700 });
Promise.all([
    fontHeading.load(),
    fontHeadingBold.load(),
    fontMain.load(),
    fontMainBold.load(),
]).then(function() {
    document.documentElement.className += " fonts-loaded";
});
</code>```

my css:

```<code> @font-face {
      font-family: 'Rubik';
      font-style: normal;
      font-weight: 400;
      src:
        url(../fonts/rubik-v6-latin-regular.woff2) format('woff2'),
        url(../fonts/rubik-v6-latin-regular.woff) format('woff');
    }
    @font-face {
      font-family: 'Rubik';
      font-style: normal;
      font-weight: 700;
      src:
        url(../fonts/rubik-v6-latin-700.woff2) format('woff2'),
        url(../fonts/rubik-v6-latin-700.woff) format('woff');
    }
    @font-face {
      font-family: 'Oxygen';
      font-style: normal;
      font-weight: 400;
      src:
        url(../fonts/oxygen-webfont.woff) format('woff'),
        url(../fonts/oxygen-webfont.woff2) format('woff2');
    }
    @font-face {
      font-family: 'Oxygen';
      font-style: normal;
      font-weight: 700;
      src:
        url(../fonts/oxygen-bold-webfont.woff) format('woff'),
        url(../fonts/oxygen-bold-webfont.woff2) format('woff2');
    }
</code>```

css:

```<code>h3 {
font-weight: bold;
font-family: "oxygen-bold";
}
</code>```

答:
Why are you using font-family: "oxygen-bold"; when you've told CSS what to do for the family "Oxygen" at two different weights?

You specified what it should do for weights 400 and 700, so just use that:

```<code>h3 {
  font-family: Oxygen; /* no quotes needed when there are no spaces/dashes/etc */
  font-weight: 700;
}
</code>```

Body:
I've got 2 local fonts each with 2 styles (normal and bold) that I want to use on a site and I'm trying to set up font face observer to load them. I have listed both fonts with the same name so that the browser can chose normal vs bold without me having to touch every bit of css to set a specific font for bold. I think normally this should work fine but with the addition of font face observer I'm not sure if I now need to specify the weight and then amend my css accordingly. I read on https://github.com/bramstein/fontfaceobserver that font weight is not mandatory but will be set to "normal" if not specified.

So this:

    var fontHeading = new FontFaceObserver("Oxygen", { weight: 400 });
    var fontMain = new FontFaceObserver("Rubik", { weight: 400 });
    Promise.all([
      fontHeading.load(),
      fontMain.load(),
    ]).then(function() {
    document.documentElement.className += " fonts-loaded";
    });

Or this:

var fontHeading = new FontFaceObserver("Oxygen", { weight: 400 });
var fontHeadingBold = new FontFaceObserver("Oxygen", { weight: 700 });
var fontMain = new FontFaceObserver("Rubik", { weight: 400 });
var fontMainBold = new FontFaceObserver("Rubik", { weight: 700 });
Promise.all([
    fontHeading.load(),
    fontHeadingBold.load(),
    fontMain.load(),
    fontMainBold.load(),
]).then(function() {
    document.documentElement.className += " fonts-loaded";
});

my css:

 @font-face {
      font-family: 'Rubik';
      font-style: normal;
      font-weight: 400;
      src:
        url(../fonts/rubik-v6-latin-regular.woff2) format('woff2'),
        url(../fonts/rubik-v6-latin-regular.woff) format('woff');
    }
    @font-face {
      font-family: 'Rubik';
      font-style: normal;
      font-weight: 700;
      src:
        url(../fonts/rubik-v6-latin-700.woff2) format('woff2'),
        url(../fonts/rubik-v6-latin-700.woff) format('woff');
    }
    @font-face {
      font-family: 'Oxygen';
      font-style: normal;
      font-weight: 400;
      src:
        url(../fonts/oxygen-webfont.woff) format('woff'),
        url(../fonts/oxygen-webfont.woff2) format('woff2');
    }
    @font-face {
      font-family: 'Oxygen';
      font-style: normal;
      font-weight: 700;
      src:
        url(../fonts/oxygen-bold-webfont.woff) format('woff'),
        url(../fonts/oxygen-bold-webfont.woff2) format('woff2');
    }

css:

h3 {
font-weight: bold;
font-family: "oxygen-bold";
}

Body:
Why are you using font-family: "oxygen-bold"; when you've told CSS what to do for the family "Oxygen" at two different weights?

You specified what it should do for weights 400 and 700, so just use that:

h3 {
  font-family: Oxygen; /* no quotes needed when there are no spaces/dashes/etc */
  font-weight: 700;
}


问:
Collection View terminates after cellForItemAtIndex
```<code>import UIKit
import Photos

class GalleryController: UICollectionViewController,
                         UIImagePickerControllerDelegate,
                         UINavigationControllerDelegate {
    var Receipts = [UIImage?]()

    //Number of Views
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        print("return1")
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print("self.receipts.count")
        return self.Receipts.count
    }
</code>```

This code below is not working as it should and everytime I run the app it comes up with this error -

```
SmartReceipts[738:137366] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'the collection view's data source did not return a valid cell from -collectionView:cellForItemAtIndexPath: for index path  {length = 2, path = 0 - 0}'
*** First throw call stack:
(0x186196364 0x1853dc528 0x186196238 0x186b317f4 0x1901010b0 0x18f6d7124 0x18f6d1de0 0x18f674f00 0x18a1d9998 0x18a1ddb20 0x18a14a36c 0x18a171b90 0x18f66a5c8 0x18613dedc 0x18613b894 0x18613be50 0x18605be58 0x187f08f84 0x18f6db67c 0x104484668 0x185b7856c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
```

Any help with this would be greatly appreciated.

And the code that needs fixing is the code below:

```<code>    func collectionView(_ collectionView: UICollectionView, cellForItemAtindexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "receipt", for: indexPath as IndexPath) as? PhotoCell

        cell?.imageView.image = self.Receipts[indexPath.row]
        print("Assigned to cell and should come up")
        return cell!
    }
}
</code>```

It now errors as this error and i'm not sure how it's doing it? Because it is sending the image to an array but it's not showing up in the UICollectionViewCell?

答:
Check your ViewController in main.storyBoard that any kind of warning that affect normal flow of working. right click on PhotoCell you have created in GalleryController, a dialogbox will appear, if there is any kind of warning. remove it by clicking close button. or else right click on top left icon of GallerViewController,you will get a popup and check any kind of yellow Warning is there.if so then remove it by clicking close button.

for example see the below images.

Use cellForItemAt instead of cellForItemAtindexPath

```<code> func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "receipt", for: indexPath as IndexPath) as? PhotoCell

            cell?.imageView.image = self.Receipts[indexPath.row]
            print("Assigned to cell and should come up")
            return cell!
    }
</code>```

Body:
import UIKit
import Photos

class GalleryController: UICollectionViewController,
                         UIImagePickerControllerDelegate,
                         UINavigationControllerDelegate {
    var Receipts = [UIImage?]()

    //Number of Views
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        print("return1")
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print("self.receipts.count")
        return self.Receipts.count
    }

This code below is not working as it should and everytime I run the app it comes up with this error -

SmartReceipts[738:137366] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'the collection view's data source did not return a valid cell from -collectionView:cellForItemAtIndexPath: for index path  {length = 2, path = 0 - 0}'
*** First throw call stack:
(0x186196364 0x1853dc528 0x186196238 0x186b317f4 0x1901010b0 0x18f6d7124 0x18f6d1de0 0x18f674f00 0x18a1d9998 0x18a1ddb20 0x18a14a36c 0x18a171b90 0x18f66a5c8 0x18613dedc 0x18613b894 0x18613be50 0x18605be58 0x187f08f84 0x18f6db67c 0x104484668 0x185b7856c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

Any help with this would be greatly appreciated.

And the code that needs fixing is the code below:

    func collectionView(_ collectionView: UICollectionView, cellForItemAtindexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "receipt", for: indexPath as IndexPath) as? PhotoCell

        cell?.imageView.image = self.Receipts[indexPath.row]
        print("Assigned to cell and should come up")
        return cell!
    }
}

It now errors as this error and i'm not sure how it's doing it? Because it is sending the image to an array but it's not showing up in the UICollectionViewCell?

Body:
Check your ViewController in main.storyBoard that any kind of warning that affect normal flow of working. right click on PhotoCell you have created in GalleryController, a dialogbox will appear, if there is any kind of warning. remove it by clicking close button. or else right click on top left icon of GallerViewController,you will get a popup and check any kind of yellow Warning is there.if so then remove it by clicking close button.

for example see the below images.

Use cellForItemAt instead of cellForItemAtindexPath

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "receipt", for: indexPath as IndexPath) as? PhotoCell

            cell?.imageView.image = self.Receipts[indexPath.row]
            print("Assigned to cell and should come up")
            return cell!
    }


问:
Serialize parallel arrays to XML in C# in a specific order
I'm currently tasked with sending data to a web service that has a very odd way of specifying lists. I am not in control of the schema, and my attempts to make the other party change the schema have failed. So I'm pretty much stuck with this.

The way their schema is defined is this (only the relevant bit is included):

```<code><xs:element name="Part">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="List">
        <xs:complexType>
          <xs:sequence maxOccurs="4">
            <xs:element name="Name" type="xs:string" />
            <xs:element name="Data" type="xs:string" />
            <xs:element name="OtherData" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>
</code>```

I used xsd.exe to generate a C# class to serialize the structure easily. The generated bit is as follows:

```<code>[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="the namespace")]
public partial class PartList {
    [System.Xml.Serialization.XmlElementAttribute("Name", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string[] Name { get; set; }

    [System.Xml.Serialization.XmlElementAttribute("Data", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string[] Data { get; set; }

    [System.Xml.Serialization.XmlElementAttribute("OtherData", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string[] OtherData  { get; set; }
}
</code>```

Yes, parallel arrays. Now, according to their documents (and anecdotal data from another party that generates the XML through other means), the correct/expected xml should look like this (for example, a list with two items - comments inline added for illustration purposes):

```<code><Part xmlns="">
    <List>
        <Name>Some Test</Name> <!-- first item -->
        <Data>123131313</Data> <!-- first item -->
        <OtherData>0.11</OtherData> <!-- first item -->
        <Name>Other Lama</Name> <!-- second item -->
        <Data>331331313</Data> <!-- second item -->
        <OtherData>0.02</OtherData> <!-- second item -->
    </List>
</Part>
</code>```

However, my autogenerated C# class serializes to:

```<code><Part xmlns="">
    <List>
        <Name>Marcos Test</Name> <!-- first item -->
        <Name>Pepe Lama</Name> <!-- second item -->
        <Data>123131313</Data> <!-- first item -->
        <Data>331331313</Data> <!-- second item -->
        <OtherData>0.11</OtherData> <!-- first item -->
        <OtherData>0.02</OtherData> <!-- second item -->
    </List>
</Part>
</code>```

My XML fails validation against the schema because of the ordering of the items. I'm serializing the class using System.Xml.Serialization.XmlSerializer with the default options. I usually don't have any trouble serializing reasonable schemas for other web services. But for some reason I just can't for the life of me figure out how to do this (if it's even possible).

Any ideas? I already tried using the XmlOrderAttribute, but didn't make a difference in the order of the result.

答:
I marked dbc's answer as correct because his comments and answer were what led me to the final implementation. For completeness sake (and to have some sort of documentation just in case I run into this in the future), this is how I ended up implementing this functionality.

I took advantage of the fact that xsd.exe generates all classes as partial classes. That made it easier for me to add the new list/collection properties that will end up being serialized, and not lose changes whenever the schema changes. For example, to override the List property of the RemoteServiceTypePart1 class:

```<code>public partial class RemoteServiceTypePart1
{
    // Tell the Xml serializer to use "List" instead of "List_Override"
    // as the element name.
    [XmlAnyElement("List")]
    public XElement List_Override
    {
        get {
            var result = new List<XElement>();

            for (int i = 0; i < List.Name.Length; i++)
            {
                result.Add(new XElement("Name", List.Name[i]));
                result.Add(new XElement("Data", List.Data[i]));
                result.Add(new XElement("OtherData", List.OtherData[i]));
            }

            return new XElement("List", result.ToArray());
        }

        set { }
    }
}
</code>```

Now the only remaining issue is how to add the [XmlIgnore] attribute to the original property, and not have to add the attribute by hand every time the schema changes. To do that, I used the XmlAttributeOverrides class and placed it where the xml serialization logic is:

```<code>var xmlIgnoreAttr = new XmlAttributes { XmlIgnore = true };

var overrides = new XmlAttributeOverrides();
// Add an override for each class that requires properties to be ignored.
overrides.Add(typeof(RemoteServiceTypePart1), "List", xmlIgnoreAttr);
overrides.Add(typeof(RemoteServiceTypePart2), "List", xmlIgnoreAttr);
overrides.Add(typeof(RemoteServiceTypePart3), "List", xmlIgnoreAttr);

// In a real-world implementation, you will need to cache this object to
// avoid a memory leak. Read: https://stackoverflow.com/a/23897411/3744182
// Thanks to dbc for letting me know in the comments.
var ser = new XmlSerializer(typeof(RemoteServiceType), overrides);
// serialize, send xml, do whatever afterwards
</code>```

That's it. Now the output XML looks like this:

```<code><RemoteServiceTypePart1 xmlns="">
  <List>
    <Name>Marcos Test</Name>
    <Data>123131313</Data>
    <OtherData>0.11</OtherData>
    <Name>Pepe Lama</Name>
    <Data>331331313</Data>
    <OtherData>0.02</OtherData>
  </List>
</RemoteServiceTypePart1>
</code>```

Body:
I'm currently tasked with sending data to a web service that has a very odd way of specifying lists. I am not in control of the schema, and my attempts to make the other party change the schema have failed. So I'm pretty much stuck with this.

The way their schema is defined is this (only the relevant bit is included):

<xs:element name="Part">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="List">
        <xs:complexType>
          <xs:sequence maxOccurs="4">
            <xs:element name="Name" type="xs:string" />
            <xs:element name="Data" type="xs:string" />
            <xs:element name="OtherData" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>

I used xsd.exe to generate a C# class to serialize the structure easily. The generated bit is as follows:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="the namespace")]
public partial class PartList {
    [System.Xml.Serialization.XmlElementAttribute("Name", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string[] Name { get; set; }

    [System.Xml.Serialization.XmlElementAttribute("Data", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string[] Data { get; set; }

    [System.Xml.Serialization.XmlElementAttribute("OtherData", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string[] OtherData  { get; set; }
}

Yes, parallel arrays. Now, according to their documents (and anecdotal data from another party that generates the XML through other means), the correct/expected xml should look like this (for example, a list with two items - comments inline added for illustration purposes):

<Part xmlns="">
    <List>
        <Name>Some Test</Name>
        <Data>123131313</Data>
        <OtherData>0.11</OtherData>
        <Name>Other Lama</Name>
        <Data>331331313</Data>
        <OtherData>0.02</OtherData>
    </List>
</Part>

However, my autogenerated C# class serializes to:

<Part xmlns="">
    <List>
        <Name>Marcos Test</Name>
        <Name>Pepe Lama</Name>
        <Data>123131313</Data>
        <Data>331331313</Data>
        <OtherData>0.11</OtherData>
        <OtherData>0.02</OtherData>
    </List>
</Part>

My XML fails validation against the schema because of the ordering of the items. I'm serializing the class using System.Xml.Serialization.XmlSerializer with the default options. I usually don't have any trouble serializing reasonable schemas for other web services. But for some reason I just can't for the life of me figure out how to do this (if it's even possible).

Any ideas? I already tried using the XmlOrderAttribute, but didn't make a difference in the order of the result.

Body:
I marked dbc's answer as correct because his comments and answer were what led me to the final implementation. For completeness sake (and to have some sort of documentation just in case I run into this in the future), this is how I ended up implementing this functionality.

I took advantage of the fact that xsd.exe generates all classes as partial classes. That made it easier for me to add the new list/collection properties that will end up being serialized, and not lose changes whenever the schema changes. For example, to override the List property of the RemoteServiceTypePart1 class:

public partial class RemoteServiceTypePart1
{
    // Tell the Xml serializer to use "List" instead of "List_Override"
    // as the element name.
    [XmlAnyElement("List")]
    public XElement List_Override
    {
        get {
            var result = new List<XElement>();

            for (int i = 0; i < List.Name.Length; i++)
            {
                result.Add(new XElement("Name", List.Name[i]));
                result.Add(new XElement("Data", List.Data[i]));
                result.Add(new XElement("OtherData", List.OtherData[i]));
            }

            return new XElement("List", result.ToArray());
        }

        set { }
    }
}

Now the only remaining issue is how to add the [XmlIgnore] attribute to the original property, and not have to add the attribute by hand every time the schema changes. To do that, I used the XmlAttributeOverrides class and placed it where the xml serialization logic is:

var xmlIgnoreAttr = new XmlAttributes { XmlIgnore = true };

var overrides = new XmlAttributeOverrides();
// Add an override for each class that requires properties to be ignored.
overrides.Add(typeof(RemoteServiceTypePart1), "List", xmlIgnoreAttr);
overrides.Add(typeof(RemoteServiceTypePart2), "List", xmlIgnoreAttr);
overrides.Add(typeof(RemoteServiceTypePart3), "List", xmlIgnoreAttr);

// In a real-world implementation, you will need to cache this object to
// avoid a memory leak. Read: https://stackoverflow.com/a/23897411/3744182
// Thanks to dbc for letting me know in the comments.
var ser = new XmlSerializer(typeof(RemoteServiceType), overrides);
// serialize, send xml, do whatever afterwards

That's it. Now the output XML looks like this:

<RemoteServiceTypePart1 xmlns="">
  <List>
    <Name>Marcos Test</Name>
    <Data>123131313</Data>
    <OtherData>0.11</OtherData>
    <Name>Pepe Lama</Name>
    <Data>331331313</Data>
    <OtherData>0.02</OtherData>
  </List>
</RemoteServiceTypePart1>


问:
Submit an HTML form with empty checkboxes
I have an HTML form - with PHP, I am sending the data of the form into a MySQL database. Some of the answers to the questions on the form have checkboxes. Obviously, the user does not have to tick all checkboxes for one question. I also want to make the other questions (including radio groups) optional.

However, if I submit the form with empty boxes, radio-groups etc, I received a long list of 'Undefined index' error messages for each of them.

How can I get around this? Thanks.

答:
To add to fmsf's code, when adding checkboxes I make them an array by having [] in the name

```<code><FORM METHOD=POST ACTION="statistics.jsp?q=1&g=1">
    <input type="radio" name="gerais_radio" value="primeiras">Primeiras Consultas por medico<br/>
    <input type="radio" name="gerais_radio" value="salas">Consultas por Sala <br/>
    <input type="radio" name="gerais_radio" value="assistencia">Pacientes por assistencia<br/>
    <input type="checkbox" name="option[]" value="Option1">Option1<br/>
    <input type="checkbox" name="option[]" value="Option2">Option2<br/>
    <input type="checkbox" name="option[]" value="Option3">Option3<br/>
    <input type="submit" value="Ver">
</code>```

OwnerDisplayName: Tray

LastEditorDisplayName: fmsf

Body:
To add to fmsf's code, when adding checkboxes I make them an array by having [] in the name

<FORM METHOD=POST ACTION="statistics.jsp?q=1&g=1">
    <input type="radio" name="gerais_radio" value="primeiras">Primeiras Consultas por medico<br/>
    <input type="radio" name="gerais_radio" value="salas">Consultas por Sala <br/>
    <input type="radio" name="gerais_radio" value="assistencia">Pacientes por assistencia<br/>
    <input type="checkbox" name="option[]" value="Option1">Option1<br/>
    <input type="checkbox" name="option[]" value="Option2">Option2<br/>
    <input type="checkbox" name="option[]" value="Option3">Option3<br/>
    <input type="submit" value="Ver">


问:
I need help writing a complex SELECT statement
i am trying to write an sql statement that will select items from one table and order it by the result of the other table..

the 2 tables are:

events:
id, name

attendance:
user, event

ive got this statement:

```<code>SELECT *
FROM `attendance`
WHERE event='1'
  AND user IN (1,2,3,4,5,6,7,8,9,10,11,12,13,444,153)
</code>```

I am using this to get the number of friends that coming to event number 1.

now I want to combine that statement with another one to create a statement that select all the events, and order it by the number of friends that going...
how can i write that statement?

Thank you very much, Amir.

答:
I would try something like this:

```<code>SELECT
    id,
    name,
    (SELECT COUNT(*) FROM attendance att WHERE att.event = ev.id) AS attending
FROM
    event ev
ORDER BY
    attending DESC
</code>```

However, although I would try something like that, fact is I haven't, so this might not work as is.

Body:
i am trying to write an sql statement that will select items from one table and order it by the result of the other table..

the 2 tables are:

events:
id, name

attendance:
user, event

ive got this statement:

SELECT *
FROM `attendance`
WHERE event='1'
  AND user IN (1,2,3,4,5,6,7,8,9,10,11,12,13,444,153)

I am using this to get the number of friends that coming to event number 1.

now I want to combine that statement with another one to create a statement that select all the events, and order it by the number of friends that going...
how can i write that statement?

Thank you very much, Amir.

Body:
I would try something like this:

SELECT
    id,
    name,
    (SELECT COUNT(*) FROM attendance att WHERE att.event = ev.id) AS attending
FROM
    event ev
ORDER BY
    attending DESC

However, although I would try something like that, fact is I haven't, so this might not work as is.


问:
Make String type compatible with ARM?
I need to compile a program for an ARM device. It seems to be failing here, perhaps because of the type difference on ARM?

```<code>unsafe { Ok(String::from(try!(CStr::from_ptr(buf.as_ptr() as *const i8).to_str()))) }
</code>```

The error is:

694 |         unsafe { Ok(String::from(try!(CStr::from_ptr(buf.as_ptr() as *const i8).to_str()))) }
    |                                                      ^^^^^^^^^^^^^^^^^^^^^^^^^ expected u8, found i8
    |
    = note: expected type `*const u8`
               found type `*const i8`
```

What is the type difference and how do I fix it?

答:
You probably want to use std::os::raw::c_char instead of i8. (Though that may not be the right place to get the type from. libc::c_char seems to exist as well.)

The basic issue is that the char type in C can be signed or unsigned depending on the platform and that is reflected in the foreign function interface. Ideally you'd like to find a way to do the conversion without having to explicitly mention the type.

Title: Make String type compatible with ARM?

Body:
I need to compile a program for an ARM device. It seems to be failing here, perhaps because of the type difference on ARM?

unsafe { Ok(String::from(try!(CStr::from_ptr(buf.as_ptr() as *const i8).to_str()))) }

The error is:

694 |         unsafe { Ok(String::from(try!(CStr::from_ptr(buf.as_ptr() as *const i8).to_str()))) }
    |                                                      ^^^^^^^^^^^^^^^^^^^^^^^^^ expected u8, found i8
    |
    = note: expected type `*const u8`
               found type `*const i8`

What is the type difference and how do I fix it?


问:
HTML 5 required attribute - constrain validation within a div?
Given a form containing 2 div's and each div containing an asp textbox with "required" attribute, is it possible to constrain html5 required attribute to only be considered within the div that contains the textbox?  So, for example, can I have required attribute on textbox in the first div that isn't validated when you click on the button in the second div?  I should add that I'm trying to do this in a content page.</p>

```<code><form>
    <div>
        <asp:textbox runat="server" id="TextBox1" required="required"></asp:textbox>
        <asp:button runat="server" id="Button1" text="Save"  />
        <asp:button runat="server" id="Button2" text="Cancel"  onclientclick="return false" />
    </div>
    <div>
        <asp:textbox runat="server" id="TextBox2" required="required"></asp:textbox>
        <asp:button runat="server" id="Button3" text="Save"  />
        <asp:button runat="server" id="Button4" text="Cancel"  onclientclick="return false" />
    </div>
</form>
</code>```

答:
The standard html5 validation does not have a built in option for "if this input meets requirements, make this input non-required". In order to accomplish this within a single form, you will need to write a very small amount of JavaScript to remove the required attribute from the other text input when the current text input meets your requirements, otherwise the form will not pass client-side validation and the other text input will match the :invalid pseudo-class.

I would suggest switching to a jquery plugin such as http://www.formvalidator.net, which will not require you to write any code. You can use html attributes such as data-validation-depends-on from the above plugin to accomplish this.

Body:
Given a form containing 2 div's and each div containing an asp textbox with "required" attribute, is it possible to constrain html5 required attribute to only be considered within the div that contains the textbox?  So, for example, can I have required attribute on textbox in the first div that isn't validated when you click on the button in the second div?  I should add that I'm trying to do this in a content page.

<form>

        <asp:textbox runat="server" id="TextBox1" required="required"></asp:textbox>
        <asp:button runat="server" id="Button1" text="Save"  />
        <asp:button runat="server" id="Button2" text="Cancel"  onclientclick="return false" />

        <asp:textbox runat="server" id="TextBox2" required="required"></asp:textbox>
        <asp:button runat="server" id="Button3" text="Save"  />
        <asp:button runat="server" id="Button4" text="Cancel"  onclientclick="return false" />

</form>