问:
How to Verify using C# if a XML file is broken
Is there anything built in to determine if an XML file is valid. One way would be to read the entire content and verify if the string represents valid XML content. Even then, how to determine if string contains valid XML data.</p>

答:
Have a look at this question:

How to check for valid xml in string input before calling .LoadXml()


来源: stackexchange

问:
Python If Statement question login system easy
The first thing to do is write "1" and then enter username and password. After that, the max number of account is 1 and you can then use the "2" to login.
First time asking a question so I am sorry if this is like a dumb question or something. My code is as following:

https://imgur.com/a/dAaYf2u - NEW LINK

Code:

```<code>print("Type 1 for Create user. Type 2 for login")
Choice = input("Number here: ")

if Choice == ("1"):
print("Welcome to the Create a user interface")
Username = input("Username: ")
Password = input("Password: ")

if Password.count("!") > 0:
   print("Not valid - no special characters!")
else:
  file = open("account.txt", "w")
  file.write(Username)
  file.write("\n")
  file.write(Password)
  file.close()
elif Choice == ("2"):

print("Welcome, please type your Username and Password")
Loginu = input("Write username here: ")
Loginp = input("Write password here: ")
file = open("account.txt", "r")
first_line = file.readline()
if Loginu == first_line:
print("you're logged in")
else:
print("fail")
</code>```

It's very basic and so on. What I don't understand is why the if Loginu == first_line can't read the first_line variable... It just jumps directly to else:

I hope it helps and I know my code is very basic lol.

答:
My advice:

follow pep8, use meaningful names for variables

split your code into functions

use infinite loop for your "menu"

even better use some package that helps with building such applications (click?) rather then reinvent the wheel

Read your file with with open(...) as f: context manager

It's probably good idea to read whole file and build dictionary instead of depending on the login to be exactly identical with first line

use strip() to remove white characters (like newline)

check that line you are looking at is not empty

if you've opened file without context manager for writting, you need to close it before opening it again for reading

use debugger to check what's exactly result of readline

ContentLicense: CC BY-SA 4.0

Body:
The first thing to do is write "1" and then enter username and password. After that, the max number of account is 1 and you can then use the "2" to login.
First time asking a question so I am sorry if this is like a dumb question or something. My code is as following:

https://imgur.com/a/dAaYf2u - NEW LINK

Code:

print("Type 1 for Create user. Type 2 for login")
Choice = input("Number here: ")

if Choice == ("1"):
print("Welcome to the Create a user interface")
Username = input("Username: ")
Password = input("Password: ")

if Password.count("!") > 0:
   print("Not valid - no special characters!")
else:
  file = open("account.txt", "w")
  file.write(Username)
  file.write("\n")
  file.write(Password)
  file.close()
elif Choice == ("2"):

print("Welcome, please type your Username and Password")
Loginu = input("Write username here: ")
Loginp = input("Write password here: ")
file = open("account.txt", "r")
first_line = file.readline()
if Loginu == first_line:
print("you're logged in")
else:
print("fail")

It's very basic and so on. What I don't understand is why the if Loginu == first_line can't read the first_line variable... It just jumps directly to else:

I hope it helps and I know my code is very basic lol.


问:
The name does not exist in the namespace despite being there
I am trying to use data binding to create a list view but get this error. Why does the following error appear even though the affected name is actually in the affected class?

The name "ListItem" does not exist in the namespace "using:My_App.Models".

MainPage.xaml

```<code><Page
    x:Class="My_App.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:data="using:My_App.Models"
    mc:Ignorable="d">

        <ListView
            ItemsSource="{x:Bind listItems}"
            ItemClick="ListView_ItemClick"
            SelectionChanged="ListView_SelectionChanged">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="data:ListItem">
                    <StackPanel>
                        <TextBlock Text="{Binding BookTitle}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</Page>
</code>```

MainPage.cs

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using My_App.Models;
using Windows.ApplicationModel.Email;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace My_App
{
    public sealed partial class MainPage : Page
    {
        private List<ListItem> listItems;

        public MainPage()
        {
            this.InitializeComponent();

            listItems = ItemManager.GetListItems();
        }
    }
}
</code>```

ListItem class (inside the 'Models' folder)

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace My_App.Models
{

    public class ListItem
    {
        public string BookTitle { get; set; }
    }

    public class ItemManager
    {
        public static List<ListItem> GetListItems()
        {
            var items = new List<ListItem>
            {
                new ListItem { BookTitle = "The Wizard of Oz" }
            };

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

答:
The name does not exist in the namespace despite being there

For checking your code, I found you have missed  My_App.Models namespace in MainPage class. I make a code sample here, and it works well please check it.

If the problem persists, please try to delete the project's bin and obj folder and build the solution before launch the app.

Body:
I am trying to use data binding to create a list view but get this error. Why does the following error appear even though the affected name is actually in the affected class?

The name "ListItem" does not exist in the namespace "using:My_App.Models".

MainPage.xaml

<Page
    x:Class="My_App.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:data="using:My_App.Models"
    mc:Ignorable="d">

        <ListView
            ItemsSource="{x:Bind listItems}"
            ItemClick="ListView_ItemClick"
            SelectionChanged="ListView_SelectionChanged">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="data:ListItem">
                    <StackPanel>
                        <TextBlock Text="{Binding BookTitle}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</Page>

MainPage.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using My_App.Models;
using Windows.ApplicationModel.Email;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace My_App
{
    public sealed partial class MainPage : Page
    {
        private List<ListItem> listItems;

        public MainPage()
        {
            this.InitializeComponent();

            listItems = ItemManager.GetListItems();
        }
    }
}

ListItem class (inside the 'Models' folder)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace My_App.Models
{

    public class ListItem
    {
        public string BookTitle { get; set; }
    }

    public class ItemManager
    {
        public static List<ListItem> GetListItems()
        {
            var items = new List<ListItem>
            {
                new ListItem { BookTitle = "The Wizard of Oz" }
            };

            return items;
        }
    }
}


问:
CS50 recover segmentation fault
This is Recover from pset4 CS50. There is no error when I compile it. When I run the code I get segmentation fault. I do not understand what exactly is the mistake. I have looked up solutions related to questions on segmentation fault posted by others but they don't seem to solve my problem. </p>

<p>Can somebody explain whats wrong and how do I solve it. </p>

```<code>#include <stdio.h>
#include <stdint.h>
typedef uint8_t BYTE;

int main(int argc, char *argv[])
{

if (argc != 2)
{
    printf("Usage: ./recover image\n");
    return 1;
}

FILE *inFile = fopen(argv[1], "r");
if(!inFile)
{
    printf("Could not open file!\n");
    return 1;
}

BYTE buffer[512];
FILE *outFile = NULL;
int imageNum = 0;
char fileName[8];

while (!feof(inFile))
{
     fread(buffer, 1, sizeof(buffer), inFile);
     if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[4] & 0xf0) == 0xef0)
     {
         if (imageNum > 0)
         {
            fclose(outFile);
         }
         imageNum++;
         sprintf(fileName, "%03i.jpg", imageNum);
         outFile = fopen(fileName, "w");
     }
    if (outFile != NULL)
    {
        fwrite(buffer, 1, sizeof(buffer), outFile);
    }
}
fclose(outFile);
fclose(inFile);
return 0;
}
</code>```

答:
The reason for the segfault is likely this declaration:

```<code>char fileName[8];
</code>```

For filenames greater than 999,  fileName will overflow.

i.e. for imagenum >= 1000

```<code>sprintf(fileName, "%03i.jpg", imageNum);//produces 8 characters + NULL == 9
</code>```

...will produce "1000.jpg" which is a buffer overflow, thus segfault.

Making fileName larger is the fix:

```<code>char filename[20];//or larger as needed.
</code>```

Also,

per definitions of fwrite() and fread(), the following function arguments are misplaced:

```<code>fread(buffer, 1, sizeof(buffer), inFile);
fwrite(buffer, 1, sizeof(buffer), outFile);
               ^        ^
</code>```

Should be:

```<code>fread(buffer, sizeof(buffer), 1, inFile);
fwrite(buffer, sizeof(buffer), 1, outFile);
                     ^         ^
