问:
How to handle xml encoding in XML GENERATE command?
We are facing an issue where in the xml messages with the special characters like [· (0xB7), Ý (0xDD), ¨(0xA8)] are getting rejected, when they are actually XML valid characters.  What we found is that are invalid characters for the default encoding that is assigned to a message, when not specified.  We can avoid this, if we specifically add the encoding type to the top of the message.  We used the UTF-8 encoding.  So by adding "" to the very beginning of the XML
message, the characters should then become valid characters.
Below is the cobol code:

```<code>XML GENERATE RESPONSEDATA FROM ACCT
    COUNT IN RESPONSEDATALL
            WITH ENCODING 1208
            WITH XML-DECLARATION
END-XML
</code>```

But when we see the xml generated it consists of characters as shown below:

```<code>..Ì_%.ÎÁÊËÑ?>.......Á>Ä?ÀÑ>Å..UTF-8....
</code>```

The expected output is that the below encoding bit should be added to the header.

```<code><?xml version=“1.0” encoding=“utf-8”?>
</code>```

So the issue is when this generated XML is parsed back again in another peice of code, it encouters an XML-EXCEPTION and backs out altogether with an exception message.

The question is is there some other peice of code or compile options which need to be added to make this xml valid?

答:
This is completely normal.

You are encoding the XML as UTF-8, however you are viewing the XML on the mainframe (which is EBCDIC). When your ISPF viewer open the XML file that you have created, it just interprets the hex values and tried to show you something. Because these values do not line up with the EBCDIC character set, it looks like garbage. If you FTP the file down to your computer, you will see that the XML is in fact the output you are looking for.

When you are parsing the XML, you actually have to do some something similar and specify the encoding that was used during the generate. The code below will parse a UTF-8 XML, and on exception, it will display the all of the XML up until the point of the exception occurred in EBCDIC so it is readable in the mainframe SYSOUT

```<code>XML PARSE WS-MY-XML
   ENCODING 1208
   PROCESSING PROCEDURE XXXX-PROCESS-XML
   ON EXCEPTION
      DISPLAY "EXCEPTION OCCURED: "
      DISPLAY FUNCTION DISPLAY-OF (
         FUNCTION NATIONAL-OF (
            XML-TEXT 1208
         )
         1140
      )
END-XML
</code>```

EDIT: that being said, there still could be a legitimate error in your XML such as an illegal character. If the code I have posted also does work, FTP the XML and run it through an XML validator online to see where the fault is.

Body:
We are facing an issue where in the xml messages with the special characters like [· (0xB7), Ý (0xDD), ¨(0xA8)] are getting rejected, when they are actually XML valid characters.  What we found is that are invalid characters for the default encoding that is assigned to a message, when not specified.  We can avoid this, if we specifically add the encoding type to the top of the message.  We used the UTF-8 encoding.  So by adding "" to the very beginning of the XML
message, the characters should then become valid characters.
Below is the cobol code:

XML GENERATE RESPONSEDATA FROM ACCT
    COUNT IN RESPONSEDATALL
            WITH ENCODING 1208
            WITH XML-DECLARATION
END-XML

But when we see the xml generated it consists of characters as shown below:

..Ì_%.ÎÁÊËÑ?>.......Á>Ä?ÀÑ>Å..UTF-8....

The expected output is that the below encoding bit should be added to the header.

<?xml version=“1.0” encoding=“utf-8”?>

So the issue is when this generated XML is parsed back again in another peice of code, it encouters an XML-EXCEPTION and backs out altogether with an exception message.

The question is is there some other peice of code or compile options which need to be added to make this xml valid?

Body:
This is completely normal.

You are encoding the XML as UTF-8, however you are viewing the XML on the mainframe (which is EBCDIC). When your ISPF viewer open the XML file that you have created, it just interprets the hex values and tried to show you something. Because these values do not line up with the EBCDIC character set, it looks like garbage. If you FTP the file down to your computer, you will see that the XML is in fact the output you are looking for.

When you are parsing the XML, you actually have to do some something similar and specify the encoding that was used during the generate. The code below will parse a UTF-8 XML, and on exception, it will display the all of the XML up until the point of the exception occurred in EBCDIC so it is readable in the mainframe SYSOUT

XML PARSE WS-MY-XML
   ENCODING 1208
   PROCESSING PROCEDURE XXXX-PROCESS-XML
   ON EXCEPTION
      DISPLAY "EXCEPTION OCCURED: "
      DISPLAY FUNCTION DISPLAY-OF (
         FUNCTION NATIONAL-OF (
            XML-TEXT 1208
         )
         1140
      )
END-XML

EDIT: that being said, there still could be a legitimate error in your XML such as an illegal character. If the code I have posted also does work, FTP the XML and run it through an XML validator online to see where the fault is.


来源: stackexchange

问:
Getting current RGB color of Image
I want to change the Alpha color of image(script) component of GameObject.

But saving the RGB values of the object.

I tried the next code:

```<code>        targetObject.GetComponent<Image>().color = new Color32(
            (byte)targetObject.GetComponent<Image>().color.r,
            (byte)targetObject.GetComponent<Image>().color.g,
            (byte)targetObject.GetComponent<Image>().color.b,
            toAlpha);
</code>```

But (byte)targetObject.GetComponent<Image>().color.r returns 0 what so ever.

Any ideas?

答:
The struct Color uses channel values in the range [0,1]. So, white is (1,1,1,1) and black (0,0,0,0). The color propriety returns a Color struct, not a Color32.

When you cast float to byte, the result will be 1 if the channel is at 1, or 0 if is less than 1. Since you're using these values in a Color32 struct (which uses an int per channel in the range [0,255]), if the starting color is full white, you'll have an almost black of (1,1,1,1), if any channel isn't full on (i.e. <255 using ints), the channel will be full off.

Just change new Color32 to new Color and remove the (byte) cast.

ContentLicense: CC BY-SA 3.0

Title: Getting current RGB color of Image

Body:
I want to change the Alpha color of image(script) component of GameObject.

But saving the RGB values of the object.

I tried the next code:

        targetObject.GetComponent<Image>().color = new Color32(
            (byte)targetObject.GetComponent<Image>().color.r,
            (byte)targetObject.GetComponent<Image>().color.g,
            (byte)targetObject.GetComponent<Image>().color.b,
            toAlpha);

But (byte)targetObject.GetComponent<Image>().color.r returns 0 what so ever.

Any ideas?


问:
Can't Update Values In Microsoft Access
I have a problem that when I try updating data the the program doesn't save it in the database.

This is the current code:

```<code>Dim y As Byte = Convert.ToByte(lblID.Text) - 1
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("dset").Rows(y).Item(1) = txtname.Text
ds.Tables("dset").Rows(y).Item(2) = txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text
ds.Tables("dset").Rows(y).Item(3) = txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text
ds.Tables("dset").Rows(y).Item(5) = txtnotes.Text
If MdComboBox1.SelectedItem = "A" Then
    ds.Tables("dset").Rows(y).Item(4) = "A"
ElseIf MdComboBox1.SelectedItem = "B" Then
Else
    MdAlertBox1.Text = "Please Select A Class The Class Box"
    MdAlertBox1.Visible = True
End If
MdAlertBox1.Text = "Data Sucessfully Updated !"
MdAlertBox1.kind = MDAlertBox._Kind.Success
MdAlertBox1.Visible = True
getinfo.Start()
updatedata.Stop()
</code>```

And the declared variables:

```<code>Dim conn As New OleDb.OleDbConnection
Dim DbProv As String = "PROVIDER=microsoft.ACE.OLEDB.12.0;"
Dim Src As String = " data source = c:\users\kingo\documents\visual studio 2013\Projects\WindowsApplication2\WindowsApplication2\BigGymDB.accdb"
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
</code>```

答:
Put a debug.print to see the values you are passing to the Database. Like this:

```<code>    ds.Tables("dset").Rows(y).Item(2) = txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text
    ds.Tables("dset").Rows(y).Item(3) = txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text
    ds.Tables("dset").Rows(y).Item(5) = txtnotes.Text
    'your code ---^

    debug.print txtname.Text; txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text;
    debug.print txtnotes.Text; txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text

    'your code ---v

    If MdComboBox1.SelectedItem = "A" Then
        ds.Tables("dset").Rows(y).Item(4) = "A"
    ElseIf MdComboBox1.SelectedItem = "B" Then
</code>```

Then in two lines in the Immdiate Window, you should see whether these txtsub.Text and the other 3 inputs actually have something.

Title: Can't Update Values In Microsoft Access

Body:
I have a problem that when I try updating data the the program doesn't save it in the database.

This is the current code:

Dim y As Byte = Convert.ToByte(lblID.Text) - 1
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("dset").Rows(y).Item(1) = txtname.Text
ds.Tables("dset").Rows(y).Item(2) = txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text
ds.Tables("dset").Rows(y).Item(3) = txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text
ds.Tables("dset").Rows(y).Item(5) = txtnotes.Text
If MdComboBox1.SelectedItem = "A" Then
    ds.Tables("dset").Rows(y).Item(4) = "A"
ElseIf MdComboBox1.SelectedItem = "B" Then
Else
    MdAlertBox1.Text = "Please Select A Class The Class Box"
    MdAlertBox1.Visible = True
End If
MdAlertBox1.Text = "Data Sucessfully Updated !"
MdAlertBox1.kind = MDAlertBox._Kind.Success
MdAlertBox1.Visible = True
getinfo.Start()
updatedata.Stop()

And the declared variables:

Dim conn As New OleDb.OleDbConnection
Dim DbProv As String = "PROVIDER=microsoft.ACE.OLEDB.12.0;"
Dim Src As String = " data source = c:\users\kingo\documents\visual studio 2013\Projects\WindowsApplication2\WindowsApplication2\BigGymDB.accdb"
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet

Body:
Put a debug.print to see the values you are passing to the Database. Like this:

    ds.Tables("dset").Rows(y).Item(2) = txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text
    ds.Tables("dset").Rows(y).Item(3) = txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text
    ds.Tables("dset").Rows(y).Item(5) = txtnotes.Text
    'your code ---^

    debug.print txtname.Text; txtsubm.Text & "/" & txtsubd.Text & "/" & txtsuby.Text;
    debug.print txtnotes.Text; txtexpm.Text & "/" & txtexpd.Text & "/" & txtexpy.Text

    'your code ---v

    If MdComboBox1.SelectedItem = "A" Then
        ds.Tables("dset").Rows(y).Item(4) = "A"
    ElseIf MdComboBox1.SelectedItem = "B" Then

Then in two lines in the Immdiate Window, you should see whether these txtsub.Text and the other 3 inputs actually have something.


