问:
Specify order of tables to copy using the Copy Data tool in Azure Data Factory to respect foreign keys
The Copy Data tool lets me select the tables I want to copy from the source to the destination, but the tables are copied in alphabetical order. Since I have foreign keys defined, this cannot work. I would like to manually change the order.

答:
Here is a simple pipeline that copies data from one database to another - it has a ForEach with 2 activities inside it.  It copies each table and then runs a stored procedure after each table.  The column names in the tables are the same.  It has a variable called tableMapping that is a json array that defines the 'from' and 'to' table names as they can be different.  The ForEach has this setting "batchCount": 1, so that it runs one at a time.  In my testing just now it processes the tables in the sequence in the variable tableMapping.  If you don't specify the batchCount = 1 then it will run them in parallel.</p>

```<code>{
    "name": "TowWorks to Azure SQL DB",
    "properties": {
        "activities": [
            {
                "name": "ForEach1",
                "type": "ForEach",
                "dependsOn": [],
                "userProperties": [],
                "typeProperties": {
                    "items": {
                        "value": "@variables('tableMapping')",
                        "type": "Expression"
                    },
                    "batchCount": 1,
                    "activities": [
                        {
                            "name": "Copy from BI to Azure",
                            "type": "Copy",
                            "dependsOn": [],
                            "policy": {
                                "timeout": "7.00:00:00",
                                "retry": 0,
                                "retryIntervalInSeconds": 30,
                                "secureOutput": false,
                                "secureInput": false
                            },
                            "userProperties": [],
                            "typeProperties": {
                                "source": {
                                    "type": "SqlServerSource",
                                    "queryTimeout": "02:00:00"
                                },
                                "sink": {
                                    "type": "AzureSqlSink",
                                    "preCopyScript": {
                                        "value": "@{concat('truncate table raw.', item().to)}",
                                        "type": "Expression"
                                    },
                                    "disableMetricsCollection": false
                                },
                                "enableStaging": false
                            },
                            "inputs": [
                                {
                                    "referenceName": "BI_TW_Raw_NoTable",
                                    "type": "DatasetReference",
                                    "parameters": {
                                        "tableName": {
                                            "value": "@item().from",
                                            "type": "Expression"
                                        }
                                    }
                                }
                            ],
                            "outputs": [
                                {
                                    "referenceName": "TW_Azure_DB_noTable",
                                    "type": "DatasetReference",
                                    "parameters": {
                                        "schema": "raw",
                                        "table": {
                                            "value": "@item().to",
                                            "type": "Expression"
                                        }
                                    }
                                }
                            ]
                        },
                        {
                            "name": "Stored Procedure1",
                            "type": "SqlServerStoredProcedure",
                            "dependsOn": [
                                {
                                    "activity": "Copy from BI to Azure",
                                    "dependencyConditions": [
                                        "Succeeded"
                                    ]
                                }
                            ],
                            "policy": {
                                "timeout": "7.00:00:00",
                                "retry": 0,
                                "retryIntervalInSeconds": 30,
                                "secureOutput": false,
                                "secureInput": false
                            },
                            "userProperties": [],
                            "typeProperties": {
                                "storedProcedureName": {
                                    "value": "@concat('raw.Update', item().to)",
                                    "type": "Expression"
                                }
                            },
                            "linkedServiceName": {
                                "referenceName": "TowWorksAzureSqlDB",
                                "type": "LinkedServiceReference"
                            }
                        }
                    ]
                }
            }
        ],
        "variables": {
            "tableMapping": {
                "type": "Array",
                "defaultValue": [
                    {
                        "from": "WORK_TASKS",
                        "to": "WorkTask"
                    },
                    {
                        "from": "Invoice",
                        "to": "Invoice"
                    },
                    {
                        "from": "ASSET",
                        "to": "Asset"
                    },
                    {
                        "from": "InvoiceDistribution",
                        "to": "InvoiceDistribution"
                    },
                    {
                        "from": "InvoiceEvent",
                        "to": "InvoiceEvent"
                    },
                    {
                        "from": "InvoiceTransaction",
                        "to": "InvoiceTransaction"
                    },
                    {
                        "from": "LOGISTICS_ORDERS",
                        "to": "LogisticOrder"
                    },
                    {
                        "from": "LOGISTICS_ORDERS_LINE_ITEMS",
                        "to": "LogisticOrderLineItem"
                    },
                    {
                        "from": "WORK_ORDERS",
                        "to": "WorkOrder"
                    },
                    {
                        "from": "WORK_ORDERS_STATUSES",
                        "to": "WorkOrderStatus"
                    }
                ]
            },
            "from": {
                "type": "String"
            },
            "to": {
                "type": "String"
            }
        },
        "folder": {
            "name": "TowWorks"
        },
        "annotations": []
    }
}
</code>```

Body:
Here is a simple pipeline that copies data from one database to another - it has a ForEach with 2 activities inside it.  It copies each table and then runs a stored procedure after each table.  The column names in the tables are the same.  It has a variable called tableMapping that is a json array that defines the 'from' and 'to' table names as they can be different.  The ForEach has this setting "batchCount": 1, so that it runs one at a time.  In my testing just now it processes the tables in the sequence in the variable tableMapping.  If you don't specify the batchCount = 1 then it will run them in parallel.

{
    "name": "TowWorks to Azure SQL DB",
    "properties": {
        "activities": [
            {
                "name": "ForEach1",
                "type": "ForEach",
                "dependsOn": [],
                "userProperties": [],
                "typeProperties": {
                    "items": {
                        "value": "@variables('tableMapping')",
                        "type": "Expression"
                    },
                    "batchCount": 1,
                    "activities": [
                        {
                            "name": "Copy from BI to Azure",
                            "type": "Copy",
                            "dependsOn": [],
                            "policy": {
                                "timeout": "7.00:00:00",
                                "retry": 0,
                                "retryIntervalInSeconds": 30,
                                "secureOutput": false,
                                "secureInput": false
                            },
                            "userProperties": [],
                            "typeProperties": {
                                "source": {
                                    "type": "SqlServerSource",
                                    "queryTimeout": "02:00:00"
                                },
                                "sink": {
                                    "type": "AzureSqlSink",
                                    "preCopyScript": {
                                        "value": "@{concat('truncate table raw.', item().to)}",
                                        "type": "Expression"
                                    },
                                    "disableMetricsCollection": false
                                },
                                "enableStaging": false
                            },
                            "inputs": [
                                {
                                    "referenceName": "BI_TW_Raw_NoTable",
                                    "type": "DatasetReference",
                                    "parameters": {
                                        "tableName": {
                                            "value": "@item().from",
                                            "type": "Expression"
                                        }
                                    }
                                }
                            ],
                            "outputs": [
                                {
                                    "referenceName": "TW_Azure_DB_noTable",
                                    "type": "DatasetReference",
                                    "parameters": {
                                        "schema": "raw",
                                        "table": {
                                            "value": "@item().to",
                                            "type": "Expression"
                                        }
                                    }
                                }
                            ]
                        },
                        {
                            "name": "Stored Procedure1",
                            "type": "SqlServerStoredProcedure",
                            "dependsOn": [
                                {
                                    "activity": "Copy from BI to Azure",
                                    "dependencyConditions": [
                                        "Succeeded"
                                    ]
                                }
                            ],
                            "policy": {
                                "timeout": "7.00:00:00",
                                "retry": 0,
                                "retryIntervalInSeconds": 30,
                                "secureOutput": false,
                                "secureInput": false
                            },
                            "userProperties": [],
                            "typeProperties": {
                                "storedProcedureName": {
                                    "value": "@concat('raw.Update', item().to)",
                                    "type": "Expression"
                                }
                            },
                            "linkedServiceName": {
                                "referenceName": "TowWorksAzureSqlDB",
                                "type": "LinkedServiceReference"
                            }
                        }
                    ]
                }
            }
        ],
        "variables": {
            "tableMapping": {
                "type": "Array",
                "defaultValue": [
                    {
                        "from": "WORK_TASKS",
                        "to": "WorkTask"
                    },
                    {
                        "from": "Invoice",
                        "to": "Invoice"
                    },
                    {
                        "from": "ASSET",
                        "to": "Asset"
                    },
                    {
                        "from": "InvoiceDistribution",
                        "to": "InvoiceDistribution"
                    },
                    {
                        "from": "InvoiceEvent",
                        "to": "InvoiceEvent"
                    },
                    {
                        "from": "InvoiceTransaction",
                        "to": "InvoiceTransaction"
                    },
                    {
                        "from": "LOGISTICS_ORDERS",
                        "to": "LogisticOrder"
                    },
                    {
                        "from": "LOGISTICS_ORDERS_LINE_ITEMS",
                        "to": "LogisticOrderLineItem"
                    },
                    {
                        "from": "WORK_ORDERS",
                        "to": "WorkOrder"
                    },
                    {
                        "from": "WORK_ORDERS_STATUSES",
                        "to": "WorkOrderStatus"
                    }
                ]
            },
            "from": {
                "type": "String"
            },
            "to": {
                "type": "String"
            }
        },
        "folder": {
            "name": "TowWorks"
        },
        "annotations": []
    }
}


来源: stackexchange

问:
Java / Mvn Local Resource not found in .jar Package
I'm tying to add a local Resource (A simple JSON File) to my Maven Project. But when I execute the code, I get the Error:
java.io.FileNotFoundException: ./resources/test.json (No such file or directory)

This is the Structure of my Project:

-Router

--src

---main

----java

----resources

-----test.json

--pom.xml

In my pom file I add the json:

```<code>    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>*.json</include>
            </includes>
        </resource>
    </resources>
</code>```

it seems it can't find the resource because in the code when instead of the path I look for

```<code>this.getClass().getResources("test.json")
</code>```

it returns null. Any suggestions how I can resolve this issue?

答:
From Class, the path is relative to the package of the class unless you include a leading slash, so if you don't want to use the current package, include a slash like this:</p>

```<code>this.getClass().getResource("/test.json")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm tying to add a local Resource (A simple JSON File) to my Maven Project. But when I execute the code, I get the Error:
java.io.FileNotFoundException: ./resources/test.json (No such file or directory)

This is the Structure of my Project:

-Router

--src

---main

----java

----resources

-----test.json

--pom.xml

In my pom file I add the json:

    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>*.json</include>
            </includes>
        </resource>
    </resources>

it seems it can't find the resource because in the code when instead of the path I look for

this.getClass().getResources("test.json")

it returns null. Any suggestions how I can resolve this issue?

Body:
From Class, the path is relative to the package of the class unless you include a leading slash, so if you don't want to use the current package, include a slash like this:

this.getClass().getResource("/test.json")


问:
why is the address of a c++ function always True?
well why would,

```<code>#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}
</code>```

give this,

1

why is every functions address true?

and how then can a function pointer work if all functions share (so it seems) the same addresss?

答:
The function address isn't "true".  There is no overload for an ostream that accepts an arbitrary function pointer.  But there is one for a boolean, and function pointers are implicitly convertable to bool.  So the compiler converts afunction from whatever its value actually is to true or false.  Since you can't have a function at address 0, the value printed is always true, which cout displays as 1.

This illustrates why implicit conversions are usually frowned upon.  If the conversion to bool were explicit, you would have had a compile error instead of silently doing the wrong thing.

ContentLicense: CC BY-SA 3.0

Body:
well why would,

#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}

give this,

1

why is every functions address true?

and how then can a function pointer work if all functions share (so it seems) the same addresss?


问:
Authenticating to jenkins with python3 requests module
I have the following problem:

I get the status and some other information from a jenkins server via a curl right now and everything works fine and I get the information. Now I wanted to exchange
the way of how to get it to the requests lib and now I can not get to authentificate anymore. I use the following right now for the request part:

```<code>data ={"Username":"foo_user","Password":"bar_pass"}
response = session.post("jenkins_url_to_trigger",data=data )
</code>```

Also I tried to set the auth parameter with http basic auth.

If anyone was able to access a jenkins server via the requests lib it would be
nice to see a example of how to do it, since i'm stuck at it now for a while.

Also for the curl part which works I use the following simple syntax:

```<code>curl -u foo_user:bar_pass -X GET -H "Content-Type: application/json" jenkins_url/something/to/get/api/json --insecure
</code>```

Also I searched for similar questions and didn't find anything that did help me.

答:
You can set the auth in the requests.Session object

```<code>import requests