</code>```

Title: CS50 recover segmentation fault

Body:
This is Recover from pset4 CS50. There is no error when I compile it. When I run the code I get segmentation fault. I do not understand what exactly is the mistake. I have looked up solutions related to questions on segmentation fault posted by others but they don't seem to solve my problem.

Can somebody explain whats wrong and how do I solve it.

#include <stdio.h>
#include <stdint.h>
typedef uint8_t BYTE;

int main(int argc, char *argv[])
{

if (argc != 2)
{
    printf("Usage: ./recover image\n");
    return 1;
}

FILE *inFile = fopen(argv[1], "r");
if(!inFile)
{
    printf("Could not open file!\n");
    return 1;
}

BYTE buffer[512];
FILE *outFile = NULL;
int imageNum = 0;
char fileName[8];

while (!feof(inFile))
{
     fread(buffer, 1, sizeof(buffer), inFile);
     if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[4] & 0xf0) == 0xef0)
     {
         if (imageNum > 0)
         {
            fclose(outFile);
         }
         imageNum++;
         sprintf(fileName, "%03i.jpg", imageNum);
         outFile = fopen(fileName, "w");
     }
    if (outFile != NULL)
    {
        fwrite(buffer, 1, sizeof(buffer), outFile);
    }
}
fclose(outFile);
fclose(inFile);
return 0;
}

Body:
The reason for the segfault is likely this declaration:

char fileName[8];

For filenames greater than 999,  fileName will overflow.

i.e. for imagenum >= 1000

sprintf(fileName, "%03i.jpg", imageNum);//produces 8 characters + NULL == 9

...will produce "1000.jpg" which is a buffer overflow, thus segfault.

Making fileName larger is the fix:

char filename[20];//or larger as needed.

Also,

per definitions of fwrite() and fread(), the following function arguments are misplaced:

fread(buffer, 1, sizeof(buffer), inFile);
fwrite(buffer, 1, sizeof(buffer), outFile);
               ^        ^

Should be:

fread(buffer, sizeof(buffer), 1, inFile);
fwrite(buffer, sizeof(buffer), 1, outFile);
                     ^         ^


问:
jQuery datatables export input text option and not export specific column at same time
I've been struggling with this code. I need to avoid specific columns from being exported. I have done that but I don't know how to export the text inside any input element.

Here is the code:

```<code>$("#campaignMaterialsTable table").DataTable({
                            dom: 'Bfrtip',
                            buttons: [
                                {
                                    extend: 'excel',
                                    className: 'export-button',
                                    text: 'Export as Excel',
                                    columns: ':not(.notexport)',
                                    //exportOptions: {
                                    //    format: {
                                    //        body: function (data, row, column, node) {
                                    //            //
                                    //            //check if type is input using jquery
                                    //            return $(data).is("input") ?
                                    //                $(data).val() :
                                    //                data;
                                    //        },
                                    //        columns: ':not(.notexport)'
                                    //    }
                                    //},
                                    title: 'Campaign Materials'
                                }]
                        });
</code>```

I don't know here to put the code at the right place.. while initializing..

I referred to this links, but still not getting what I want:

https://datatables.net/forums/discussion/50724/export-values-typed-in-input-box-excelhtml5

https://datatables.net/forums/discussion/42205/export-data-with-text-box-in-td-of-data-table#latest

https://datatables.net/extensions/buttons/examples/html5/outputFormat-function.html

https://datatables.net/forums/discussion/50724/export-values-typed-in-input-box-excelhtml5

答:
I assume you have a DataTable containing one or more input fields, something like this:

The user can type values into the input fields.

You want to export data to Excel, so that the result looks like this:

Here we can see the user-provided data as well as the standard table data.

To achieve this, I used the following table data:

```<code><table id="example" class="display nowrap dataTable cell-border" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Adélaïde Nixon</td>
            <td>System Architect</td>
            <td><input type="text" id="office" name="office"></td>
            <td>432434</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td>John Smith</td>
            <td>Maager</td>
            <td><input type="text" id="office" name="office"></td>
            <td>6123</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td>John Smith 2</td>
            <td>Director</td>
            <td><input type="text" id="office" name="office"></td>
            <td>6123</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
    </tbody>
</table>
</code>```

And I used the following DataTable initialization code:

```<code><script type="text/javascript">

  $(document).ready(function() {

    $('#example').DataTable({
      dom: 'Bfrtip',

      buttons: [
        {
          extend: 'excel',
          exportOptions: {
            format: {
              body: function ( inner, rowidx, colidx, node ) {
                if ($(node).children("input").length > 0) {
                  return $(node).children("input").first().val();
                } else {
                  return inner;
                }
              }
            }
          }
        }
      ]

    });

  });
</script>
</code>```

The body function assumes that, for input fields, there is only an input field in the cell (i.e. the input field is not contained in a form or any other element).

It uses the node parameter to check for input data, to avoid data formatting issues that could occur (e.g. with dates). I recommend doing that rather than using $(data).is("input").

If there is no input field found in the cell, then the cell contents (inner) are returned.

If the structure of your table does not match these assumptions, then you may need to adjust the above code, of course.

Edit

Regarding the follow-up question about choosing  which columns to export, there are various ways.

You can hard-code the column indexes you want to export (where index 0 means the first column). For example:

```<code>exportOptions: {
  columns: [ 0, 1, 2, 3, 5 ],
    format: {
      body: function ( inner, rowidx, colidx, node ) {
        if ($(node).children("input").length > 0) {
          return $(node).children("input").first().val();
        } else {
          return inner;
        }
      }
    }
}
</code>```

This exports all columns apart from the Start Date column (index 4).

Or you can use the approach in your question, based on a class, I believe. I have not actually tried that one.

Take note of where the columns: [ 0, 1, 2, 3, 5 ] directive is placed - it is inside the exportOptions section.

Body:
I've been struggling with this code. I need to avoid specific columns from being exported. I have done that but I don't know how to export the text inside any input element.

Here is the code:

$("#campaignMaterialsTable table").DataTable({
                            dom: 'Bfrtip',
                            buttons: [
                                {
                                    extend: 'excel',
                                    className: 'export-button',
                                    text: 'Export as Excel',
                                    columns: ':not(.notexport)',
                                    //exportOptions: {
                                    //    format: {
                                    //        body: function (data, row, column, node) {
                                    //            //
                                    //            //check if type is input using jquery
                                    //            return $(data).is("input") ?
                                    //                $(data).val() :
                                    //                data;
                                    //        },
                                    //        columns: ':not(.notexport)'
                                    //    }
                                    //},
                                    title: 'Campaign Materials'
                                }]
                        });

I don't know here to put the code at the right place.. while initializing..

I referred to this links, but still not getting what I want:

https://datatables.net/forums/discussion/50724/export-values-typed-in-input-box-excelhtml5

https://datatables.net/forums/discussion/42205/export-data-with-text-box-in-td-of-data-table#latest

https://datatables.net/extensions/buttons/examples/html5/outputFormat-function.html

https://datatables.net/forums/discussion/50724/export-values-typed-in-input-box-excelhtml5

Body:
I assume you have a DataTable containing one or more input fields, something like this:

The user can type values into the input fields.

You want to export data to Excel, so that the result looks like this:

Here we can see the user-provided data as well as the standard table data.

To achieve this, I used the following table data:

<table id="example" class="display nowrap dataTable cell-border" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Adélaïde Nixon</td>
            <td>System Architect</td>
            <td><input type="text" id="office" name="office"></td>
            <td>432434</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td>John Smith</td>
            <td>Maager</td>
            <td><input type="text" id="office" name="office"></td>
            <td>6123</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td>John Smith 2</td>
            <td>Director</td>
            <td><input type="text" id="office" name="office"></td>
            <td>6123</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
    </tbody>
</table>

And I used the following DataTable initialization code:

<script type="text/javascript">

  $(document).ready(function() {

    $('#example').DataTable({
      dom: 'Bfrtip',

      buttons: [
        {
          extend: 'excel',
          exportOptions: {
            format: {
              body: function ( inner, rowidx, colidx, node ) {
                if ($(node).children("input").length > 0) {
                  return $(node).children("input").first().val();
                } else {
                  return inner;
                }
              }
            }
          }
        }
      ]

    });

  });
</script>

The body function assumes that, for input fields, there is only an input field in the cell (i.e. the input field is not contained in a form or any other element).

It uses the node parameter to check for input data, to avoid data formatting issues that could occur (e.g. with dates). I recommend doing that rather than using $(data).is("input").

If there is no input field found in the cell, then the cell contents (inner) are returned.

If the structure of your table does not match these assumptions, then you may need to adjust the above code, of course.

Edit

Regarding the follow-up question about choosing  which columns to export, there are various ways.

You can hard-code the column indexes you want to export (where index 0 means the first column). For example:

exportOptions: {
  columns: [ 0, 1, 2, 3, 5 ],
    format: {
      body: function ( inner, rowidx, colidx, node ) {
        if ($(node).children("input").length > 0) {
          return $(node).children("input").first().val();
        } else {
          return inner;
        }
      }
    }
}

This exports all columns apart from the Start Date column (index 4).

Or you can use the approach in your question, based on a class, I believe. I have not actually tried that one.

Take note of where the columns: [ 0, 1, 2, 3, 5 ] directive is placed - it is inside the exportOptions section.


问:
Python Dictionary to CSV
I have written code to read a CSV into a python dictionary, which works fine. I'm trying to get the dictionary back to a CSV. I have written the following:

```<code>import csv

itemDict={}

listReader = csv.reader(open('/Users/broberts/Desktop/Sum_CSP1.csv','rU'), delimiter = ',', quotechar='|')

for row in listReader:
    fID = row[0]
    fClassRange = row[1]
    fArea = row[2]

    if itemDict.has_key(fID):
        itemDict[fID][fClassRange]=fArea
    else:
        itemDict[fID] = {'5.0 to 5.25':'','5.25 to 5.5':'','5.5 to 5.75':'','5.75 to 6.0':'','6.0 to 6.25':'','6.25 to 6.5':'','6.5 to 6.75':'','6.75 to 7.0':'','7.0 to 7.25':'','7.25 to 7.5':'','7.5 to 7.75':'','7.75 to 8.0':'','8.0 to 8.25':'',}
        itemDict[fID][fClassRange]=fArea