问:
How to call a method daily, at specific time, in C#?
I've searched on SO and found answers about Quartz.net. But it seems to be too big for my project. I want an equivalent solution, but simpler and (at best) in-code (no external library required). How can I call a method daily, at a specific time?

I need to add some information about this:

the simplest (and ugly) way to do this, is check the time every second/minute and call the method, at right time

I want a more-effective way to do this, no need to check the time constantly, and I have control about whether the job is done a not. If the method fails (because of any problems), the program should know to write to log/send a email. That's why I need to call a method, not schedule a job.

I found this solution Call a method at fixed time in Java in Java. Is there a similar way in C#?

EDIT: I've done this. I added a parameter into void Main(), and created a bat (scheduled by Windows Task Scheduler) to run the program with this parameter. The program runs, does the job, and then exits. If a job fails, it's capable of writing log and sending email. This approach fits my requirements well :)

答:
I created a simple scheduler that is easy to use and you do not need to use external library. TaskScheduler is a singleton that keeps references on the timers so timers will not be garbage collected, it can schedule multiple tasks. You can set the first run (hour and minute), if at the time of scheduling this time is over scheduling start on the next day this at that time. But it is easy to customize the code.

Scheduling a new task is so simple. Example: At 11:52 the first task is for every 15 secunds, the second example is for every 5 secunds. For daily execution set 24 to the 3 parameter.

```<code>TaskScheduler.Instance.ScheduleTask(11, 52, 0.00417,
    () =>
    {
        Debug.WriteLine("task1: " + DateTime.Now);
        //here write the code that you want to schedule
    });

TaskScheduler.Instance.ScheduleTask(11, 52, 0.00139,
    () =>
    {
        Debug.WriteLine("task2: " + DateTime.Now);
        //here write the code that you want to schedule
    });
</code>```

My debug window:

```<code>task2: 07.06.2017 11:52:00
task1: 07.06.2017 11:52:00
task2: 07.06.2017 11:52:05
task2: 07.06.2017 11:52:10
task1: 07.06.2017 11:52:15
task2: 07.06.2017 11:52:15
task2: 07.06.2017 11:52:20
task2: 07.06.2017 11:52:25
...
</code>```

Just add this class to your project:

```<code>public class TaskScheduler
{
    private static TaskScheduler _instance;
    private List<Timer> timers = new List<Timer>();

    private TaskScheduler() { }

    public static TaskScheduler Instance => _instance ?? (_instance = new TaskScheduler());

    public void ScheduleTask(int hour, int min, double intervalInHour, Action task)
    {
        DateTime now = DateTime.Now;
        DateTime firstRun = new DateTime(now.Year, now.Month, now.Day, hour, min, 0, 0);
        if (now > firstRun)
        {
            firstRun = firstRun.AddDays(1);
        }

        TimeSpan timeToGo = firstRun - now;
        if (timeToGo <= TimeSpan.Zero)
        {
            timeToGo = TimeSpan.Zero;
        }

        var timer = new Timer(x =>
        {
            task.Invoke();
        }, null, timeToGo, TimeSpan.FromHours(intervalInHour));

        timers.Add(timer);
    }
}
</code>```

Body:
I created a simple scheduler that is easy to use and you do not need to use external library. TaskScheduler is a singleton that keeps references on the timers so timers will not be garbage collected, it can schedule multiple tasks. You can set the first run (hour and minute), if at the time of scheduling this time is over scheduling start on the next day this at that time. But it is easy to customize the code.

Scheduling a new task is so simple. Example: At 11:52 the first task is for every 15 secunds, the second example is for every 5 secunds. For daily execution set 24 to the 3 parameter.

TaskScheduler.Instance.ScheduleTask(11, 52, 0.00417,
    () =>
    {
        Debug.WriteLine("task1: " + DateTime.Now);
        //here write the code that you want to schedule
    });

TaskScheduler.Instance.ScheduleTask(11, 52, 0.00139,
    () =>
    {
        Debug.WriteLine("task2: " + DateTime.Now);
        //here write the code that you want to schedule
    });

My debug window:

task2: 07.06.2017 11:52:00
task1: 07.06.2017 11:52:00
task2: 07.06.2017 11:52:05
task2: 07.06.2017 11:52:10
task1: 07.06.2017 11:52:15
task2: 07.06.2017 11:52:15
task2: 07.06.2017 11:52:20
task2: 07.06.2017 11:52:25
...

Just add this class to your project:

public class TaskScheduler
{
    private static TaskScheduler _instance;
    private List<Timer> timers = new List<Timer>();

    private TaskScheduler() { }

    public static TaskScheduler Instance => _instance ?? (_instance = new TaskScheduler());

    public void ScheduleTask(int hour, int min, double intervalInHour, Action task)
    {
        DateTime now = DateTime.Now;
        DateTime firstRun = new DateTime(now.Year, now.Month, now.Day, hour, min, 0, 0);
        if (now > firstRun)
        {
            firstRun = firstRun.AddDays(1);
        }

        TimeSpan timeToGo = firstRun - now;
        if (timeToGo <= TimeSpan.Zero)
        {
            timeToGo = TimeSpan.Zero;
        }

        var timer = new Timer(x =>
        {
            task.Invoke();
        }, null, timeToGo, TimeSpan.FromHours(intervalInHour));

        timers.Add(timer);
    }
}


问:
How to show particular image as thumbnail while implementing share on Facebook?
I am trying to implement share this method. I am using the code as follows

```<code>http://www.facebook.com/share.php?u=my_website_url
</code>```

Now when Facebook is showing it showing some thumbnails at left side. These images are picked from my website. How can I pick a particular image as thumbnail or at least stop it showing thumbnail?

You can check it with my blog address.

答:
My tags were correct but Facebook only scrapes every 24 hours, according to their documentation.  Using the Facebook Lint page got the image into Facebook.

Enter your URL here and FB will update the metadata from your page:

https://developers.facebook.com/tools/debug (updated link)

OwnerDisplayName: Tanmoy Rajguru

ContentLicense: CC BY-SA 2.5

Body:
I am trying to implement share this method. I am using the code as follows

http://www.facebook.com/share.php?u=my_website_url

Now when Facebook is showing it showing some thumbnails at left side. These images are picked from my website. How can I pick a particular image as thumbnail or at least stop it showing thumbnail?

You can check it with my blog address.


问:
In JavaScript, does using await inside a loop block the loop?
Take the following loop:

```<code>for(var i=0; i<100; ++i){
    let result = await some_slow_async_function();
    do_something_with_result();
}
</code>```

Does await block the loop? Or does the i continue to be incremented while awaiting?

Is the order of do_something_with_result() guaranteed sequential with regard to i? Or does it depend on how fast the awaited function is for each i?

答:
Does await block the loop? Or does the i continue to be incremented while awaiting?

"Block" is not the right word, but yes, i does not continue to be incremented while awaiting. Instead the execution jumps back to where the async function was called, providing a promise as return value, continuing the rest of the code that follows after the function call, until the code stack has been emptied. Then when the awaiting is over, the state of the function is restored, and execution continues within that function. Whenever that function returns (completes), the corresponding promise -- that was returned earlier on -- is resolved.

Is the order of do_something_with_result() guaranteed sequential with regard to i? Or does it depend on how fast the awaited function is for each i?

The order is guaranteed. The code following the await is also guaranteed to execute only after the call stack has been emptied, i.e. at least on or after the next microtask can execute.

See how the output is in this snippet. Note especially where it says "after calling test":

async function test() {
    for (let i = 0; i < 2; i++) {
        console.log('Before await for ', i);
        let result = await Promise.resolve(i);
        console.log('After await. Value is ', result);
    }
}

test().then(_ => console.log('After test() resolved'));

console.log('After calling test');```

ContentLicense: CC BY-SA 4.0

Body:
Take the following loop:

for(var i=0; i<100; ++i){
    let result = await some_slow_async_function();
    do_something_with_result();
}

Does await block the loop? Or does the i continue to be incremented while awaiting?

Is the order of do_something_with_result() guaranteed sequential with regard to i? Or does it depend on how fast the awaited function is for each i?


问:
Is it possible to refresh/update the data in a treeview?
I'm new at GUI development and I've been working on a project with gtk+ 3 for some days, but I'm stuck at this point.

My app contains two treeviews, the data in the rows is obtained from an sql query, by right clicking on a row a popup-menu appears, giving the option to set the data as "known", updating the database table.

The previous data now should belong in the other treeview, and so it does when the app is restarted, but I'm looking to do it in real time.

Is it possible to update/refresh the data in a treeview?

The model is obtained with the function:

```<code>static GtkTreeStore* create_and_fill(char* known)
{
  GtkTreeStore* store;
  GtkTreeIter iter;
  GtkWidget* tree;
  store = gtk_tree_store_new(2,G_TYPE_STRING,G_TYPE_STRING);

  char source_mac[50] = {0};
  char source_ip[50] = {0};
  int num_fields;

  char query[300] = {0};
  sprintf(query, "select mac,ip from hosts where known=%s", known);
  if(mysql_query(conn, query))
  {
    fprintf(stderr,"%s\n", mysql_error(conn));
  }
  res = mysql_store_result(conn);
  num_fields = mysql_num_fields(res);

  while((row = mysql_fetch_row(res)))
  {
    sprintf(source_mac,"%s", row[0]);
    sprintf(source_ip,"%s", row[1]);
    gtk_tree_store_append(store, &iter, NULL);
    gtk_tree_store_set(store, &iter, MAC_ADDRESS, source_mac, IP_ADDRESS, source_ip,-1);
  }
  gtk_tree_store_append(store, &iter, NULL);
  mysql_free_result(res);
  return store;
}
</code>```

答:
I never used gtk_tree_store, but only gtk_list_store. Nevertheless the logic should be applicable for gtk_tree_store as well.

Depending on the result of a new SQL-query some entries might be changed, added or deleted.

There are basically 2 ways to update your view.

If lines might be added and removed in your table, the easiest way might be to clean up your whole tree and populate it again.

```<code>GtkTreeIter       iter;
gboolean          iter_valid;

iter_valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
while (iter_valid)
{
  // Maybe additional cleanup of related data
  // gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, .... -1);
  iter_valid = gtk_tree_store_remove(store, &iter);
}
// Maybe update filtering and sorting afterwards
gtk_tree_model_filter_refilter(store_filtered);

// Populate again with result of SQL query.
</code>```

If you can be sure that only the content changes, then you could just change it in the storage:

```<code>GtkTreeIter       iter;
gboolean          iter_valid;