session = requests.Session()
session.auth = ('myuser', 'mypass')

resp = session.post('jenkins_url_to_trigger')
</code>```

Session object reference: https://requests.readthedocs.io/en/latest/user/advanced/#session-objects

Body:
I have the following problem:

I get the status and some other information from a jenkins server via a curl right now and everything works fine and I get the information. Now I wanted to exchange
the way of how to get it to the requests lib and now I can not get to authentificate anymore. I use the following right now for the request part:

data ={"Username":"foo_user","Password":"bar_pass"}
response = session.post("jenkins_url_to_trigger",data=data )

Also I tried to set the auth parameter with http basic auth.

If anyone was able to access a jenkins server via the requests lib it would be
nice to see a example of how to do it, since i'm stuck at it now for a while.

Also for the curl part which works I use the following simple syntax:

curl -u foo_user:bar_pass -X GET -H "Content-Type: application/json" jenkins_url/something/to/get/api/json --insecure

Also I searched for similar questions and didn't find anything that did help me.

Body:
You can set the auth in the requests.Session object

import requests

session = requests.Session()
session.auth = ('myuser', 'mypass')

resp = session.post('jenkins_url_to_trigger')

Session object reference: https://requests.readthedocs.io/en/latest/user/advanced/#session-objects


问:
Python xml2csv xmlutils program need
I have a set of code on a recently installed machine I need to activate. Basically it is a script that convert xml style .dat file into a .csv file by creating a temporary file as an intermediary and converting the text using a convert() function. This appears to use the source code from the pypi.org site.

```<code>from xmlutils.xml2csv import xml2csv
import sys

xml_source = sys.argv[1]
obj_name = sys.argv[2]
filename_temp = xml_source + '.temp'
filename_csv = xml_source.replace('.dat','') + '.csv'

fin = open(xml_source)
fout = open(filename_temp, "wt")
fout.write("<root>")
for line in fin:
    fout.write( line.replace("<?xml version='1.0' encoding='UTF-8'?>", '') )
fout.write("</root>")
fin.close()
fout.close()

converter = xml2csv(filename_temp, filename_csv)
converter.convert(tag=obj_name)
</code>```

Below is a sample of the input in the xml format that gets translated line by line grouped into one record in the .csv file by the  tag. The output will be one line of a .csv file.

```<code>    <?xml version='1.0' encoding='UTF-8'?>
<Account>
  <Name>Alta Paints & Coatings  Inc</Name>
  <Type>Non Customer</Type>
  <RecordTypeId>012E0000000PR3uIAG</RecordTypeId>
  <ShippingStreet>136 W 3300 S</ShippingStreet>
  <ShippingCity>Salt Lake City</ShippingCity>
  <ShippingState>UT</ShippingState>
  <ShippingPostalCode>84115-3704</ShippingPostalCode>
  <Phone>801-466-9625</Phone>
  <Sic>5198</Sic>
  <NumberOfEmployees>16</NumberOfEmployees>
  <Description>PAINTS, VARNISHES, AND SUPPLIES</Description>
  <Sales_Channel__c>NAAO</Sales_Channel__c>
  <Xerox_Address_1__c>136 W 3300 S</Xerox_Address_1__c>
  <Xerox_City__c>Salt Lake City</Xerox_City__c>
  <Duns__c>197857873</Duns__c>
  <Legal_Name__c>ALTA PAINTS & COATINGS, INC.</Legal_Name__c>
  <Secondary_Name__c />
  <Latitude__c>40.699928</Latitude__c>
  <Longitude__c>-111.895096</Longitude__c>
  <Map_Status__c>G_GEO_SUCCESS</Map_Status__c>
  <Xerox_County__c>SALT LAKE</Xerox_County__c>
  <Xerox_State__c>UT</Xerox_State__c>
  <Xerox_Zip_4__c>3704</Xerox_Zip_4__c>
  <County__c>SALT LAKE</County__c>
  <Department__c>1</Department__c>
  <Franchise__c />
  <County_Code__c>035</County_Code__c>
  <Domestic_Ultimate_DUNS_Number__c>197857873</Domestic_Ultimate_DUNS_Number__c>
  <Global_Ultimate_DUNS_Number__c>197857873</Global_Ultimate_DUNS_Number__c>
  <Headquarters_DUNS_Number__c>197857873</Headquarters_DUNS_Number__c>
  <Location_Employee_Qty__c>16</Location_Employee_Qty__c>
  <Xerox_Zip_Code__c>84115-3704</Xerox_Zip_Code__c>
  <Org_Group_Code__c>1</Org_Group_Code__c>
  <Parent_DUNS__c />
  <Potential_Copy_Dupl_Qty__c>4974.4</Potential_Copy_Dupl_Qty__c>
  <Potential_Printing_Sys_Qty__c>10152.0</Potential_Printing_Sys_Qty__c>
  <Telephone_Last_4__c />
  <Subsidiary_Indicator__c>0</Subsidiary_Indicator__c>
  <Trade_Name__c />
  <XNAC_Code__c />
  <XNAC_Division__c />
  <Zip_4__c>3704</Zip_4__c>
  <Customer_Indicator__c>0.0</Customer_Indicator__c>
  <Franchise_Parent__c />
  <Telephone_Area_Code__c>801</Telephone_Area_Code__c>
  <Telephone_Exchange__c>466</Telephone_Exchange__c>
  <Total_Lsr_Prtg_Vol__c>0.0</Total_Lsr_Prtg_Vol__c>
  <Open_Sales_Channel__c>USCO</Open_Sales_Channel__c>
  <Estab_Copy_Volume__c>0.0</Estab_Copy_Volume__c>
</Account><?xml version='1.0' encoding='UTF-8'?>
<Account>
  <Name>Alta Paints & Coatings  Inc</Name>
  <Type>Non Customer</Type>
  <RecordTypeId>012E0000000PR3uIAG</RecordTypeId>
  <ShippingStreet>136 W 3300 S</ShippingStreet>
  <ShippingCity>Salt Lake City</ShippingCity>
  <ShippingState>UT</ShippingState>
  <ShippingPostalCode>84115-3704</ShippingPostalCode>
  <Phone>801-466-9625</Phone>
  <Sic>5198</Sic>
  <NumberOfEmployees>16</NumberOfEmployees>
  <Description>PAINTS, VARNISHES, AND SUPPLIES</Description>
  <Sales_Channel__c>NAAO</Sales_Channel__c>
  <Xerox_Address_1__c>136 W 3300 S</Xerox_Address_1__c>
  <Xerox_City__c>Salt Lake City</Xerox_City__c>
  <Duns__c>197857873</Duns__c>
  <Legal_Name__c>ALTA PAINTS & COATINGS, INC.</Legal_Name__c>
  <Secondary_Name__c />
  <Latitude__c>40.699928</Latitude__c>
  <Longitude__c>-111.895096</Longitude__c>
  <Map_Status__c>G_GEO_SUCCESS</Map_Status__c>
  <Xerox_County__c>SALT LAKE</Xerox_County__c>
  <Xerox_State__c>UT</Xerox_State__c>
  <Xerox_Zip_4__c>3704</Xerox_Zip_4__c>
  <County__c>SALT LAKE</County__c>
  <Department__c>1</Department__c>
  <Franchise__c />
  <County_Code__c>035</County_Code__c>
  <Domestic_Ultimate_DUNS_Number__c>197857873</Domestic_Ultimate_DUNS_Number__c>
  <Global_Ultimate_DUNS_Number__c>197857873</Global_Ultimate_DUNS_Number__c>
  <Headquarters_DUNS_Number__c>197857873</Headquarters_DUNS_Number__c>
  <Location_Employee_Qty__c>16</Location_Employee_Qty__c>
  <Xerox_Zip_Code__c>84115-3704</Xerox_Zip_Code__c>
  <Org_Group_Code__c>1</Org_Group_Code__c>
  <Parent_DUNS__c />
  <Potential_Copy_Dupl_Qty__c>4974.4</Potential_Copy_Dupl_Qty__c>
  <Potential_Printing_Sys_Qty__c>10152.0</Potential_Printing_Sys_Qty__c>
  <Telephone_Last_4__c />
  <Subsidiary_Indicator__c>0</Subsidiary_Indicator__c>
  <Trade_Name__c />
  <XNAC_Code__c />
  <XNAC_Division__c />
  <Zip_4__c>3704</Zip_4__c>
  <Customer_Indicator__c>0.0</Customer_Indicator__c>
  <Franchise_Parent__c />
  <Telephone_Area_Code__c>801</Telephone_Area_Code__c>
  <Telephone_Exchange__c>466</Telephone_Exchange__c>
  <Total_Lsr_Prtg_Vol__c>0.0</Total_Lsr_Prtg_Vol__c>
  <Open_Sales_Channel__c>GIS</Open_Sales_Channel__c>
  <Estab_Copy_Volume__c>0.0</Estab_Copy_Volume__c>
</Account><?xml version='1.0' encoding='UTF-8'?>
<Account>
  <Name>Sun & Moon Cafe</Name>
  <Type>Non Customer</Type>
  <RecordTypeId>012E0000000PR3uIAG</RecordTypeId>
  <ShippingStreet>22929 Highway 99</ShippingStreet>
  <ShippingCity>Edmonds</ShippingCity>
  <ShippingState>WA</ShippingState>
  <ShippingPostalCode>98026-8468</ShippingPostalCode>
  <Phone>425-977-2929</Phone>
  <Sic>5812</Sic>
  <NumberOfEmployees>9</NumberOfEmployees>
  <Description>EATING PLACES</Description>
  <Sales_Channel__c>NAAO</Sales_Channel__c>
  <Xerox_Address_1__c>22929 Highway 99</Xerox_Address_1__c>
  <Xerox_City__c>Edmonds</Xerox_City__c>
  <Duns__c>031593575</Duns__c>
  <Legal_Name__c>SUN & MOON CAFE</Legal_Name__c>
  <Secondary_Name__c />
  <Latitude__c>47.791194</Latitude__c>
  <Longitude__c>-122.337749</Longitude__c>
  <Map_Status__c>G_GEO_SUCCESS</Map_Status__c>
  <Xerox_County__c>SNOHOMISH</Xerox_County__c>
  <Xerox_State__c>WA</Xerox_State__c>
  <Xerox_Zip_4__c>8468</Xerox_Zip_4__c>
  <County__c>SNOHOMISH</County__c>
  <Department__c />
  <Franchise__c />
  <County_Code__c>061</County_Code__c>
  <Domestic_Ultimate_DUNS_Number__c />
  <Global_Ultimate_DUNS_Number__c />
  <Headquarters_DUNS_Number__c />
  <Location_Employee_Qty__c>9</Location_Employee_Qty__c>
  <Xerox_Zip_Code__c>98026-8468</Xerox_Zip_Code__c>
  <Org_Group_Code__c>0</Org_Group_Code__c>
  <Parent_DUNS__c />
  <Potential_Copy_Dupl_Qty__c>994.5</Potential_Copy_Dupl_Qty__c>
  <Potential_Printing_Sys_Qty__c>1976.67</Potential_Printing_Sys_Qty__c>
  <Telephone_Last_4__c />
  <Subsidiary_Indicator__c>0</Subsidiary_Indicator__c>
  <Trade_Name__c />
  <XNAC_Code__c />
  <XNAC_Division__c />
  <Zip_4__c>8468</Zip_4__c>
  <Customer_Indicator__c>0.0</Customer_Indicator__c>
  <Franchise_Parent__c />
  <Telephone_Area_Code__c>425</Telephone_Area_Code__c>
  <Telephone_Exchange__c>977</Telephone_Exchange__c>
  <Total_Lsr_Prtg_Vol__c>0.0</Total_Lsr_Prtg_Vol__c>
  <Open_Sales_Channel__c>USCO</Open_Sales_Channel__c>
  <Estab_Copy_Volume__c>0.0</Estab_Copy_Volume__c>