listWriter = csv.writer(open('/Users/broberts/Desktop/Sum_CSP1_output.csv', 'wb'), delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)

for a in itemDict:
    print a
    listWriter.writerow(a)
</code>```

In the last block, listWriter will not write anything to the CSV though it will print a.  I believe this has something to do with a dictionary being unordered.  I really need to write out the fID and each of the keys associated with each fID (fClassRange ex. "5.0 to 5.25") and then the value fArea associated with each fClassRange to the CSV, but I haven't even gotten that far in my code since I can't figure out how to write out even the fID.

I looked into using DictWriter, but I can't figure out how to tell it what the required fieldnames are.

答:
```<code>d = [{'a': 1, 'b': 2},{'a': 3, 'b': 4}]

with open('csv_file.csv', 'w', newline='\n') as f:
    w = csv.DictWriter(f, d[0].keys())
    w.writeheader()
    for i in d:
        w.writerow(i)
</code>```

gets you

```<code>a,b
1,2
3,4
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python Dictionary to CSV

Body:
I have written code to read a CSV into a python dictionary, which works fine. I'm trying to get the dictionary back to a CSV. I have written the following:

import csv

itemDict={}

listReader = csv.reader(open('/Users/broberts/Desktop/Sum_CSP1.csv','rU'), delimiter = ',', quotechar='|')

for row in listReader:
    fID = row[0]
    fClassRange = row[1]
    fArea = row[2]

    if itemDict.has_key(fID):
        itemDict[fID][fClassRange]=fArea
    else:
        itemDict[fID] = {'5.0 to 5.25':'','5.25 to 5.5':'','5.5 to 5.75':'','5.75 to 6.0':'','6.0 to 6.25':'','6.25 to 6.5':'','6.5 to 6.75':'','6.75 to 7.0':'','7.0 to 7.25':'','7.25 to 7.5':'','7.5 to 7.75':'','7.75 to 8.0':'','8.0 to 8.25':'',}
        itemDict[fID][fClassRange]=fArea

listWriter = csv.writer(open('/Users/broberts/Desktop/Sum_CSP1_output.csv', 'wb'), delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)

for a in itemDict:
    print a
    listWriter.writerow(a)

In the last block, listWriter will not write anything to the CSV though it will print a.  I believe this has something to do with a dictionary being unordered.  I really need to write out the fID and each of the keys associated with each fID (fClassRange ex. "5.0 to 5.25") and then the value fArea associated with each fClassRange to the CSV, but I haven't even gotten that far in my code since I can't figure out how to write out even the fID.

I looked into using DictWriter, but I can't figure out how to tell it what the required fieldnames are.

Body:
d = [{'a': 1, 'b': 2},{'a': 3, 'b': 4}]

with open('csv_file.csv', 'w', newline='\n') as f:
    w = csv.DictWriter(f, d[0].keys())
    w.writeheader()
    for i in d:
        w.writerow(i)

gets you

a,b
1,2
3,4


问:
React Developer Tools shows all components as "Anonymous"
I've installed the React Developer Tools extension on Google Chrome to debug a React application written in TypeScript, but once I start debugging the application and open the "Components" window, all components are shown as "Anonymous".

Granted, the application uses mostly function components.

Does anyone know if there is a way to get React Developer Tools to show component names in its component tree?

答:
This happens when you define your components like so:

// Default arrow function export
export default () => {
    // ...
}

// Default function export
export default function() {
    // ...
}
```
<p>You can replace with the following to fix the issue:</p>
<pre class="lang-js prettyprint-override"><code>const CustomComponent = () => {
    // ...
}

export default CustomComponent;

// or

export default function YourComponent() {
  // ...
}
</code>```

Body:
This happens when you define your components like so:

// Default arrow function export
export default () => {
    // ...
}

// Default function export
export default function() {
    // ...
}

You can replace with the following to fix the issue:

const CustomComponent = () => {
    // ...
}

export default CustomComponent;

// or

export default function YourComponent() {
  // ...
}


问:
SXSSF workbook createSheet() fails on linux environments
Was trying to implement an excel export feature on an app using apache POI 3.17.