iter_valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
while (iter_valid)
{
  gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, < add fields here >, -1);

  bool           update = FALSE;
  // Check if this entry needs to be updated
  // .... => set update = TRUE;

  if (update)
    gtk_tree_store_set(store, &iter, < field names and values here... > -1);

  iter_valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
}
// Optionally update filtering and sorting...
</code>```

Body:
I'm new at GUI development and I've been working on a project with gtk+ 3 for some days, but I'm stuck at this point.

My app contains two treeviews, the data in the rows is obtained from an sql query, by right clicking on a row a popup-menu appears, giving the option to set the data as "known", updating the database table.

The previous data now should belong in the other treeview, and so it does when the app is restarted, but I'm looking to do it in real time.

Is it possible to update/refresh the data in a treeview?

The model is obtained with the function:

static GtkTreeStore* create_and_fill(char* known)
{
  GtkTreeStore* store;
  GtkTreeIter iter;
  GtkWidget* tree;
  store = gtk_tree_store_new(2,G_TYPE_STRING,G_TYPE_STRING);

  char source_mac[50] = {0};
  char source_ip[50] = {0};
  int num_fields;

  char query[300] = {0};
  sprintf(query, "select mac,ip from hosts where known=%s", known);
  if(mysql_query(conn, query))
  {
    fprintf(stderr,"%s\n", mysql_error(conn));
  }
  res = mysql_store_result(conn);
  num_fields = mysql_num_fields(res);

  while((row = mysql_fetch_row(res)))
  {
    sprintf(source_mac,"%s", row[0]);
    sprintf(source_ip,"%s", row[1]);
    gtk_tree_store_append(store, &iter, NULL);
    gtk_tree_store_set(store, &iter, MAC_ADDRESS, source_mac, IP_ADDRESS, source_ip,-1);
  }
  gtk_tree_store_append(store, &iter, NULL);
  mysql_free_result(res);
  return store;
}

Body:
I never used gtk_tree_store, but only gtk_list_store. Nevertheless the logic should be applicable for gtk_tree_store as well.

Depending on the result of a new SQL-query some entries might be changed, added or deleted.

There are basically 2 ways to update your view.

If lines might be added and removed in your table, the easiest way might be to clean up your whole tree and populate it again.

GtkTreeIter       iter;
gboolean          iter_valid;

iter_valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
while (iter_valid)
{
  // Maybe additional cleanup of related data
  // gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, .... -1);
  iter_valid = gtk_tree_store_remove(store, &iter);
}
// Maybe update filtering and sorting afterwards
gtk_tree_model_filter_refilter(store_filtered);

// Populate again with result of SQL query.

If you can be sure that only the content changes, then you could just change it in the storage:

GtkTreeIter       iter;
gboolean          iter_valid;

iter_valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
while (iter_valid)
{
  gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, < add fields here >, -1);

  bool           update = FALSE;
  // Check if this entry needs to be updated
  // .... => set update = TRUE;

  if (update)
    gtk_tree_store_set(store, &iter, < field names and values here... > -1);

  iter_valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
}
// Optionally update filtering and sorting...


问:
CSS Change background color by User
i'm writing a page for a mobile version of a website and i'd like to insert a checkbox with label Dark Theme, when an user check this box change background color (of entire website) to black and text color to white, i found many part of codes in internet but it doesn't works, i don't know why.

For Example i tried this:

#select1:checked ~ div .wrapper{
 background-color:black;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
<input id="select1" name="check1" type="checkbox" />
<label for="select1">Dark Theme</label>
</div></code>```

Can you help me?
Thank you

答:
this code is the example of Change background Color

```<code><div id= "genre">
    What do you bust a move to?
    <br>
    <br>
    <form name="music" method="post" action="">
    <p>
    <input type="radio" name="music" value="radio" onClick="changeColour('b')">Doo
    <br>
    <input type="radio" name="music" value="radio" onClick="changeColour('r')">Rock
    <br>
    <input type="radio" name="music" value="radio" onClick="changeColour('p')">Pop
    <br>
    </form>
    </div>

    function changeColour(value)
    {
        var color = document.body.style.backgroundColor;
        switch(value)
        {
            case 'b':
                color = "#FF0000";
            break;
            case 'r':
                color = "#0000FF";
            break;
            case 'p':
                color = "#FF00FF";
            break;
        }
        document.body.style.backgroundColor = color;
    }
</code>```

Jsfiddle

Title: CSS Change background color by User

Body:
i'm writing a page for a mobile version of a website and i'd like to insert a checkbox with label Dark Theme, when an user check this box change background color (of entire website) to black and text color to white, i found many part of codes in internet but it doesn't works, i don't know why.

For Example i tried this:

#select1:checked ~ div .wrapper{
 background-color:black;
  color: white;
}

<input id="select1" name="check1" type="checkbox" />
Dark Theme

Can you help me?
Thank you

Body:
this code is the example of Change background Color

<div id= "genre">
    What do you bust a move to?
    <br>
    <br>
    <form name="music" method="post" action="">
    <p>
    <input type="radio" name="music" value="radio" onClick="changeColour('b')">Doo
    <br>
    <input type="radio" name="music" value="radio" onClick="changeColour('r')">Rock
    <br>
    <input type="radio" name="music" value="radio" onClick="changeColour('p')">Pop
    <br>
    </form>
    </div>

    function changeColour(value)
    {
        var color = document.body.style.backgroundColor;
        switch(value)
        {
            case 'b':
                color = "#FF0000";
            break;
            case 'r':
                color = "#0000FF";
            break;
            case 'p':
                color = "#FF00FF";
            break;
        }
        document.body.style.backgroundColor = color;
    }

Jsfiddle


问:
How to execute shell script by double clicking in centos?
As the tile,I have a shell script needs to run every time I have to open a terminal and type "./ xxx.sh"  .it is annoying when it gets too frequent now how do I execute by double clicking like the way you do it in windows?

I know there is an option just for that in Ubuntu but I can't see that here in CentOS.

答:
For the record this is how I do it:
In terminal

```<code>[youname@localhost ~]$ gedit ~/Desktop/YourApplication.desktop
</code>```

In the file

```<code>    [Desktop Entry]
Name=My Application
Comment=My Application run script
Exec=/AddressOfyourScript/yourscript.sh
Icon=/AddressOfyourIcon/youricon.png
Terminal=true
Type=Application
</code>```

save and done.Apparently CentOS should give a GUI for this function.

Body:
For the record this is how I do it:
In terminal

[youname@localhost ~]$ gedit ~/Desktop/YourApplication.desktop

In the file

    [Desktop Entry]
Name=My Application
Comment=My Application run script
Exec=/AddressOfyourScript/yourscript.sh
Icon=/AddressOfyourIcon/youricon.png
Terminal=true
Type=Application

save and done.Apparently CentOS should give a GUI for this function.


问:
Replace empty alt tag on  tag
I would like to replace my empty alt tags on images in a string. I have a string that contains all the text for a curtain page. In the text are also images, and a lot of them have empty tags (old data), but most of the time they do have title tags.
For example:

What I wish to have:

So:
I need to find all the images in my string, loop trough the images, find title tags, find alt tags, and replace the empty alt tags with the title tags that do have a value.

This is what i tried:

```<code>preg_match_all('/<img[^>]+>/i',$return, $text);
if(isset($text)) {
            foreach( $text as $itemImg ) {
                foreach( $itemImg as $item ) {
                    $array = array();
                    preg_match( '/title="([^"]*)"/i', $item, $array );
                    if(isset($array[1])) {
                        //So $array[1] is a title tag, now what?
                    }
                }

            }
        }
</code>```

I don't know have to complete the code, and I think there must be a easier fix for this. Suggestions?

答:
maybe you could use Javascript for this kind of things with jquery
like:

```<code>$('img').each(function(){
    $(this).attr('alt', $(this).attr('title'));
});
</code>```

hope it helps

Regards.

Title: Replace empty alt tag on <img> tag

Body:
I would like to replace my empty alt tags on images in a string. I have a string that contains all the text for a curtain page. In the text are also images, and a lot of them have empty tags (old data), but most of the time they do have title tags.
For example:

What I wish to have:

So:
I need to find all the images in my string, loop trough the images, find title tags, find alt tags, and replace the empty alt tags with the title tags that do have a value.

This is what i tried:

preg_match_all('/]+>/i',$return, $text);
if(isset($text)) {
            foreach( $text as $itemImg ) {
                foreach( $itemImg as $item ) {
                    $array = array();
                    preg_match( '/title="([^"]*)"/i', $item, $array );
                    if(isset($array[1])) {
                        //So $array[1] is a title tag, now what?
                    }
                }

            }
        }

I don't know have to complete the code, and I think there must be a easier fix for this. Suggestions?

Body:
maybe you could use Javascript for this kind of things with jquery
like:

$('img').each(function(){
    $(this).attr('alt', $(this).attr('title'));
});

hope it helps

Regards.


问:
Private vs Public variables
```<code>namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         public int numberTwo = 12;

         static void yo()
         {
             public int numberThree = 12;
             private int numberFour = 12;
         }
    }
}
</code>```

Can someone tell me the difference between the variables numberOne, numberTwo, numberThree and numberFour in this code excerpt?

答:
numberOne and numberTwo are member variables of the class.
numberThree and numberFour are local variables, scoped to the function.

Next to that, you cannot declare an access modifier (private / public) for local variables.

Title: Private vs Public variables

Body:
namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         public int numberTwo = 12;

         static void yo()
         {
             public int numberThree = 12;
             private int numberFour = 12;
         }
    }
}

Can someone tell me the difference between the variables numberOne, numberTwo, numberThree and numberFour in this code excerpt?


问:
How do I configure which DNS server docker uses in Docker Desktop for Mac?
The built in DNS server in Docker Desktop for Mac is really slow, so I'd like to use a different DNS server by default. I know I can add --dns=... when running docker commands, but I'd like a way to set the default DNS server for all containers to avoid having to specify the DNS server individually for every container.

How can I set the default DNS server for all containers on Docker for Mac?

答:
In current versions of Docker for Mac, you can go to the Whale Icon -> Preferences -> Daemon -> Advanced and adjust the daemon level DNS settings with a daemon.json config. If your config is currently empty, this would add your own DNS setting with two entries:

```<code>{
  "dns": ["8.8.8.8", "192.168.0.1"]
}
</code>```

If you already have content in here, then add an entry for "dns" to your json. See the daemon configuration documentation for other options you can add here.

Body:
In current versions of Docker for Mac, you can go to the Whale Icon -> Preferences -> Daemon -> Advanced and adjust the daemon level DNS settings with a daemon.json config. If your config is currently empty, this would add your own DNS setting with two entries:

{
  "dns": ["8.8.8.8", "192.168.0.1"]
}

If you already have content in here, then add an entry for "dns" to your json. See the daemon configuration documentation for other options you can add here.


问:
Laravel Collective Formbuilder label localization
I just started using the Laravel Collective Form Service Provider/FormBuilder.

