问:
Append or remove data from JSON
The result i want to get:

```<code>[
{"id":1,"name":"example1","description":"An example"},
{"id":2, "name":"example2","description":"Just another example"},
... ]
</code>```

To add new data to JSON i tried this:

```<code>String jsonDataString = ALL MY JSON DATA HERE;
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("id", "3");
valuesObject.put("name", "example3");
valuesObject.put("description", "Yet another example");
list.put(valuesObject);
mainObject.accumulate("", list);
</code>```

But i don't get a proper result.

And how to remove a JSON data depend on the value of the ID ?

Thank's.

答:
To build a fresh JSONArray you can use below codes:

```<code>try {

    JSONArray jsonArray = new JSONArray();

    // Object 1
    JSONObject jsonObject1 = new JSONObject();
    jsonObject1.put("id", 1);
    jsonObject1.put("name", "example1");
    jsonObject1.put("description", "An example");

    // Object 2
    JSONObject jsonObject2 = new JSONObject();
    jsonObject2.put("id", 2);
    jsonObject2.put("name", "example2");
    jsonObject2.put("description", "Just another example");

    // Add Object 1 & 2 JSONArray
    jsonArray.put(jsonObject1);
    jsonArray.put(jsonObject2);

    Log.d("JSON", "JSON: " + jsonArray.toString());

} catch (final JSONException e) {
    Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
</code>```

OUTPUT:

```<code>D/JSON: JSON: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"}]
</code>```

To add new JSONObject into existing JSONArray you can use below codes:

```<code>// Your Existing JSONArray
// [{"id":1,"name":"example1","description":"An example"},
//  {"id":2, "name":"example2","description":"Just another example"}]

String jsonDataString = "[{\"id\":1,\"name\":\"example1\",\"description\":\"An example\"},{\"id\":2,\"name\":\"example2\",\"description\":\"Just another example\"}]";

try {

    JSONArray jsonArray = new JSONArray(jsonDataString);

    // Object 3
    JSONObject jsonObject3 = new JSONObject();
    jsonObject3.put("id", 3);
    jsonObject3.put("name", "example3");
    jsonObject3.put("description", "Third example");

    // Add Object 3 JSONArray
    jsonArray.put(jsonObject3);

    Log.d("JSON", "JSON: " + jsonArray.toString());

} catch (final JSONException e) {
    Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
</code>```

OUTPUT:

```<code>D/JSON: JSON: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"},{"id":3,"name":"example3","description":"Third example"}]
</code>```

To remove JSONObject from JSONArray you can use below codes:

```<code>// Your Existing JSONArray
// [{"id":1,"name":"example1","description":"An example"},
//  {"id":2,"name":"example2","description":"Just another example"},
//  {"id":3,"name":"example3","description":"Third example"}]

String jsonDataString = "[{\"id\":1,\"name\":\"example1\",\"description\":\"An example\"},{\"id\":2,\"name\":\"example2\",\"description\":\"Just another example\"},{\"id\":3,\"name\":\"example3\",\"description\":\"Third example\"}]";

try {

    JSONArray jsonArray = new JSONArray(jsonDataString);

    Log.d("JSON", "JSON before Remove: " + jsonArray.toString());

    // Remove Object id = 2
    int removeId = 2;

    for (int i = 0; i < jsonArray.length(); i++)
    {
        JSONObject object = jsonArray.getJSONObject(i);

        if (object.has("id") && !object.isNull("id")) {

            int id = object.getInt("id");

            if (id == removeId)
            {
                jsonArray.remove(i);
                break;
            }
        }
    }

    Log.d("JSON", "JSON After Remove: " + jsonArray.toString());

} catch (final JSONException e) {
    Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
</code>```

OUTPUT:

```<code>D/JSON: JSON Before Remove: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"},{"id":3,"name":"example3","description":"Third example"}]

D/JSON: JSON After Remove: [{"id":1,"name":"example1","description":"An example"},{"id":3,"name":"example3","description":"Third example"}]
</code>```

Hope this will help you.

Title: Append or remove data from JSON

Body:
The result i want to get:

[
{"id":1,"name":"example1","description":"An example"},
{"id":2, "name":"example2","description":"Just another example"},
... ]

To add new data to JSON i tried this:

String jsonDataString = ALL MY JSON DATA HERE;
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("id", "3");
valuesObject.put("name", "example3");
valuesObject.put("description", "Yet another example");
list.put(valuesObject);
mainObject.accumulate("", list);

But i don't get a proper result.

And how to remove a JSON data depend on the value of the ID ?

Thank's.

Body:
To build a fresh JSONArray you can use below codes:

try {

    JSONArray jsonArray = new JSONArray();

    // Object 1
    JSONObject jsonObject1 = new JSONObject();
    jsonObject1.put("id", 1);
    jsonObject1.put("name", "example1");
    jsonObject1.put("description", "An example");

    // Object 2
    JSONObject jsonObject2 = new JSONObject();
    jsonObject2.put("id", 2);
    jsonObject2.put("name", "example2");
    jsonObject2.put("description", "Just another example");

    // Add Object 1 & 2 JSONArray
    jsonArray.put(jsonObject1);
    jsonArray.put(jsonObject2);

    Log.d("JSON", "JSON: " + jsonArray.toString());

} catch (final JSONException e) {
    Log.e("FAILED", "Json parsing error: " + e.getMessage());
}

OUTPUT:

D/JSON: JSON: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"}]

To add new JSONObject into existing JSONArray you can use below codes:

// Your Existing JSONArray
// [{"id":1,"name":"example1","description":"An example"},
//  {"id":2, "name":"example2","description":"Just another example"}]

String jsonDataString = "[{\"id\":1,\"name\":\"example1\",\"description\":\"An example\"},{\"id\":2,\"name\":\"example2\",\"description\":\"Just another example\"}]";

try {

    JSONArray jsonArray = new JSONArray(jsonDataString);

    // Object 3
    JSONObject jsonObject3 = new JSONObject();
    jsonObject3.put("id", 3);
    jsonObject3.put("name", "example3");
    jsonObject3.put("description", "Third example");

    // Add Object 3 JSONArray
    jsonArray.put(jsonObject3);

    Log.d("JSON", "JSON: " + jsonArray.toString());

} catch (final JSONException e) {
    Log.e("FAILED", "Json parsing error: " + e.getMessage());
}

OUTPUT:

D/JSON: JSON: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"},{"id":3,"name":"example3","description":"Third example"}]

To remove JSONObject from JSONArray you can use below codes:

// Your Existing JSONArray
// [{"id":1,"name":"example1","description":"An example"},
//  {"id":2,"name":"example2","description":"Just another example"},
//  {"id":3,"name":"example3","description":"Third example"}]

String jsonDataString = "[{\"id\":1,\"name\":\"example1\",\"description\":\"An example\"},{\"id\":2,\"name\":\"example2\",\"description\":\"Just another example\"},{\"id\":3,\"name\":\"example3\",\"description\":\"Third example\"}]";

try {

    JSONArray jsonArray = new JSONArray(jsonDataString);

    Log.d("JSON", "JSON before Remove: " + jsonArray.toString());

    // Remove Object id = 2
    int removeId = 2;

    for (int i = 0; i < jsonArray.length(); i++)
    {
        JSONObject object = jsonArray.getJSONObject(i);

        if (object.has("id") && !object.isNull("id")) {

            int id = object.getInt("id");

            if (id == removeId)
            {
                jsonArray.remove(i);
                break;
            }
        }
    }

    Log.d("JSON", "JSON After Remove: " + jsonArray.toString());

} catch (final JSONException e) {
    Log.e("FAILED", "Json parsing error: " + e.getMessage());
}

OUTPUT:

D/JSON: JSON Before Remove: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"},{"id":3,"name":"example3","description":"Third example"}]

D/JSON: JSON After Remove: [{"id":1,"name":"example1","description":"An example"},{"id":3,"name":"example3","description":"Third example"}]

Hope this will help you.


来源: stackexchange

问:
How does cardIO create the extra activity or View?
The basic app that uses card.IO has only one activity, the MainActivity.
When a specific button is clicked, that button calls another activity that does not have a java file or XML file in android studio but is only specified in the manifest like this:
I have noticed other apps using this method of creating new activities but I have not figured out how such activities get created. Does anyone know how they are created?
Here is the gitHub link.
as you can see there is only one java file and XML layout file for the MainActivity. However once the button is clicked, this starts a new activity requiring the entry of card details. This other activity is only specified in the manifest.

答:
The dependency is pulled in from the gradle build file which then downloads the card.io library. The library is where you can find all the activities here that are not found in the linked project.

Gradle is a build tool that android uses to help organize all the tasks associated with building an app.

ContentLicense: CC BY-SA 3.0


问:
Trigger in mysql causing error
What is the error in the following code. I am executing in mysql

```<code>CREATE TRIGGER tg_order_insert
BEFORE INSERT
    ON `order` FOR EACH ROW
BEGIN
    INSERT INTO `grocery`.`order_seqid` VALUE(NULL);
    SET NEW.order_id = CONCAT('#GNC', LPAD(LAST_INSERT_ID(),3,'0'));
END;
</code>```

Grocery is the database and order_seqid and order are 2 table.
order_seqid is a table with only 1 attribute if type int and auto increment.

Am trying to put a prefix on the id which we insert into order table.
I am getting 2 errors in INSERT INTO..... and END; line

答:
Did you declare a delimiter before your trigger definition? Something like

```<code>DELIMITER //
CREATE TRIGGER tg_order_insert
BEFORE INSERT
    ON `order` FOR EACH ROW
BEGIN
    INSERT INTO `grocery`.`order_seqid` VALUE(NULL);
    SET NEW.order_id = CONCAT('#GNC', LPAD(LAST_INSERT_ID(),3,'0'));
END
//
</code>```

Because if you don't, then MySQL thinks you're trying to end your trigger definition when it sees that first ; and calls syntax error.

Title: Trigger in mysql causing error

Body:
What is the error in the following code. I am executing in mysql

CREATE TRIGGER tg_order_insert
BEFORE INSERT
    ON `order` FOR EACH ROW
BEGIN
    INSERT INTO `grocery`.`order_seqid` VALUE(NULL);
    SET NEW.order_id = CONCAT('#GNC', LPAD(LAST_INSERT_ID(),3,'0'));
END;

Grocery is the database and order_seqid and order are 2 table.
order_seqid is a table with only 1 attribute if type int and auto increment.

Am trying to put a prefix on the id which we insert into order table.
I am getting 2 errors in INSERT INTO..... and END; line

Body:
Did you declare a delimiter before your trigger definition? Something like

DELIMITER //
CREATE TRIGGER tg_order_insert
BEFORE INSERT
    ON `order` FOR EACH ROW