</Account><?xml version='1.0' encoding='UTF-8'?>
</code>```

On my previous machine, I was able to enter the path of the python conversion script name, the xml style .dat file name, the Account handle and process accordingly.

Example:

```<code>C:\data\convert_xml_to_csv.py C:\data\csv\2020-02-13-estab-insert.dat Account
</code>```

At first, I got an error message that the program wasn't available, so I eventually found the page to download the latest version of Python (v 3.8.1). I selected the executable x86-64 version of the download. After that, the command just goes to the next line without any action or anything processed. I'm not sure if I have to download anything else off the xmlutils source code page or what action to take next. I may need to be walked through the rest of the process to activate this script on a new machine. It was transferred once before but the creator is no longer with the company. Is anyone able to help me?

Joao,

So I downloaded the latest version of Python (version 3.8.1), identified the path of the .exe install file and added it to the Path in environmental variables. The paths are in screenshots 2 and 3 below:

I then tried to run my script from the Powershell, however, it simply skipped to the next line without creating an output file. So then I tried to run the same script on the Command Prompt and it yielded that the xmlutils module was not found.

So it looks like I may have to download the xmlutils package from the PyPl site. But it doesn't look like there's a clear way for me to do that at this point with running a .tar.gz file.

Update: 2/18/20

I believe I have successfully installed the latest version of the xmlutils python package via the pip command. Once I did that, I tried to convert a file again where it doesn't recognize part of the code. My only guess with this error at this point is that it's an error related to an updated version of these program. Is anyone able to make the necessary tweaks from here based on this information?

Update: 3/5/2020

So after installing the xmlutils and the setuptools package where both are located in the path for Environment Variables, running the script now does in fact create the cloned temporary file this script customary has done. However, it leaves the destination file of the finished output blank for the .csv file. Anyone have any other suggestions in regards to correcting this?

xml2csv python script result - Mar 5th

Conversion error with xmlutils installed

Command Prompt Output

Python Environment check result

Python Path image

Environmental variable path

答:
When invoking python scripts from the terminal, you should pass the scripts as arguments to the python call.

First of all, when you installed Python, did you add it to the PATH environment variable?
Run the following command, and report the output:

```<code>python -V
</code>```

If the command runs fine, and prints your Python version in the command prompt, you can now invoke your script by running:

```<code>python C:\data\convert_xml_to_csv.py C:\data\csv\2020-02-13-estab-insert.dat Account
</code>```

Let me know if you still have issues

Edit
In response to your Powershell Get-command output, you either do not have Python (in which case go through step 1), or you just do not have it in the PATH environment variable (skip step 1 and go directly to step 2).

Step 1: Install Python

Go to Python's website and download a Python version of your
choice (for that script, I think you're good with any version of
Python 3). For Python 3.7, for example, download this file;

Open the executable you just downloaded, and choose "Install Now", or "Customize Installation" if you'd prefer choosing the Install location, but write down that location, if you go with the latter option;

You can select here to add Python to the PATH environment variable, but I purposefully ignored it to cover the other scenario.

Step 2: Adding Python to your PATH environment variable

Before you start this step, you'll need the path to your Python executable. If you followed step 1 and chose the default install location, it will be something along the lines of C:\Users\<your user here>\AppData\Local\Programs\Python\Python37\

Navigate to the environment variables windows (System properties->Advanced Tab->Environment Variables, or just press the windows key and search for environment variables);

In the System variables box, search for the Path entry, select it and choose to edit the variable;

Now's a good time to double check that there're no Python related directories there (there probably aren't, given the screenshot you've showed). Select New, and a new line will show up, insert the path you've taken notice of;

Accept the changes;

Now open a new powershell and try out the command once again;

Title: Python xml2csv xmlutils program need

Body:
I have a set of code on a recently installed machine I need to activate. Basically it is a script that convert xml style .dat file into a .csv file by creating a temporary file as an intermediary and converting the text using a convert() function. This appears to use the source code from the pypi.org site.

from xmlutils.xml2csv import xml2csv
import sys

xml_source = sys.argv[1]
obj_name = sys.argv[2]
filename_temp = xml_source + '.temp'
filename_csv = xml_source.replace('.dat','') + '.csv'

fin = open(xml_source)
fout = open(filename_temp, "wt")
fout.write("<root>")
for line in fin:
    fout.write( line.replace("<?xml version='1.0' encoding='UTF-8'?>", '') )
fout.write("</root>")
fin.close()
fout.close()

converter = xml2csv(filename_temp, filename_csv)
converter.convert(tag=obj_name)

Below is a sample of the input in the xml format that gets translated line by line grouped into one record in the .csv file by the  tag. The output will be one line of a .csv file.

    <?xml version='1.0' encoding='UTF-8'?>
<Account>
  <Name>Alta Paints & Coatings  Inc</Name>
  <Type>Non Customer</Type>
  <RecordTypeId>012E0000000PR3uIAG</RecordTypeId>
  <ShippingStreet>136 W 3300 S</ShippingStreet>
  <ShippingCity>Salt Lake City</ShippingCity>
  <ShippingState>UT</ShippingState>
  <ShippingPostalCode>84115-3704</ShippingPostalCode>
  <Phone>801-466-9625</Phone>
  <Sic>5198</Sic>
  <NumberOfEmployees>16</NumberOfEmployees>
  <Description>PAINTS, VARNISHES, AND SUPPLIES</Description>
  <Sales_Channel__c>NAAO</Sales_Channel__c>
  <Xerox_Address_1__c>136 W 3300 S</Xerox_Address_1__c>
  <Xerox_City__c>Salt Lake City</Xerox_City__c>
  <Duns__c>197857873</Duns__c>
  <Legal_Name__c>ALTA PAINTS & COATINGS, INC.</Legal_Name__c>
  <Secondary_Name__c />
  <Latitude__c>40.699928</Latitude__c>
  <Longitude__c>-111.895096</Longitude__c>
  <Map_Status__c>G_GEO_SUCCESS</Map_Status__c>
  <Xerox_County__c>SALT LAKE</Xerox_County__c>
  <Xerox_State__c>UT</Xerox_State__c>
  <Xerox_Zip_4__c>3704</Xerox_Zip_4__c>
  <County__c>SALT LAKE</County__c>
  <Department__c>1</Department__c>
  <Franchise__c />
  <County_Code__c>035</County_Code__c>
  <Domestic_Ultimate_DUNS_Number__c>197857873</Domestic_Ultimate_DUNS_Number__c>
  <Global_Ultimate_DUNS_Number__c>197857873</Global_Ultimate_DUNS_Number__c>
  <Headquarters_DUNS_Number__c>197857873</Headquarters_DUNS_Number__c>
  <Location_Employee_Qty__c>16</Location_Employee_Qty__c>
  <Xerox_Zip_Code__c>84115-3704</Xerox_Zip_Code__c>
  <Org_Group_Code__c>1</Org_Group_Code__c>
  <Parent_DUNS__c />
  <Potential_Copy_Dupl_Qty__c>4974.4</Potential_Copy_Dupl_Qty__c>
  <Potential_Printing_Sys_Qty__c>10152.0</Potential_Printing_Sys_Qty__c>
  <Telephone_Last_4__c />
  <Subsidiary_Indicator__c>0</Subsidiary_Indicator__c>
  <Trade_Name__c />
  <XNAC_Code__c />
  <XNAC_Division__c />
  <Zip_4__c>3704</Zip_4__c>
  <Customer_Indicator__c>0.0</Customer_Indicator__c>
  <Franchise_Parent__c />
  <Telephone_Area_Code__c>801</Telephone_Area_Code__c>
  <Telephone_Exchange__c>466</Telephone_Exchange__c>
  <Total_Lsr_Prtg_Vol__c>0.0</Total_Lsr_Prtg_Vol__c>
  <Open_Sales_Channel__c>USCO</Open_Sales_Channel__c>
  <Estab_Copy_Volume__c>0.0</Estab_Copy_Volume__c>
</Account><?xml version='1.0' encoding='UTF-8'?>
<Account>
  <Name>Alta Paints & Coatings  Inc</Name>
  <Type>Non Customer</Type>
  <RecordTypeId>012E0000000PR3uIAG</RecordTypeId>
  <ShippingStreet>136 W 3300 S</ShippingStreet>
  <ShippingCity>Salt Lake City</ShippingCity>
  <ShippingState>UT</ShippingState>
  <ShippingPostalCode>84115-3704</ShippingPostalCode>
  <Phone>801-466-9625</Phone>
  <Sic>5198</Sic>
  <NumberOfEmployees>16</NumberOfEmployees>
  <Description>PAINTS, VARNISHES, AND SUPPLIES</Description>
  <Sales_Channel__c>NAAO</Sales_Channel__c>
  <Xerox_Address_1__c>136 W 3300 S</Xerox_Address_1__c>
  <Xerox_City__c>Salt Lake City</Xerox_City__c>
  <Duns__c>197857873</Duns__c>
  <Legal_Name__c>ALTA PAINTS & COATINGS, INC.</Legal_Name__c>
  <Secondary_Name__c />
  <Latitude__c>40.699928</Latitude__c>
  <Longitude__c>-111.895096</Longitude__c>
  <Map_Status__c>G_GEO_SUCCESS</Map_Status__c>
  <Xerox_County__c>SALT LAKE</Xerox_County__c>
  <Xerox_State__c>UT</Xerox_State__c>
  <Xerox_Zip_4__c>3704</Xerox_Zip_4__c>
  <County__c>SALT LAKE</County__c>
  <Department__c>1</Department__c>
  <Franchise__c />
  <County_Code__c>035</County_Code__c>
  <Domestic_Ultimate_DUNS_Number__c>197857873</Domestic_Ultimate_DUNS_Number__c>
  <Global_Ultimate_DUNS_Number__c>197857873</Global_Ultimate_DUNS_Number__c>
  <Headquarters_DUNS_Number__c>197857873</Headquarters_DUNS_Number__c>
  <Location_Employee_Qty__c>16</Location_Employee_Qty__c>
  <Xerox_Zip_Code__c>84115-3704</Xerox_Zip_Code__c>
  <Org_Group_Code__c>1</Org_Group_Code__c>
  <Parent_DUNS__c />
  <Potential_Copy_Dupl_Qty__c>4974.4</Potential_Copy_Dupl_Qty__c>
  <Potential_Printing_Sys_Qty__c>10152.0</Potential_Printing_Sys_Qty__c>
  <Telephone_Last_4__c />
  <Subsidiary_Indicator__c>0</Subsidiary_Indicator__c>
  <Trade_Name__c />
  <XNAC_Code__c />
  <XNAC_Division__c />
  <Zip_4__c>3704</Zip_4__c>
  <Customer_Indicator__c>0.0</Customer_Indicator__c>
  <Franchise_Parent__c />
  <Telephone_Area_Code__c>801</Telephone_Area_Code__c>
  <Telephone_Exchange__c>466</Telephone_Exchange__c>
  <Total_Lsr_Prtg_Vol__c>0.0</Total_Lsr_Prtg_Vol__c>
  <Open_Sales_Channel__c>GIS</Open_Sales_Channel__c>
  <Estab_Copy_Volume__c>0.0</Estab_Copy_Volume__c>
</Account><?xml version='1.0' encoding='UTF-8'?>
<Account>
  <Name>Sun & Moon Cafe</Name>
  <Type>Non Customer</Type>
  <RecordTypeId>012E0000000PR3uIAG</RecordTypeId>
  <ShippingStreet>22929 Highway 99</ShippingStreet>
  <ShippingCity>Edmonds</ShippingCity>
  <ShippingState>WA</ShippingState>
  <ShippingPostalCode>98026-8468</ShippingPostalCode>
  <Phone>425-977-2929</Phone>
  <Sic>5812</Sic>
  <NumberOfEmployees>9</NumberOfEmployees>
  <Description>EATING PLACES</Description>
  <Sales_Channel__c>NAAO</Sales_Channel__c>
  <Xerox_Address_1__c>22929 Highway 99</Xerox_Address_1__c>
  <Xerox_City__c>Edmonds</Xerox_City__c>
  <Duns__c>031593575</Duns__c>
  <Legal_Name__c>SUN & MOON CAFE</Legal_Name__c>
  <Secondary_Name__c />
  <Latitude__c>47.791194</Latitude__c>
  <Longitude__c>-122.337749</Longitude__c>
  <Map_Status__c>G_GEO_SUCCESS</Map_Status__c>
  <Xerox_County__c>SNOHOMISH</Xerox_County__c>
  <Xerox_State__c>WA</Xerox_State__c>
  <Xerox_Zip_4__c>8468</Xerox_Zip_4__c>
  <County__c>SNOHOMISH</County__c>
  <Department__c />
  <Franchise__c />
  <County_Code__c>061</County_Code__c>
  <Domestic_Ultimate_DUNS_Number__c />
  <Global_Ultimate_DUNS_Number__c />
  <Headquarters_DUNS_Number__c />
  <Location_Employee_Qty__c>9</Location_Employee_Qty__c>
  <Xerox_Zip_Code__c>98026-8468</Xerox_Zip_Code__c>
  <Org_Group_Code__c>0</Org_Group_Code__c>
  <Parent_DUNS__c />
  <Potential_Copy_Dupl_Qty__c>994.5</Potential_Copy_Dupl_Qty__c>
  <Potential_Printing_Sys_Qty__c>1976.67</Potential_Printing_Sys_Qty__c>
  <Telephone_Last_4__c />
  <Subsidiary_Indicator__c>0</Subsidiary_Indicator__c>
  <Trade_Name__c />
  <XNAC_Code__c />
  <XNAC_Division__c />
  <Zip_4__c>8468</Zip_4__c>
  <Customer_Indicator__c>0.0</Customer_Indicator__c>
  <Franchise_Parent__c />
  <Telephone_Area_Code__c>425</Telephone_Area_Code__c>
  <Telephone_Exchange__c>977</Telephone_Exchange__c>
  <Total_Lsr_Prtg_Vol__c>0.0</Total_Lsr_Prtg_Vol__c>
  <Open_Sales_Channel__c>USCO</Open_Sales_Channel__c>
  <Estab_Copy_Volume__c>0.0</Estab_Copy_Volume__c>
</Account><?xml version='1.0' encoding='UTF-8'?>

On my previous machine, I was able to enter the path of the python conversion script name, the xml style .dat file name, the Account handle and process accordingly.

Example:

C:\data\convert_xml_to_csv.py C:\data\csv\2020-02-13-estab-insert.dat Account

At first, I got an error message that the program wasn't available, so I eventually found the page to download the latest version of Python (v 3.8.1). I selected the executable x86-64 version of the download. After that, the command just goes to the next line without any action or anything processed. I'm not sure if I have to download anything else off the xmlutils source code page or what action to take next. I may need to be walked through the rest of the process to activate this script on a new machine. It was transferred once before but the creator is no longer with the company. Is anyone able to help me?

Joao,

So I downloaded the latest version of Python (version 3.8.1), identified the path of the .exe install file and added it to the Path in environmental variables. The paths are in screenshots 2 and 3 below:

I then tried to run my script from the Powershell, however, it simply skipped to the next line without creating an output file. So then I tried to run the same script on the Command Prompt and it yielded that the xmlutils module was not found.

So it looks like I may have to download the xmlutils package from the PyPl site. But it doesn't look like there's a clear way for me to do that at this point with running a .tar.gz file.

Update: 2/18/20

I believe I have successfully installed the latest version of the xmlutils python package via the pip command. Once I did that, I tried to convert a file again where it doesn't recognize part of the code. My only guess with this error at this point is that it's an error related to an updated version of these program. Is anyone able to make the necessary tweaks from here based on this information?

Update: 3/5/2020

So after installing the xmlutils and the setuptools package where both are located in the path for Environment Variables, running the script now does in fact create the cloned temporary file this script customary has done. However, it leaves the destination file of the finished output blank for the .csv file. Anyone have any other suggestions in regards to correcting this?

xml2csv python script result - Mar 5th

Conversion error with xmlutils installed

Command Prompt Output

Python Environment check result

Python Path image

Environmental variable path

Body:
When invoking python scripts from the terminal, you should pass the scripts as arguments to the python call.

First of all, when you installed Python, did you add it to the PATH environment variable?
Run the following command, and report the output:

python -V

If the command runs fine, and prints your Python version in the command prompt, you can now invoke your script by running:

python C:\data\convert_xml_to_csv.py C:\data\csv\2020-02-13-estab-insert.dat Account

Let me know if you still have issues

Edit
In response to your Powershell Get-command output, you either do not have Python (in which case go through step 1), or you just do not have it in the PATH environment variable (skip step 1 and go directly to step 2).

Step 1: Install Python

Go to Python's website and download a Python version of your
choice (for that script, I think you're good with any version of
Python 3). For Python 3.7, for example, download this file;

Open the executable you just downloaded, and choose "Install Now", or "Customize Installation" if you'd prefer choosing the Install location, but write down that location, if you go with the latter option;

You can select here to add Python to the PATH environment variable, but I purposefully ignored it to cover the other scenario.

Step 2: Adding Python to your PATH environment variable

Before you start this step, you'll need the path to your Python executable. If you followed step 1 and chose the default install location, it will be something along the lines of C:\Users\<your user here>\AppData\Local\Programs\Python\Python37\

Navigate to the environment variables windows (System properties->Advanced Tab->Environment Variables, or just press the windows key and search for environment variables);

In the System variables box, search for the Path entry, select it and choose to edit the variable;

Now's a good time to double check that there're no Python related directories there (there probably aren't, given the screenshot you've showed). Select New, and a new line will show up, insert the path you've taken notice of;

Accept the changes;

Now open a new powershell and try out the command once again;


问:
Black status bar doesn't disappear when closing Contex Action Mode
To be able to make the drawer layout go under the status bar, I've needed to set its color to transparent and set SystemUIVisibility to fullscreen. When starting Context Action Mode the status bar becomes black.

This can be "solved" by setting the color of the status bar in the OnCreateActionMode and making it transparent again in OnDestroyActionMode (although you can still see the black bar for a moment).

The real problem appears when I'm in Contextual Action Mode and I navigate to another fragment, finishing the contextual mode before navigating. This makes the black view appear over the fragment's layout and it can't be removed.

You can see an image of this behavior:

.

I'm using Xamarin Android, but the implementation in java should be fairly similar. The drawer layout and main content are all created programmatically:

To set the status bar:

```<code>if (Build.VERSION.SdkInt > BuildVersionCodes.Lollipop)
{
      //we don't need the translucent flag this is handled by the theme
      StatusBarHelper.SetTranslucentStatusFlag(Activity, false);
      //set the statusbarcolor transparent to remove the black shadow
      StatusBarHelper.SetStatusBarColor(Activity, Color.Transparent);
}
StatusBarHelper.SetLightStatusBar(Activity, false);`
</code>```