I use this custom component for rendering a text field with label. The problem is that I am trying to translate it's label with the __() function but the $name variable gets tansformed from first_name to First Name in a really late stage.

```<code><div class="control-group">
    {{ Form::label($name, null, ['class' => 'group__label']) }}
    {{ Form::text($name, $value, array_merge(['class' => 'control-
    group__control'], $attributes)) }}
</div>
</code>```

I can't simply do this:

```<code>{{ Form::label(__($name), null, ['class' => 'group__label']) }}
</code>```

Again, because it gets first_name and later transforms it into First Name. My nl.json file contains a translation for First Name, not first_name.

If I  add the _() translate function to the last rule of the label method in FormBuilder is, then it solves my problem. But ofcourse, I don't want to modify vendor code!

```<code> return $this->toHtmlString('<label for="' . $name . '"' . $options . '>' . __($value) . '</label>');
</code>```

So. How to solve this issue? Do I, somehow, need to create a custom FormBuilder->label() method?

答:
Using name of field with trans() can create errors when the language changed.

you should use somthing like this

```<code>{{ Form::label('name', trans(''), ['class' => '']) }}
</code>```

Body:
I just started using the Laravel Collective Form Service Provider/FormBuilder.

I use this custom component for rendering a text field with label. The problem is that I am trying to translate it's label with the __() function but the $name variable gets tansformed from first_name to First Name in a really late stage.

    {{ Form::label($name, null, ['class' => 'group__label']) }}
    {{ Form::text($name, $value, array_merge(['class' => 'control-
    group__control'], $attributes)) }}

I can't simply do this:

{{ Form::label(__($name), null, ['class' => 'group__label']) }}

Again, because it gets first_name and later transforms it into First Name. My nl.json file contains a translation for First Name, not first_name.

If I  add the _() translate function to the last rule of the label method in FormBuilder is, then it solves my problem. But ofcourse, I don't want to modify vendor code!

 return $this->toHtmlString('' . __($value) . '');

So. How to solve this issue? Do I, somehow, need to create a custom FormBuilder->label() method?

Body:
Using name of field with trans() can create errors when the language changed.

you should use somthing like this

{{ Form::label('name', trans(''), ['class' => '']) }}


问:
Getting ZoneId from a SimpleTimeZone
Using Java I have a SimpleTimeZone instance with GMT offset and daylight saving time information from a legacy system.

I would like to retrieve ZoneId to be able to use Java 8 time API.

Actually, toZoneId returns a ZoneId without the daylight Saving time infos

```<code>SimpleTimeZone stz = new SimpleTimeZone( 2 * 60 * 60 * 1000, "GMT", Calendar.JANUARY,1,1,1, Calendar.FEBRUARY,1,1,1, 1 * 60 * 60 * 1000);
stz.toZoneId();
</code>```

答:
I don’t think this is possible. One may also ask what sense it would make. If a time zone is not in the Olson database, it is hardly used in the real world, so what good use could it have in your program? I understand, of course, the case where your legacy program creates a SimpleTimeZone that does represent a time zone used in the wild, but just gives it an incorrect ID so that TimeZone.toZoneId() cannot make the correct translation.

I checked the source code of TimeZone.toZoneId(). It relies solely on the value obtained from the getID method. It does not look at offset or zone rules. And importantly, SimpleTimeZone does not override the method. So it appears that if your SimpleTimeZone has an known ID (including the frowned-upon abbreviations like EST or ACT), you will get the correct ZoneId. Otherwise you will not.

So I suppose your best bet is to find out what is the correct time zone ID for the time zone that your legacy code is trying to give you, and then get your ZoneId from ZoneId.of(String). Or slightly nicer, build your own map of aliases containing the ID or IDs from your legacy code and the corresponding modern ID/s, and then use ZoneId.of(String, Map<String,String>).

One possible attempt at automating the translation would be to iterate through the available time zones (which you obtain through TimeZone.getAvailableIDs() and TImeZone.getTimeZone(String)) and compare with each using hasSameRules(). Then create your ZoneId from the ID string or the TimeZone obtained from it.

Sorry, this was not the answer you were hoping for.

Title: Getting ZoneId from a SimpleTimeZone

Body:
Using Java I have a SimpleTimeZone instance with GMT offset and daylight saving time information from a legacy system.

I would like to retrieve ZoneId to be able to use Java 8 time API.

Actually, toZoneId returns a ZoneId without the daylight Saving time infos

SimpleTimeZone stz = new SimpleTimeZone( 2 * 60 * 60 * 1000, "GMT", Calendar.JANUARY,1,1,1, Calendar.FEBRUARY,1,1,1, 1 * 60 * 60 * 1000);
stz.toZoneId();


问:
PHP PDO prepare() prepared statements not working, but query() works
Having trouble getting these PDO prepared statements to work. Working with PHP 7.0.9 on Windows / MAMP and SQLite here.

PHP PDO driver pdo_sqlite installed version 3.8.10.2

Anyone see what am I doing wrong here?

This works as expected:

```<code>$st = $pdo->query("SELECT * FROM `e48` WHERE `parallel` >= 4000 AND `parallel` <= 4010");
$results = $st->fetchAll();
</code>```

This does not work, and gives zero results:

```<code>$st = $pdo->prepare("SELECT * FROM `e48` WHERE `parallel` >= :x AND `parallel` <= :y");
$st->execute(array(':x' => 4000, ':y' => 4010));
$results = $st->fetchAll();
</code>```

This also does not work:

```<code>$st = $pdo->prepare("SELECT * FROM `e48` WHERE `parallel` >= 4000 AND `parallel` <= :y");
$st->execute(array(':y' => 4010));
$results = $st->fetchAll();
</code>```

And ends up giving me the same results as:

```<code>SELECT * FROM `e48` WHERE `parallel` >= 4000
</code>```

P.S Also tested in Linux virtual machine web server with same results.

答:
```<code>$array=array('x' => 4000, 'y' => 4010);
$st = $pdo->prepare("SELECT * FROM `e48` WHERE `parallel` >= :x AND `parallel` <= :y");
$st->execute($array);
$results = $st->fetchAll();
</code>```

Body:
Having trouble getting these PDO prepared statements to work. Working with PHP 7.0.9 on Windows / MAMP and SQLite here.

PHP PDO driver pdo_sqlite installed version 3.8.10.2

Anyone see what am I doing wrong here?

This works as expected:

$st = $pdo->query("SELECT * FROM `e48` WHERE `parallel` >= 4000 AND `parallel` <= 4010");
$results = $st->fetchAll();

This does not work, and gives zero results:

$st = $pdo->prepare("SELECT * FROM `e48` WHERE `parallel` >= :x AND `parallel` <= :y");
$st->execute(array(':x' => 4000, ':y' => 4010));
$results = $st->fetchAll();

This also does not work:

$st = $pdo->prepare("SELECT * FROM `e48` WHERE `parallel` >= 4000 AND `parallel` <= :y");
$st->execute(array(':y' => 4010));
$results = $st->fetchAll();

And ends up giving me the same results as:

SELECT * FROM `e48` WHERE `parallel` >= 4000

P.S Also tested in Linux virtual machine web server with same results.


问:
Failed to find configured root error in android 7.0
I get this error: failed to find configured root that contains /storage/emulated/0/android/data/
There are some similar questions but they are using other location for storing files.
I am using:
   Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)  method and this is the code I'm using to open camera:

```<code> private void TakePicture() {
    photoFile = FileManager.generateFileStampedPhotoFile();
    PicturesHelper.TryTakePictureWithAnIntent(this, photoFile, REQUEST_IMAGE_CAPTURE);
}

public static File generateFileStampedPhotoFile()
{
    Uri photoFileUri=null;
    File photoFile=null;
    File outputDir=getPhotoDirectory();
    if(outputDir!=null)
    {
        String timeStamp=new SimpleDateFormat("yyyyMMDD_HHmmss").format(new Date());
        String photoFileName="IMG_"+timeStamp+".jpg";
         photoFile=new File(outputDir,photoFileName);
       // photoFileUri=Uri.fromFile(photoFile);

    }
    return  photoFile;
}

 public static void TryTakePictureWithAnIntent(Activity context,File
   photoFile,int requestCode)
  {
    Intent takePictureIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if(takePictureIntent.resolveActivity(context.getPackageManager())!=null) //if user has camera?
    {

        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(context,
                    "com.myapp.fileprovider",
                    photoFile);
            takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

            context.startActivityForResult(takePictureIntent, requestCode);
        }

    }
}

public static File getPhotoDirectory()
{
    File outputDir=null;
    String externalStorageState=Environment.getExternalStorageState();
    if(externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
        File pictureDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        outputDir=new File(new File(pictureDir,"Adriagate"),"Online");
        if(!outputDir.exists())//V.P. if directory/ies not exist/s it will be created. mksdrs method follows file structure and creates directory by direcory if needed
        {
            if(!outputDir.mkdirs())
            {
                return null;
            }
        }
    }
    return outputDir;
}
</code>```

I have put provider inside AndroidManifest:

```<code>  <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.myapp.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
    </provider>
</code>```

And this is file_paths.xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files name="Whatever_Nothing_Works"/>
</code>```

答:
Add this in Menifest

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

Replace in file_paths.xml with

```<code><?xml version="1.0" encoding="utf-8"?>
<paths>
       <external-files-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>
</code>```

Your file is stored under getExternalFilesDir(). That maps to <external-files-path>, not <files-path>

Body:
I get this error: failed to find configured root that contains /storage/emulated/0/android/data/
There are some similar questions but they are using other location for storing files.
I am using:
   Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)  method and this is the code I'm using to open camera:

 private void TakePicture() {
    photoFile = FileManager.generateFileStampedPhotoFile();
    PicturesHelper.TryTakePictureWithAnIntent(this, photoFile, REQUEST_IMAGE_CAPTURE);
}

public static File generateFileStampedPhotoFile()
{
    Uri photoFileUri=null;
    File photoFile=null;
    File outputDir=getPhotoDirectory();
    if(outputDir!=null)
    {
        String timeStamp=new SimpleDateFormat("yyyyMMDD_HHmmss").format(new Date());
        String photoFileName="IMG_"+timeStamp+".jpg";
         photoFile=new File(outputDir,photoFileName);
       // photoFileUri=Uri.fromFile(photoFile);

    }
    return  photoFile;
}

 public static void TryTakePictureWithAnIntent(Activity context,File
   photoFile,int requestCode)
  {
    Intent takePictureIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if(takePictureIntent.resolveActivity(context.getPackageManager())!=null) //if user has camera?
    {

        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(context,
                    "com.myapp.fileprovider",
                    photoFile);
            takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

            context.startActivityForResult(takePictureIntent, requestCode);
        }

    }
}

public static File getPhotoDirectory()
{
    File outputDir=null;
    String externalStorageState=Environment.getExternalStorageState();
    if(externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
        File pictureDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        outputDir=new File(new File(pictureDir,"Adriagate"),"Online");
        if(!outputDir.exists())//V.P. if directory/ies not exist/s it will be created. mksdrs method follows file structure and creates directory by direcory if needed
        {
            if(!outputDir.mkdirs())
            {
                return null;
            }
        }
    }
    return outputDir;
}

I have put provider inside AndroidManifest:

  <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.myapp.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
    </provider>

And this is file_paths.xml file:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files name="Whatever_Nothing_Works"/>

Body:
Add this in Menifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Replace in file_paths.xml with

<?xml version="1.0" encoding="utf-8"?>
<paths>
       <external-files-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>

Your file is stored under getExternalFilesDir(). That maps to <external-files-path>, not <files-path>


问:
python - readable list of objects
This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;

```<code><__main__.evolutions instance at 0x01B8EA08>
</code>```

but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?

答: You need to override either the __str__, or __repr__ methods of your object[s]

Title: python - readable list of objects

Body:
This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;

<__main__.evolutions instance at 0x01B8EA08>

but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?

OwnerDisplayName: cddr


问:
Generating WSDL & disco files
i want to generate a wsdl and a disco file automatically (e.g. via a bat-file).

these files will be generated if a service reference is added to a (test) project.

wsdl.exe and disco.exe are missing.

can you tell me best practice ?

答: These tools are installed in the Windows SDK directory.  For VS2010, the default install path is C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin</p>

Title: Generating WSDL & disco files


问:
svn error when checkoutng: "Not authorized to open root of edit operation"
I have svnserve with current settings:

svnserve.conf:

```<code>anon-access = read #I also tried anon-access = none or comment this line
auth-access = write
password-db = passwd
authz-db = authz
</code>```

authz:

```<code>[/]
foo = rw

[/Subdir]
foo = rw
bar = rw
</code>```

If user 'bar' try checkout /Subdir folder then he get error: "Not authorized to open root of edit operation".
User foo can do it correctly.

What I can do with this trouble?

答:
I resolve this issue
best you will check the svn network by following steps.
1. Open the SVN Setting, select saved data, click Clear... button of the Authentication data, try one more time, if same issue you got, please follow below steps.
2. Open the SVN Setting, select Network menu, click Edit button of the Subversion server file, Add below line at end of file
        http-auth-types=basic;digest
3. save that file and try now

Body:
I have svnserve with current settings:

svnserve.conf:

anon-access = read #I also tried anon-access = none or comment this line
auth-access = write
password-db = passwd
authz-db = authz

authz:

[/]
foo = rw

[/Subdir]
foo = rw
bar = rw

If user 'bar' try checkout /Subdir folder then he get error: "Not authorized to open root of edit operation".
User foo can do it correctly.

What I can do with this trouble?


问:
How could I ignore a field in json response?
```<code>@Column(name = "password", nullable = false)
@JSonIgnore
private String password;
</code>```

I have given the above field in my model class, but It did not work for the POST method.

Error:null value in column "password" violates not-null constraint

答:
I had solved the problem.
This was my old code:
    @Column(name = "password", nullable = false)

```<code>`@JSonIgnore`

`private String password;`
</code>```

Instead of JSonIgnore, we can use JSonProperty. Below is the code:

This is the new code:
    @Column(name = "password", nullable = false)

@JsonProperty(access = Access.WRITE_ONLY)

private String password;

Thanks to everyone for helping...

Body:
@Column(name = "password", nullable = false)
@JSonIgnore
private String password;

I have given the above field in my model class, but It did not work for the POST method.

Error:null value in column "password" violates not-null constraint

Body:
I had solved the problem.
This was my old code:
    @Column(name = "password", nullable = false)

`@JSonIgnore`

`private String password;`

Instead of JSonIgnore, we can use JSonProperty. Below is the code:

This is the new code:
    @Column(name = "password", nullable = false)

@JsonProperty(access = Access.WRITE_ONLY)

private String password;

Thanks to everyone for helping...


问:
Specialize template class for different parameter sets
Suppose I have a template struct like

```<code>template <typename T> struct Parser {
  //specializations are expected to have these methods
  inline static const byte* objectEnd(const byte* begin, const byte* end);
  inline static const byte* tryRead(const byte* begin, const byte* end, T* obj);
}
</code>```

It is used in different classes, some of which are also template classes (so they may not have full info about what class they pass to Parser as a parameter).

Implementing Parser for any given type is easy, like this:

```<code>template<> struct Parser<text_line> {
  inline static const byte* objectEnd(const byte* begin, const byte* end){
    return helper::NextByteOrEnd<'\n'>(begin, end);
  }
  inline static const byte* tryRead(const byte* begin const byte* end, text_line* obj){
    const byte* lf = objectEnd(begin, end);
    obj = text_line(begin, lf);
    return lf==end ? lf : lf+1;
  }
}
</code>```

I can specialize Parser for a family of templates, as well:

```<code>template<int sz> struct Parser<be_uint<sz>> {
  inline static const byte* objectEnd(const byte* begin, const byte* end){
    return begin+be_uint<sz>::size > end ? begin : begin+be_uint<sz>::size;
  }
  inline static const byte* tryRead(const byte* begin const byte* end, be_uint<sz>* obj){
    if(begin + be_uint<sz>::size > end) return begin;
    obj = be_uint<sz>::read(begin);
    return begin + be_uint<sz>::size;
  }
}
</code>```

But what if I want to specialize Parser for some other set of types? Suppose I have a type predicate, say, std::is_base_of<MyHeader, T> and I want to write something like

```<code>//not actual code - how would I write this?
template<typename Header> struct Parser<Header> {
  static_assert(std::is_base_of<MyHeader, Header>::value, "Wrong!");
  inline static const byte* objectEnd(const byte* begin, const byte* end){
    //MyHeader-specific code here
  }
  inline static const byte* tryRead(const byte* begin const byte* end, Header* obj){
    //MyHeader-specific code here
  }
}
</code>```

Adding optional parameters to the initial definition of Parser, like

```<code>template <typename T, bool MyHeaderFlag = std::is_base_of<MyHeader, T>::value>
struct Parser { //...
</code>```

doesn't seem like a good idea - I (or any other programmer) may want to use other predicates, say, my_types::is_scientific<T>.

The problem seems like something you could resolve with SFINAE (there's a problem of what should happen if one type fits several predicates - I prefer that it wouldn't result in compiler error, but it isn't very important since such Parser specializations are likely to be palced in .cpp-files). But I couldn't find a way to do this.

Just to be clear, there is no constraint on preserving the exact definition of `Parser' or its methods (or even it being a template), as long as client code can write something like

```<code>Parser<TypeArg>::objectEnd(block.begin, block.begin+block.size)
</code>```

without caring what TypeArg actually is.

答:
If you want to make specialization for some set of types, best way is to add second template parameter to your base template.

You can do that with bool, or with actually type and use std::enable_if in specializations.

I prefer the second way.

```<code>template <typename T, typename = void> struct Parser {
  //specializations are expected to have these methods
  inline static const byte* objectEnd(const byte* begin, const byte* end);
  inline static const byte* tryRead(const byte* begin, const byte* end, T* obj);
}
</code>```

and specialization example

```<code>template<typename Header>
struct Parser<Header, typename std::enable_if<std::is_base_of<MyHeader, Header>::value>::type> {
  inline static const byte* objectEnd(const byte* begin, const byte* end){
    //MyHeader-specific code here
  }
  inline static const byte* tryRead(const byte* begin, const byte* end, Header* obj){
    //MyHeader-specific code here
  }
}
</code>```

Body:
Suppose I have a template struct like

template <typename T> struct Parser {
  //specializations are expected to have these methods
  inline static const byte* objectEnd(const byte* begin, const byte* end);
  inline static const byte* tryRead(const byte* begin, const byte* end, T* obj);
}

It is used in different classes, some of which are also template classes (so they may not have full info about what class they pass to Parser as a parameter).

Implementing Parser for any given type is easy, like this:

template<> struct Parser<text_line> {
  inline static const byte* objectEnd(const byte* begin, const byte* end){
    return helper::NextByteOrEnd<'\n'>(begin, end);
  }
  inline static const byte* tryRead(const byte* begin const byte* end, text_line* obj){
    const byte* lf = objectEnd(begin, end);
    obj = text_line(begin, lf);
    return lf==end ? lf : lf+1;
  }
}

I can specialize Parser for a family of templates, as well:

template<int sz> struct Parser<be_uint<sz>> {
  inline static const byte* objectEnd(const byte* begin, const byte* end){
    return begin+be_uint<sz>::size > end ? begin : begin+be_uint<sz>::size;
  }
  inline static const byte* tryRead(const byte* begin const byte* end, be_uint<sz>* obj){
    if(begin + be_uint<sz>::size > end) return begin;
    obj = be_uint<sz>::read(begin);
    return begin + be_uint<sz>::size;
  }
}

But what if I want to specialize Parser for some other set of types? Suppose I have a type predicate, say, std::is_base_of<MyHeader, T> and I want to write something like

//not actual code - how would I write this?
template<typename Header> struct Parser {
  static_assert(std::is_base_of<MyHeader, Header>::value, "Wrong!");
  inline static const byte* objectEnd(const byte* begin, const byte* end){
    //MyHeader-specific code here
  }
  inline static const byte* tryRead(const byte* begin const byte* end, Header* obj){
    //MyHeader-specific code here
  }
}

Adding optional parameters to the initial definition of Parser, like

template <typename T, bool MyHeaderFlag = std::is_base_of<MyHeader, T>::value>
struct Parser { //...

doesn't seem like a good idea - I (or any other programmer) may want to use other predicates, say, my_types::is_scientific<T>.

The problem seems like something you could resolve with SFINAE (there's a problem of what should happen if one type fits several predicates - I prefer that it wouldn't result in compiler error, but it isn't very important since such Parser specializations are likely to be palced in .cpp-files). But I couldn't find a way to do this.

Just to be clear, there is no constraint on preserving the exact definition of `Parser' or its methods (or even it being a template), as long as client code can write something like

Parser<TypeArg>::objectEnd(block.begin, block.begin+block.size)

without caring what TypeArg actually is.

Body:
If you want to make specialization for some set of types, best way is to add second template parameter to your base template.

You can do that with bool, or with actually type and use std::enable_if in specializations.

I prefer the second way.

template <typename T, typename = void> struct Parser {
  //specializations are expected to have these methods
  inline static const byte* objectEnd(const byte* begin, const byte* end);
  inline static const byte* tryRead(const byte* begin, const byte* end, T* obj);
}

and specialization example

template<typename Header>
struct Parser<Header, typename std::enable_if<std::is_base_of<MyHeader, Header>::value>::type> {
  inline static const byte* objectEnd(const byte* begin, const byte* end){
    //MyHeader-specific code here
  }
  inline static const byte* tryRead(const byte* begin, const byte* end, Header* obj){
    //MyHeader-specific code here
  }
}


问:
Xcode playground gets stuck on 'Running playground' or 'Launching simulator' and won't run the code, what to do?
Every time I create a new playground in order to test some code, Xcode gets stuck and won't run the code. It simply presents 'Running playground' or 'Launching simulator' statement at the top of the screen with the loading icon promisingly spinning next to it but nothing happens. Sometimes this continues indefinitely and sometimes Xcode halts and prints this to console :

```<code>Playground execution failed: error: Couldn't lookup symbols:
__swift_FORCE_LOAD_$_swiftCoreImage
__swift_FORCE_LOAD_$_swiftFoundation
_playground_log_hidden
_playground_logger_initialize
_playground_log_postprint

thread #1: tid = 0xc0cd0, 0x000000010ea7c3c0 MyPlayground`executePlayground, queue = 'com.apple.main-thread', stop reason = breakpoint 1.2

frame #0: 0x000000010ea7c3c0 MyPlayground`executePlayground
frame #1: 0x000000010ea7b9c0 MyPlayground`__37-[XCPAppDelegate enqueueRunLoopBlock]_block_invoke + 32
frame #2: 0x000000010f59625c CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
frame #3: 0x000000010f57b304 CoreFoundation`__CFRunLoopDoBlocks + 356
frame #4: 0x000000010f57aa75 CoreFoundation`__CFRunLoopRun + 901
frame #5: 0x000000010f57a494 CoreFoundation`CFRunLoopRunSpecific + 420
frame #6: 0x0000000114985a6f GraphicsServices`GSEventRunModal + 161
frame #7: 0x0000000110124f34 UIKit`UIApplicationMain + 159
frame #8: 0x000000010ea7b6e9 MyPlayground`main + 201
frame #9: 0x0000000112ad268d libdyld.dylib`start + 1
frame #10: 0x0000000112ad268d libdyld.dylib`start + 1
</code>```

I am running Xcode 8.0 (8A218a) on macOS Sierra 10.12.

Hardware:

MacBook Pro (13" Mid-2012)

2,5 GHz Intel Core i5

4 GB 1600 MHz Ram DDR3

I have looked around but at least neither of these threads have provided an answer:

https://forums.developer.apple.com/thread/5902

https://github.com/jas/playground/issues/9

Things I have already tried with zero success:

Restarting Xcode

Reinstalling Xcode (downgraded to 7.3 but since that didn't help I
upgraded back to 8.0)

Restarting the machine

Creating a new playground

Do you have any ideas on how to solve this problem? I am new to programming and eagerly trying to learn Swift but Xcode is making it practically impossible.

答:
In my case, Xcode 8.3.2, it works when I try as steps below:

File -> Close "Name.playground"

File -> Close Playground

Quit Xcode

Re-open Xcode

Body:
Every time I create a new playground in order to test some code, Xcode gets stuck and won't run the code. It simply presents 'Running playground' or 'Launching simulator' statement at the top of the screen with the loading icon promisingly spinning next to it but nothing happens. Sometimes this continues indefinitely and sometimes Xcode halts and prints this to console :

Playground execution failed: error: Couldn't lookup symbols:
__swift_FORCE_LOAD_$_swiftCoreImage
__swift_FORCE_LOAD_$_swiftFoundation
_playground_log_hidden
_playground_logger_initialize
_playground_log_postprint

thread #1: tid = 0xc0cd0, 0x000000010ea7c3c0 MyPlayground`executePlayground, queue = 'com.apple.main-thread', stop reason = breakpoint 1.2

frame #0: 0x000000010ea7c3c0 MyPlayground`executePlayground
frame #1: 0x000000010ea7b9c0 MyPlayground`__37-[XCPAppDelegate enqueueRunLoopBlock]_block_invoke + 32
frame #2: 0x000000010f59625c CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
frame #3: 0x000000010f57b304 CoreFoundation`__CFRunLoopDoBlocks + 356
frame #4: 0x000000010f57aa75 CoreFoundation`__CFRunLoopRun + 901
frame #5: 0x000000010f57a494 CoreFoundation`CFRunLoopRunSpecific + 420
frame #6: 0x0000000114985a6f GraphicsServices`GSEventRunModal + 161
frame #7: 0x0000000110124f34 UIKit`UIApplicationMain + 159
frame #8: 0x000000010ea7b6e9 MyPlayground`main + 201
frame #9: 0x0000000112ad268d libdyld.dylib`start + 1
frame #10: 0x0000000112ad268d libdyld.dylib`start + 1

I am running Xcode 8.0 (8A218a) on macOS Sierra 10.12.

Hardware:

MacBook Pro (13" Mid-2012)

2,5 GHz Intel Core i5

4 GB 1600 MHz Ram DDR3

I have looked around but at least neither of these threads have provided an answer:

https://forums.developer.apple.com/thread/5902

https://github.com/jas/playground/issues/9

Things I have already tried with zero success:

Restarting Xcode

Reinstalling Xcode (downgraded to 7.3 but since that didn't help I
upgraded back to 8.0)

Restarting the machine

Creating a new playground

Do you have any ideas on how to solve this problem? I am new to programming and eagerly trying to learn Swift but Xcode is making it practically impossible.


问:
jmeter latency problem
After deployment from the nightly build, the response time of logging into the page is sometimes very high (30mins to more than an hour). I know jsps need to be recompiled after redeployment. However, it only takes 5 secs to login through the browser. It'd be great if anyone has any advice. Thanks!</p>

答: When they updated code, did they modify anything on the login page? I would recommend re-recording the login process and compare to the original.  You may find your script points to the wrong server or is now missing a required parameter.</p>

Title: jmeter latency problem


问:
eclipse and gradle: do not deploy test classes
We have here a JEE Vaadin project in eclipse (neon) IDE and as build system we use gradle. But we have a problem with our test classes. If we build our war/ear with gradle all is fine. The test classes are not part of the war archive.

But if we want to deploy the ear project on the wildfly server from inside of eclipse it seems that the test classes are part of the war archive. Because while deploy the ear we getting some errors like:

```<code>...
Caused by: com.google.common.util.concurrent.ExecutionError: com.google.common.util.concurrent.ExecutionError: java.lang.LinkageError: Failed to link com/coco_on/docFlow/vaadin/admin/TestAdminRoles (Module "deployment.DFl_EAR.ear.DFl_Vaadin.war:main" from Service Module Loader)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2201)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3937)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3941)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4824)
    at org.jboss.weld.util.cache.LoadingCacheUtils.getCacheValue(LoadingCacheUtils.java:49)
    at org.jboss.weld.resources.DefaultReflectionCache.getBackedAnnotatedTypeAnnotationSet(DefaultReflectionCache.java:169)
    at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType.getAnnotations(BackedAnnotatedType.java:112)
    at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType.getAnnotation(BackedAnnotatedType.java:98)
    at org.jboss.weld.bootstrap.BeanDeployer.processPriority(BeanDeployer.java:105)
    at org.jboss.weld.bootstrap.BeanDeployer.processAnnotatedTypes(BeanDeployer.java:174)
    at org.jboss.weld.bootstrap.BeanDeployment.createTypes(BeanDeployment.java:224)
    at org.jboss.weld.bootstrap.WeldStartup.startInitialization(WeldStartup.java:381)
    at org.jboss.weld.bootstrap.WeldBootstrap.startInitialization(WeldBootstrap.java:76)
    at org.jboss.as.weld.WeldStartService.start(WeldStartService.java:92)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881)
    ... 3 more
Caused by: java.lang.NoClassDefFoundError: com/vaadin/testbench/TestBenchTestCase
...
</code>```

TestAdminRoles is one of our test classes and TestBenchTestCase is one of the needed classes in a test framework (Vaadin Testbench). But this test framework will be not found and this is also ok, because we don't want link this library into the ear/war.

We have also read this post: https://stackoverflow.com/a/9820317/1465758

So we have removed the src/test/ directories from the deployment and set a different bin directory for the test source directories. But without success. The error above is still there.

And so my question is: How can I configure eclipse so that eclipse don't put the compiled test classes to the war file?

答:
You need to change the output-folder of the sourcefolders for test-sources and remove the test-directories from the deployment assembly.

This should be added to the build.gradle. (the eclipse-plugin needs to be also applied)

```<code>eclipse {
    // change output dir of the sourcefolders
    classpath.file.whenMerged {
        entries.findAll { it instanceof org.gradle.plugins.ide.eclipse.model.SourceFolder }.each {
            it.output = 'build/eclipse/' + (it.path.startsWith('src/test') ? 'output-test' : 'output')
        }
    }

    // removes test dirs from deployment assemble
    wtp.component.file.whenMerged {
        wbModuleEntries.removeIf {
            it instanceof org.gradle.plugins.ide.eclipse.model.WbResource && it.sourcePath.startsWith('/src/test')
        }
    }
}
</code>```

Code Source (small changes where applied)

In this example the output-directory from non test-sources are also changed, that all output-directories are inside the build-directory from Gradle.

Body:
We have here a JEE Vaadin project in eclipse (neon) IDE and as build system we use gradle. But we have a problem with our test classes. If we build our war/ear with gradle all is fine. The test classes are not part of the war archive.

But if we want to deploy the ear project on the wildfly server from inside of eclipse it seems that the test classes are part of the war archive. Because while deploy the ear we getting some errors like:

...
Caused by: com.google.common.util.concurrent.ExecutionError: com.google.common.util.concurrent.ExecutionError: java.lang.LinkageError: Failed to link com/coco_on/docFlow/vaadin/admin/TestAdminRoles (Module "deployment.DFl_EAR.ear.DFl_Vaadin.war:main" from Service Module Loader)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2201)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3937)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3941)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4824)
    at org.jboss.weld.util.cache.LoadingCacheUtils.getCacheValue(LoadingCacheUtils.java:49)
    at org.jboss.weld.resources.DefaultReflectionCache.getBackedAnnotatedTypeAnnotationSet(DefaultReflectionCache.java:169)
    at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType.getAnnotations(BackedAnnotatedType.java:112)
    at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType.getAnnotation(BackedAnnotatedType.java:98)
    at org.jboss.weld.bootstrap.BeanDeployer.processPriority(BeanDeployer.java:105)
    at org.jboss.weld.bootstrap.BeanDeployer.processAnnotatedTypes(BeanDeployer.java:174)
    at org.jboss.weld.bootstrap.BeanDeployment.createTypes(BeanDeployment.java:224)
    at org.jboss.weld.bootstrap.WeldStartup.startInitialization(WeldStartup.java:381)
    at org.jboss.weld.bootstrap.WeldBootstrap.startInitialization(WeldBootstrap.java:76)
    at org.jboss.as.weld.WeldStartService.start(WeldStartService.java:92)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881)
    ... 3 more
Caused by: java.lang.NoClassDefFoundError: com/vaadin/testbench/TestBenchTestCase
...

TestAdminRoles is one of our test classes and TestBenchTestCase is one of the needed classes in a test framework (Vaadin Testbench). But this test framework will be not found and this is also ok, because we don't want link this library into the ear/war.

We have also read this post: https://stackoverflow.com/a/9820317/1465758

So we have removed the src/test/ directories from the deployment and set a different bin directory for the test source directories. But without success. The error above is still there.

And so my question is: How can I configure eclipse so that eclipse don't put the compiled test classes to the war file?

Body:
You need to change the output-folder of the sourcefolders for test-sources and remove the test-directories from the deployment assembly.

This should be added to the build.gradle. (the eclipse-plugin needs to be also applied)

eclipse {
    // change output dir of the sourcefolders
    classpath.file.whenMerged {
        entries.findAll { it instanceof org.gradle.plugins.ide.eclipse.model.SourceFolder }.each {
            it.output = 'build/eclipse/' + (it.path.startsWith('src/test') ? 'output-test' : 'output')
        }
    }

    // removes test dirs from deployment assemble
    wtp.component.file.whenMerged {
        wbModuleEntries.removeIf {
            it instanceof org.gradle.plugins.ide.eclipse.model.WbResource && it.sourcePath.startsWith('/src/test')
        }
    }
}

Code Source (small changes where applied)

In this example the output-directory from non test-sources are also changed, that all output-directories are inside the build-directory from Gradle.


问:
Function meaning, how is it deleting zero expression genes?
I'm working with an expression matrix obtained by single cell RNA sequencing, but I have a question related with the R code one mate has sent me...

```<code>sort(unique(1 + slot(as(data_matrix, "dgTMatrix"), "i")))
# there isn't more details in the code...
</code>```

In theory, this function is to delete non expressed genes (if it's zero in all samples, it think...), but it's impossible for me to understand it, anyone can give me a tip?

答:
Well, I think I have understood this code... let's try to explain it! (please, correct me if I'm wrong).

Our data has a structure of sparse matrix (ie. more handly in regards to memory, link) and with as it's coerced to a specific format for this kind of matrix (Triplet Format for Sparse Matrices, link): three columns with i and j index for these non-zero values.

```<code>y <- matrix_counts   # sparse matrix
                AAACCTGAGAACAACT-1 AAACCTGTCGGAAATA-1 AAACGGGAGAGCTGCA-1
ENSG00000243485                  1                  .                  .
ENSG00000237613                  .                  .                  2

y2 <- as(y, "dgTMatrix")  #triplet format for sparse matrix
  i j x
1  9 1 1  #in row(9) and column(1) we have the value 1
2 50 1 2
3 60 1 1
4 62 1 2
5 78 1 1
6 87 1 1
</code>```

After, it takes only the column "i" (slot(data, "i")), because we only need the row index (to know what rows are different to zero), and delete duplicates (unique) to finally obtain a vector with the row index which will be used to filter the raw data:

```<code>y3 <- unique(1 + slot(as(exprs(gbm), "dgTMatrix"), "i"))
[1]  9 50 60 62 78 87
data <- data_raw[y3,]
</code>```

I am a bit confused with sort and 1+, but I think this is the basic concept. So, to summarize, we take the row index from this non-zero rows (genes) and use it to filter our raw data... another original method for delete non-expressed genes, interesting!

Body:
I'm working with an expression matrix obtained by single cell RNA sequencing, but I have a question related with the R code one mate has sent me...

sort(unique(1 + slot(as(data_matrix, "dgTMatrix"), "i")))
# there isn't more details in the code...

In theory, this function is to delete non expressed genes (if it's zero in all samples, it think...), but it's impossible for me to understand it, anyone can give me a tip?

Body:
Well, I think I have understood this code... let's try to explain it! (please, correct me if I'm wrong).

Our data has a structure of sparse matrix (ie. more handly in regards to memory, link) and with as it's coerced to a specific format for this kind of matrix (Triplet Format for Sparse Matrices, link): three columns with i and j index for these non-zero values.

y <- matrix_counts   # sparse matrix
                AAACCTGAGAACAACT-1 AAACCTGTCGGAAATA-1 AAACGGGAGAGCTGCA-1
ENSG00000243485                  1                  .                  .
ENSG00000237613                  .                  .                  2

y2 <- as(y, "dgTMatrix")  #triplet format for sparse matrix
  i j x
1  9 1 1  #in row(9) and column(1) we have the value 1
2 50 1 2
3 60 1 1
4 62 1 2
5 78 1 1
6 87 1 1

After, it takes only the column "i" (slot(data, "i")), because we only need the row index (to know what rows are different to zero), and delete duplicates (unique) to finally obtain a vector with the row index which will be used to filter the raw data:

y3 <- unique(1 + slot(as(exprs(gbm), "dgTMatrix"), "i"))
[1]  9 50 60 62 78 87
data <- data_raw[y3,]

I am a bit confused with sort and 1+, but I think this is the basic concept. So, to summarize, we take the row index from this non-zero rows (genes) and use it to filter our raw data... another original method for delete non-expressed genes, interesting!


问:
pyplot: Closing a show() window doesn't continue code
I have successfully been using pyplot to show heatmaps.  Today it seems to have stopped working.

My problem is that setting up my plot, then calling the show() method shows the figure in a window, but when I close this window (by clicking the x at the top), my code doesn't continue past where the show() method is called. It seems to hang on show().

matrix is a numpy matrix.

This is an example of my code:

```<code>plt.pcolor(matrix, cmap=plt.cm.binary)
plt.xlabel('xaxis', fontsize=20)
plt.ylabel('yaxis', fontsize=20)
plt.axis([0, matrix.shape[1], 0, matrix.shape[0]])
plt.colorbar()
#This is where my code hangs...
plt.show()
#Closing the window manually does nothing.
#And the close() method doesn't seem to do anything.
plt.close()
</code>```

After the show() method is called, and the window is closed, my process keeps going, and I have to manually terminate it.

Does anyone know the reason why this is happening?

答: because plt.show() is a "blocking function" and the code will not resume until you close the figure. it will not even get to plt.close() before you close the figure, as it is written after plt.show()

Body:
I have successfully been using pyplot to show heatmaps.  Today it seems to have stopped working.

My problem is that setting up my plot, then calling the show() method shows the figure in a window, but when I close this window (by clicking the x at the top), my code doesn't continue past where the show() method is called. It seems to hang on show().

matrix is a numpy matrix.

This is an example of my code:

plt.pcolor(matrix, cmap=plt.cm.binary)
plt.xlabel('xaxis', fontsize=20)
plt.ylabel('yaxis', fontsize=20)
plt.axis([0, matrix.shape[1], 0, matrix.shape[0]])
plt.colorbar()
#This is where my code hangs...
plt.show()
#Closing the window manually does nothing.
#And the close() method doesn't seem to do anything.
plt.close()

After the show() method is called, and the window is closed, my process keeps going, and I have to manually terminate it.

Does anyone know the reason why this is happening?


问:
WPF How to create, save and load multiple setting files
In my WPF application I have settings accessed by Properties.Settings.Default.Something.
In these user settings I'm saving different textbox, radiobutton, checkbox values.
I need to have sets of these settings depending on one combobox choice, and saved it. For example, user picks "1" in combobox, sets text in textbox, picks 2, sets text in textbox again. After reopening application I want those textbox values saved. Content of combobox options is generated dynamically.

I know those settings are saved in config file located in Users/appdata/... but I have no clue how and if its even possible to make multiple files like this to be manually saved and loaded on runtime.

答:
Serialize them as xml-file. Here is an generic example how to do this.
Please check out DataContract here

C#

```<code> private static T ReadXmlFile<T>(string path) where T : class
    {

        T result = null;
            if (File.Exists(path))
            {

                try
                {
                    using (XmlReader reader = XmlReader.Create(path))
                    {
                        DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                        result = (T)serializer.ReadObject(reader);
                    }
                }
                catch (Exception ex)
                {
                    throw ex; // or what ever
                }
            }
            return result;
        }

    private static void WriteXmlFile<T>(string path, T content2write) where T : class
    {
        if (!Directory.Exists(Path.GetDirectoryName(path)))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(path));
        }

        using (XmlWriter writer = XmlWriter.Create(path,
                                                   new XmlWriterSettings
                                                   {
                                                       Indent = true,
                                                       IndentChars = "  ",
                                                       Encoding = Encoding.UTF8,
                                                       CloseOutput = true
                                                   }))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(writer, content2write);
        }
    }
</code>```

Maybe save them in your own AppData-folder with Environment.SpecialFolder.LocalApplicationData ;-) and go like this

```<code>private static readonly string MyPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"MyApp\AppDescription");
</code>```

Body:
Serialize them as xml-file. Here is an generic example how to do this.
Please check out DataContract here

C#

 private static T ReadXmlFile<T>(string path) where T : class
    {

        T result = null;
            if (File.Exists(path))
            {

                try
                {
                    using (XmlReader reader = XmlReader.Create(path))
                    {
                        DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                        result = (T)serializer.ReadObject(reader);
                    }
                }
                catch (Exception ex)
                {
                    throw ex; // or what ever
                }
            }
            return result;
        }

    private static void WriteXmlFile<T>(string path, T content2write) where T : class
    {
        if (!Directory.Exists(Path.GetDirectoryName(path)))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(path));
        }

        using (XmlWriter writer = XmlWriter.Create(path,
                                                   new XmlWriterSettings
                                                   {
                                                       Indent = true,
                                                       IndentChars = "  ",
                                                       Encoding = Encoding.UTF8,
                                                       CloseOutput = true
                                                   }))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(writer, content2write);
        }
    }