All was working fine on my local tomcat server and on a windows dev environment. However, the SXSSFWorkbook workbook.createSheet() method fails on a linux tomcat server without throwing any kind of meaningful error (it's just hanging).

Strangely, the same method on the XSSFWorkbook createSheet class works fine. Below are the snippets of code. Has anyone experienced a similar issue before?

```<code>    final SXSSFWorkbook workbook = new SXSSFWorkbook();
    workbook.setCompressTempFiles(true);
    SXSSFSheet sheet = workbook.createSheet("Sheet 1"); //this method fails

    final XSSFWorkbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("Sheet 1"); // this works fine
</code>```

Edit

I created a custom TempFileCreationStrategy to ensure tomcat is writing the file to a directory it has full access to. I can see the file has been created but it's hanging as it tries to write any data to the file.

I cannot figure this one out.

Edit2

I've enabled POI logging but it I'm still not getting anything meaningful that I can investigate. On my local server POI logging spits out the following as it begins to write the file:

```<code>[20:13:05,005]DEBUG (?:?) - Save core properties part
[20:13:05,005]DEBUG (?:?) - Save package relationships
[20:13:05,005]DEBUG (?:?) - Save content types part
[20:13:05,005]DEBUG (?:?) - Save part 'docProps/app.xml'
[20:13:05,005]DEBUG (?:?) - Save part 'docProps/core.xml'
[20:13:05,005]DEBUG (?:?) - Save part 'xl/sharedStrings.xml'
[20:13:05,005]DEBUG (?:?) - Save part 'xl/styles.xml'
[20:13:05,005]DEBUG (?:?) - Save part 'xl/workbook.xml'
[20:13:05,005]DEBUG (?:?) - Save part 'xl/worksheets/sheet1.xml'
</code>```

On the Linux box, it's not even getting as far as the first log output. Need to find a way to get more detail about the failure!

Edit3

Is it possible to get more detailed logging beyond the default logging I have enabled below?

```<code>System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.SystemOutLogger" );

String tmpDir = System.getProperty("java.io.tmpdir")+File.separator+"excelfiles";
ExcelFileCreationStrategy tfcs = new ExcelFileCreationStrategy();

try {
    tfcs.createTempDirectory(tmpDir);
} catch (IOException e) {
    e.printStackTrace();
    LOG.error(e);
}

TempFile.setTempFileCreationStrategy(tfcs);

final SXSSFWorkbook workbook = new SXSSFWorkbook();
workbook.setCompressTempFiles(true);

LOG.debug("creating work sheet - next line fails");
Sheet sheet = workbook.createSheet(); //hangs here
LOG.debug("It's worked!!!!");
</code>```

答:
I had the same problem and after a long time of debugging and analysis, the "bug" is that when streaming, it tries to use the font to determine the width of the characters to adjust the columns. This fails without a message and simply aborts the creation if the font cannot be created / determined. The only solution I could find was to install the package "fontconfig".

```<code>sudo apt-get update
sudo apt-get install fontconfig
</code>```

Without the package java unfortunately cannot work with java.awt.Fonts.

Body:
Was trying to implement an excel export feature on an app using apache POI 3.17.

All was working fine on my local tomcat server and on a windows dev environment. However, the SXSSFWorkbook workbook.createSheet() method fails on a linux tomcat server without throwing any kind of meaningful error (it's just hanging).

Strangely, the same method on the XSSFWorkbook createSheet class works fine. Below are the snippets of code. Has anyone experienced a similar issue before?

    final SXSSFWorkbook workbook = new SXSSFWorkbook();
    workbook.setCompressTempFiles(true);
    SXSSFSheet sheet = workbook.createSheet("Sheet 1"); //this method fails

    final XSSFWorkbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("Sheet 1"); // this works fine

Edit

I created a custom TempFileCreationStrategy to ensure tomcat is writing the file to a directory it has full access to. I can see the file has been created but it's hanging as it tries to write any data to the file.

I cannot figure this one out.

Edit2

I've enabled POI logging but it I'm still not getting anything meaningful that I can investigate. On my local server POI logging spits out the following as it begins to write the file:

[20:13:05,005]DEBUG (?:?) - Save core properties part
[20:13:05,005]DEBUG (?:?) - Save package relationships
[20:13:05,005]DEBUG (?:?) - Save content types part
[20:13:05,005]DEBUG (?:?) - Save part 'docProps/app.xml'
[20:13:05,005]DEBUG (?:?) - Save part 'docProps/core.xml'
[20:13:05,005]DEBUG (?:?) - Save part 'xl/sharedStrings.xml'
[20:13:05,005]DEBUG (?:?) - Save part 'xl/styles.xml'
[20:13:05,005]DEBUG (?:?) - Save part 'xl/workbook.xml'
[20:13:05,005]DEBUG (?:?) - Save part 'xl/worksheets/sheet1.xml'

On the Linux box, it's not even getting as far as the first log output. Need to find a way to get more detail about the failure!

Edit3

Is it possible to get more detailed logging beyond the default logging I have enabled below?

System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.SystemOutLogger" );

String tmpDir = System.getProperty("java.io.tmpdir")+File.separator+"excelfiles";
ExcelFileCreationStrategy tfcs = new ExcelFileCreationStrategy();

try {
    tfcs.createTempDirectory(tmpDir);
} catch (IOException e) {
    e.printStackTrace();
    LOG.error(e);
}

TempFile.setTempFileCreationStrategy(tfcs);

final SXSSFWorkbook workbook = new SXSSFWorkbook();
workbook.setCompressTempFiles(true);

LOG.debug("creating work sheet - next line fails");
Sheet sheet = workbook.createSheet(); //hangs here
LOG.debug("It's worked!!!!");

Body:
I had the same problem and after a long time of debugging and analysis, the "bug" is that when streaming, it tries to use the font to determine the width of the characters to adjust the columns. This fails without a message and simply aborts the creation if the font cannot be created / determined. The only solution I could find was to install the package "fontconfig".

sudo apt-get update
sudo apt-get install fontconfig

Without the package java unfortunately cannot work with java.awt.Fonts.


问:
How to create Android Facebook Key Hash?
I do not understand this process at all. I have been able to navigate to the folder containing the keytool in the Java SDK. Although I keep getting the error openssl not recognised as an internal or external command. The problem is even if I can get this to work, what would I do and with what afterwards?</p>

答:
keytool -exportcert -alias androiddebugkey -keystore "C:\Users**Deepak**.android\debug.keystore" | "C:\Users\Deepak\ssl\bin\openssl" sha1 -binary | "C:\Users\Deepak\ssl\bin\openssl" base64

2 Changes in this above command
1.Deepak===Replace by your System USERNAME
2.C:\Users\Deepak\ssl=== replce your Open SSL path

run this command and get output like this

C:\Users\Deepak>keytool -exportcert -alias androiddebugkey -keystore "C:\Users\D
eepak.android\debug.keystore" | "C:\Users\Deepak\ssl\bin\openssl" sha1 -binary
| "C:\Users\Deepak\ssl\bin\openssl" base64
Enter keystore password:  ******
ga0RGNY******************=


问:
Why does my site works properly in IE7 mode in IE9 but not IE7?
I have a problem with IE9. I am using this:

```<code> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
 <html>
 <head>
 <meta http-equiv="X-UA-Compatible" content="IE=7">
</code>```

So as to have IE7 mode in all browsers. IE8 and IE9 work fine; they work like IE7. Native IE7 does not work properly. Does anyone know what's the problem?

Thanks in advance

答:
i think it may be this
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">
i got that from here  http://msdn.microsoft.com/en-us/library/cc288325(v=vs.85).aspx</p>

Body:
I have a problem with IE9. I am using this:

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

 <meta http-equiv="X-UA-Compatible" content="IE=7">

So as to have IE7 mode in all browsers. IE8 and IE9 work fine; they work like IE7. Native IE7 does not work properly. Does anyone know what's the problem?

Thanks in advance


问:
How do I tell tensorflow to ignore some calculations?
I have two cases where I want to perform two different calculations based on some condition, currently I am using tf.cond to switch between the two conditions, however I have noticed that Tensorflow calculates both the cases and then simply uses the condition to determine which one to return. This is basically what my code looks like:

```<code>Tensor_1 = #Lots of complex calculations
Tensor_2 = tf.eye(dimensions)
Result = tf.cond( my_condition, lambda: Tensor_1, lambda: Tensor_2 )
</code>```

My problem is that one of these calculations is a lot slower than the other but a lot rarer too, how do I go about telling Tensorflow not to perform the calculations unless a condition is satisfied?

I have also tried tf.case and tf.switch_case, both appear to have the same problem.

答:
From tensorflows documentation:
"Warning: Any Tensors or Operations created outside of true_fn and false_fn will be executed regardless of which branch is selected at runtime."

You do not have any true_fn or false_fn which does any operations, hence there's nothing to "ignore". The tensors has to be evaluated first since they are input arguments to the functions in tf.cond. Move the "Lots of complex calculations" to a separate function and then call that function, so something like this:

```<code>Tensor_1 = #Input to lots of complex calculations
Result = tf.cond( my_condition, lambda: complex_calculations(Tensor_1), function_returning_eye )
</code>```

I have also discovered that putting a python for loop inside the functions breaks this behaviour and forces tensorflow to evaluate that branch no matter the condition.

Body:
I have two cases where I want to perform two different calculations based on some condition, currently I am using tf.cond to switch between the two conditions, however I have noticed that Tensorflow calculates both the cases and then simply uses the condition to determine which one to return. This is basically what my code looks like:

Tensor_1 = #Lots of complex calculations
Tensor_2 = tf.eye(dimensions)
Result = tf.cond( my_condition, lambda: Tensor_1, lambda: Tensor_2 )

My problem is that one of these calculations is a lot slower than the other but a lot rarer too, how do I go about telling Tensorflow not to perform the calculations unless a condition is satisfied?

I have also tried tf.case and tf.switch_case, both appear to have the same problem.

Body:
From tensorflows documentation:
"Warning: Any Tensors or Operations created outside of true_fn and false_fn will be executed regardless of which branch is selected at runtime."

You do not have any true_fn or false_fn which does any operations, hence there's nothing to "ignore". The tensors has to be evaluated first since they are input arguments to the functions in tf.cond. Move the "Lots of complex calculations" to a separate function and then call that function, so something like this:

Tensor_1 = #Input to lots of complex calculations
Result = tf.cond( my_condition, lambda: complex_calculations(Tensor_1), function_returning_eye )

I have also discovered that putting a python for loop inside the functions breaks this behaviour and forces tensorflow to evaluate that branch no matter the condition.


问:
ionic5 white screen. Why is it not loaded tabs.ts
My development environment
click here

config.xml文件内容

```<code><feature name="CDVWKWebViewEngine">
        <param name="ios-package" value="CDVWKWebViewEngine" />
    </feature>
    <preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />
    <preference name="DisallowOverscroll" value="true" />
    <preference name="AllowedSchemes" value="netspay" />
    <preference name="ScrollEnabled" value="false" />
    <preference name="android-minSdkVersion" value="19" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="ShowSplashScreen" value="true" />
    <preference name="SplashScreen" value="screen" />
    <preference name="SplashScreenDelay" value="3000" />
    <preference name="AutoHideSplashScreen" value="false" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <preference name="ShowSplashScreenSpinner" value="false" />
    <preference name="FadeSplashScreenDuration" value="1000" />
    <preference name="SplashShowOnlyFirstTime" value="false" />
    <preference name="Orientation" value="portrait" />
</code>```

app.component.ts    file part function

```<code>initializeApp() {
    this.platform.ready().then(() => {
      // this.statusBar.styleDefault();
      this.statusBar.backgroundColorByHexString('#27507E');
      setTimeout(() => {
        this.splashScreen.hide();
      }, 2000);
    });
}
</code>```

app-routing.module.ts config content

```<code>import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
  },
  {
    path: 'products',
    loadChildren: () => import('./pages/products/products.module').then( m => m.ProductsPageModule)
  },
  {
    path: 'proDetail',
    loadChildren: () => import('./pages/proDetail/proDetail.module').then( m => m.ProDetailPageModule)
  },
  {
    path: 'cartPage',
    loadChildren: () => import('./pages/cartPage/cartPage.module').then( m => m.CartPageModule)
  },
  {
    path: 'orderDetail',
    loadChildren: () => import('./pages/orderDetail/orderDetail.module').then( m => m.OrderDetailPageModule)
  },
  {
    path: 'payment',
    loadChildren: () => import('./pages/payment/payment.module').then( m => m.PaymentPageModule)
  },
  {
    path: 'receipt',
    loadChildren: () => import('./pages/receipt/receipt.module').then( m => m.ReceiptPageModule)
  },
  {
    path: 'setting',
    loadChildren: () => import('./pages/setting/setting.module').then( m => m.SettingPageModule)
  },
  {
    path: 'notification',
    loadChildren: () => import('./pages/notification/notification.module').then( m => m.NotificationPageModule)
  },
  {
    path: 'scanner',
    loadChildren: () => import('./pages/home/scanner/scanner.module').then( m => m.ScannerPageModule)
  },
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}
</code>```

tabs.page.ts part code

```<code>ngOnInit(): void {
    console.log('page load');
  }
</code>```

Sometimes the screen appears white on startup. But not every time.
Page load success, display 'page load' log.
Page white screen, Does not display 'page load' log. Please tell why tabs.Page.ts file were not load!
Who can help me! thank you very much.

答:
I once encountered this problem, this is how I fixed it:

update your platform-android version to 6.4.0

reinstall plugin cordova-plugin-webview

Body:
My development environment
click here

config.xml文件内容

<feature name="CDVWKWebViewEngine">
        <param name="ios-package" value="CDVWKWebViewEngine" />
    </feature>
    <preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />
    <preference name="DisallowOverscroll" value="true" />
    <preference name="AllowedSchemes" value="netspay" />
    <preference name="ScrollEnabled" value="false" />
    <preference name="android-minSdkVersion" value="19" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="ShowSplashScreen" value="true" />
    <preference name="SplashScreen" value="screen" />
    <preference name="SplashScreenDelay" value="3000" />
    <preference name="AutoHideSplashScreen" value="false" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <preference name="ShowSplashScreenSpinner" value="false" />
    <preference name="FadeSplashScreenDuration" value="1000" />
    <preference name="SplashShowOnlyFirstTime" value="false" />
    <preference name="Orientation" value="portrait" />

app.component.ts    file part function

initializeApp() {
    this.platform.ready().then(() => {
      // this.statusBar.styleDefault();
      this.statusBar.backgroundColorByHexString('#27507E');
      setTimeout(() => {
        this.splashScreen.hide();
      }, 2000);
    });
}

app-routing.module.ts config content

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
  },
  {
    path: 'products',
    loadChildren: () => import('./pages/products/products.module').then( m => m.ProductsPageModule)
  },
  {
    path: 'proDetail',
    loadChildren: () => import('./pages/proDetail/proDetail.module').then( m => m.ProDetailPageModule)
  },
  {
    path: 'cartPage',
    loadChildren: () => import('./pages/cartPage/cartPage.module').then( m => m.CartPageModule)
  },
  {
    path: 'orderDetail',
    loadChildren: () => import('./pages/orderDetail/orderDetail.module').then( m => m.OrderDetailPageModule)
  },
  {
    path: 'payment',
    loadChildren: () => import('./pages/payment/payment.module').then( m => m.PaymentPageModule)
  },
  {
    path: 'receipt',
    loadChildren: () => import('./pages/receipt/receipt.module').then( m => m.ReceiptPageModule)
  },
  {
    path: 'setting',
    loadChildren: () => import('./pages/setting/setting.module').then( m => m.SettingPageModule)
  },
  {
    path: 'notification',
    loadChildren: () => import('./pages/notification/notification.module').then( m => m.NotificationPageModule)
  },
  {
    path: 'scanner',
    loadChildren: () => import('./pages/home/scanner/scanner.module').then( m => m.ScannerPageModule)
  },
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}