BEGIN
    INSERT INTO `grocery`.`order_seqid` VALUE(NULL);
    SET NEW.order_id = CONCAT('#GNC', LPAD(LAST_INSERT_ID(),3,'0'));
END
//

Because if you don't, then MySQL thinks you're trying to end your trigger definition when it sees that first ; and calls syntax error.


问:
Docker for Mac and VMWare Fusion
So I have Docker for Mac installed and I would like to use VMWare Fusion rather than VirtualBox. Doing a search, I came across https://docs.docker.com/machine/drivers/vm-fusion/ using docker-machine. Not sure if that's what I'm looking for but when the Docker app starts I can see that the VMWare Fusion machine is suspended. Is there additional setup required to get new containers to run off of VMWare Fusion rather than VirtualBox?

答:
Docker for Mac actually uses a native virtual machine implementation called xhyve based on the OSX Hypervisor.framework. Docker for Windows uses HyperV in a similar fashion.

Using a native VM implementation allows for tighter integration into the Docker app, rather than doing everything via Virtualbox's VBoxManage command as with the original boot2docker image and Docker Toolbox setup.

Title: Docker for Mac and VMWare Fusion


问:
Pandas can't add column at index 0
I have a Pandas dataframe that has 2 columns after transposing.  If I export to Excel, the first column comes in with formatting which cannot be controlled by xlsxwriter (all the other columns can be formatted).  If I attempt to insert a new column in the Pandas dataframe at Index 0, it comes in at Index 1.  Why is this first dataframe column unalterable in Pandas and not able to be formatted by xlsxwriter?

Here is my original code:

```<code>data_xls = pandas.read_excel(excelPath, "FlowTimes", index_col=None)

del data_xls['OBJECTID'] #Remove OBJECTID column
del data_xls['Shape_Length'] #Remove the Shape_Length column
data_xls.drop(data_xls.columns[0], axis =1) #Remove nameless first column

decimals = pandas.Series([0,2,0,2,0,2,0,2], index=['Length FT', 'Length MI','Flow Minutes - Mean Annual','Flow Hours - Mean Annual')
data_xls2 = data_xls.round(decimals)

data_export = data_xls2.transpose() #Transpose columns to rows
data_export.reset_index()
data_export.insert(0,"Temp", None)  #THIS IS A TESTING LINE TO SEE WHERE THE COLUMN INSERTS - IT SHOULD INSERT AS THE FIRST COLUMN AT INDEX 0

print data_export
os.remove(excelPath)

writer = pandas.ExcelWriter(excelPath + "x")
data_export.to_excel(writer, sheet_name = 'FlowTimes', startcol = 0, startrow = 0, header=False) #header = false removes the 0 index in the first row
workbook = writer.book
worksheet = writer.sheets['FlowTimes']
format1 = workbook.add_format()
format1.set_align('right')
format1.set_border(0)

format2 = workbook.add_format()
format2.set_bold()

worksheet.set_column("A:A", 30, format1)
worksheet.set_column("B:Z", 12, format1)
worksheet.set_row(0,None, format2)

writer.save()
</code>```

If I don't include the data_export.insert column for testing, the output looks like this:

```<code>                                    0
Key Strategy Location       Location A
Length FT                         3551
Length MI                         0.67
Flow Minutes - Mean Annual          35
Flow Hours - Mean Annual          0.58
</code>```

But if I include the data_export.insert column at index 0, it inserts after the first column like this:

```<code>                           Temp           0
Key Strategy Location       None  Location A
Length FT                   None        3551
Length MI                   None        0.67
Flow Minutes - Mean Annual  None          35
Flow Hours - Mean Annual    None        0.58
</code>```

How can I either insert a new column at index 0 or control formatting of the first column while exporting with xlsxwriter?

答:
It turns out that xlsxwriter imports the pandas index (row names) with formatting that cannot be altered. I worked around this by copying the index to the first column, then exporting to Excel without header or index. The xlsxwriter formatting for all columns and rows works now.  Here is the working code:</p>

```<code>data_xls = pandas.read_excel(excelPath, "FlowTimes" + gdbNum, index_col=None)
del data_xls['OBJECTID'] #Remove OBJECTID column
del data_xls['Shape_Length'] #Remove the Shape_Length column
data_xls.drop(data_xls.columns[0], axis =1) #Remove nameless first column

decimals = pandas.Series([0,2,0,2,0,2,0,2], index=['Length FT', 'Length MI','Flow Minutes - Mean Annual','Flow Hours - Mean Annual')

data_export = data_xls2.transpose() #Transpose columns to rows
data_export.reset_index()
data_export.columns = data_export.iloc[0]
data_export['Key Strategy Location'] = data_export.index #adds index names (row names) as last column

cols = data_export.columns.tolist() #Create list of columns
cols.insert(0, cols.pop(-1)) #Move column with index names (row names) to be the first column
data_export = data_export[cols]

os.remove(excelPath)

writer = pandas.ExcelWriter(excelPath + "x")
data_export.to_excel(writer, sheet_name = 'FlowTimes', startcol = 0, startrow = 0, header=False, index=False) #header = false removes index in the first row, index=false removes first column
workbook = writer.book
worksheet = writer.sheets['FlowTimes']
format1 = workbook.add_format()
format1.set_align('right')
format1.set_border(0)

format2 = workbook.add_format()
format2.set_bold()
format2.set_align('center')

worksheet.set_column("B:Z", 20, format1)
worksheet.set_row(0,None, format2)
worksheet.set_column("A:A", 30, format1)

writer.save()
</code>```

Title: Pandas can't add column at index 0

Body:
I have a Pandas dataframe that has 2 columns after transposing.  If I export to Excel, the first column comes in with formatting which cannot be controlled by xlsxwriter (all the other columns can be formatted).  If I attempt to insert a new column in the Pandas dataframe at Index 0, it comes in at Index 1.  Why is this first dataframe column unalterable in Pandas and not able to be formatted by xlsxwriter?

Here is my original code:

data_xls = pandas.read_excel(excelPath, "FlowTimes", index_col=None)

del data_xls['OBJECTID'] #Remove OBJECTID column
del data_xls['Shape_Length'] #Remove the Shape_Length column
data_xls.drop(data_xls.columns[0], axis =1) #Remove nameless first column