Maybe save them in your own AppData-folder with Environment.SpecialFolder.LocalApplicationData ;-) and go like this

private static readonly string MyPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"MyApp\AppDescription");


问:
Apache POI XSLF creating section (s)
I'm struggling with section creation in apache POI. I want to be able to defina sections with slides, how can I manage to do that? I can append slides without any problem so far.

Here is an PowerPoint part of presentation saved as an XML where you can see how the sections are stored:

```<code><pkg:part pkg:name="/ppt/presentation.xml" pkg:contentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml">
    <pkg:xmlData>
        <p:presentation xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" showSpecialPlsOnTitleSld="0" embedTrueTypeFonts="1" saveSubsetFonts="1">
            (... cut out unrelevant nodes...)
            <p:sldIdLst>
                <p:sldId id="296" r:id="rId10"/>
                <p:sldId id="312" r:id="rId11"/>
                <p:sldId id="274" r:id="rId12"/>
                <p:sldId id="311" r:id="rId13"/>
                <p:sldId id="275" r:id="rId14"/>
                <p:sldId id="276" r:id="rId15"/>
                <p:sldId id="317" r:id="rId16"/>
                <p:sldId id="313" r:id="rId17"/>
                <p:sldId id="318" r:id="rId18"/>
                <p:sldId id="319" r:id="rId19"/>
                <p:sldId id="307" r:id="rId20"/>
                <p:sldId id="314" r:id="rId21"/>
                <p:sldId id="315" r:id="rId22"/>
                <p:sldId id="321" r:id="rId23"/>
                <p:sldId id="320" r:id="rId24"/>
                <p:sldId id="308" r:id="rId25"/>
                <p:sldId id="322" r:id="rId26"/>
                <p:sldId id="303" r:id="rId27"/>
                <p:sldId id="264" r:id="rId28"/>
                <p:sldId id="300" r:id="rId29"/>
                <p:sldId id="287" r:id="rId30"/>
                <p:sldId id="309" r:id="rId31"/>
                <p:sldId id="289" r:id="rId32"/>
            </p:sldIdLst>

            <p:extLst>
                <p:ext uri="{521415D9-36F7-43E2-AB2F-B90AF26B5E84}">
                    <p14:sectionLst xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main">
                        <p14:section name="Default Section" id="{F7FF9A22-6035-4F7F-86B4-79EDB5AF0A91}">
                            <p14:sldIdLst>
                                <p14:sldId id="296"/>
                            </p14:sldIdLst>
                        </p14:section>
                        <p14:section name="PPT section example" id="{376F793D-518A-4B6E-AAA6-8CD5D37CFC8B}">
                            <p14:sldIdLst>
                                <p14:sldId id="312"/>
                                <p14:sldId id="274"/>
                                <p14:sldId id="311"/>
                                <p14:sldId id="275"/>
                                <p14:sldId id="276"/>
                                <p14:sldId id="317"/>
                                <p14:sldId id="313"/>
                                <p14:sldId id="318"/>
                                <p14:sldId id="319"/>
                                <p14:sldId id="307"/>
                                <p14:sldId id="314"/>
                                <p14:sldId id="315"/>
                                <p14:sldId id="321"/>
                                <p14:sldId id="320"/>
                                <p14:sldId id="308"/>
                                <p14:sldId id="322"/>
                                <p14:sldId id="303"/>
                                <p14:sldId id="264"/>
                                <p14:sldId id="300"/>
                                <p14:sldId id="287"/>
                                <p14:sldId id="309"/>
                                <p14:sldId id="289"/>
                            </p14:sldIdLst>
                        </p14:section>
                    </p14:sectionLst>
                </p:ext> (...more contents not relevant I guess ...)
</code>```