tabs.page.ts part code

ngOnInit(): void {
    console.log('page load');
  }

Sometimes the screen appears white on startup. But not every time.
Page load success, display 'page load' log.
Page white screen, Does not display 'page load' log. Please tell why tabs.Page.ts file were not load!
Who can help me! thank you very much.


问:
Getting error while redeploying nodes
I am still using Corda 1.0 version. when i try to redeploy nodes with existing data, getting below error while start-up but able to access the nodes . If i clear the data and redeploy the nodes, i didn't face these error message.</p>

```<code>Logs can be found in                    :
C:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\kotlin-
source\build\nodes\xxxxxxxx\logs
Database connection url is              : jdbc:h2:tcp://xxxxxxxxx/node
E 18:38:46+0530 [main] core.client.createConnection - AMQ214016: Failed to
create netty connection
javax.net.ssl.SSLException: handshake timed out
at io.netty.handler.ssl.SslHandler.handshake(...)(Unknown Source) ~[netty
all-4.1.9.Final.jar:4.1.9.Final]
Incoming connection address             : xxxxxxxxxxxx
Listening on port                       : 10014
RPC service listening on port           : 10015
Loaded CorDapps                         : corda-finance-1.0.0, kotlin-
source-0.1, corda-core-1.0.0
Node for "xxxxxxxxxxx" started up and registered in 213.08 sec

Welcome to the Corda interactive shell.
Useful commands include 'help' to see what is available, and 'bye' to shut
down the node.

Wed May 23 18:39:20 IST 2018>>> E 18:39:24+0530 [Thread-6 (ActiveMQ-server-
org.apache.activemq.artemis.core.server.impl.ActiveMQServerImp
l$3@4a532271)] core.client.createConnection - AMQ214016: Failed to create
netty connection
javax.net.ssl.SSLException: handshake timed out
at io.netty.handler.ssl.SslHandler.handshake(...)(Unknown Source) ~[netty-
all-4.1.9.Final.jar:4.1.9.Final]
</code>```

答:
This looks like the Artemis failed to connect to the node which means the node fails to start.

You should look at the log and if there are any other previous Corda node started which occupy the node.

If there are any legacy Corda nodes that have not been killed, try ps -ef |grep java to see if there is any other java still alive. Especially look for the port number and check if they are overlapped

Title: Getting error while redeploying nodes

Body:
I am still using Corda 1.0 version. when i try to redeploy nodes with existing data, getting below error while start-up but able to access the nodes . If i clear the data and redeploy the nodes, i didn't face these error message.

Logs can be found in                    :
C:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\kotlin-
source\build\nodes\xxxxxxxx\logs
Database connection url is              : jdbc:h2:tcp://xxxxxxxxx/node
E 18:38:46+0530 [main] core.client.createConnection - AMQ214016: Failed to
create netty connection
javax.net.ssl.SSLException: handshake timed out
at io.netty.handler.ssl.SslHandler.handshake(...)(Unknown Source) ~[netty
all-4.1.9.Final.jar:4.1.9.Final]
Incoming connection address             : xxxxxxxxxxxx
Listening on port                       : 10014
RPC service listening on port           : 10015
Loaded CorDapps                         : corda-finance-1.0.0, kotlin-
source-0.1, corda-core-1.0.0
Node for "xxxxxxxxxxx" started up and registered in 213.08 sec

Welcome to the Corda interactive shell.
Useful commands include 'help' to see what is available, and 'bye' to shut
down the node.

Wed May 23 18:39:20 IST 2018>>> E 18:39:24+0530 [Thread-6 (ActiveMQ-server-
org.apache.activemq.artemis.core.server.impl.ActiveMQServerImp
l$3@4a532271)] core.client.createConnection - AMQ214016: Failed to create
netty connection
javax.net.ssl.SSLException: handshake timed out
at io.netty.handler.ssl.SslHandler.handshake(...)(Unknown Source) ~[netty-
all-4.1.9.Final.jar:4.1.9.Final]


问:
How can I stop Python from recognizing string literals such as "\n" or "\b"?
I am using an API to convert LaTeX to PNG format. The latex strings that I am converting are written in latex, .tex, and so they use phrases such as '\n'.

On example of a string that I have is

```<code>query = "$\displaystyle \binom n r = \dfrac{n!}{r!(n-r)!}$"
</code>```

However, Python recognizes the \b in \binom and thus the string is recognized as having a line break, even though all I want it to do is just recognize the individual characters.

If at all possible, I would like to not have to modify the string itself, as the string too is taken from an API. So is there any way to ignore these string literals such as '\b' or '\n'?

答:
I've updated my answer for clarity.

If the string comes directly from an API then it should already be in a raw format (or the rawest that will be accessible to you), such as r"$\displaystyle \binom n r = \dfrac{n!}{r!(n-r)!}$". Therefore, Python won't be assuming escaped characters and there shouldn't be an issue.

To answer your other question about raw strings - to print a string as a raw string in Python try the repr function, which returns a printable representational string of the given object.

```<code>query = "$\displaystyle \binom n r = \dfrac{n!}{r!(n-r)!}$"
print(repr(query))
</code>```

Here is the output:
'$\\displaystyle \x08inom n r = \\dfrac{n!}{r!(n-r)!}$'

Note that in the true raw data of query above, the \b character is still technically stored as the \b encoding (or \x08), not as two separate characters. Why isn't \d stored as an encoding, you may ask? Because \d is not a valid encoded escape sequence, so it is overlooked and Python treats the \ as a character. (Ahh... silently ignoring parsing errors, isn't this why we love Python?)

Then what about this example?

```<code>query = r"$\displaystyle \binom n r = \dfrac{n!}{r!(n-r)!}$"
print(repr(query))
</code>```

Looks good, but wait, Python prints '$\\displaystyle \\binom n r = \\dfrac{n!}{r!(n-r)!}$'.

Why the \\? Well, the repr function returns a printable representational string of the given object, so to avoid any confusion the \ character is properly escaped with \, creating \\.

All of that coming full circle and back to your question - if the value of a string comes directly from an API call, then the string data should already be translated from a binary encoding and things like escape sequences shouldn't be an issue (because the aren't in the raw data). But in the example you provided you declared a string in a query = "st\ring" format, which unfortunately isn't equivalent to retrieving a string from an API, and the obvious solution would be to use the query = r"st\ring" format.

Body:
I am using an API to convert LaTeX to PNG format. The latex strings that I am converting are written in latex, .tex, and so they use phrases such as '\n'.

On example of a string that I have is

query = "$\displaystyle \binom n r = \dfrac{n!}{r!(n-r)!}$"

However, Python recognizes the \b in \binom and thus the string is recognized as having a line break, even though all I want it to do is just recognize the individual characters.

If at all possible, I would like to not have to modify the string itself, as the string too is taken from an API. So is there any way to ignore these string literals such as '\b' or '\n'?

Body:
I've updated my answer for clarity.

If the string comes directly from an API then it should already be in a raw format (or the rawest that will be accessible to you), such as r"$\displaystyle \binom n r = \dfrac{n!}{r!(n-r)!}$". Therefore, Python won't be assuming escaped characters and there shouldn't be an issue.

To answer your other question about raw strings - to print a string as a raw string in Python try the repr function, which returns a printable representational string of the given object.

query = "$\displaystyle \binom n r = \dfrac{n!}{r!(n-r)!}$"
print(repr(query))