To create the main view (with the drawer):

```<code>_drawerLayout = new DrawerLayout(inflater.Context)
{
    LayoutParameters = new DrawerLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent),
};

ViewCompat.SetOnApplyWindowInsetsListener(_drawerLayout, this); // This only works from lollipop

using (FrameLayout contentContainer = new FrameLayout(inflater.Context))
{
    contentContainer.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
    // Sets fullscreen to be able to go under the status bar
    if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
    {
        // Already works since Kitkat, but since SetOnApplyWindowInsets only works from lollipop, for the moment we enable this later
        contentContainer.SystemUiVisibility = (StatusBarVisibility)(SystemUiFlags.LayoutStable | SystemUiFlags.LayoutFullscreen | SystemUiFlags.LayoutHideNavigation);
    }

    // Make the content ViewGroup ignore insets so that it does not use the default padding
    ViewCompat.SetOnApplyWindowInsetsListener(contentContainer, this);

    // Scrim view. This is used to paint under the status bar the color that we want
    using (View statusBarScrim = new View(inflater.Context))
    {
        statusBarScrim.Id = Resource.Id.scrim_view;
        statusBarScrim.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 0);

        statusBarScrim.SetBackgroundColor(new Color(ResourcesCompat.GetColor(Resources, Resource.Color.primaryDark, null)));

        ViewCompat.SetOnApplyWindowInsetsListener(statusBarScrim, this);

        contentContainer.AddView(statusBarScrim);
    }

    //Create main content (toolbar and fragment container)
    using (var mainContent = CreateMainContent(inflater))
    {
        contentContainer.AddView(mainContent);
    }

    contentContainer.SetFitsSystemWindows(true);

    _drawerLayout.AddView(contentContainer);
}
</code>```

Finally the code for the insetListener:

```<code>// This is used to handle the scrim view
// The scrim view is used to cover the status bar with a color
// The scrim consumes the top inset by getting its height
// All other views are ignored
public WindowInsetsCompat OnApplyWindowInsets(View v, WindowInsetsCompat insets)
{
    // Check if it's the scrim view
    // If it's not the scrim it will not consume the insets
    if (v.Id == Resource.Id.scrim_view)
    {
        var topInset = insets.SystemWindowInsetTop;
        if (v.LayoutParameters.Height != topInset)
        {
            v.LayoutParameters.Height = topInset;
            v.RequestLayout();
        }
    }

    return insets;
}
</code>```

To create the Context Action Menu I use the StartSupportActionMode and in the OnCreateActionMode I'm just setting up the menu. The status bar becomes black (Context Action Mode adds a view like the scrim I'm using, but I haven't found a way to color it).

There's an item in this menu that navigates to the screen you see in the image I attached previously. When this item is pressed i call _actionMode.Finish() and then navigate there. The result is that the Context Action Mode toolbar disappears but this black scrim view doesn't.