Does anyone know how to create a section in Apache POI and append slides to it? How to append multiple section and single slides after that? Any help appreciated.

答:
Ok So I managed the whole thing :) You need to create a default section like this:

```<code>    CTExtensionList extensionsList = ppt.getCTPresentation().getExtLst();//create default section
    CTExtension extension = extensionsList.insertNewExt(0);
    extension.setUri("{521415D9-36F7-43E2-AB2F-B90AF26B5E84}");
    Node ext = extension.getDomNode();
    Element sectionLst = ext.getOwnerDocument().createElementNS(p14Xmlns, "p14:sectionLst");
    sectionLst.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:p14", p14Xmlns);
    ext.appendChild(sectionLst);
    Element section = sectionLst.getOwnerDocument().createElementNS(p14Xmlns, "p14:section");
    section.setAttribute("name", "Default section");
    section.setAttribute("id", "{" + UUID.randomUUID().toString().toUpperCase() + "}");
    Element sldIdLst = section.getOwnerDocument().createElementNS(p14Xmlns, "p14:sldIdLst");
    section.appendChild(sldIdLst);
    sectionLst.appendChild(section);
    return sldIdLst;
</code>```

Then you can use this method to create additional sections if needed:

private Element createSection(Element sldIdLst, Node parent)
    {
        String sectionName = "";
        if (parent.getAttributes() != null && parent.getAttributes().getNamedItem("title") != null)
        {
            sectionName = parent.getAttributes().getNamedItem("title").getNodeValue();
        }
        Node sectionLst = sldIdLst.getParentNode().getParentNode();

```<code>    Element section = sectionLst.getOwnerDocument().createElementNS(p14Xmlns, "p14:section");
    section.setAttribute("name", sectionName);
    section.setAttribute("id", "{" + UUID.randomUUID().toString().toUpperCase() + "}");
    Element newSldIdLst = section.getOwnerDocument().createElementNS(p14Xmlns, "p14:sldIdLst");
    section.appendChild(newSldIdLst);
    sectionLst.appendChild(section);
    sldIdLst = newSldIdLst;
    return sldIdLst;
}
</code>```

Then I had to manually relate the XSLSlide to the sldIdLst liek this:

```<code> XSLFSlide slide = createSlideFromXml(parent, ppt);
        if (slide != null)
        {
            List<CTSlideIdListEntry> sldIdList = ppt.getCTPresentation().getSldIdLst().getSldIdList();
            long slideInternalId = 0;
            for (CTSlideIdListEntry entry : sldIdList)
            {
                if (entry.getId2().equals(slide.getPackageRelationship().getId()))
                {
                    slideInternalId = entry.getId();
                    break;
                }
            }
            Element sldId = sldIdLst.getOwnerDocument().createElementNS("http://schemas.microsoft.com/office/powerpoint/2010/main", "p14:sldId");
            sldId.setAttribute("id", String.valueOf(slideInternalId));
            sldIdLst.appendChild(sldId);
        }
</code>```

I hope you will get the idea.

Title: Apache POI XSLF creating section (s)

Body:
I'm struggling with section creation in apache POI. I want to be able to defina sections with slides, how can I manage to do that? I can append slides without any problem so far.

Here is an PowerPoint part of presentation saved as an XML where you can see how the sections are stored:

<pkg:part pkg:name="/ppt/presentation.xml" pkg:contentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml">
    <pkg:xmlData>

            (... cut out unrelevant nodes...)

                    <p14:sectionLst xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main">
                        <p14:section name="Default Section" id="{F7FF9A22-6035-4F7F-86B4-79EDB5AF0A91}">
                            <p14:sldIdLst>
                                <p14:sldId id="296"/>
                            </p14:sldIdLst>
                        </p14:section>
                        <p14:section name="PPT section example" id="{376F793D-518A-4B6E-AAA6-8CD5D37CFC8B}">
                            <p14:sldIdLst>
                                <p14:sldId id="312"/>
                                <p14:sldId id="274"/>
                                <p14:sldId id="311"/>
                                <p14:sldId id="275"/>
                                <p14:sldId id="276"/>
                                <p14:sldId id="317"/>
                                <p14:sldId id="313"/>
                                <p14:sldId id="318"/>
                                <p14:sldId id="319"/>
                                <p14:sldId id="307"/>
                                <p14:sldId id="314"/>
                                <p14:sldId id="315"/>
                                <p14:sldId id="321"/>
                                <p14:sldId id="320"/>
                                <p14:sldId id="308"/>
                                <p14:sldId id="322"/>
                                <p14:sldId id="303"/>
                                <p14:sldId id="264"/>
                                <p14:sldId id="300"/>
                                <p14:sldId id="287"/>
                                <p14:sldId id="309"/>
                                <p14:sldId id="289"/>
                            </p14:sldIdLst>
                        </p14:section>
                    </p14:sectionLst>

 (...more contents not relevant I guess ...)

Does anyone know how to create a section in Apache POI and append slides to it? How to append multiple section and single slides after that? Any help appreciated.

Body:
Ok So I managed the whole thing :) You need to create a default section like this:

    CTExtensionList extensionsList = ppt.getCTPresentation().getExtLst();//create default section
    CTExtension extension = extensionsList.insertNewExt(0);
    extension.setUri("{521415D9-36F7-43E2-AB2F-B90AF26B5E84}");
    Node ext = extension.getDomNode();
    Element sectionLst = ext.getOwnerDocument().createElementNS(p14Xmlns, "p14:sectionLst");
    sectionLst.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:p14", p14Xmlns);
    ext.appendChild(sectionLst);
    Element section = sectionLst.getOwnerDocument().createElementNS(p14Xmlns, "p14:section");
    section.setAttribute("name", "Default section");
    section.setAttribute("id", "{" + UUID.randomUUID().toString().toUpperCase() + "}");
    Element sldIdLst = section.getOwnerDocument().createElementNS(p14Xmlns, "p14:sldIdLst");
    section.appendChild(sldIdLst);
    sectionLst.appendChild(section);
    return sldIdLst;