Here is the output:
'$\\displaystyle \x08inom n r = \\dfrac{n!}{r!(n-r)!}$'

Note that in the true raw data of query above, the \b character is still technically stored as the \b encoding (or \x08), not as two separate characters. Why isn't \d stored as an encoding, you may ask? Because \d is not a valid encoded escape sequence, so it is overlooked and Python treats the \ as a character. (Ahh... silently ignoring parsing errors, isn't this why we love Python?)

Then what about this example?

query = r"$\displaystyle \binom n r = \dfrac{n!}{r!(n-r)!}$"
print(repr(query))

Looks good, but wait, Python prints '$\\displaystyle \\binom n r = \\dfrac{n!}{r!(n-r)!}$'.

Why the \\? Well, the repr function returns a printable representational string of the given object, so to avoid any confusion the \ character is properly escaped with \, creating \\.

All of that coming full circle and back to your question - if the value of a string comes directly from an API call, then the string data should already be translated from a binary encoding and things like escape sequences shouldn't be an issue (because the aren't in the raw data). But in the example you provided you declared a string in a query = "st\ring" format, which unfortunately isn't equivalent to retrieving a string from an API, and the obvious solution would be to use the query = r"st\ring" format.


问:
Image vertically aligned in div
I'm trying to center this image vertically inside a div. As you can see I've accomplished that, however, it's still pushed slightly towards the bottom of the div. I can't find any reasons why this would be and I've even tried a different image.

HTML:

```<code><div class="site-header">
            <img class="logo" src="CGLOGO.png" alt="logo">
</div>
</code>```

My CSS:

```<code>html, body {
    margin: 0;
    background: #F7B267;
}
.site-header {
    background: #eee;
    color: #555;
    height: 3.125em;
    line-height: 3.125em;
    margin-bottom: 1rem;
}
.logo {
    max-height: 75%;
    vertical-align: middle;
  }
</code>```

Result:

答:
You can center it with flexbox:</p>

```<code>html, body {
    margin: 0;
    background: #F7B267;
}
.site-header {
    background: #eee;
    color: #555;
    height: 3.125em;
    line-height: 3.125em;
    display: flex;
}
.logo {
    display: block;
    max-height: 75%;
    margin: auto 0;
}
</code>```

Title: Image vertically aligned in div

Body:
I'm trying to center this image vertically inside a div. As you can see I've accomplished that, however, it's still pushed slightly towards the bottom of the div. I can't find any reasons why this would be and I've even tried a different image.

HTML:

My CSS:

html, body {
    margin: 0;
    background: #F7B267;
}
.site-header {
    background: #eee;
    color: #555;
    height: 3.125em;
    line-height: 3.125em;
    margin-bottom: 1rem;
}
.logo {
    max-height: 75%;
    vertical-align: middle;
  }

Result:

Body:
You can center it with flexbox:

html, body {
    margin: 0;
    background: #F7B267;
}
.site-header {
    background: #eee;
    color: #555;
    height: 3.125em;
    line-height: 3.125em;
    display: flex;
}
.logo {
    display: block;
    max-height: 75%;
    margin: auto 0;
}


问:
looking for Windows RAM-based shared memory solution in C++
I'm facing a situation where I need to pass up to several hundreds of megabytes of memory from one process to another. Right now I'm doing it via files and it's too slow.
I guess that to make it quicker, those files should be written directly to RAM and be accessible from another process. No fancy synchronization required. One process would create  shared memory objects and would fill them with data. The other process would read and remove them. However I've done a quick research and it seems like you can't share memory in RAM in Windows - the shared memory is backed by either a file or paging file. The docs of boost::interprocess confirm this. Where is the speed up then if the shared memory implementation still uses disk? Is there any C++ library that uses RAM-based shared memory?

EDIT: I made some further reading:
1. from boost::interprocess docs:
"as the operating system has to synchronize the file contents with the memory contents, memory-mapped files are not as fast as shared memory. "
2. from http://msdn.microsoft.com/en-us/library/ms810613.aspx:
"A memory-mapped file can also be mapped by more than one application simultaneously. This represents the only mechanism for two or more processes to directly share data in Windows NT."

答:
I think that here is a fundamental misunderstanding: you think that, if you create a file mapping backed by the paging file, it will be as slow as actually writing stuff on disk.

This is definitely not the case: the meaning of "backed by the paging file" in the documentation means that the shared memory in general resides in memory, but it has a reserved place in the paging file to write such data if there's not enough free physical memory and the virtual memory manager needs to swap out memory pages.

This is not really clear from the documentation but the File Mapping page on MSDN confirms:

[...] It is backed by the file on disk. This means that when the system swaps out pages of the file mapping object, any changes made to the file mapping object are written to the file. When the pages of the file mapping object are swapped back in, they are restored from the file.

Notice that this applies to shared memory backed by the paging file as well as memory backed by regular files (the VMM guarantees that the various views are kept coherent).

Incidentally, this is how "regular" (=virtual) memory in user processes works: every bit of allocated memory can be swapped out to the paging file if it's not currently used and the system need to use physical memory for other stuff (e.g. making memory pages that are used at the moment available to your/another application).


问:
Is promise.all used to de-capsulate promise value?
I'm trying to understand what Promise.all() is doing exactly.

As far as I understand,
promise is something which holds a return value for asynchronous execution in javascript.

So the values encapsulated(?) by promise is not directly accessible in sychronoous running.

(Terminology warning! I'm going to use analogy to show how I see promise and promise.all())

To get a direct access to the promisified values,
I need to peel off a shell called promise, which is
promise.all at the end of asynchronous function.

after this 'peeling-off', I could access to a synchronously available values.

Am I understanding Promise.all correctly?

Thank you so much.

Example is from mdn website.

```<code>const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values);
});
// expected output: Array [3, 42, "foo"]
</code>```

all the promises and just synchronous value (const promise2) were successfully approached by synchronous execution 'console.log()'.

If I don't peel off the promise shell like below,

```<code>Promise.all([promise2, promise3]).then((values) => {
  console.log(values);
  console.log(promise1)
});
</code>```

The values that js spits out are as below.

Array [42, "foo"]

[object Promise]

Please feel free to criticize my analogy and
let me know if I understand something wrong.

Thank you in advance.

答:
Your analogy is a very interesting one, but I'm sure it's a common perception of how Promises work. Promises are constructs that manage deffered values - values that will be at some stage, time-dependent. Using the term "wrapping" makes it sound like the value is already there, when in fact it most likely isn't.. yet.

A promise can be used to represent the response from an API, or perhaps a lookup from a database - both of these take time - something synchronous code can't handle. You might make a request, and get a promise in response. You can then use this promise as a helper to get the value you intended to receive.

When you call promise.then(value => ...), the then function is waiting until the value is ready. Inside the promise, something must call resolve(value) before the then function will fire (note that the promise can also be rejected via reject, in which case promise.catch would be fired). Here's a full example:

```<code>const promise = new Promise(resolve => {
  setTimeout(() => {
    resolve(10);
  }, 2000);
});

promise.then(value => {
  // This fires after about 2 seconds
  console.log(value); // 10
});
</code>```

So the trick here is to visualise that getting results from a promise occurs on a different "thread".. perhaps in a callback or after an await call. Also, once a promise has been resolved, calling then a second time will return the same value as previously, and it will be faster, but still not instant as promises "values" are always asynchronously returned.

Promise.all waits until all the provided promises have resolved. What is returned by Promise.all is an array containing all of the resolved results in order.  So if you have the following:

```<code>const promise1 = Promise.resolve(12); // Asynchronously returns 12
const promise2 = new Promise(resolve => {
  setTimeout(() => {
    resolve(10);
  }, 2000);
});

Promise.all([promise1, promise2]).then(results => {
 // results will be [12, 10], and will fire after about 2 seconds
});

// here, even though we're after the promise assignments,
// the values to BOTH of the promises are still not yet defined (not resolved)
</code>```

TLDR; A promise is a class that records a value once its provided function resolves. The then method will call its callback with the value once it is set by the promise function (by calling resolve or reject).

Body:
I'm trying to understand what Promise.all() is doing exactly.

As far as I understand,
promise is something which holds a return value for asynchronous execution in javascript.

So the values encapsulated(?) by promise is not directly accessible in sychronoous running.

(Terminology warning! I'm going to use analogy to show how I see promise and promise.all())

To get a direct access to the promisified values,
I need to peel off a shell called promise, which is
promise.all at the end of asynchronous function.

after this 'peeling-off', I could access to a synchronously available values.

Am I understanding Promise.all correctly?

Thank you so much.

Example is from mdn website.

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values);
});
// expected output: Array [3, 42, "foo"]

all the promises and just synchronous value (const promise2) were successfully approached by synchronous execution 'console.log()'.

If I don't peel off the promise shell like below,

Promise.all([promise2, promise3]).then((values) => {
  console.log(values);
  console.log(promise1)
});

The values that js spits out are as below.

Array [42, "foo"]

[object Promise]

Please feel free to criticize my analogy and
let me know if I understand something wrong.

Thank you in advance.

Body:
Your analogy is a very interesting one, but I'm sure it's a common perception of how Promises work. Promises are constructs that manage deffered values - values that will be at some stage, time-dependent. Using the term "wrapping" makes it sound like the value is already there, when in fact it most likely isn't.. yet.