If I add a delay before navigating this error doesn't occur, so I'm thinking it has something to do with the animation? Either way, solving things with delay is always bad practice because it will be different in each device.

答:
Okay, so I'm pretty sure this must be a bug with AppCompat's ActionMode. In the end, I was lucky and setting FitSystemWindows on the fragment navigated to seems to fix the issue.

Also, I found how to set the color of the scrim layout Action Mode adds without ever seeing the black bar.

I found the answer here https://stackoverflow.com/a/38702953/10054508 so all the credit goes to him. Either way, I'll paste it here:

```<code><color name="abc_input_method_navigation_guard" tools:override="true">@color/primary_dark</color>
</code>```

Body:
To be able to make the drawer layout go under the status bar, I've needed to set its color to transparent and set SystemUIVisibility to fullscreen. When starting Context Action Mode the status bar becomes black.

This can be "solved" by setting the color of the status bar in the OnCreateActionMode and making it transparent again in OnDestroyActionMode (although you can still see the black bar for a moment).

The real problem appears when I'm in Contextual Action Mode and I navigate to another fragment, finishing the contextual mode before navigating. This makes the black view appear over the fragment's layout and it can't be removed.

You can see an image of this behavior:

.

I'm using Xamarin Android, but the implementation in java should be fairly similar. The drawer layout and main content are all created programmatically:

To set the status bar:

if (Build.VERSION.SdkInt > BuildVersionCodes.Lollipop)
{
      //we don't need the translucent flag this is handled by the theme
      StatusBarHelper.SetTranslucentStatusFlag(Activity, false);
      //set the statusbarcolor transparent to remove the black shadow
      StatusBarHelper.SetStatusBarColor(Activity, Color.Transparent);
}
StatusBarHelper.SetLightStatusBar(Activity, false);`

To create the main view (with the drawer):

_drawerLayout = new DrawerLayout(inflater.Context)
{
    LayoutParameters = new DrawerLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent),
};

ViewCompat.SetOnApplyWindowInsetsListener(_drawerLayout, this); // This only works from lollipop

using (FrameLayout contentContainer = new FrameLayout(inflater.Context))
{
    contentContainer.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
    // Sets fullscreen to be able to go under the status bar
    if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
    {
        // Already works since Kitkat, but since SetOnApplyWindowInsets only works from lollipop, for the moment we enable this later
        contentContainer.SystemUiVisibility = (StatusBarVisibility)(SystemUiFlags.LayoutStable | SystemUiFlags.LayoutFullscreen | SystemUiFlags.LayoutHideNavigation);
    }

    // Make the content ViewGroup ignore insets so that it does not use the default padding
    ViewCompat.SetOnApplyWindowInsetsListener(contentContainer, this);

    // Scrim view. This is used to paint under the status bar the color that we want
    using (View statusBarScrim = new View(inflater.Context))
    {
        statusBarScrim.Id = Resource.Id.scrim_view;
        statusBarScrim.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 0);

        statusBarScrim.SetBackgroundColor(new Color(ResourcesCompat.GetColor(Resources, Resource.Color.primaryDark, null)));

        ViewCompat.SetOnApplyWindowInsetsListener(statusBarScrim, this);

        contentContainer.AddView(statusBarScrim);
    }

    //Create main content (toolbar and fragment container)
    using (var mainContent = CreateMainContent(inflater))
    {
        contentContainer.AddView(mainContent);
    }

    contentContainer.SetFitsSystemWindows(true);

    _drawerLayout.AddView(contentContainer);
}

Finally the code for the insetListener:

// This is used to handle the scrim view
// The scrim view is used to cover the status bar with a color
// The scrim consumes the top inset by getting its height
// All other views are ignored
public WindowInsetsCompat OnApplyWindowInsets(View v, WindowInsetsCompat insets)
{
    // Check if it's the scrim view
    // If it's not the scrim it will not consume the insets
    if (v.Id == Resource.Id.scrim_view)
    {
        var topInset = insets.SystemWindowInsetTop;
        if (v.LayoutParameters.Height != topInset)
        {
            v.LayoutParameters.Height = topInset;
            v.RequestLayout();
        }
    }

    return insets;
}

To create the Context Action Menu I use the StartSupportActionMode and in the OnCreateActionMode I'm just setting up the menu. The status bar becomes black (Context Action Mode adds a view like the scrim I'm using, but I haven't found a way to color it).

There's an item in this menu that navigates to the screen you see in the image I attached previously. When this item is pressed i call _actionMode.Finish() and then navigate there. The result is that the Context Action Mode toolbar disappears but this black scrim view doesn't.

If I add a delay before navigating this error doesn't occur, so I'm thinking it has something to do with the animation? Either way, solving things with delay is always bad practice because it will be different in each device.

Body:
Okay, so I'm pretty sure this must be a bug with AppCompat's ActionMode. In the end, I was lucky and setting FitSystemWindows on the fragment navigated to seems to fix the issue.

Also, I found how to set the color of the scrim layout Action Mode adds without ever seeing the black bar.

I found the answer here https://stackoverflow.com/a/38702953/10054508 so all the credit goes to him. Either way, I'll paste it here:

<color name="abc_input_method_navigation_guard" tools:override="true">@color/primary_dark</color>


问:
How to rearrange child divs on data attribute by recent date time in jQuery?
I have set each section with its own category name and wanted to rearrange its child div elements based on the data attribute sorted by recent date time published at the top then descending to the bottom.

I'm trying to loop through each of the child elements of its parent but the function reArrangeVideosByRecentUploads() isn't working. I debugged it and it would stop at this line of code $('.section' + ALPHA_CLASS_NAME + ' .thumb .video-thumbnail').each(function(i) { and then skip the function entirely. There's no error in the code, so I'm not sure why this is the case.

var dates = [];
var _old;

var ALPHA_CLASS_NAME = ".alpha";
var BRAVO_CLASS_NAME = ".bravo";
var CHARLIE_CLASS_NAME = ".charlie";

function sortDates(a, b) {
  return new Date(b).getTime() - new Date(a).getTime();
}

function reArrangeVideosByRecentUploads() {
  if ($(this).parent('.section' + ALPHA_CLASS_NAME)) {
    $('.section' + ALPHA_CLASS_NAME + ' .thumb .video-thumbnail').each(function(i) {
      _old = $(this).parent();
      dates.push($(this).data('date'));

      sorted = dates.sort(sortDates);
      _new = $('
').insertBefore(_old);

      $.each(sorted, function(i, val) {
        $('div[data-date="' + val + '"]').appendTo(_new);
      });

      _old.remove();
    });
  } else if ($(this).parent('.section' + BRAVO_CLASS_NAME)) {
    $('.section' + BRAVO_CLASS_NAME + ' .thumb .video-thumbnail').each(function(i) {
      _old = $(this).parent();
      dates.push($(this).data('date'));

      sorted = dates.sort(sortDates);
      _new = $('
').insertBefore(_old);

      $.each(sorted, function(i, val) {
        $('div[data-date="' + val + '"]').appendTo(_new);
      });

      _old.remove();
    });
  } else if ($(this).parent('.section' + CHARLIE_CLASS_NAME)) {
    $('.section' + CHARLIE_CLASS_NAME + ' .thumb .video-thumbnail').each(function(i) {
      _old = $(this).parent();
      dates.push($(this).data('date'));

      sorted = dates.sort(sortDates);
      _new = $('
').insertBefore(_old);

      $.each(sorted, function(i, val) {
        $('div[data-date="' + val + '"]').appendTo(_new);
      });

      _old.remove();
    });
  }
}

reArrangeVideosByRecentUploads();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="alpha">
  <h1>
    Alpha
  </h1>
  <div class="thumb">
    <div class="video-thumbnail" data-date="2012-04-02T13:04:48.000Z">A1 - 4/2012</div>
    <div class="video-thumbnail" data-date="2011-06-30T21:21:16.000Z">A2 - 6/2011</div>
    <div class="video-thumbnail" data-date="2013-03-05T18:35:47.000Z">A3 - 3/2013</div>
    <div class="video-thumbnail" data-date="2011-01-24T15:20:14.000Z">A4 - 1/2011</div>
    <div class="video-thumbnail" data-date="2016-05-12T17:25:43.000Z">A5 - 5/12/2016</div>
    <div class="video-thumbnail" data-date="2016-05-19T08:32:24.000Z">A6 - 5/19/2016</div>
    <div class="video-thumbnail" data-date="2020-02-03T22:05:25.000Z">A7 - 2/2020</div>
    <div class="video-thumbnail" data-date="2016-05-31T18:13:21.000Z">A8 - 5/31/2016</div>
    <div class="video-thumbnail" data-date="2014-01-24T17:00:02.000Z">A9 - 1/2014</div>
  </div>
</section>
<section class="bravo">
  <h1>
    Bravo
  </h1>
  <div class="thumb">
    <div class="video-thumbnail" data-date="2013-03-05T18:35:47.000Z">B1 - 3/2013</div>
    <div class="video-thumbnail" data-date="2011-01-24T15:20:14.000Z">B2 - 1/2011</div>
    <div class="video-thumbnail" data-date="2016-05-12T17:25:43.000Z">B3 - 5/12/2016</div>
    <div class="video-thumbnail" data-date="2016-05-19T08:32:24.000Z">B4 - 5/19/2016</div>
  </div>
</section>
<section class="charlie">
  <h1>
    Charlie
  </h1>
  <div class="thumb">
    <div class="video-thumbnail" data-date="2012-04-02T13:04:48.000Z">C1 - 4/2012</div>
    <div class="video-thumbnail" data-date="2011-06-30T21:21:16.000Z">C2 - 6/2011</div>
    <div class="video-thumbnail" data-date="2016-05-31T18:13:21.000Z">C3 - 5/31/2016</div>
    <div class="video-thumbnail" data-date="2014-01-24T17:00:02.000Z">C4 - 1/2014</div>
  </div>
</section></code>```

JSfiddle

答:
You're overcomplicating this a little. To sort elements you can use the sort() method. Provide this method a function which accepts two arguments which are the elements in the iteration to compare to each other. Convert the data-date values to Date objects and compare them, returning 1 or -1 depending on which is the most recent.

To keep the logic DRY you can loop over all the section .thumb containers and sort them individually. Try this:

$('section .thumb').each(function() {
  $(this).find('div').sort(function(a, b) {
    return new Date($(a).data('date')) < new Date($(b).data('date')) ? 1 : -1;
  }).appendTo(this);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="alpha">
  <h1>Alpha</h1>
  <div class="thumb">
    <div class="video-thumbnail" data-date="2012-04-02T13:04:48.000Z">A1 - 4/2012</div>
    <div class="video-thumbnail" data-date="2011-06-30T21:21:16.000Z">A2 - 6/2011</div>
    <div class="video-thumbnail" data-date="2013-03-05T18:35:47.000Z">A3 - 3/2013</div>
    <div class="video-thumbnail" data-date="2011-01-24T15:20:14.000Z">A4 - 1/2011</div>
    <div class="video-thumbnail" data-date="2016-05-12T17:25:43.000Z">A5 - 5/12/2016</div>
    <div class="video-thumbnail" data-date="2016-05-19T08:32:24.000Z">A6 - 5/19/2016</div>
    <div class="video-thumbnail" data-date="2020-02-03T22:05:25.000Z">A7 - 2/2020</div>
    <div class="video-thumbnail" data-date="2016-05-31T18:13:21.000Z">A8 - 5/31/2016</div>
    <div class="video-thumbnail" data-date="2014-01-24T17:00:02.000Z">A9 - 1/2014</div>
  </div>
</section>
<section class="bravo">
  <h1>Bravo</h1>
  <div class="thumb">
    <div class="video-thumbnail" data-date="2013-03-05T18:35:47.000Z">B1 - 3/2013</div>
    <div class="video-thumbnail" data-date="2011-01-24T15:20:14.000Z">B2 - 1/2011</div>
    <div class="video-thumbnail" data-date="2016-05-12T17:25:43.000Z">B3 - 5/12/2016</div>
    <div class="video-thumbnail" data-date="2016-05-19T08:32:24.000Z">B4 - 5/19/2016</div>
  </div>
</section>
<section class="charlie">
  <h1>Charlie</h1>
  <div class="thumb">
    <div class="video-thumbnail" data-date="2012-04-02T13:04:48.000Z">C1 - 4/2012</div>
    <div class="video-thumbnail" data-date="2011-06-30T21:21:16.000Z">C2 - 6/2011</div>
    <div class="video-thumbnail" data-date="2016-05-31T18:13:21.000Z">C3 - 5/31/2016</div>
    <div class="video-thumbnail" data-date="2014-01-24T17:00:02.000Z">C4 - 1/2014</div>
  </div>
</section></code>```

Body:
I have set each section with its own category name and wanted to rearrange its child div elements based on the data attribute sorted by recent date time published at the top then descending to the bottom.

I'm trying to loop through each of the child elements of its parent but the function reArrangeVideosByRecentUploads() isn't working. I debugged it and it would stop at this line of code $('.section' + ALPHA_CLASS_NAME + ' .thumb .video-thumbnail').each(function(i) { and then skip the function entirely. There's no error in the code, so I'm not sure why this is the case.

var dates = [];
var _old;

var ALPHA_CLASS_NAME = ".alpha";
var BRAVO_CLASS_NAME = ".bravo";
var CHARLIE_CLASS_NAME = ".charlie";

function sortDates(a, b) {
  return new Date(b).getTime() - new Date(a).getTime();
}

function reArrangeVideosByRecentUploads() {
  if ($(this).parent('.section' + ALPHA_CLASS_NAME)) {
    $('.section' + ALPHA_CLASS_NAME + ' .thumb .video-thumbnail').each(function(i) {
      _old = $(this).parent();
      dates.push($(this).data('date'));

      sorted = dates.sort(sortDates);
      _new = $('
').insertBefore(_old);

      $.each(sorted, function(i, val) {
        $('div[data-date="' + val + '"]').appendTo(_new);
      });

      _old.remove();
    });
  } else if ($(this).parent('.section' + BRAVO_CLASS_NAME)) {
    $('.section' + BRAVO_CLASS_NAME + ' .thumb .video-thumbnail').each(function(i) {
      _old = $(this).parent();
      dates.push($(this).data('date'));

      sorted = dates.sort(sortDates);
      _new = $('
').insertBefore(_old);

      $.each(sorted, function(i, val) {
        $('div[data-date="' + val + '"]').appendTo(_new);
      });

      _old.remove();
    });
  } else if ($(this).parent('.section' + CHARLIE_CLASS_NAME)) {
    $('.section' + CHARLIE_CLASS_NAME + ' .thumb .video-thumbnail').each(function(i) {
      _old = $(this).parent();
      dates.push($(this).data('date'));

      sorted = dates.sort(sortDates);
      _new = $('
').insertBefore(_old);

      $.each(sorted, function(i, val) {
        $('div[data-date="' + val + '"]').appendTo(_new);
      });

      _old.remove();
    });
  }
}

reArrangeVideosByRecentUploads();

    Alpha

A1 - 4/2012

A2 - 6/2011

A3 - 3/2013

A4 - 1/2011

A5 - 5/12/2016

A6 - 5/19/2016

A7 - 2/2020

A8 - 5/31/2016

A9 - 1/2014

    Bravo

B1 - 3/2013

B2 - 1/2011

B3 - 5/12/2016

B4 - 5/19/2016

    Charlie

C1 - 4/2012

C2 - 6/2011

C3 - 5/31/2016

C4 - 1/2014

JSfiddle

Body:
You're overcomplicating this a little. To sort elements you can use the sort() method. Provide this method a function which accepts two arguments which are the elements in the iteration to compare to each other. Convert the data-date values to Date objects and compare them, returning 1 or -1 depending on which is the most recent.

To keep the logic DRY you can loop over all the section .thumb containers and sort them individually. Try this:

$('section .thumb').each(function() {
  $(this).find('div').sort(function(a, b) {
    return new Date($(a).data('date')) < new Date($(b).data('date')) ? 1 : -1;
  }).appendTo(this);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="alpha">
  <h1>Alpha</h1>
  <div class="thumb">
    <div class="video-thumbnail" data-date="2012-04-02T13:04:48.000Z">A1 - 4/2012</div>
    <div class="video-thumbnail" data-date="2011-06-30T21:21:16.000Z">A2 - 6/2011</div>
    <div class="video-thumbnail" data-date="2013-03-05T18:35:47.000Z">A3 - 3/2013</div>
    <div class="video-thumbnail" data-date="2011-01-24T15:20:14.000Z">A4 - 1/2011</div>
    <div class="video-thumbnail" data-date="2016-05-12T17:25:43.000Z">A5 - 5/12/2016</div>
    <div class="video-thumbnail" data-date="2016-05-19T08:32:24.000Z">A6 - 5/19/2016</div>
    <div class="video-thumbnail" data-date="2020-02-03T22:05:25.000Z">A7 - 2/2020</div>
    <div class="video-thumbnail" data-date="2016-05-31T18:13:21.000Z">A8 - 5/31/2016</div>
    <div class="video-thumbnail" data-date="2014-01-24T17:00:02.000Z">A9 - 1/2014</div>
  </div>
</section>
<section class="bravo">
  <h1>Bravo</h1>
  <div class="thumb">
    <div class="video-thumbnail" data-date="2013-03-05T18:35:47.000Z">B1 - 3/2013</div>
    <div class="video-thumbnail" data-date="2011-01-24T15:20:14.000Z">B2 - 1/2011</div>
    <div class="video-thumbnail" data-date="2016-05-12T17:25:43.000Z">B3 - 5/12/2016</div>
    <div class="video-thumbnail" data-date="2016-05-19T08:32:24.000Z">B4 - 5/19/2016</div>
  </div>
</section>
<section class="charlie">
  <h1>Charlie</h1>
  <div class="thumb">
    <div class="video-thumbnail" data-date="2012-04-02T13:04:48.000Z">C1 - 4/2012</div>
    <div class="video-thumbnail" data-date="2011-06-30T21:21:16.000Z">C2 - 6/2011</div>
    <div class="video-thumbnail" data-date="2016-05-31T18:13:21.000Z">C3 - 5/31/2016</div>
    <div class="video-thumbnail" data-date="2014-01-24T17:00:02.000Z">C4 - 1/2014</div>
  </div>
</section>


问:
Are there drawbacks in using classes to construct redux store?
One of our developers suggested it is preferable to not use classes to construct redux store, but didn't give a concrete reason, mostly saying "it is not idiomatic and classes are not that well-implemented in ES6; it is preferable to avoid using classes in React".

Are there any issues (even if it's actually not an industry-standard?) to construct a redux store in this manner?

```<code>class Item {
  public name: string;
}

class ItemState {
  public items: Item[];
  public currentItem: Item;
}

// redux store
class AppState {
  public Items = new ItemState();
}

// then createStore(/*reducer*/, new AppState())
</code>```

答:
One thing that comes to mind is serialization. If you want to support things like hydration and time-travel debugging you need to be able to serialize your store and restore it.

Your example class doesn't use any methods or inheritence, so maybe that's not an issue for you. But if you plan to add that stuff, be aware that you may be cutting yourself off from the features i mentioned.

See also this section of the redux documentation

Body:
One of our developers suggested it is preferable to not use classes to construct redux store, but didn't give a concrete reason, mostly saying "it is not idiomatic and classes are not that well-implemented in ES6; it is preferable to avoid using classes in React".

Are there any issues (even if it's actually not an industry-standard?) to construct a redux store in this manner?

class Item {
  public name: string;
}

class ItemState {
  public items: Item[];
  public currentItem: Item;
}

// redux store
class AppState {
  public Items = new ItemState();
}

// then createStore(/*reducer*/, new AppState())


问:
Updating excel tables and pivot tables from within access
I am running an update from within an Access 2010 database using VBA code.  The update needs to update some tables by calling queries.  This part works fine.  I need to call a VBA macro in an Excel workbook to update the tables and pivot tables (which happen to get their data from the same Access database from which the VBA code is executing).

I get an error on the first line of code in the Excel workbook.  The first line simply is to select the approprite worksheet.  I know I am over complicating this.  But the whole reason is that I have to update the data since the code in the Access macro takes the summary worksheet and spits it out as html in a outlook mail message (which works beautifully).

Should I just take the code for calling the refresh and add the code for the html email to it?  Calling the Access stuff first, exit Access, then call the function by calling for Excel to open, do its thing, then exit Excel?

答:
A few options here, since I don't know your exact setup or the whys and wherefors of how things are being done:

Try setting your excel pivottables to
get their data by linking directly to
the access file, instead of copying
the data from it.  There's an option in pivot table settings to "refresh data on open."

Check out the Import External Data
wizard in the Data menu of Excel.  This will create a worksheet that just links to data.  This also has a "refresh data on open" option.  Then you can base your pivot tables on this, and have them refresh on open as well.  I think the first option is better, however :D


问:
{Flex: 1} not working with relative positioning
I want the second View to be relatively positioned at -50 below the first View, but the second View does not extend completely at the bottom.

```<code>import React from 'react';
import {View, Text} from 'react-native';

export const OverlayStorybook = () => {
  return (
    <View style={{flex: 1}}>
      <View style={{height: 100, backgroundColor: 'red'}}>
        <Text>OverlayStorybook</Text>
      </View>
      <View style={{flex: 1, backgroundColor: 'blue', top: 0}} />
    </View>
  );
};
</code>```

```<code>import React from 'react';
import {View, Text} from 'react-native';

export const OverlayStorybook = () => {
  return (
    <View style={{flex: 1}}>
      <View style={{height: 100, backgroundColor: 'red'}}>
        <Text>OverlayStorybook</Text>
      </View>
      <View style={{flex: 1, backgroundColor: 'blue', top: -50}} />
    </View>
  );
};
</code>```

You can see at the bottom there are 50 pixels that are white.

答:
Well I have found the answer to my question by myself. Just needed to wrap the second View inside a View and put position absolute.

```<code>import React from 'react';
import {View, Text} from 'react-native';

export const OverlayStorybook = () => {
  return (
    <View style={{flex: 1}}>
      <View style={{height: 100, backgroundColor: 'red'}}>
        <Text>OverlayStorybook</Text>
      </View>
      <View style={{flex: 1}}>
        <View
          style={{
            flex: 1,
            position: 'absolute',
            backgroundColor: 'blue',
            top: -50,
            left: 0,
            right: 0,
            bottom: 0,
          }}
        />
      </View>
    </View>
  );
};
</code>```

Body:
I want the second View to be relatively positioned at -50 below the first View, but the second View does not extend completely at the bottom.

import React from 'react';
import {View, Text} from 'react-native';

export const OverlayStorybook = () => {
  return (
    <View style={{flex: 1}}>
      <View style={{height: 100, backgroundColor: 'red'}}>
        <Text>OverlayStorybook</Text>
      </View>
      <View style={{flex: 1, backgroundColor: 'blue', top: 0}} />
    </View>
  );
};

import React from 'react';
import {View, Text} from 'react-native';

export const OverlayStorybook = () => {
  return (
    <View style={{flex: 1}}>
      <View style={{height: 100, backgroundColor: 'red'}}>
        <Text>OverlayStorybook</Text>
      </View>
      <View style={{flex: 1, backgroundColor: 'blue', top: -50}} />
    </View>
  );
};

You can see at the bottom there are 50 pixels that are white.

Body:
Well I have found the answer to my question by myself. Just needed to wrap the second View inside a View and put position absolute.

import React from 'react';
import {View, Text} from 'react-native';

export const OverlayStorybook = () => {
  return (
    <View style={{flex: 1}}>
      <View style={{height: 100, backgroundColor: 'red'}}>
        <Text>OverlayStorybook</Text>
      </View>
      <View style={{flex: 1}}>
        <View
          style={{
            flex: 1,
            position: 'absolute',
            backgroundColor: 'blue',
            top: -50,
            left: 0,
            right: 0,
            bottom: 0,
          }}
        />
      </View>
    </View>
  );
};


问:
Accessing pytest options set in pytest.ini in marking conditions
I'm writing tests for webapp and sometimes it takes a while for changes to be visible at the production server. I didn't want these tests to fail but I didn't want to ignore them either.  Thus I want to mark such tests as xfail when running against production server but I am failing to access the options object in the marking which can be accessed inside of the testcase. As soon as these tests would pass with XPASS, the marking would be removed. Also those tests should not be

Is there any possibility to do that?

```<code>@pytest.mark.xfail(
    options.getini("base_url") == options.getini("production_server"),
    reason="Change not yet deployed to the production server")
def test_apidoc(self, request, base_url):
</code>```

The only workaround I can see is this:

```<code>def test_apidoc(self, request, base_url):
    not_production_ready(request)
    if request.config.getoption("base_url") == request.config.getini("production_server"):
        pytest.xfail("Changes not yet deployed to the production")
    pass
</code>```

but that will ignore the test immediately.

答:
You can attach markers dynamically - I would introduce another marker, e.g. provisional_xfail that serves only one purpose: if the settings match the desired ones and the marker is present, the test gets an xfail marker added. Example:

```<code># conftest.py

def pytest_collection_modifyitems(config, items):
    if config.getoption('prod') == True:
        for item in items:
            if item.get_closest_marker('provisional_xfail') is not None:
                item.add_marker(pytest.mark.xfail(reason='Should fail for now with prod settings'))
</code>```

The test gets the provisional_xfail marker:

```<code>import pytest

@pytest.mark.provisional_xfail
def test_spam():
    assert False
</code>```

Body:
I'm writing tests for webapp and sometimes it takes a while for changes to be visible at the production server. I didn't want these tests to fail but I didn't want to ignore them either.  Thus I want to mark such tests as xfail when running against production server but I am failing to access the options object in the marking which can be accessed inside of the testcase. As soon as these tests would pass with XPASS, the marking would be removed. Also those tests should not be

Is there any possibility to do that?

@pytest.mark.xfail(
    options.getini("base_url") == options.getini("production_server"),
    reason="Change not yet deployed to the production server")
def test_apidoc(self, request, base_url):

The only workaround I can see is this:

def test_apidoc(self, request, base_url):
    not_production_ready(request)
    if request.config.getoption("base_url") == request.config.getini("production_server"):
        pytest.xfail("Changes not yet deployed to the production")
    pass

but that will ignore the test immediately.

Body:
You can attach markers dynamically - I would introduce another marker, e.g. provisional_xfail that serves only one purpose: if the settings match the desired ones and the marker is present, the test gets an xfail marker added. Example:

# conftest.py

def pytest_collection_modifyitems(config, items):
    if config.getoption('prod') == True:
        for item in items:
            if item.get_closest_marker('provisional_xfail') is not None:
                item.add_marker(pytest.mark.xfail(reason='Should fail for now with prod settings'))

The test gets the provisional_xfail marker:

import pytest

@pytest.mark.provisional_xfail
def test_spam():
    assert False


问:
Primary key not a Measure in cube?
I'm new to SSAS, so please bear with me.

I have two tables: FactTest and DimLocation.  I'm including the table schema, but in essence,  and FactTest.LocationName is foreign key to DimLocation.LocationName and DimLocation.LocationName is primary key:

```<code>CREATE TABLE [dbo].[FactTest](
    [test_date] [date] NULL,
    [DOWNLOAD] [float] NULL,
    [LocationName] [varchar](50) NULL
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[FactTest]  WITH CHECK ADD  CONSTRAINT [FK_FactTest_DimLocation] FOREIGN KEY([LocationName])
REFERENCES [dbo].[DimLocation] ([LocationName])
GO

ALTER TABLE [dbo].[FactTest] CHECK CONSTRAINT [FK_FactTest_DimLocation]
GO

CREATE TABLE [dbo].[DimLocation](
    [LocationId] [int] IDENTITY(1,1) NOT NULL,
    [LocationName] [varchar](50) NOT NULL,
 CONSTRAINT [PK_DimLocation] PRIMARY KEY CLUSTERED
(
    [LocationName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
</code>```

DimLocation looks like this:

```<code>LocationId      LocationName
1               Houston
2               San Antonio
3               Dallas
4               Austin
</code>```

and FactTest looks like this:

```<code>test_date       Download      LocationName
1/4/2020        8.56          Houston
1/4/2020        9.43          Dallas
1/5/2020        3.20          Houston
</code>```

When I'm creating the cube in VS 2013, I notice that the column LocationName is not included as one of the Measures. I also have other Dimension tables, and none of the primary key columns are part of the Measures.

Aren't the primary keys supposed to be used as Measures when creating a cube? If not, then how am I supposed to link the fact tables to the dim tables?

答:
It is caused by incorrect PK definition in DimLocation.

All dimensions PK should be integers, so LocationId should be your PK and you should include it in the fact table instead of LocationName. Location Name should be defined as a dimension attribute.

In your cube the only measure is "[DOWNLOAD] [float]".

Definition of a Measure: It is any numeric quantity/value that represents a metric aligned to an organization's goals. Measures are stored in the fact table.

Title: Primary key not a Measure in cube?

Body:
I'm new to SSAS, so please bear with me.

I have two tables: FactTest and DimLocation.  I'm including the table schema, but in essence,  and FactTest.LocationName is foreign key to DimLocation.LocationName and DimLocation.LocationName is primary key:

CREATE TABLE [dbo].[FactTest](
    [test_date] [date] NULL,
    [DOWNLOAD] [float] NULL,
    [LocationName] [varchar](50) NULL
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[FactTest]  WITH CHECK ADD  CONSTRAINT [FK_FactTest_DimLocation] FOREIGN KEY([LocationName])
REFERENCES [dbo].[DimLocation] ([LocationName])
GO

ALTER TABLE [dbo].[FactTest] CHECK CONSTRAINT [FK_FactTest_DimLocation]
GO

CREATE TABLE [dbo].[DimLocation](
    [LocationId] [int] IDENTITY(1,1) NOT NULL,
    [LocationName] [varchar](50) NOT NULL,
 CONSTRAINT [PK_DimLocation] PRIMARY KEY CLUSTERED
(
    [LocationName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

DimLocation looks like this:

LocationId      LocationName
1               Houston
2               San Antonio
3               Dallas
4               Austin

and FactTest looks like this:

test_date       Download      LocationName
1/4/2020        8.56          Houston
1/4/2020        9.43          Dallas
1/5/2020        3.20          Houston

When I'm creating the cube in VS 2013, I notice that the column LocationName is not included as one of the Measures. I also have other Dimension tables, and none of the primary key columns are part of the Measures.

Aren't the primary keys supposed to be used as Measures when creating a cube? If not, then how am I supposed to link the fact tables to the dim tables?


问:
testng - Get name of the class that contains failed test
```<code><test name="Test">
   <classes>
     <class name="io.test.FirstTest"/>
   </classes>
</test>
</code>```

I want to  get name of the FirsTest class without the package name inside onTestFailure. In other wors, I need to get FirstTest, not io.test.FirstTest.  How to do so?

```<code>   public class TestListener extends TestListenerAdapter {

    @Override
    public void onTestFailure(ITestResult testResult) {

    }
  }
</code>```

I have used testResult.getInstanceName(), but it returns  io.test.FirstTest. Therefore, I have used string.substring():

```<code>   final String name = testResult.getInstanceName();
   final String result = name.substring(navn.lastIndexOf(".") + 1).trim();
</code>```

But is there a better solution?

答:
Try this approach:

package click.webelement.testng;

import org.testng.Assert;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

@Listeners({TListenerTest.class})
public class TListenerTest implements ITestListener {

    @Test
    public void toFail(){
        Assert.assertTrue(false);
    }

    @Override
    public void onTestFailure(ITestResult result) {
        System.out.println(result.getInstance().getClass().getSimpleName());
        System.out.println(result.getTestClass().getClass().getSimpleName());
    }
}
```

However I would not rely on the "simple names". They look nice unless you run into dups sooner or later (since you wouldn't be able to distinguish classes with the same name but from different packages).

Body:
<test name="Test">
   <classes>
     <class name="io.test.FirstTest"/>
   </classes>
</test>

I want to  get name of the FirsTest class without the package name inside onTestFailure. In other wors, I need to get FirstTest, not io.test.FirstTest.  How to do so?

   public class TestListener extends TestListenerAdapter {

    @Override
    public void onTestFailure(ITestResult testResult) {

    }
  }

I have used testResult.getInstanceName(), but it returns  io.test.FirstTest. Therefore, I have used string.substring():

   final String name = testResult.getInstanceName();
   final String result = name.substring(navn.lastIndexOf(".") + 1).trim();

But is there a better solution?

Body:
Try this approach:

package click.webelement.testng;

import org.testng.Assert;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

@Listeners({TListenerTest.class})
public class TListenerTest implements ITestListener {

    @Test
    public void toFail(){
        Assert.assertTrue(false);
    }

    @Override
    public void onTestFailure(ITestResult result) {
        System.out.println(result.getInstance().getClass().getSimpleName());
        System.out.println(result.getTestClass().getClass().getSimpleName());
    }
}

However I would not rely on the "simple names". They look nice unless you run into dups sooner or later (since you wouldn't be able to distinguish classes with the same name but from different packages).


问:
ActiveMQ 5.1.5: individualDeadLetterStrategy not working as expected
I'm trying to configure a DLQ per queue based on the following config
as described here:

<policyEntry queue=">">
   <deadLetterStrategy>

      <individualDeadLetterStrategy queueSuffix=".DLQ" useQueueForQueueMessages="true"/>
   </deadLetterStrategy>
</policyEntry>
```

I'm using virtual topics so have a topic named like

VirtualTopic.Things.1.0

which means I can create a Queue called

Consumer.Me.VirtualTopic.Things.1.0

to automatically subscribe to this topic.

The individualDeadLetterStrategy above creates a DLQ that has the name:

ActiveMQ.DLQ.Queue.Consumer.Me.VirtualTopic.Things.1.0.DLQ

I was hoping for simply

Consumer.Me.VirtualTopic.Things.1.0.DLQ

Are my expectations correct? Have I done something wrong?

答:
The default queuePrefix is ActiveMQ.DLQ.Queue. and the default queueSuffix is empty. Since you're using queueSuffix=".DLQ" and not defining queuePrefix then it is creating queues with the default prefix and your custom suffix resulting in ActiveMQ.DLQ.Queue.<queueName>.DLQ. If you don't want to use the default prefix you should set queuePrefix="", e.g.:

<individualDeadLetterStrategy queuePrefix="" queueSuffix=".DLQ" useQueueForQueueMessages="true"/>
```

Body:
I'm trying to configure a DLQ per queue based on the following config
as described here:

<policyEntry queue=">">
   <deadLetterStrategy>

      <individualDeadLetterStrategy queueSuffix=".DLQ" useQueueForQueueMessages="true"/>
   </deadLetterStrategy>
</policyEntry>

I'm using virtual topics so have a topic named like

VirtualTopic.Things.1.0

which means I can create a Queue called

Consumer.Me.VirtualTopic.Things.1.0

to automatically subscribe to this topic.

The individualDeadLetterStrategy above creates a DLQ that has the name:

ActiveMQ.DLQ.Queue.Consumer.Me.VirtualTopic.Things.1.0.DLQ

I was hoping for simply

Consumer.Me.VirtualTopic.Things.1.0.DLQ

Are my expectations correct? Have I done something wrong?


问:
NSLog only prints right value when I have a warning
I'm getting garbage values when manipulating some of my NSString objects. I think the problem stems from my misunderstanding of how NSString works at a basic level. Below, I have a object which has a string pointer as a synthesized property. When I try to log it out directly, the compiler gives me a warning, but it does log out the value I expect. On the very next line, I try to log that string out the proper way but I end up getting garbage.

Code snippet

```<code>MyObject *object = [self.objects objectAtIndex:indexPath.row];
NSString *myString = object.myString;
NSLog(myString); // format not a string literal and no formal arguments
NSLog(@"formatted = %s", myString);
</code>```

Output

```<code>2011-05-16 13:06:51.137 MyProgram[917:207] thisValueIsGood
2011-05-16 13:06:51.138 MyProgram[917:207] formatted = `å
</code>```

This problem has snowballed onto other functions which use this final string. When I concatenate that string with other strings, I get even more garbage.

答: NSString is an object, instead of %s, use %@.

Body:
I'm getting garbage values when manipulating some of my NSString objects. I think the problem stems from my misunderstanding of how NSString works at a basic level. Below, I have a object which has a string pointer as a synthesized property. When I try to log it out directly, the compiler gives me a warning, but it does log out the value I expect. On the very next line, I try to log that string out the proper way but I end up getting garbage.

Code snippet

MyObject *object = [self.objects objectAtIndex:indexPath.row];
NSString *myString = object.myString;
NSLog(myString); // format not a string literal and no formal arguments
NSLog(@"formatted = %s", myString);

Output

2011-05-16 13:06:51.137 MyProgram[917:207] thisValueIsGood
2011-05-16 13:06:51.138 MyProgram[917:207] formatted = `å

This problem has snowballed onto other functions which use this final string. When I concatenate that string with other strings, I get even more garbage.


问:
How is memory deallocated in c++
I understand pointer allocation of memory fully, but deallocation of memory only on a higher level. What I'm most curious about is how C++ keeps track of what memory has already been deallocated?

```<code>int* ptr = new int;
cout << ptr;
delete ptr;
cout << ptr;
// still pointing to the same place however it knows you can't access it or delete it again
*ptr // BAD
delete ptr // BAD
</code>```

How does C++ know I deallocated that memory. If it just turns it to arbitrary garbage binary numbers, wouldn't I just be reading in that garbage number when I dereference the pointer?

Instead, of course, c++ knows that these are segfaults somehow.

答:
C++ still has a strong C inheritance when it comes to memory addressing. And C was invented to build an OS (first version of Unix) where it makes sense to use well known register addresses or to whatever low level operation. That means that when you address memory through a pointer, you as the programmer are supposed to know what lies there and the language just trusts you.

On common implementations, the language requests chunks of memory from the OS for new dynamic objects, and keeps track of used and unused memory block. The goal is to re-use free blocks for new dynamic objects instead of asking the OS for each and every allocation and de-allocation.

Still for common implementation, nothing changes in a freshly allocated or deallocated block, but the pointers maintaining a list of free blocks. AFAIK few return memory to the OS until the end of the process. But a free block could be later re-used, that is the reason why when a careless programmer tries to access a block of memory containing pointers that has been re-used, SEGFAULT is not far, because the program could try to use arbitrary memory addresses that could not be mapped for the process.

BTW, the only point required by the standard is that accessing an object past its end of life, specifically here using the pointer after the delete statement invokes Undefined Behaviour. Said differently anything can happen from an immediate crash to normal results, passing through later crash or abnormal result in unrelated places of the program...

Title: How is memory deallocated in c++

Body:
I understand pointer allocation of memory fully, but deallocation of memory only on a higher level. What I'm most curious about is how C++ keeps track of what memory has already been deallocated?

int* ptr = new int;
cout << ptr;
delete ptr;
cout << ptr;
// still pointing to the same place however it knows you can't access it or delete it again
*ptr // BAD
delete ptr // BAD

How does C++ know I deallocated that memory. If it just turns it to arbitrary garbage binary numbers, wouldn't I just be reading in that garbage number when I dereference the pointer?

Instead, of course, c++ knows that these are segfaults somehow.


问:
JavaFX BufferOverflowException on embedded device
We're using a iMX6 SoM chip and a 480x272 LVDS display for our application.

We're also using Gluon's OpenJFX and an embedded build of Java 8u241.

Whenever we launch the jar file, we get spammed with the following errors

```<code>java.nio.BufferOverflowException
    at java.nio.DirectIntBufferU.put(DirectIntBufferU.java:363)
    at com.sun.javafx.tk.quantum.UploadingPainter.run(UploadingPainter.java:153)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
    at com.sun.javafx.tk.RenderJob.run(RenderJob.java:58)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)Setting up UI took 127 ms
    at com.sun.javafx.tk.quantum.QuantumRenderer$PipelineRunnable.run(QuantumRenderer.java:125)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Well I've been looking around the internet, but the only connection to the same error I saw, was the one with Monocle. We're not using it, but I've resized the app to 479x271, to see if the errors might vanish, but they persisted.

Now I'm running out of ideas to try.

答:
I've fixed it!

So, the problem was that a button was outside of the window's border(for a pixel), and it was resizing the window outside the framebuffer size.

I just moved the button up for a pixel and it runs flawlessly now.

Body:
We're using a iMX6 SoM chip and a 480x272 LVDS display for our application.

We're also using Gluon's OpenJFX and an embedded build of Java 8u241.

Whenever we launch the jar file, we get spammed with the following errors

java.nio.BufferOverflowException
    at java.nio.DirectIntBufferU.put(DirectIntBufferU.java:363)
    at com.sun.javafx.tk.quantum.UploadingPainter.run(UploadingPainter.java:153)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
    at com.sun.javafx.tk.RenderJob.run(RenderJob.java:58)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)Setting up UI took 127 ms
    at com.sun.javafx.tk.quantum.QuantumRenderer$PipelineRunnable.run(QuantumRenderer.java:125)
    at java.lang.Thread.run(Thread.java:748)

Well I've been looking around the internet, but the only connection to the same error I saw, was the one with Monocle. We're not using it, but I've resized the app to 479x271, to see if the errors might vanish, but they persisted.

Now I'm running out of ideas to try.


问:
`sizeof` struct in union definition
To access a struct byte-wise, I'm using a union.

```<code>typedef struct {
    char hi;
    char lo;
} range;

union {
    range by_name;
    char as_bytes[sizeof(range)];
} U1;

char use_U1(void){
    char c = U1.as_bytes[0];
    return U1.by_name.hi;
}
</code>```

Question 1: Is it possible to skip the typedef? Like this:

```<code>union {
    struct {
        char hi;
        char lo;
    } by_name;
    char as_bytes[2]; //want sizeof()
} U2;
</code>```

A naive char as_bytes[sizeof(by_name)] doesn't compile:

error: 'by_name' undeclared here (not in a function)

Question 2: Same but with anonymous structure, to avoid typing .by_name when using.

```<code>union {
    struct {
        char hi;
        char lo;
    };
    char as_bytes[2]; //want sizeof()
} U3;

int use_U3(void){
    char c = U3.as_bytes[0];
    return U3.hi; // anonymous structure
}
</code>```

Read so far: union, struct

答:
You can give the struct a tag name and use that.

```<code>union {
    struct inner {
        char hi;
        char lo;
    } by_name;
    char as_bytes[sizeof(struct inner)];
} U2;
</code>```

Note that this does require that the inner struct has a name.  If there's no name, the tag must be omitted.

Title: `sizeof` struct in union definition

Body:
To access a struct byte-wise, I'm using a union.

typedef struct {
    char hi;
    char lo;
} range;

union {
    range by_name;
    char as_bytes[sizeof(range)];
} U1;

char use_U1(void){
    char c = U1.as_bytes[0];
    return U1.by_name.hi;
}

Question 1: Is it possible to skip the typedef? Like this:

union {
    struct {
        char hi;
        char lo;
    } by_name;
    char as_bytes[2]; //want sizeof()
} U2;

A naive char as_bytes[sizeof(by_name)] doesn't compile:

error: 'by_name' undeclared here (not in a function)

Question 2: Same but with anonymous structure, to avoid typing .by_name when using.

union {
    struct {
        char hi;
        char lo;
    };
    char as_bytes[2]; //want sizeof()
} U3;

int use_U3(void){
    char c = U3.as_bytes[0];
    return U3.hi; // anonymous structure
}

Read so far: union, struct

Body:
You can give the struct a tag name and use that.

union {
    struct inner {
        char hi;
        char lo;
    } by_name;
    char as_bytes[sizeof(struct inner)];
} U2;

Note that this does require that the inner struct has a name.  If there's no name, the tag must be omitted.


问:
Oracle 19c compatibility with jdk7
I would like to know if oracle 19c is compatible with jdk 7.

I have found out 2 drivers for oracle 19c

ojdbc8 : for jdk8, jdk9 and jdk11

ojdbc10 : for jdk10 and jdk11

I would like to know if there is a way to have oracle 19c with a jdk7, and if yes what is the driver that will allow to do it ?

答:
According to the Oracle JDBC FAQ (Question "What are the Oracle JDBC releases Vs JDK versions?"), only the Java versions you listed (Java 8 to 11) are supported for Oracle 19c.

I expect that support for later Java versions will be added in the future.

Java 9 and Java 10 were short-life releases, and are both end-of-life.

As a comment notes, Java 7 has been "end of life" since April 2015.  It would be counter-productive for Oracle to encourage continued use of Java 7 by supporting it with new JDBC drivers for new Oracle database releases.

Note that the Oracle drivers are proprietary and source code is not available.  So back-porting one of the Oracle 19c compatible drivers to Java 7 is not an option.

You may be able to identify a 3rd-party vendor who will provide (probably sell) you a driver that works.  The best I could come up with is this old page that lists vendors:

https://www.mindprod.com/jgloss/jdbcvendors.html

In summary: If you want to use Oracle 19c with Oracle supported drivers, upgrading to Java 8 LTS or later is the only feasible solution.  Upgrading to Java 11 LTS is advisable:

Oracle Java 8 LTS free public updates (for commercial users) have ended, and Premium Support is due to end in March 2022; see the Oracle Java SE Support Roadmap.

You can still get free public Java 8 LTS updates from 3rd-party vendors post 2020; see Java is Still Free for all of the details.

Title: Oracle 19c compatibility with jdk7