Then you can use this method to create additional sections if needed:

private Element createSection(Element sldIdLst, Node parent)
    {
        String sectionName = "";
        if (parent.getAttributes() != null && parent.getAttributes().getNamedItem("title") != null)
        {
            sectionName = parent.getAttributes().getNamedItem("title").getNodeValue();
        }
        Node sectionLst = sldIdLst.getParentNode().getParentNode();

    Element section = sectionLst.getOwnerDocument().createElementNS(p14Xmlns, "p14:section");
    section.setAttribute("name", sectionName);
    section.setAttribute("id", "{" + UUID.randomUUID().toString().toUpperCase() + "}");
    Element newSldIdLst = section.getOwnerDocument().createElementNS(p14Xmlns, "p14:sldIdLst");
    section.appendChild(newSldIdLst);
    sectionLst.appendChild(section);
    sldIdLst = newSldIdLst;
    return sldIdLst;
}

Then I had to manually relate the XSLSlide to the sldIdLst liek this:

 XSLFSlide slide = createSlideFromXml(parent, ppt);
        if (slide != null)
        {
            List<CTSlideIdListEntry> sldIdList = ppt.getCTPresentation().getSldIdLst().getSldIdList();
            long slideInternalId = 0;
            for (CTSlideIdListEntry entry : sldIdList)
            {
                if (entry.getId2().equals(slide.getPackageRelationship().getId()))
                {
                    slideInternalId = entry.getId();
                    break;
                }
            }
            Element sldId = sldIdLst.getOwnerDocument().createElementNS("http://schemas.microsoft.com/office/powerpoint/2010/main", "p14:sldId");
            sldId.setAttribute("id", String.valueOf(slideInternalId));
            sldIdLst.appendChild(sldId);
        }

I hope you will get the idea.