A promise can be used to represent the response from an API, or perhaps a lookup from a database - both of these take time - something synchronous code can't handle. You might make a request, and get a promise in response. You can then use this promise as a helper to get the value you intended to receive.

When you call promise.then(value => ...), the then function is waiting until the value is ready. Inside the promise, something must call resolve(value) before the then function will fire (note that the promise can also be rejected via reject, in which case promise.catch would be fired). Here's a full example:

const promise = new Promise(resolve => {
  setTimeout(() => {
    resolve(10);
  }, 2000);
});

promise.then(value => {
  // This fires after about 2 seconds
  console.log(value); // 10
});

So the trick here is to visualise that getting results from a promise occurs on a different "thread".. perhaps in a callback or after an await call. Also, once a promise has been resolved, calling then a second time will return the same value as previously, and it will be faster, but still not instant as promises "values" are always asynchronously returned.

Promise.all waits until all the provided promises have resolved. What is returned by Promise.all is an array containing all of the resolved results in order.  So if you have the following:

const promise1 = Promise.resolve(12); // Asynchronously returns 12
const promise2 = new Promise(resolve => {
  setTimeout(() => {
    resolve(10);
  }, 2000);
});

Promise.all([promise1, promise2]).then(results => {
 // results will be [12, 10], and will fire after about 2 seconds
});

// here, even though we're after the promise assignments,
// the values to BOTH of the promises are still not yet defined (not resolved)

TLDR; A promise is a class that records a value once its provided function resolves. The then method will call its callback with the value once it is set by the promise function (by calling resolve or reject).


问:
Define a method in trait returning a default implementation of Self
I would like to have the following functionality

trait Policy {
    fn eval(&self, k: u32) -> bool;

    fn default() -> Box<dyn Policy>
    where
        Self: Sized,
    {
        Box::new(MaxPolicy { max: 2 })
    }
}

struct MaxPolicy {
    max: u32,
}

impl Policy for MaxPolicy {
    fn eval(&self, k: u32) -> bool {
        println!("MaxPolicy");
        k < self.max
    }
}

#[test]
fn max_policy() {
    let p = MaxPolicy { max: 2 };
    assert!(!p.eval(3));
}

#[test]
fn default_policy() {
    let p = Policy::default();
    assert!(!p.eval(3));
}
```

<p>(Playground) </p>

<p>This does not compile:</p>

<pre class="lang-none prettyprint-override"><code>error[E0283]: type annotations needed
  --> src/lib.rs:31:13
   |
4  |     fn default() -> Box<dyn Policy>
   |        -------
5  |     where
6  |         Self: Sized,
   |               ----- required by this bound in `Policy::default`
...
31 |     let p = Policy::default();
   |             ^^^^^^^^^^^^^^^ cannot infer type
   |
   = note: cannot resolve `_: Policy`
</code>```

Would it possible to alter the approach to make it work? Is this even possible for trait objects to have a method returning some implementation of Self? If not, why not?

答:
I constructed a workaround which has a similar nice API

trait Policy {
    fn eval(&self, k: u32) -> bool;
}

struct MaxPolicy {
    max: u32,
}

impl Policy for MaxPolicy {
    fn eval(&self, k: u32) -> bool {
        println!("MaxPolicy");
        k < self.max
    }
}

struct MinPolicy {
    min: u32,
}

impl Policy for MinPolicy {
    fn eval(&self, k: u32) -> bool {
        println!("MinPolicy");
        k > self.min
    }
}

enum PolicyEnum {
    Custom(Box<dyn Policy>),
    Default,
}

impl PolicyEnum {
    const DEFAULT: MaxPolicy = MaxPolicy { max: 4 };
}

impl Policy for PolicyEnum {
    fn eval(&self, k: u32) -> bool {
        match self {
            PolicyEnum::Custom(p) => p.eval(k),
            PolicyEnum::Default => Self::DEFAULT.eval(k),
        }
    }
}
```

<p>Playground</p>

<p>With that, it's possible to do:</p>

<pre class="lang-rust prettyprint-override"><code>#[test]
fn default() {
    let p = PolicyEnum::Default;

    assert!(p.eval(3));
}

#[test]
fn custom() {
    let p = PolicyEnum::Custom(Box::new(MinPolicy{min: 4}));

    assert!(p.eval(5));
}
</code>```

Body:
I would like to have the following functionality

trait Policy {
    fn eval(&self, k: u32) -> bool;

    fn default() -> Box<dyn Policy>
    where
        Self: Sized,
    {
        Box::new(MaxPolicy { max: 2 })
    }
}

struct MaxPolicy {
    max: u32,
}

impl Policy for MaxPolicy {
    fn eval(&self, k: u32) -> bool {
        println!("MaxPolicy");
        k < self.max
    }
}

#[test]
fn max_policy() {
    let p = MaxPolicy { max: 2 };
    assert!(!p.eval(3));
}

#[test]
fn default_policy() {
    let p = Policy::default();
    assert!(!p.eval(3));
}

(Playground)

This does not compile:

error[E0283]: type annotations needed
  --> src/lib.rs:31:13
   |
4  |     fn default() -> Box<dyn Policy>
   |        -------
5  |     where
6  |         Self: Sized,
   |               ----- required by this bound in `Policy::default`
...
31 |     let p = Policy::default();
   |             ^^^^^^^^^^^^^^^ cannot infer type
   |
   = note: cannot resolve `_: Policy`

Would it possible to alter the approach to make it work? Is this even possible for trait objects to have a method returning some implementation of Self? If not, why not?

Body:
I constructed a workaround which has a similar nice API

trait Policy {
    fn eval(&self, k: u32) -> bool;
}

struct MaxPolicy {
    max: u32,
}

impl Policy for MaxPolicy {
    fn eval(&self, k: u32) -> bool {
        println!("MaxPolicy");
        k < self.max
    }
}

struct MinPolicy {
    min: u32,
}

impl Policy for MinPolicy {
    fn eval(&self, k: u32) -> bool {
        println!("MinPolicy");
        k > self.min
    }
}

enum PolicyEnum {
    Custom(Box<dyn Policy>),
    Default,
}

impl PolicyEnum {
    const DEFAULT: MaxPolicy = MaxPolicy { max: 4 };
}

impl Policy for PolicyEnum {
    fn eval(&self, k: u32) -> bool {
        match self {
            PolicyEnum::Custom(p) => p.eval(k),
            PolicyEnum::Default => Self::DEFAULT.eval(k),
        }
    }
}

Playground

With that, it's possible to do:

#[test]
fn default() {
    let p = PolicyEnum::Default;

    assert!(p.eval(3));
}

#[test]
fn custom() {
    let p = PolicyEnum::Custom(Box::new(MinPolicy{min: 4}));

    assert!(p.eval(5));
}


问:
namespace altering the function definition
I have a small snipped of code, which just produces a function to get the current directory for either Windows or Linux platform:

```<code>#include <stdio.h>  /* defines FILENAME_MAX */
#include <string>
#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

    std::string getcwd(){
    char mCurrentPath[FILENAME_MAX];
    GetCurrentDir(mCurrentPath, sizeof(mCurrentPath));
    return *(new std::string (mCurrentPath));

    }
</code>```

This is all great and working; however, I'd like to make the getcwd() function inside the namespace, fUtils, hence I did this:

```<code>#include <stdio.h>  /* defines FILENAME_MAX */
#include <string>
#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

namespace fUtils{
    std::string getcwd(){
    char mCurrentPath[FILENAME_MAX];
    GetCurrentDir(mCurrentPath, sizeof(mCurrentPath));
    return *(new std::string (mCurrentPath));

    }
}
</code>```

But this gives an error in VSCode which says:

no matching function for call to 'getcwd'

What mistake am I making in this? If this isn't how I put the function to the namespace fUtils, then how should I put it into the namespace?

答:
Use of macros in such context is invitation to problems in future.

Just wrap those functions with own API and all problems will be resolved.

Header file:

#include <string>

namepsace fUtils {
std::string getcwd();
}
```

<p>Then you can have platform specific cpp files, Windows:</p>

<pre class="lang-cpp prettyprint-override"><code>namepsace fUtils {
std::string getcwd() {
    char mCurrentPath[FILENAME_MAX];
    ::_getcwd(mCurrentPath, sizeof(mCurrentPath));
    return {mCurrentPath};
}
}
</code>```

Mac version is obvious.

You also can use this macros inside single cpp file and this way contain them there if you do not what to do larger clean up.

Side notes:

there is boost::filesystem which has such api also use of boost::filesystem::path is quite handy

C++17 introduces std::filesystem, but it is not well supported yet (for example MacOS)

if you wrap this functionality in classes you will open your way for better testing (mocks).

Body:
I have a small snipped of code, which just produces a function to get the current directory for either Windows or Linux platform:

#include <stdio.h>  /* defines FILENAME_MAX */
#include <string>
#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

    std::string getcwd(){
    char mCurrentPath[FILENAME_MAX];
    GetCurrentDir(mCurrentPath, sizeof(mCurrentPath));
    return *(new std::string (mCurrentPath));

    }