decimals = pandas.Series([0,2,0,2,0,2,0,2], index=['Length FT', 'Length MI','Flow Minutes - Mean Annual','Flow Hours - Mean Annual')
data_xls2 = data_xls.round(decimals)

data_export = data_xls2.transpose() #Transpose columns to rows
data_export.reset_index()
data_export.insert(0,"Temp", None)  #THIS IS A TESTING LINE TO SEE WHERE THE COLUMN INSERTS - IT SHOULD INSERT AS THE FIRST COLUMN AT INDEX 0

print data_export
os.remove(excelPath)

writer = pandas.ExcelWriter(excelPath + "x")
data_export.to_excel(writer, sheet_name = 'FlowTimes', startcol = 0, startrow = 0, header=False) #header = false removes the 0 index in the first row
workbook = writer.book
worksheet = writer.sheets['FlowTimes']
format1 = workbook.add_format()
format1.set_align('right')
format1.set_border(0)

format2 = workbook.add_format()
format2.set_bold()

worksheet.set_column("A:A", 30, format1)
worksheet.set_column("B:Z", 12, format1)
worksheet.set_row(0,None, format2)

writer.save()

If I don't include the data_export.insert column for testing, the output looks like this:

                                    0
Key Strategy Location       Location A
Length FT                         3551
Length MI                         0.67
Flow Minutes - Mean Annual          35
Flow Hours - Mean Annual          0.58

But if I include the data_export.insert column at index 0, it inserts after the first column like this:

                           Temp           0
Key Strategy Location       None  Location A
Length FT                   None        3551
Length MI                   None        0.67
Flow Minutes - Mean Annual  None          35
Flow Hours - Mean Annual    None        0.58

How can I either insert a new column at index 0 or control formatting of the first column while exporting with xlsxwriter?

Body:
It turns out that xlsxwriter imports the pandas index (row names) with formatting that cannot be altered. I worked around this by copying the index to the first column, then exporting to Excel without header or index. The xlsxwriter formatting for all columns and rows works now.  Here is the working code:

data_xls = pandas.read_excel(excelPath, "FlowTimes" + gdbNum, index_col=None)
del data_xls['OBJECTID'] #Remove OBJECTID column
del data_xls['Shape_Length'] #Remove the Shape_Length column
data_xls.drop(data_xls.columns[0], axis =1) #Remove nameless first column

decimals = pandas.Series([0,2,0,2,0,2,0,2], index=['Length FT', 'Length MI','Flow Minutes - Mean Annual','Flow Hours - Mean Annual')

data_export = data_xls2.transpose() #Transpose columns to rows
data_export.reset_index()
data_export.columns = data_export.iloc[0]
data_export['Key Strategy Location'] = data_export.index #adds index names (row names) as last column

cols = data_export.columns.tolist() #Create list of columns
cols.insert(0, cols.pop(-1)) #Move column with index names (row names) to be the first column
data_export = data_export[cols]

os.remove(excelPath)

writer = pandas.ExcelWriter(excelPath + "x")
data_export.to_excel(writer, sheet_name = 'FlowTimes', startcol = 0, startrow = 0, header=False, index=False) #header = false removes index in the first row, index=false removes first column
workbook = writer.book
worksheet = writer.sheets['FlowTimes']
format1 = workbook.add_format()
format1.set_align('right')
format1.set_border(0)

format2 = workbook.add_format()
format2.set_bold()
format2.set_align('center')

worksheet.set_column("B:Z", 20, format1)
worksheet.set_row(0,None, format2)
worksheet.set_column("A:A", 30, format1)

writer.save()


问:
Can I use one data type to define multiple functions in C?
Example:

```<code>void WriteNos(), ConvertDecInt2Binary(), ConvertDecimal2Binary(), ReadNos(),
ConvertBinary2DecInt(), ConvertDecFloat2Binary();
</code>```

or do I need to place void before  each function? This is basic C only question.

答:
Because declarations have this grammar:

```<code>declaration:
                 declaration-specifiers init-declarator-listopt ;
                 static_assert-declaration
          declaration-specifiers:
                 storage-class-specifier declaration-specifiersopt
                 type-specifier declaration-specifiersopt
                 type-qualifier declaration-specifiersopt
                 function-specifier declaration-specifiersopt
                 alignment-specifier declaration-specifiersopt
          init-declarator-list:
                  init-declarator
                  init-declarator-list , init-declarator
          init-declarator:
                  declarator
                  declarator = initializer
</code>```

you can do it with declarations, but not with function definitions.

Example:

```<code>#include <stdio.h>
//declarations
void a(void), b(void); /*OK*/

#if 0
void a() { puts("a"); }, b() { puts("b"); } /*NOPE*/
#else
//definitions
void a() { puts("a"); }
void b() { puts("b"); }
#endif
</code>```

Body:
Example:

void WriteNos(), ConvertDecInt2Binary(), ConvertDecimal2Binary(), ReadNos(),
ConvertBinary2DecInt(), ConvertDecFloat2Binary();

or do I need to place void before  each function? This is basic C only question.

Body:
Because declarations have this grammar:

declaration:
                 declaration-specifiers init-declarator-listopt ;
                 static_assert-declaration
          declaration-specifiers:
                 storage-class-specifier declaration-specifiersopt
                 type-specifier declaration-specifiersopt
                 type-qualifier declaration-specifiersopt
                 function-specifier declaration-specifiersopt
                 alignment-specifier declaration-specifiersopt
          init-declarator-list:
                  init-declarator
                  init-declarator-list , init-declarator
          init-declarator:
                  declarator
                  declarator = initializer

you can do it with declarations, but not with function definitions.

Example:

#include <stdio.h>
//declarations
void a(void), b(void); /*OK*/

#if 0
void a() { puts("a"); }, b() { puts("b"); } /*NOPE*/
#else
//definitions
void a() { puts("a"); }
void b() { puts("b"); }
#endif


问:
How do I get same result without using enumerate?
I do not need char in this example, but I include it to get my desired results.

```<code>charlist = [strval[0:count+1] for count, char in enumerate(strval)]
</code>```

How do I get the same result without using enumerate?

答:
How about replacing enumerate(...) with zip(xrange(...),...)?

```<code>[strval[0:count+1] for count, char in zip(xrange(len(strval)),strval)]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I do not need char in this example, but I include it to get my desired results.

charlist = [strval[0:count+1] for count, char in enumerate(strval)]

How do I get the same result without using enumerate?

Body:
How about replacing enumerate(...) with zip(xrange(...),...)?

[strval[0:count+1] for count, char in zip(xrange(len(strval)),strval)]


问:
What does git-rm mean by working tree and index?
The documentation for git-rm contains this short description:

git-rm - Remove files from the working tree and from the index

What exactly is meant by the working tree and the index, and which local or remote files will be removed?

答:
The "working tree" is your checkout of the files sitting on disk.

The "index", "staging area", or "cache" (you'll see it referred to as all three) is internal to Git. It's the space you prepare the next commit. When you git add you're copying the files from the working tree to the staging area. When you git commit you're committing what's in the staging area.

git rm removes files from both the working tree and the staging area (unless you tell it to just remove from the staging area with --cached).

This cheat sheet might help you understand the relationship between the working tree, staging area, and HEAD (the currently checked out commit). More importantly, it tells you how to manipulate them because the commands are really not-intuitive.


问:
Bootstrap 3: opened navbar's content can't scroll on mobile
I need to work with Bootstrap 3's navbar, but it seems to be a little buggy. On my Lumia 820 I checked out the default navbar but I can't scroll the content of the menu inside the navbar. Instead of the menu I can scroll the body behind the menu.
On desktop I can scroll the menu's content well with overflow:auto CSS but on my mobile I can't scroll nor auto nor hidden.. Any idea?

Image here: http://i.stack.imgur.com/8lxXj.png

答:
You can fix it just using below jQuery code:

$(".navbar-collapse").css({ maxHeight: $(window).height() - $(".navbar-header").height() + "px" });


问:
Alternative of NOT EXISTS in MySQL as query is taking time to execute with NOT EXISTS
Dummy table:

```<code>id   FileName    DateLastSaved
1    Marium.doc    2015-01-01
2    Amna.doc      2016-01-01
3    Marium.doc    2016-01-01
</code>```

I want the query to return such rows where FileName is unique in the whole table. Rows should be returned for particular date range.
Suppose date ranges are of 2016 only, so third row should not be returned as FileName is not unique.

The query that I have created is:

```<code>$presentquery="SELECT * FROM InitialLog i WHERE MDid='$MDid' AND
(DateLastSaved>='$firstdate' AND DateLastSaved<='$presentdate') AND NOT
 EXISTS (SELECT id FROM InitialLog i2  WHERE i2.id<i.id AND i.FileName=i2.FileName )";
</code>```

(Where $firstdate and $presentdate are 2 dates for date ranges)

The query is returning the accurate results but it's taking time to execute. Is there any other way that I can rewrite this query??

(I have table with many rows)

答:
It looks like you are trying to get the data associated with the first occurrence of each file name, this should work:

```<code>SELECT *
FROM InitialLog i
WHERE MDid='$MDid'
   AND DateLastSaved>='$firstdate'
   AND DateLastSaved<='$presentdate'
   AND id IN (SELECT MIN(id) FROM InitialLog GROUP BY FileName)
;
</code>```

Alternatively, you can do a JOIN with the same subquery instead:

```<code>SELECT i.*
FROM InitialLog AS i
   INNER JOIN (SELECT MIN(id) AS id
               FROM InitialLog
               GROUP BY FileName
   ) AS firsts USING (id)
WHERE i.MDid='$MDid'
   AND i.DateLastSaved>='$firstdate'
   AND i.DateLastSaved<='$presentdate'
;
</code>```

Body:
Dummy table:

id   FileName    DateLastSaved
1    Marium.doc    2015-01-01
2    Amna.doc      2016-01-01
3    Marium.doc    2016-01-01

I want the query to return such rows where FileName is unique in the whole table. Rows should be returned for particular date range.
Suppose date ranges are of 2016 only, so third row should not be returned as FileName is not unique.

The query that I have created is:

$presentquery="SELECT * FROM InitialLog i WHERE MDid='$MDid' AND
(DateLastSaved>='$firstdate' AND DateLastSaved<='$presentdate') AND NOT
 EXISTS (SELECT id FROM InitialLog i2  WHERE i2.id<i.id AND i.FileName=i2.FileName )";

(Where $firstdate and $presentdate are 2 dates for date ranges)

The query is returning the accurate results but it's taking time to execute. Is there any other way that I can rewrite this query??

(I have table with many rows)

Body:
It looks like you are trying to get the data associated with the first occurrence of each file name, this should work:

SELECT *
FROM InitialLog i
WHERE MDid='$MDid'
   AND DateLastSaved>='$firstdate'
   AND DateLastSaved<='$presentdate'
   AND id IN (SELECT MIN(id) FROM InitialLog GROUP BY FileName)
;

Alternatively, you can do a JOIN with the same subquery instead:

SELECT i.*
FROM InitialLog AS i
   INNER JOIN (SELECT MIN(id) AS id
               FROM InitialLog
               GROUP BY FileName
   ) AS firsts USING (id)
WHERE i.MDid='$MDid'
   AND i.DateLastSaved>='$firstdate'
   AND i.DateLastSaved<='$presentdate'
;


问:
Umbraco 7.5.1 umbracoNaviHide
To be able to filter out items that should not be rendered with .Where("Visible") I need a property called umbracoNaviHide that returns true or false.

In earlier versions this was added to the Generic tab. However now you cant append to that tab anymore.

How would I accomplish hiding pages now?

Here's my foreach:

```<code> @foreach (var Area in Model.Content.Children.Where("Visible"))
 {
</code>```

Here's a statement about it. But I cant find any workaround.

Related Changes Summary - 7.4 beta - Option toCannot add properties to the "Generic properties" tab

Description - In the 7.4 beta it's not possible anymore to add
  properties to the "Generic properties" tab. I know this has been done
  because properties can be a bit hidden on that tab and usually are
  better on a separate tab. But there are situations where the
  properties are better on that tab.

答:
You can create a composition for node visibility with a checkbox to show or hide the menu item. And you can inherit this to the doc types that you do not want to show.

And then you can do

```<code>_homeNode.Children.Where(x => !x.GetPropertyValue<bool>("hideInNavigation"));
</code>```

Hope this helps!

Title: Umbraco 7.5.1 umbracoNaviHide

Body:
To be able to filter out items that should not be rendered with .Where("Visible") I need a property called umbracoNaviHide that returns true or false.

In earlier versions this was added to the Generic tab. However now you cant append to that tab anymore.

How would I accomplish hiding pages now?

Here's my foreach:

 @foreach (var Area in Model.Content.Children.Where("Visible"))
 {

Here's a statement about it. But I cant find any workaround.

Related Changes Summary - 7.4 beta - Option toCannot add properties to the "Generic properties" tab

Description - In the 7.4 beta it's not possible anymore to add
  properties to the "Generic properties" tab. I know this has been done
  because properties can be a bit hidden on that tab and usually are
  better on a separate tab. But there are situations where the
  properties are better on that tab.

Body:
You can create a composition for node visibility with a checkbox to show or hide the menu item. And you can inherit this to the doc types that you do not want to show.

And then you can do

_homeNode.Children.Where(x => !x.GetPropertyValue<bool>("hideInNavigation"));

Hope this helps!


问:
PHP function - custom string length function
In php what is a function to only display strings that have a length greater than 50 characters, truncate it to not display more than 130 characters and limit it to one result?

so for example say i have 30 rows in a result set but I only want to show the newest row that have these parameters. If the newest row has 25 characters it should not display. It should only display the newest one that has a string length of 50 or more characters.

答:
Use an SQL query.  For finding the newest you want max on either an auto_increment primary key (ill call it id) or a date/time when the row was created (say, time time_created).

So I am assuming table with:   id (int), stringVal (string, char(), varchar(), whatever)

```<code>SELECT MAX(id),  SUBSTRING(stringVal, 1, 130)
FROM yourTable
WHERE LENGTH(stringVal) > 30
</code>```

Replace id with a time field if you have to.  You're going to have a hard time finding the newest without one of them, but you can always arbitrarily pick one row.

--Edit-- a sample of using mysql functions in PHP to run above query and fetch desired output

```<code>$sql = "SELECT MAX(id),  SUBSTRING(stringVal, 1, 130) FROM yourTable WHERE LENGTH(stringVal) > 30";
$r = mysql_query($sql, $conn); //im hoping $conn or something like it is already set up
$row = mysql_fetch_assoc($r);
$desiredString = $row['stringVal'];
</code>```

Body:
Use an SQL query.  For finding the newest you want max on either an auto_increment primary key (ill call it id) or a date/time when the row was created (say, time time_created).

So I am assuming table with:   id (int), stringVal (string, char(), varchar(), whatever)

SELECT MAX(id),  SUBSTRING(stringVal, 1, 130)
FROM yourTable
WHERE LENGTH(stringVal) > 30

Replace id with a time field if you have to.  You're going to have a hard time finding the newest without one of them, but you can always arbitrarily pick one row.

--Edit-- a sample of using mysql functions in PHP to run above query and fetch desired output

$sql = "SELECT MAX(id),  SUBSTRING(stringVal, 1, 130) FROM yourTable WHERE LENGTH(stringVal) > 30";
$r = mysql_query($sql, $conn); //im hoping $conn or something like it is already set up
$row = mysql_fetch_assoc($r);
$desiredString = $row['stringVal'];


问:
IPython console can't locate "backports.shutil_get_terminal_size" and won't load
I'm running Python2.7 on windows 10 doing env and most pkg management with Anaconda. After upgrading a number of packages, my ipython console now fails to start in any IDE or at the console. When I attempt to run it at the console I get this error:

```<code>Traceback (most recent call last):
File "C:\Anaconda3\Scripts\ipython-script.py", line 3, in <module>
import IPython
File "C:\Anaconda3\lib\site-packages\IPython\__init__.py", line 48, in  <module>
from .core.application import Application
File "C:\Anaconda3\lib\site-packages\IPython\core\application.py", line 24, in <module>
from IPython.core import release, crashhandler
File "C:\Anaconda3\lib\site-packages\IPython\core\crashhandler.py", line 28, in <module>
from IPython.core import ultratb
File "C:\Anaconda3\lib\site-packages\IPython\core\ultratb.py", line 121, in <module>
from IPython.utils.terminal import get_terminal_size
File "C:\Anaconda3\lib\site-packages\IPython\utils\terminal.py", line 27, in <module>
import backports.shutil_get_terminal_size
ImportError: No module named backports.shutil_get_terminal_size
</code>```

The first thing I tried to do was:

```<code>pip install --upgrade backports.shutil_get_terminal_size
</code>```

output:

```<code>Requirement already up-to-date: backports.shutil_get_terminal_size in c:\anaconda3\lib\site-packages
</code>```

I've uninstalled and reinstalled ipython with both

```<code>conda uninstall ipython
conda install ipython
</code>```

and

```<code>pip uninstall ipython
pip install ipython
</code>```

Still won't work. Help please!

答:
Virtualenv can prove very useful in a case like this, and even more specifically, a virtualenv with no global site packages allowed. Rule out many causes just by doing a clean install in an isolated virtualenv.

In my experience IPython and its dependencies really want to be in the same site. If you have the backports package installed globally but IPython installed in the user roaming site, you might expect runtime import errors such as the ones described in the OP.

I realize that sometimes we need global site packages but the penalty is a more complicated site and dependency handling within pip/setuptools. Depending on several python configuration and windows environment conditions, your packages may be spread across global sites, user (roaming) sites, and virtualenv sites.

Rule out weird site problems by building and installing clean in a virtualenv with no access to global or user packages. The virtualenvwrapper and add2virtualenv command can be used to cleanly allow certain global packages.

Body:
I'm running Python2.7 on windows 10 doing env and most pkg management with Anaconda. After upgrading a number of packages, my ipython console now fails to start in any IDE or at the console. When I attempt to run it at the console I get this error:

Traceback (most recent call last):
File "C:\Anaconda3\Scripts\ipython-script.py", line 3, in <module>
import IPython
File "C:\Anaconda3\lib\site-packages\IPython\__init__.py", line 48, in  <module>
from .core.application import Application
File "C:\Anaconda3\lib\site-packages\IPython\core\application.py", line 24, in <module>
from IPython.core import release, crashhandler
File "C:\Anaconda3\lib\site-packages\IPython\core\crashhandler.py", line 28, in <module>
from IPython.core import ultratb
File "C:\Anaconda3\lib\site-packages\IPython\core\ultratb.py", line 121, in <module>
from IPython.utils.terminal import get_terminal_size
File "C:\Anaconda3\lib\site-packages\IPython\utils\terminal.py", line 27, in <module>
import backports.shutil_get_terminal_size
ImportError: No module named backports.shutil_get_terminal_size

The first thing I tried to do was:

pip install --upgrade backports.shutil_get_terminal_size

output:

Requirement already up-to-date: backports.shutil_get_terminal_size in c:\anaconda3\lib\site-packages

I've uninstalled and reinstalled ipython with both

conda uninstall ipython
conda install ipython

and

pip uninstall ipython
pip install ipython

Still won't work. Help please!


问:
How to set the metadata type according to the file format?
Example:

if bitstream format =

```<code>   .mp4
   .mpeg
   .avi
</code>```

set dc.type = video

if bitstream format =

```<code>   .pdf
   .text
   .doc
</code>```

set dc.type = text

if bitstream format =

```<code>   .png
   .jpeg
   .gif
</code>```

set dc.type = image

etc...

It is possible do this for internal collections and collections collected externally via harvest?

Via database or altering source-code?

答:
If you want to fix your existing records, you could run a SQL query to find the item_id for items that need modification.  Once you have that list of ids, you can use the following tool to add a dc.type to your items:

https://wiki.duraspace.org/display/DSDOC5x/Batch+Metadata+Editing

I do not believe that DSpace is able to assign a dc.type based on the bitstream uploaded. You would need to code that yourself.

Looking at the Submission process documentation, you can configure a submission workflow collection by collection: https://wiki.duraspace.org/display/DSDOC6x/Submission+User+Interface#SubmissionUserInterface-AssigningacustomSubmissionProcesstoaCollection

It is possible to define a default template for a collection.  New items submitted to that collection will receive template values by default.

Body:
Example:

if bitstream format =

   .mp4
   .mpeg
   .avi

set dc.type = video

if bitstream format =

   .pdf
   .text
   .doc

set dc.type = text

if bitstream format =

   .png
   .jpeg
   .gif

set dc.type = image

etc...

It is possible do this for internal collections and collections collected externally via harvest?

Via database or altering source-code?


问:
Call function for paired arguments
Here is simple script to generate greeting messages:

```<code>def greeting(event, person):
    print("Happy " + event + ", dear " + person + ".")

event = "Birthday"
person = "Emily"
greeting(event, person) # Happy Birtday, dear Emily.

event = "New Year"
person = "Mark"
greeting(event, person) # Happy New Year, dear Mark.
</code>```

Is there way to get the same result, but call the greeting function only once?

答:
Either of the options mentioned by other users will work.  It depends on whether you want to put the loop in the function or outside of it:</p>

```<code>def greeting(event, person):
    print("Happy " + event + ", dear " + person + ".")

for event, person in [("Birthday", "Emily"),
              ("New Year", "Mark")]:
    greeting(event, person)
</code>```

Title: Call function for paired arguments

Body:
Here is simple script to generate greeting messages:

def greeting(event, person):
    print("Happy " + event + ", dear " + person + ".")

event = "Birthday"
person = "Emily"
greeting(event, person) # Happy Birtday, dear Emily.

event = "New Year"
person = "Mark"
greeting(event, person) # Happy New Year, dear Mark.

Is there way to get the same result, but call the greeting function only once?

Body:
Either of the options mentioned by other users will work.  It depends on whether you want to put the loop in the function or outside of it:

def greeting(event, person):
    print("Happy " + event + ", dear " + person + ".")

for event, person in [("Birthday", "Emily"),
              ("New Year", "Mark")]:
    greeting(event, person)


问:
cannot instantiate concrete class in Julia
I am just getting started with Julia and have defined a module as follows:

MyModule.jl

```<code>module MyModule
export ConcreteClass
end
</code>```

Then I have a file which defined some trivial abstract class as:

generics.jl

```<code>abstract MyAbstract
</code>```

After this I try and inherit this class:

concrete.jl

```<code>type ConcreteClass <: MyAbstract

end
</code>```

Of course, this is trivial but I just wanted to be able to instantiate a trivial example. I added the path to my project sources to the LOAD_PATH variable and in my julia console i ran the following:

```<code>using MyModule   # No error
r = ConcreteClass()
</code>```

The second line fails with: ERROR: UndefVarError: ConcreteClass not defined. The thing in the Julia console when I type the second line the autocomplete does suggest ConcreteClass, so the type is recognized but not sure why the not defined error comes.

答:
I think I figured it out. I was missing some include statements which seem to be necessary.

MyModule.jl

```<code>module MyModule
export ConcreteClass
include("concrete.jl")
end
</code>```

concrete.jl

```<code>include("generics.jl")
type ConcreteClass <: MyAbstract

end
</code>```

After adding these lines:

```<code>r = ConcreteClass()  # works fine
</code>```

Body:
I am just getting started with Julia and have defined a module as follows:

MyModule.jl

module MyModule
export ConcreteClass
end

Then I have a file which defined some trivial abstract class as:

generics.jl

abstract MyAbstract

After this I try and inherit this class:

concrete.jl

type ConcreteClass <: MyAbstract

end

Of course, this is trivial but I just wanted to be able to instantiate a trivial example. I added the path to my project sources to the LOAD_PATH variable and in my julia console i ran the following:

using MyModule   # No error
r = ConcreteClass()

The second line fails with: ERROR: UndefVarError: ConcreteClass not defined. The thing in the Julia console when I type the second line the autocomplete does suggest ConcreteClass, so the type is recognized but not sure why the not defined error comes.

Body:
I think I figured it out. I was missing some include statements which seem to be necessary.

MyModule.jl

module MyModule
export ConcreteClass
include("concrete.jl")
end

concrete.jl

include("generics.jl")
type ConcreteClass <: MyAbstract

end

After adding these lines:

r = ConcreteClass()  # works fine


问:
matching the regular expression with the whole string
im kinda strumped in a situation where i need to match a whole string with a regular expression rather than finding if the pattern exists in the string.

suppose if i have a regular expression

```<code>/\\^^\\w+\\$^/
</code>```

what i want is that the code will run through various strings , compare the strings with the regular expression and perform some task if the strings start and end with a ^.

Examples

^hello world^ is a match

my ^hello world^ should not be a match

the php function preg_match matches both of the results

any clues ???

答:
Another pattern is: ^\^[^\^]*\^$ if you want match "^hello world^" and not "hello ^world^" , while \^[^\^]*\^ if you want match "^hello world^" and world in the "hello ^world^" string.

For Will: ^\^.*\^$  this match also "^hello^wo^rld^" i think isn't correct.

Body:
im kinda strumped in a situation where i need to match a whole string with a regular expression rather than finding if the pattern exists in the string.

suppose if i have a regular expression

/\\^^\\w+\\$^/

what i want is that the code will run through various strings , compare the strings with the regular expression and perform some task if the strings start and end with a ^.

Examples

^hello world^ is a match

my ^hello world^ should not be a match

the php function preg_match matches both of the results

any clues ???


问:
Why are my gunicorn Python/Flask workers exiting from signal term?
I have a Python/Flask web application that I am deploying via Gunicorn in a docker image on Amazon ECS. Everything is going fine, and then suddenly, including the last successful request, I see this in the logs:

[2017-03-29 21:49:42 +0000] [14] [DEBUG] GET /heatmap_column/e4c53623-2758-4863-af06-91bd002e0107/ADA
[2017-03-29 21:49:43 +0000] [1] [INFO] Handling signal: term
[2017-03-29 21:49:43 +0000] [14] [INFO] Worker exiting (pid: 14)
[2017-03-29 21:49:43 +0000] [8] [INFO] Worker exiting (pid: 8)
[2017-03-29 21:49:43 +0000] [12] [INFO] Worker exiting (pid: 12)
[2017-03-29 21:49:43 +0000] [10] [INFO] Worker exiting (pid: 10)
...
[2017-03-29 21:49:43 +0000] [1] [INFO] Shutting down: Master

And the processes die off and the program exits. ECS then restarts the service, and the docker image is run again, but in the meanwhile the service is interrupted.

What would be causing my program to get a TERM signal? I can't find any references to this happening on the web. Note that this only happens in Docker on ECS, not locally.

答: It turned out that after adding a login page to the system, the health check was getting a 302 redirect to /login at /, which was failing the health check. So the container was periodically killed. Amazon support is awesome!</p>


问:
PL/SQL ORACLE FUNCTION
I want to make function to count my all ID.
But my function does not work. Do not know why ?
I am using Oracle SQL Developer.</p>

```<code>CREATE FUNCTION policz(wartosc as NUMBER)
RETURN INT
IS
ile INT
BEGIN
SELECT COUNT(Id) INTO ile FROM t_dane
RETURN ILE;
end;
</code>```

答:
You say you're USING Oracle SQL Developer.

But are you REALLY?

The plsql editor shows you quote clearly where your issues are and how to fix them.

Your original code has problems on the first line. You'll notice squiggles on the NUMBER in your parameter declaration - that's because we don't recognize the 'AS' as a valid keyword in your plsql block.

Remove the AS.

Compile.

See errors.

Fix errors.

Compile.

Repeat.

Assuming you have a table named T_DANE with a column named ID, you should be good to go.

```<code>create or replace FUNCTION policz(wartosc   NUMBER)
RETURN INT
IS
ile INT;
BEGIN
SELECT COUNT(Id) INTO ile FROM t_dane;
RETURN ILE;
end;
</code>```

Once it compiles without errors, hit the 'green play button' to generate the script to execute your stored proc. Put in the value for 'wartosc' and hit 'OK.'

At the bottom of the screen you'll see an 'output variables' panel. Click on it. You'll see the value returned for ile.

Then, you'll truly be using Oracle SQL Developer.

Title: PL/SQL ORACLE FUNCTION

Body:
I want to make function to count my all ID.
But my function does not work. Do not know why ?
I am using Oracle SQL Developer.

CREATE FUNCTION policz(wartosc as NUMBER)
RETURN INT
IS
ile INT
BEGIN
SELECT COUNT(Id) INTO ile FROM t_dane
RETURN ILE;
end;

Body:
You say you're USING Oracle SQL Developer.

But are you REALLY?

The plsql editor shows you quote clearly where your issues are and how to fix them.

Your original code has problems on the first line. You'll notice squiggles on the NUMBER in your parameter declaration - that's because we don't recognize the 'AS' as a valid keyword in your plsql block.

Remove the AS.

Compile.

See errors.

Fix errors.

Compile.

Repeat.

Assuming you have a table named T_DANE with a column named ID, you should be good to go.

create or replace FUNCTION policz(wartosc   NUMBER)
RETURN INT
IS
ile INT;
BEGIN
SELECT COUNT(Id) INTO ile FROM t_dane;
RETURN ILE;
end;

Once it compiles without errors, hit the 'green play button' to generate the script to execute your stored proc. Put in the value for 'wartosc' and hit 'OK.'

At the bottom of the screen you'll see an 'output variables' panel. Click on it. You'll see the value returned for ile.

Then, you'll truly be using Oracle SQL Developer.


问:
angular 2 flex layout: Can't bind to ngStyle.md since it isn't a known property of div
Iam using flex layout with angular 2.3.1, I am trying to create a responsive style using the responsive api's provided by flex layout module, my divs looks like this

```<code><div class="container popular-projects" classfxLayout="row" fxLayoutWrap="wrap" fxLayout.xs="column" fxLayoutAlign="center"
     fxLayoutGap="30px"
     fxLayoutGap.xs="5px">
<div class="item" [ngStyle]="{width:'263px',height:'384px'}" [ngStyle.md]="{width:'156px',height:'257px'}" >

<div [ngStyle]="{'padding-left':'11px','font-size':'18px', 'padding-top': '10px'}" [ngStyle.md]="{'padding-left':'10px','font-size':'14px', 'padding-top': '12px'}" class="title">     PROJECT NAME</div>
<div [ngStyle]="{'padding-left':'11px','font-size':'16px', 'padding-top': '10px'}" [ngStyle.md]="{'padding-left':'10px','font-size':'11px', 'padding-top': '10px'}" class="description">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce imperdiet ac arcu in auctor.</div>
</div>
</code>```

the flex layout directives are working normally until I started using the binding [ngStyle.md].

in my app.module I imported flexlayoutModule like this

```<code>import { FlexLayoutModule } from "@angular/flex-layout";
</code>```

then I added it to the imports so its accessed in all the application

```<code>   imports: [
BrowserModule,
FormsModule,
HttpModule,
MaterialModule,
FlexLayoutModule,
Md2Module,
MdGridListModule,
routing,
CommonModule
</code>```

Any help is appreciated.

答:
see here https://github.com/angular/flex-layout/issues/215

Looks like they are fixing it / fixed it

Body:
Iam using flex layout with angular 2.3.1, I am trying to create a responsive style using the responsive api's provided by flex layout module, my divs looks like this

     PROJECT NAME

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce imperdiet ac arcu in auctor.

the flex layout directives are working normally until I started using the binding [ngStyle.md].

in my app.module I imported flexlayoutModule like this

import { FlexLayoutModule } from "@angular/flex-layout";

then I added it to the imports so its accessed in all the application

   imports: [
BrowserModule,
FormsModule,
HttpModule,
MaterialModule,
FlexLayoutModule,
Md2Module,
MdGridListModule,
routing,
CommonModule

Any help is appreciated.


问:
Where to find body of email depending of mimeType
I am making a request to the User.messages endpoint. All objects returned (the emails) have a mimeType property which I'm struggling to understand.

More specifically, I want to be able to extract the body of the email depending of the mimeType since I've been able to notice that depending on the mimeType, the body will be inside the body property in payload, or in the parts array. What are the different mimeTypes that can be returned, and where can I find the body of the email for each one of them?

答:
I know this question is not new but I've wrote a PHP script which correctly parses messages pulled from Gmail API, including any type of attachment.

The script includes a recursive "iterateParts" function which iterates all message parts so we can be sure we extracted all available data from each message.

Script steps are:

Pull all message ids from API

Get some important headers (subject & from address)

Either body is directly on payload or send payload to iterateParts

iterateParts is parsing each message to $msgArr with it's data, base64 encoded

Push $msgArr to master array $allmsgArr

Traverse master array and save each part as file according to it's MIME type and filename

```

    $maxToPull = 1;
    $gmailQuery = "ALL";

    // Initializing Google API
    $service = new Google_Service_Gmail($client);

    // Pulling all gmail messages into $messages array
    $user = 'me';
    $msglist = $service->users_messages->listUsersMessages($user, ["maxResults"=>$maxToPull, "q"=>$gmailQuery]);
    $messages = $msglist->getMessages();

    // Master array that will hold all parsed messages data, including attachments
    $allmsgArr = array();

    // Traverse each message
    foreach($messages as $message)
    {
        $msgArr = array();
        $single_message = $service->users_messages->get('me', $message->getId());
        $payload = $single_message->getPayload();

        // Nice to have the gmail msg id, can be used to direct access the message in Gmail's web gui
        $msgArr['gmailmsgid'] = $message->getId();

        // Retrieving the subject and "from" email address
        foreach($payload->getheaders() as $oneheader)
        {
            if($oneheader['name'] == 'Subject')
                $msgArr['subject'] = $oneheader['value'];
            if($oneheader['name'] == 'From')
                $msgArr['fromaddress'] = substr($oneheader['value'], strpos($oneheader['value'], '<')+1, -1);
        }

        // If body is directly in the message payload (only for plain text messages where there's no HTML part and no attachments, normally this is not the case)
        if($payload['body']['size'] > 0)
            $msgArr['textplain'] = $payload['body']['data'];
        // Else, iterate over each message part and continue to dig if necessary
        else
            iterateParts($payload, $message->getId());

        // Push the parsed $msgArr (parsed by iterateParts) to master array
        array_push($allmsgArr, $msgArr);
    }

    // Traverse each parsed message and saving it's content and attachments to files
    foreach($allmsgArr as $onemsgArr)
    {

        $folder = "messages/".$onemsgArr['gmailmsgid'];
        mkdir($folder);

        if($onemsgArr['textplain'])
            file_put_contents($folder."/textplain.txt", decodeData($onemsgArr['textplain']));
        if($onemsgArr['texthtml'])
            file_put_contents($folder."/texthtml.html", decodeData($onemsgArr['texthtml']));
        if($onemsgArr['attachments'])
        {
            foreach($onemsgArr['attachments'] as $oneattachment)
            {
                if(!empty($oneattachment['filename']))
                    $filename = $oneattachment['filename'];
                else if($oneattachment['mimetype'] == "message/rfc822" && empty($oneattachment['filename'])) // email attachments
                    $filename = "noname.eml";
                else
                    $filename = "unknown";
                file_put_contents($folder."/".$filename, decodeData($oneattachment['data']));
            }
        }
    }

    function iterateParts($obj, $msgid) {

        global $msgArr;
        global $service;
        foreach($obj as $parts)
        {
            // if found body data
            if($parts['body']['size'] > 0)
            {
                // plain text representation of message body
                if($parts['mimeType'] == 'text/plain')
                {
                    $msgArr['textplain'] = $parts['body']['data'];
                }
                // html representation of message body
                else if($parts['mimeType'] == 'text/html')
                {
                    $msgArr['texthtml'] = $parts['body']['data'];
                }
                // if it's an attachment
                else if(!empty($parts['body']['attachmentId']))
                {
                    $attachArr['mimetype'] = $parts['mimeType'];
                    $attachArr['filename'] = $parts['filename'];
                    $attachArr['attachmentId'] = $parts['body']['attachmentId'];

                    // the message holds the attachment id, retrieve it's data from users_messages_attachments
                    $attachmentId_base64 = $parts['body']['attachmentId'];
                    $single_attachment = $service->users_messages_attachments->get('me', $msgid, $attachmentId_base64);

                    $attachArr['data'] = $single_attachment->getData();

                    $msgArr['attachments'][] = $attachArr;
                }
            }

            // if there are other parts inside, go get them
            if(!empty($parts['parts']) && !empty($parts['mimeType']) && empty($parts['body']['attachmentId']))
            {
                iterateParts($parts->getParts(), $msgid);
            }

        }
    }

    // All data returned from API is base64 encoded
    function decodeData($data)
    {
        $sanitizedData = strtr($data,'-_', '+/');
        return base64_decode($sanitizedData);
    }

```

This is how $allmsgArr will look like (where only one message was pulled):

```

Array
(
    [0] => Array
        (
            [gmailmsgid] => 25k1asfa556x2da
            [fromaddress] => john@gmail.com
            [subject] => Fwd: Sea gulls picture
            [textplain] => UE5SIDQxQzAwMg0KDQpBUkJFTFRFU1QxDQoNCg0K
            [texthtml] => PGRpdiBkaXI9Imx0ciI-PHNwYW4gc3R5bGU9ImZi
            [attachments] => Array
                (
                    [0] => Array
                        (
                            [mimetype] => image/png
                            [filename] => sea_gulls.png
                            [attachmentId] => ANGjdJ9tmy4d8vPXhU_BjNEFEaDODOpu29W2u5OTM7a0
                            [data] => iVBORw0KGgoAAAANSUhEUgAABSYAAAKWCAYAAABUP
                        )

                    [1] => Array
                        (
                            [mimetype] => image/jpeg
                            [filename] => Outlook_Signature.jpg
                            [attachmentId] => ANGjdJ-CgZTK0oK44Q8j7TlN_JlaexxGKZ_wHFfoEB
                            [data] => 6jRXhpZgAATU0AKgAAAAgABwESAAMAAAABAAEAAAEa
                        )

                )
        )
)

```

ContentLicense: CC BY-SA 4.0

Body:
I know this question is not new but I've wrote a PHP script which correctly parses messages pulled from Gmail API, including any type of attachment.

The script includes a recursive "iterateParts" function which iterates all message parts so we can be sure we extracted all available data from each message.

Script steps are:

Pull all message ids from API

Get some important headers (subject & from address)

Either body is directly on payload or send payload to iterateParts

iterateParts is parsing each message to $msgArr with it's data, base64 encoded

Push $msgArr to master array $allmsgArr

Traverse master array and save each part as file according to it's MIME type and filename

    $maxToPull = 1;
    $gmailQuery = "ALL";

    // Initializing Google API
    $service = new Google_Service_Gmail($client);

    // Pulling all gmail messages into $messages array
    $user = 'me';
    $msglist = $service->users_messages->listUsersMessages($user, ["maxResults"=>$maxToPull, "q"=>$gmailQuery]);
    $messages = $msglist->getMessages();

    // Master array that will hold all parsed messages data, including attachments
    $allmsgArr = array();

    // Traverse each message
    foreach($messages as $message)
    {
        $msgArr = array();
        $single_message = $service->users_messages->get('me', $message->getId());
        $payload = $single_message->getPayload();

        // Nice to have the gmail msg id, can be used to direct access the message in Gmail's web gui
        $msgArr['gmailmsgid'] = $message->getId();

        // Retrieving the subject and "from" email address
        foreach($payload->getheaders() as $oneheader)
        {
            if($oneheader['name'] == 'Subject')
                $msgArr['subject'] = $oneheader['value'];
            if($oneheader['name'] == 'From')
                $msgArr['fromaddress'] = substr($oneheader['value'], strpos($oneheader['value'], '<')+1, -1);
        }

        // If body is directly in the message payload (only for plain text messages where there's no HTML part and no attachments, normally this is not the case)
        if($payload['body']['size'] > 0)
            $msgArr['textplain'] = $payload['body']['data'];
        // Else, iterate over each message part and continue to dig if necessary
        else
            iterateParts($payload, $message->getId());

        // Push the parsed $msgArr (parsed by iterateParts) to master array
        array_push($allmsgArr, $msgArr);
    }

    // Traverse each parsed message and saving it's content and attachments to files
    foreach($allmsgArr as $onemsgArr)
    {

        $folder = "messages/".$onemsgArr['gmailmsgid'];
        mkdir($folder);

        if($onemsgArr['textplain'])
            file_put_contents($folder."/textplain.txt", decodeData($onemsgArr['textplain']));
        if($onemsgArr['texthtml'])
            file_put_contents($folder."/texthtml.html", decodeData($onemsgArr['texthtml']));
        if($onemsgArr['attachments'])
        {
            foreach($onemsgArr['attachments'] as $oneattachment)
            {
                if(!empty($oneattachment['filename']))
                    $filename = $oneattachment['filename'];
                else if($oneattachment['mimetype'] == "message/rfc822" && empty($oneattachment['filename'])) // email attachments
                    $filename = "noname.eml";
                else
                    $filename = "unknown";
                file_put_contents($folder."/".$filename, decodeData($oneattachment['data']));
            }
        }
    }

    function iterateParts($obj, $msgid) {

        global $msgArr;
        global $service;
        foreach($obj as $parts)
        {
            // if found body data
            if($parts['body']['size'] > 0)
            {
                // plain text representation of message body
                if($parts['mimeType'] == 'text/plain')
                {
                    $msgArr['textplain'] = $parts['body']['data'];
                }
                // html representation of message body
                else if($parts['mimeType'] == 'text/html')
                {
                    $msgArr['texthtml'] = $parts['body']['data'];
                }
                // if it's an attachment
                else if(!empty($parts['body']['attachmentId']))
                {
                    $attachArr['mimetype'] = $parts['mimeType'];
                    $attachArr['filename'] = $parts['filename'];
                    $attachArr['attachmentId'] = $parts['body']['attachmentId'];

                    // the message holds the attachment id, retrieve it's data from users_messages_attachments
                    $attachmentId_base64 = $parts['body']['attachmentId'];
                    $single_attachment = $service->users_messages_attachments->get('me', $msgid, $attachmentId_base64);

                    $attachArr['data'] = $single_attachment->getData();

                    $msgArr['attachments'][] = $attachArr;
                }
            }

            // if there are other parts inside, go get them
            if(!empty($parts['parts']) && !empty($parts['mimeType']) && empty($parts['body']['attachmentId']))
            {
                iterateParts($parts->getParts(), $msgid);
            }

        }
    }

    // All data returned from API is base64 encoded
    function decodeData($data)
    {
        $sanitizedData = strtr($data,'-_', '+/');
        return base64_decode($sanitizedData);
    }

This is how $allmsgArr will look like (where only one message was pulled):

Array
(
    [0] => Array
        (
            [gmailmsgid] => 25k1asfa556x2da
            [fromaddress] => john@gmail.com
            [subject] => Fwd: Sea gulls picture
            [textplain] => UE5SIDQxQzAwMg0KDQpBUkJFTFRFU1QxDQoNCg0K
            [texthtml] => PGRpdiBkaXI9Imx0ciI-PHNwYW4gc3R5bGU9ImZi
            [attachments] => Array
                (
                    [0] => Array
                        (
                            [mimetype] => image/png
                            [filename] => sea_gulls.png
                            [attachmentId] => ANGjdJ9tmy4d8vPXhU_BjNEFEaDODOpu29W2u5OTM7a0
                            [data] => iVBORw0KGgoAAAANSUhEUgAABSYAAAKWCAYAAABUP
                        )

                    [1] => Array
                        (
                            [mimetype] => image/jpeg
                            [filename] => Outlook_Signature.jpg
                            [attachmentId] => ANGjdJ-CgZTK0oK44Q8j7TlN_JlaexxGKZ_wHFfoEB
                            [data] => 6jRXhpZgAATU0AKgAAAAgABwESAAMAAAABAAEAAAEa
                        )

                )
        )
)


问:
Ruby sort by multiple values?
I have an array of hashes:

```<code>a=[{ 'foo'=>0,'bar'=>1 },
   { 'foo'=>0,'bar'=>2 },
   ... ]
</code>```

I want to sort the array first by each hash's 'foo', then by 'bar'. Google tells me this is how it's done:

```<code>a.sort_by {|h| [ h['foo'],h['bar'] ]}
</code>```

But this gives me the ArgumentError "comparison of Array with Array failed". What does this mean?

Title: Ruby sort by multiple values?

Body:
I have an array of hashes:

a=[{ 'foo'=>0,'bar'=>1 },
   { 'foo'=>0,'bar'=>2 },
   ... ]

I want to sort the array first by each hash's 'foo', then by 'bar'. Google tells me this is how it's done:

a.sort_by {|h| [ h['foo'],h['bar'] ]}

But this gives me the ArgumentError "comparison of Array with Array failed". What does this mean?

Body:
What you have posted works in Ruby 1.8.7:

ruby-1.8.7-p302 > a = [{'foo'=>99,'bar'=>1},{'foo'=>0,'bar'=>2}]
 => [{"foo"=>99, "bar"=>1}, {"foo"=>0, "bar"=>2}]

ruby-1.8.7-p302 > a.sort_by{ |h| [h['foo'],h['bar']] }
 => [{"foo"=>0, "bar"=>2}, {"foo"=>99, "bar"=>1}]

ruby-1.8.7-p302 > a.sort_by{ |h| [h['bar'],h['foo']] }
 => [{"foo"=>99, "bar"=>1}, {"foo"=>0, "bar"=>2}]


问:
How do I rewrite a 'for loop' as a 'while loop' in python?
This is the loop:

```<code>for c in "Hi there":
     print(c.upper())
</code>```

This is my attempt of rewriting as a while loop:

```<code>phrase = "Hi there"
while len.phrase > 0
    print (c.upper())
</code>```

答:
Use an iterator

```<code>phrase = "Hi there"
limit = len(phrase);
itery =0;
while itery<limit:
    print (phrase[itery].upper());
    itery+=1;
</code>```

Body:
This is the loop:

for c in "Hi there":
     print(c.upper())

This is my attempt of rewriting as a while loop:

phrase = "Hi there"
while len.phrase > 0
    print (c.upper())

Body:
Use an iterator

phrase = "Hi there"
limit = len(phrase);
itery =0;
while itery<limit:
    print (phrase[itery].upper());
    itery+=1;


问:
Javascript - Sending Signature-Pad results to Flask
I'm using the signature-pad JavaScript library to have people digitally sign documents (this is just for testing, nothing legally binding, etc.) but I'm having a hard time passing the signature result back to Flask/Python from JS.

The following code is my HTML form, it submits the form.stu_name field perfectly, and even triggers my JS to "submit"(meaning the code executes and a new window opens displaying the signature) but I'm not sure how to submit the JS result back to Flask - see the second code block example for more.

```<code><div class="container">
    {% from "_formhelper.html" import render_field %}
    <form id="upload-form" method="POST" action="/sixth_form/" enctype="multipart/form-data">
    <dl>
      {{render_field(form.stu_name)}}
        </dl>
        <p>Student Signature</p>
<div class="wrapper">
  <img src="{{ url_for('static', filename='images/grey.jpeg') }}" width=400 height=200 />
  <canvas id="signature-pad" class="signature-pad" width=400 height=200></canvas>
</div>
<div>
  <button id="clear" type="Button">Clear</button>
</div>
<br>
    <p><input id="finalsub" type="submit" value="Submit"></p>
    </form>
</div>
</code>```

Here's the script itself, when run it opens a new window with the result of the signature presented as an URI encoded image (that part is fine, I can decode it later in Python), what I need help with - Instead of opening a new window I want to submit the image back to Flask and then store it in a variable so I can append it to another image. I'm not very knowledgeable with JS, so any suggestions are very welcome!

```<code><script>
var signaturePad = new SignaturePad(document.getElementById('signature-pad'), {
  backgroundColor: 'rgba(255, 255, 255, 0)',
  penColor: 'rgb(0, 0, 0)'
});
var saveButton = document.getElementById('finalsub');
var cancelButton = document.getElementById('clear');

saveButton.addEventListener('click', function (event) {
  var data = signaturePad.toDataURL('image/png');

// Send data to server instead...
  window.open(data);
});

cancelButton.addEventListener('click', function (event) {
  signaturePad.clear();
});
</script>
</code>```

答:
This answer seems to be what you're looking for. This is using jQuery however. To do this in pure JavaScript look at this answer. Then to access the file you would use flask.request.files.

A blind (read: untested) example would be:

```<code>$(function() {
    $('#upload-file-btn').click(function() {
        var data = signaturePad.toDataURL('image/png');
        $.ajax({
            type: 'POST',
            url: '/uploadUrl',
            data: data,
            contentType: false,
            cache: false,
            processData: false,
            async: false,
            success: function(data) {
                console.log('Success!');
            },
        });
    });
});
</code>```

Now in your flask's endpoint view function, you can access the file's
  data via flask.request.files.

Note: As I said this is untested, and I don't know if the ajax config (for instance making the request synchronous or setting contentType to false) are all necessary. My intuition would be to rewrite it like this:

NOT TESTED

```<code>$(function() {
    $('#upload-file-btn').click(function() {
        var data = signaturePad.toDataURL('image/png');
        $.ajax({
            type: 'POST',
            url: '/uploadUrl',
            data: data,
            contentType: 'image/png'
        }).done(function(data) {
            console.log('Success!');
        }).fail(function(data) {
            console.log('Fail!');
        });
    });
});
</code>```

Body:
I'm using the signature-pad JavaScript library to have people digitally sign documents (this is just for testing, nothing legally binding, etc.) but I'm having a hard time passing the signature result back to Flask/Python from JS.

The following code is my HTML form, it submits the form.stu_name field perfectly, and even triggers my JS to "submit"(meaning the code executes and a new window opens displaying the signature) but I'm not sure how to submit the JS result back to Flask - see the second code block example for more.

    {% from "_formhelper.html" import render_field %}
    <form id="upload-form" method="POST" action="/sixth_form/" enctype="multipart/form-data">

      {{render_field(form.stu_name)}}

Student Signature

  <canvas id="signature-pad" class="signature-pad" width=400 height=200></canvas>

  <button id="clear" type="Button">Clear</button>

<input id="finalsub" type="submit" value="Submit">

    </form>

Here's the script itself, when run it opens a new window with the result of the signature presented as an URI encoded image (that part is fine, I can decode it later in Python), what I need help with - Instead of opening a new window I want to submit the image back to Flask and then store it in a variable so I can append it to another image. I'm not very knowledgeable with JS, so any suggestions are very welcome!

Body:
This answer seems to be what you're looking for. This is using jQuery however. To do this in pure JavaScript look at this answer. Then to access the file you would use flask.request.files.

A blind (read: untested) example would be:

$(function() {
    $('#upload-file-btn').click(function() {
        var data = signaturePad.toDataURL('image/png');
        $.ajax({
            type: 'POST',
            url: '/uploadUrl',
            data: data,
            contentType: false,
            cache: false,
            processData: false,
            async: false,
            success: function(data) {
                console.log('Success!');
            },
        });
    });
});

Now in your flask's endpoint view function, you can access the file's
  data via flask.request.files.

Note: As I said this is untested, and I don't know if the ajax config (for instance making the request synchronous or setting contentType to false) are all necessary. My intuition would be to rewrite it like this:

NOT TESTED

$(function() {
    $('#upload-file-btn').click(function() {
        var data = signaturePad.toDataURL('image/png');
        $.ajax({
            type: 'POST',
            url: '/uploadUrl',
            data: data,
            contentType: 'image/png'
        }).done(function(data) {
            console.log('Success!');
        }).fail(function(data) {
            console.log('Fail!');
        });
    });
});


问:
Setting the include path with bindgen
I'm writing a Rust interface to a small C library, which has headers spread in a few locations. It's not a system library, and is normally used by some executables in the same package; I'm currently including it as a git submodule in my Cargo project.

Building the library seems to be pretty easy; I've opted to use the gcc crate from build.rs:

```<code>gcc::Config::new()
            .file("external/foo/dir1/file1.c")
            .file("external/foo/dir2/file2.c")
            .include("external/foo/dir1/")
            .include("external/foo/dir2/")
            .include("external/foo/config_a/")
            .compile("libfoo.a");
</code>```

Now I was hoping to use the bindgen crate to generate the FFI interface without too much fuss, but it doesn't seem to have a way of setting include paths.

I can create a wrapper.h as suggested by this blog and include several headers, but if dir1/dir1.h includes conf.h directly, which works when building due to .include("external/foo/config_a/") it can't be found.

I can't find anything in bindgen's API to help here (essentially I want to pass the equivalent of gcc/clang's -I option).  Am I missing anything?

The best option I can think of so far is to copy the various headers from the library source into some temporary directory in build.rs and run bindgen on that, but that seems somewhat messy if there's a nicer way.

答:
With the API you can use Builder::clang_arg with arbitrary arguments:

```<code>let b = bindgen::builder().header("foo.h").clang_arg("-I/path");
</code>```

From the command line you can do the same by appending arguments after --, like:

bindgen foo.h -- -I/path
```

Title: Setting the include path with bindgen

Body:
I'm writing a Rust interface to a small C library, which has headers spread in a few locations. It's not a system library, and is normally used by some executables in the same package; I'm currently including it as a git submodule in my Cargo project.

Building the library seems to be pretty easy; I've opted to use the gcc crate from build.rs:

gcc::Config::new()
            .file("external/foo/dir1/file1.c")
            .file("external/foo/dir2/file2.c")
            .include("external/foo/dir1/")
            .include("external/foo/dir2/")
            .include("external/foo/config_a/")
            .compile("libfoo.a");

Now I was hoping to use the bindgen crate to generate the FFI interface without too much fuss, but it doesn't seem to have a way of setting include paths.

I can create a wrapper.h as suggested by this blog and include several headers, but if dir1/dir1.h includes conf.h directly, which works when building due to .include("external/foo/config_a/") it can't be found.

I can't find anything in bindgen's API to help here (essentially I want to pass the equivalent of gcc/clang's -I option).  Am I missing anything?

The best option I can think of so far is to copy the various headers from the library source into some temporary directory in build.rs and run bindgen on that, but that seems somewhat messy if there's a nicer way.

Body:
With the API you can use Builder::clang_arg with arbitrary arguments:

let b = bindgen::builder().header("foo.h").clang_arg("-I/path");

From the command line you can do the same by appending arguments after --, like:

bindgen foo.h -- -I/path


问:
Javascript: Need to replace an object in an HTML code which is stored as a string
I am working on a website that shows different APIs we provide. It showcases the example code and preview for each API and a button to open code in plunker. Since we have 100s of examples, we are not creating plunker for every example, but opening a new tab "https://plnkr.co/edit/?p=preview" and appending the corresponding html code into it.

Problem:

I have a total HTML document as a string in a javascript variable.

```<code>var html = "`<DOCTYPE html><html>....<body><script>abc.loader.load({apiToken:'', name:'',...});</script></body>`"
</code>```

I have to change the object inside abc.loader.load(). Is there any way I can pick up the object inside abc.loader.load() and make changes in javascript and replace with existing object.

答:
You can use a template literal and inject ${JSON.stringify(obj)} into that, like this:

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

<p>The script content is wrapped in <code><!--   --></code> to avoid misinterpretation of <code><</code> inside your string. </p>

<h3>Reading out the object and writing it again after mutation:</h3>

<p>Although I would try to stick to the above template string, and would repeat the injection of different objects into it, here is what you could do when you have a given HTML string, and need to extract the object. This only works if the object literal is JSON compliant, i.e. it double quotes strings, and also property names:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><!--
var html = `<!DOCTYPE html><html>....<body>
            <script>abc.loader.load({"apiToken":"", "name":""});</script></body></html>`;
html = html.replace(/(loader\.load\()(.*?)(?=\);<\/script>)/, function (_, prefix, json) {
    var obj = JSON.parse(json); // get the object
    obj.test = 3; // modify the object as you wish
    return prefix + JSON.stringify(obj); // put the object
});
console.log(html);
--></code>```

Body:
I am working on a website that shows different APIs we provide. It showcases the example code and preview for each API and a button to open code in plunker. Since we have 100s of examples, we are not creating plunker for every example, but opening a new tab "https://plnkr.co/edit/?p=preview" and appending the corresponding html code into it.

Problem:

I have a total HTML document as a string in a javascript variable.

var html = "`<DOCTYPE html><html>....<body><script>abc.loader.load({apiToken:'', name:'',...});</script></body>`"

I have to change the object inside abc.loader.load(). Is there any way I can pick up the object inside abc.loader.load() and make changes in javascript and replace with existing object.

Body:
You can use a template literal and inject ${JSON.stringify(obj)} into that, like this:

<!--
var obj = {apiToken:'', name:''};
var html = `<!DOCTYPE html><html>....<body>
            <script>abc.loader.load(${JSON.stringify(obj)});</script></body></html>`;

console.log(html);
-->

The script content is wrapped in <!--   --> to avoid misinterpretation of < inside your string.

Reading out the object and writing it again after mutation:

Although I would try to stick to the above template string, and would repeat the injection of different objects into it, here is what you could do when you have a given HTML string, and need to extract the object. This only works if the object literal is JSON compliant, i.e. it double quotes strings, and also property names:

<!--
var html = `<!DOCTYPE html><html>....<body>
            <script>abc.loader.load({"apiToken":"", "name":""});</script></body></html>`;
html = html.replace(/(loader\.load\()(.*?)(?=\);<\/script>)/, function (_, prefix, json) {
    var obj = JSON.parse(json); // get the object
    obj.test = 3; // modify the object as you wish
    return prefix + JSON.stringify(obj); // put the object
});
console.log(html);
-->


问:
How to do on-behalf-of auth in .NET Core (missing BootstrapContext)?
I've run the on-behalf-of sample in .NET 4.5:

https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof

But I need to do the same thing in .NET core.  When trying to port the sample service to .NET core everything compiles except for this line:

```<code>var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;
</code>```

It won't compile because System.IdentityModel isn't available in .NET Core.

I discovered that if I acquire the user access token and the user name using this code instead it works for users in the same tenant as the service:

```<code>System.Security.Claims.ClaimsIdentity identity =
    User.Identity as System.Security.Claims.ClaimsIdentity;
string userAccessToken = identity.BootstrapContext as string;
string userName = (User.FindFirst(ClaimTypes.Upn))?.Value;
</code>```

But for users in a different tenant (multi-tenant authentication), userAccessToken and userName are set to null.  What do I need to do differently to get this working for users coming from a different tenant?

答:
I figured out that the reason userAccessToken and userName were coming back as null is because I was missing the SaveSigninToken parameter when calling UseJwtBearerAuthentication in Startup.cs:

```<code>app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    Authority = String.Format(CultureInfo.InvariantCulture, Configuration["Authentication:AzureAd:AADInstance"], Configuration["Authentication:AzureAd:Tenant"]),
    Audience = Configuration["Authentication:AzureAd:Audience"],
            TokenValidationParameters = new TokenValidationParameters { SaveSigninToken = true, ValidateIssuer = false }
});
</code>```

Without SaveSigninToken = true, the caller's access token and identity doesn't flow through in the case where the caller is from another tenant.

Body:
I've run the on-behalf-of sample in .NET 4.5:

https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof

But I need to do the same thing in .NET core.  When trying to port the sample service to .NET core everything compiles except for this line:

var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;

It won't compile because System.IdentityModel isn't available in .NET Core.

I discovered that if I acquire the user access token and the user name using this code instead it works for users in the same tenant as the service:

System.Security.Claims.ClaimsIdentity identity =
    User.Identity as System.Security.Claims.ClaimsIdentity;
string userAccessToken = identity.BootstrapContext as string;
string userName = (User.FindFirst(ClaimTypes.Upn))?.Value;

But for users in a different tenant (multi-tenant authentication), userAccessToken and userName are set to null.  What do I need to do differently to get this working for users coming from a different tenant?

Body:
I figured out that the reason userAccessToken and userName were coming back as null is because I was missing the SaveSigninToken parameter when calling UseJwtBearerAuthentication in Startup.cs:

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    Authority = String.Format(CultureInfo.InvariantCulture, Configuration["Authentication:AzureAd:AADInstance"], Configuration["Authentication:AzureAd:Tenant"]),
    Audience = Configuration["Authentication:AzureAd:Audience"],
            TokenValidationParameters = new TokenValidationParameters { SaveSigninToken = true, ValidateIssuer = false }
});

Without SaveSigninToken = true, the caller's access token and identity doesn't flow through in the case where the caller is from another tenant.


问:
How to make this code less repetitive? (openpyxl)
I'm a teacher and I'm making a program to facilitate myself to catalog my students' grades. This isn't so much of a problem, the deal is, I'm doing it mostly to practice programming.

```<code># Name the first line
sheet['A1'] = 'Index'
sheet['B1'] = 'Name'
sheet['C1'] = 'Grade'

# Changes the style of the first line to bold
sheet['A1'].font = font_bold
sheet['B1'].font = font_bold
sheet['C1'].font = font_bold

# Widens the columns
sheet.column_dimensions['A'].width = 10
sheet.column_dimensions['B'].width = 30
sheet.column_dimensions['C'].width = 30

# Aligns to center
sheet.cell('A1').alignment = Alignment(horizontal='center', vertical='center')
sheet.cell('B1').alignment = Alignment(horizontal='center', vertical='center')
sheet.cell('C1').alignment = Alignment(horizontal='center', vertical='center')

# Freeze the first row
sheet.freeze_panes = 'A2'

# Index number of the lines
i = 2

--

--

# function to calculate the grade
def grade():
</code>```

As you may notice, it is all, to some extent, repetitive. The code functions exactly as I want it to, but I would like to know some other way to make it more... succint.

It is important to remember the variables reach, because up next a function will start, and, soon after, a While loop.

The irrelevant parts of the code for this question have been omitted with a ---. If they are somehow needed I'll edit them in, but to my knowledge, they are not.

Thank you in advance.

答:
Here's a good start:</p>

```<code>items = [
  {"sheet": "A1", "column": "A", "column_width": 10, "title": "Index"},
  {"sheet": "B1", "column": "B", "column_width": 30, "title": "Name"},
  {"sheet": "C1", "column": "C", "column_width": 30} "title": "Grade"},
]

for item in items:
    sheet[item["sheet"]] = item["title"]
    sheet[item["sheet"]].font = font_bold # always bold
    sheet.column_dimensions[item["column"]] = item["column_width"] # shared value
    sheet.cell(item["sheet"]).alignment = Alignment(horizontal='center', vertical='center') # shared value
</code>```

Body:
I'm a teacher and I'm making a program to facilitate myself to catalog my students' grades. This isn't so much of a problem, the deal is, I'm doing it mostly to practice programming.

# Name the first line
sheet['A1'] = 'Index'
sheet['B1'] = 'Name'
sheet['C1'] = 'Grade'

# Changes the style of the first line to bold
sheet['A1'].font = font_bold
sheet['B1'].font = font_bold
sheet['C1'].font = font_bold

# Widens the columns
sheet.column_dimensions['A'].width = 10
sheet.column_dimensions['B'].width = 30
sheet.column_dimensions['C'].width = 30

# Aligns to center
sheet.cell('A1').alignment = Alignment(horizontal='center', vertical='center')
sheet.cell('B1').alignment = Alignment(horizontal='center', vertical='center')
sheet.cell('C1').alignment = Alignment(horizontal='center', vertical='center')

# Freeze the first row
sheet.freeze_panes = 'A2'

# Index number of the lines
i = 2

--

--

# function to calculate the grade
def grade():

As you may notice, it is all, to some extent, repetitive. The code functions exactly as I want it to, but I would like to know some other way to make it more... succint.

It is important to remember the variables reach, because up next a function will start, and, soon after, a While loop.

The irrelevant parts of the code for this question have been omitted with a ---. If they are somehow needed I'll edit them in, but to my knowledge, they are not.

Thank you in advance.

Body:
Here's a good start:

items = [
  {"sheet": "A1", "column": "A", "column_width": 10, "title": "Index"},
  {"sheet": "B1", "column": "B", "column_width": 30, "title": "Name"},
  {"sheet": "C1", "column": "C", "column_width": 30} "title": "Grade"},
]

for item in items:
    sheet[item["sheet"]] = item["title"]
    sheet[item["sheet"]].font = font_bold # always bold
    sheet.column_dimensions[item["column"]] = item["column_width"] # shared value
    sheet.cell(item["sheet"]).alignment = Alignment(horizontal='center', vertical='center') # shared value


问:
Root.plist app settings missing when debugging
I have created a settings bundle and Root.plist.  When I run my app using the Release|iPhoneSimulator build I can see and edit my settings in the "Settings app" just fine, as expected.

However when I run my app in Debug|iPhoneSimulation mode my settings are gone and replaced by the Debugger Settings.  Is there a way to keep my original Root.plist settings intack while debugging??

I must be doing something stupid because I can't find any references to anyone else having this problem.

Thanks.

答:
It might be a case sensitivity issue.

MonoDevelop merges the debug settings into your settings files, if it finds a file called  Settings.bundle/Root.plist marked as Content in the project, but this check is case sensitive.

If it does not find this file - for example your settings file is cased differently - MD will simply create a new settings file, but the Apple case-insensitive filesystem will consider the filenames to be the same, so it'll end up overwriting yours in the app bundle.


问:
Get All Active Service Instances on Service Start
I'm creating a stateless service inside Azure Service Fabric. However, once service starts (or on start of custom communication listener) I need to get addresses of all other instances/partitions of that service.

I'm doing so by creating new FabricClient and calling fabricClient.QueryManager.GetPartitionListAsync(serviceUri). However I'm getting FabricServiceNotFoundException with message Service does not exist. when a first service instance starts running.

I couldn't find that in documentation, so my question is: how can I get a list of listening endpoint addresses for all active instances of a particular service, running in Azure Service Fabric, when a new instance of that service starts running?

答:
I'm new to commenting on StackOverflow but here is how I did my service resolution. I ended up making a small library to take care of it.

```<code>ResolvedServicePartition partition = await fabricClient.ServiceManager.ResolveServicePartitionAsync("fabric:/Application1/Service1");

// This "endpoint" looks something like this: {\"Endpoints\":{\"\":\"http:\/\/localhost:8448\/\"}}
string randomConfigStoreEndpointJson = partition.GetEndpoint().Address;

// Use Newtonsoft.Json to parse this mess, since JavaScriptSerializer isn't up to the job
JObject endpointObject = JObject.Parse(randomConfigStoreEndpointJson);

// This is the only way I could actually extract the baseUrl without regular expressions
string actualEndpointBaseUrl = endpointObject["Endpoints"].First.First.ToString();
</code>```

@DannyMeister This takes care of parsing that odd endpoint JSON syntax.

This also works to resolve a stateful service with only one partition. To resolve a stateful service with multiple partitions, you must figure out the partitionKey on the client, then call await fabricClient.ServiceManager.ResolveServicePartitionAsync("fabric:/Application1/Service1", statefulPartitionKey); instead!

Body:
I'm new to commenting on StackOverflow but here is how I did my service resolution. I ended up making a small library to take care of it.

ResolvedServicePartition partition = await fabricClient.ServiceManager.ResolveServicePartitionAsync("fabric:/Application1/Service1");

// This "endpoint" looks something like this: {\"Endpoints\":{\"\":\"http:\/\/localhost:8448\/\"}}
string randomConfigStoreEndpointJson = partition.GetEndpoint().Address;

// Use Newtonsoft.Json to parse this mess, since JavaScriptSerializer isn't up to the job
JObject endpointObject = JObject.Parse(randomConfigStoreEndpointJson);

// This is the only way I could actually extract the baseUrl without regular expressions
string actualEndpointBaseUrl = endpointObject["Endpoints"].First.First.ToString();

@DannyMeister This takes care of parsing that odd endpoint JSON syntax.

This also works to resolve a stateful service with only one partition. To resolve a stateful service with multiple partitions, you must figure out the partitionKey on the client, then call await fabricClient.ServiceManager.ResolveServicePartitionAsync("fabric:/Application1/Service1", statefulPartitionKey); instead!