This is all great and working; however, I'd like to make the getcwd() function inside the namespace, fUtils, hence I did this:

#include <stdio.h>  /* defines FILENAME_MAX */
#include <string>
#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

namespace fUtils{
    std::string getcwd(){
    char mCurrentPath[FILENAME_MAX];
    GetCurrentDir(mCurrentPath, sizeof(mCurrentPath));
    return *(new std::string (mCurrentPath));

    }
}

But this gives an error in VSCode which says:

no matching function for call to 'getcwd'

What mistake am I making in this? If this isn't how I put the function to the namespace fUtils, then how should I put it into the namespace?

Body:
Use of macros in such context is invitation to problems in future.

Just wrap those functions with own API and all problems will be resolved.

Header file:

#include <string>

namepsace fUtils {
std::string getcwd();
}

Then you can have platform specific cpp files, Windows:

namepsace fUtils {
std::string getcwd() {
    char mCurrentPath[FILENAME_MAX];
    ::_getcwd(mCurrentPath, sizeof(mCurrentPath));
    return {mCurrentPath};
}
}

Mac version is obvious.

You also can use this macros inside single cpp file and this way contain them there if you do not what to do larger clean up.

Side notes:

there is boost::filesystem which has such api also use of boost::filesystem::path is quite handy

C++17 introduces std::filesystem, but it is not well supported yet (for example MacOS)

if you wrap this functionality in classes you will open your way for better testing (mocks).


问:
Compiling C/GTK within Eclipse
I'm fiddling around with the C/C++ version of Eclipse to build a simple GTK app. However, I can't seem to be able to compile a GTK sample from within Eclipse. I can compile a simple Hello World style test app, so I know the tool chain itself is working. However, the moment I start adding GTK into the mix the compiler comes up with errors. The funny thing is that I can compile the examples outside the Eclipse environment just fine. E.g., I'm using the examples on this page and following the instructions given there let me build a working binary.

I think the first problem is that the main GTK include file is referenced differently when I try to compile within Eclipse. The non-Eclipse version I can compile with (as in the example):

```<code>#include <gtk/gtk.h>
</code>```

However, within Eclipse this doesn't work. I need to change it to:

```<code>#include <gtk-2.0/gtk/gtk.h>
</code>```

The include file can then be found but the compilation process then starts to throw errors about the GtkWidget type. E.g.:

```<code>#include <gtk-2.0/gtk/gtk.h>

int main( int argc, char *argv[] )
{
    GtkWidget *window;

    gtk_init (&argc, &argv);

    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_widget_show  (window);

    gtk_main ();

    return 0;
}
</code>```

Results in these errors:

```<code>make all
Building file: ../src/main.c
Invoking: GCC C Compiler
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/main.d" -MT"src/main.d" -o"src/main.o" "../src/main.c"
../src/main.c: In function ‘main’:
../src/main.c:7: error: ‘GtkWidget’ undeclared (first use in this function)
../src/main.c:7: error: (Each undeclared identifier is reported only once
../src/main.c:7: error: for each function it appears in.)
../src/main.c:7: error: ‘window’ undeclared (first use in this function)
../src/main.c:9: warning: implicit declaration of function ‘gtk_init’
../src/main.c:11: warning: implicit declaration of function ‘gtk_window_new’
../src/main.c:11: error: ‘GTK_WINDOW_TOPLEVEL’ undeclared (first use in this function)
../src/main.c:12: warning: implicit declaration of function ‘gtk_widget_show’
../src/main.c:14: warning: implicit declaration of function ‘gtk_main’
make: *** [src/main.o] Error 1
</code>```

Not sure how to go about this. Any assistance would be very much appreciated.

答:
A long waited relief considering the pkg-config support for Eclipse CDT is coming soon.

The support is under development and will be integrated to CDT around August or so.

The most important feature is that an easy to use user interface allows to select the required packages.

Project website:
http://code.google.com/p/pkg-config-support-for-eclipse-cdt/

Update:
Feel free to test the beta version:

http://marketplace.eclipse.org/content/pkg-config-support-eclipse-cdt

Feedback is appreciated!

ContentLicense: CC BY-SA 2.5

Title: Compiling C/GTK within Eclipse

Body:
I'm fiddling around with the C/C++ version of Eclipse to build a simple GTK app. However, I can't seem to be able to compile a GTK sample from within Eclipse. I can compile a simple Hello World style test app, so I know the tool chain itself is working. However, the moment I start adding GTK into the mix the compiler comes up with errors. The funny thing is that I can compile the examples outside the Eclipse environment just fine. E.g., I'm using the examples on this page and following the instructions given there let me build a working binary.

I think the first problem is that the main GTK include file is referenced differently when I try to compile within Eclipse. The non-Eclipse version I can compile with (as in the example):

#include <gtk/gtk.h>

However, within Eclipse this doesn't work. I need to change it to:

#include <gtk-2.0/gtk/gtk.h>

The include file can then be found but the compilation process then starts to throw errors about the GtkWidget type. E.g.:

#include <gtk-2.0/gtk/gtk.h>

int main( int argc, char *argv[] )
{
    GtkWidget *window;

    gtk_init (&argc, &argv);

    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_widget_show  (window);

    gtk_main ();

    return 0;
}

Results in these errors:

make all
Building file: ../src/main.c
Invoking: GCC C Compiler
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/main.d" -MT"src/main.d" -o"src/main.o" "../src/main.c"
../src/main.c: In function ‘main’:
../src/main.c:7: error: ‘GtkWidget’ undeclared (first use in this function)
../src/main.c:7: error: (Each undeclared identifier is reported only once
../src/main.c:7: error: for each function it appears in.)
../src/main.c:7: error: ‘window’ undeclared (first use in this function)
../src/main.c:9: warning: implicit declaration of function ‘gtk_init’
../src/main.c:11: warning: implicit declaration of function ‘gtk_window_new’
../src/main.c:11: error: ‘GTK_WINDOW_TOPLEVEL’ undeclared (first use in this function)
../src/main.c:12: warning: implicit declaration of function ‘gtk_widget_show’
../src/main.c:14: warning: implicit declaration of function ‘gtk_main’
make: *** [src/main.o] Error 1

Not sure how to go about this. Any assistance would be very much appreciated.


问:
React useState: pushing a sub-array into an array
Am using function based component and am having trouble in pushing a subarray into a useState array.
my code is shown below. There is an array called mode coming from the props which i need to append it as a sub array of more

```<code>const ViewCharts = (props) =>{

//other codes

let [more,setMore] = useState([])

useEffect(()=>{
        console.log(props.mode,' mode array')
        let temp = [...more,props.mode]
        console.log(temp, ': this will append to more')
        setMore(temp)
        setTimeout(()=>{
            console.log(more,'after setting')
        },2000)
},[//some value])

}
</code>```

when the props.mode has value ['top','bottom'] i expect more to have value of [['top','bottom']] and when next time if the props.mode is ['top'] i need more to have [['top','bottom'],['top']]. but this is what am getting when i run the above code.

["top"] mode array

["top"] : this will append to more"

[] : "after setting"

why the setMore is not adding array even when the temp is having the expected value.

答:
If I remember correctly the useState variable will change value in the next render when you set it. You are trying to read the new more value in the same render you've changed it (as you are reading it in the same effect you've set the value in), which will be [] the first time as that's how you initialised it.

Try creating a second useEffect with a more dependency to see if it gives you the value you want:

// You can also just console.log() before the return, needing no `useEffect` to see if the value indeed changed.
React.useEffect(() => {
  console.log('More: ', more);
}, [more]);
```

https://reactjs.org/docs/hooks-state.html#recap

Line 9: When the user clicks, we call setCount with a new value. React will then re-render the Example component, passing the new count value to it.

I would suggest reading the hooks API to better understand how they work.

Body:
Am using function based component and am having trouble in pushing a subarray into a useState array.
my code is shown below. There is an array called mode coming from the props which i need to append it as a sub array of more

const ViewCharts = (props) =>{

//other codes

let [more,setMore] = useState([])

useEffect(()=>{
        console.log(props.mode,' mode array')
        let temp = [...more,props.mode]
        console.log(temp, ': this will append to more')
        setMore(temp)
        setTimeout(()=>{
            console.log(more,'after setting')
        },2000)
},[//some value])

}

when the props.mode has value ['top','bottom'] i expect more to have value of [['top','bottom']] and when next time if the props.mode is ['top'] i need more to have [['top','bottom'],['top']]. but this is what am getting when i run the above code.

["top"] mode array

["top"] : this will append to more"

[] : "after setting"

why the setMore is not adding array even when the temp is having the expected value.

Body:
If I remember correctly the useState variable will change value in the next render when you set it. You are trying to read the new more value in the same render you've changed it (as you are reading it in the same effect you've set the value in), which will be [] the first time as that's how you initialised it.

Try creating a second useEffect with a more dependency to see if it gives you the value you want:

// You can also just console.log() before the return, needing no `useEffect` to see if the value indeed changed.
React.useEffect(() => {
  console.log('More: ', more);
}, [more]);

https://reactjs.org/docs/hooks-state.html#recap

Line 9: When the user clicks, we call setCount with a new value. React will then re-render the Example component, passing the new count value to it.

I would suggest reading the hooks API to better understand how they work.