问:
Filter pandas dataframe on columns if contains *
I have a pandas dataframe where some column values have a astrix *.

I want to remoeve rows that have this.

I have tries this but its not working

```<code>df.loc[~(df['col_name'].str.contains('*'))]
</code>```

答:
Because * is special regex character add regex=False to Series.str.contains:

```<code>df.loc[~(df['col_name'].str.contains('*', regex=False))]
</code>```

Or escape *:

```<code>df.loc[~(df['col_name'].str.contains('\*'))]
</code>```

Body:
I have a pandas dataframe where some column values have a astrix *.

I want to remoeve rows that have this.

I have tries this but its not working

df.loc[~(df['col_name'].str.contains('*'))]

Body:
Because * is special regex character add regex=False to Series.str.contains:

df.loc[~(df['col_name'].str.contains('*', regex=False))]

Or escape *:

df.loc[~(df['col_name'].str.contains('\*'))]


来源: stackexchange

问:
D365 Display deeply related information on a form in subgrid
Have a requirement to show list of Unterweisung (trainings) titles in Contact's form as a subgrid. Please, look at:

Is there a way to display those?

I have tried to append fetchXML to form grid vie JS, but no success there by two reasons:

1) FetchXML is not valid, because of twin-linked entity search, i suppose. If it is not supported, the whole approach is wrong.

2) Even if leaving filtering only for one entity, d365 drops an error Invalid FetchXML on opening Contact form. FetchXML validators are stating opposite.

Estimated full fetchXML (not valid):

```<code><fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">
  <entity name="new_schulungstyp">
    <attribute name="new_name" />
    <attribute name="createdon" />
    <attribute name="new_schulungstypid" />
    <attribute name="new_typ" />
    <attribute name="new_intervall" />
    <order attribute="createdon" descending="false" />
    <filter type="and">
      <condition attribute="statecode" operator="eq" value="0" />
    </filter>
    <link-entity name="new_new_schulungstyp_new_azttigkeit" from="new_schulungstypid" to="new_schulungstypid" visible="false" intersect="true">
      <link-entity name="new_azttigkeit" from="new_azttigkeitid" to="new_azttigkeitid" alias="aa">
        <link-entity name="new_new_profil_new_azttigkeit" from="new_azttigkeitid" to="new_azttigkeitid" visible="false" intersect="true">
          <link-entity name="new_profil" from="new_profilid" to="new_profilid" alias="ab">
            <link-entity name="new_contact_new_profil" from="new_profilid" to="new_profilid" visible="false" intersect="true">
              <link-entity name="contact" from="contactid" to="contactid" alias="ac">
                <filter type="or">
                  <condition attribute="contactid" operator="eq" value="currentContactIdInsertedViaJs" />
                </filter>
              </link-entity>
            </link-entity>
          </link-entity>
        </link-entity>
      </link-entity>
    </link-entity>
    <link-entity name="new_new_betriebsmittel_new_schulungstyp" from="new_schulungstypid" to="new_schulungstypid" visible="false" intersect="true">
      <link-entity name="new_betriebsmittel" from="new_betriebsmittelid" to="new_betriebsmittelid" alias="ad">
        <link-entity name="new_new_betriebsmittel_new_profil" from="new_betriebsmittelid" to="new_betriebsmittelid" visible="false" intersect="true">
          <link-entity name="new_profil" from="new_profilid" to="new_profilid" alias="ae">
            <link-entity name="new_contact_new_profil" from="new_profilid" to="new_profilid" visible="false" intersect="true">
              <link-entity name="contact" from="contactid" to="contactid" alias="af">
                <filter type="or">
                  <condition attribute="contactid" operator="eq" value="currentContactIdInsertedViaJs" />
                </filter>
              </link-entity>
            </link-entity>
          </link-entity>
        </link-entity>
      </link-entity>
    </link-entity>
  </entity>
</fetch>
</code>```

JS code with single entity filter:

```<code>function filterTrainings(executionContext) {
    var formContext = executionContext.getFormContext();
    var guid = Xrm.Page.data.entity.getId();
    var fullname = formContext.getAttribute("fullname").getValue();

    //var fullName = formContext.getAttribute("fullname_d").getValue();
var fetchXML = "<fetch>";
    fetchXML+=  "<entity name='new_schulungstyp'>";
    fetchXML+= "<attribute name='new_name' />";
    fetchXML+= "<attribute name='createdon' />";
    fetchXML+= "<attribute name='new_schulungstypid' />";
    fetchXML+= "<attribute name='new_typ' />";
    fetchXML+= "<attribute name='new_intervall' />";
    fetchXML+= "<order attribute='createdon' descending='false' />";
    fetchXML+= "<filter type='and'>";
    fetchXML+= "<condition attribute='statecode' operator='eq' value='0' />";
    fetchXML+=  "</filter>";
    fetchXML+= "<link-entity name='new_new_schulungstyp_new_azttigkeit' from='new_schulungstypid' to='new_schulungstypid' visible='false' intersect='true'>";
    fetchXML+= "<link-entity name='new_azttigkeit' from='new_azttigkeitid' to='new_azttigkeitid' alias='aj'>";
    fetchXML+= "<link-entity name='new_new_profil_new_azttigkeit' from='new_azttigkeitid' to='new_azttigkeitid' visible='false' intersect='true'>";
    fetchXML+= "<link-entity name='new_profil' from='new_profilid' to='new_profilid' alias='ak'>";
    fetchXML+= "<link-entity name='new_contact_new_profil' from='new_profilid' to='new_profilid' visible='false' intersect='true'>";
    fetchXML+= "<link-entity name='contact' from='contactid' to='contactid' alias='al'>";
    fetchXML+= "<filter type='and'>";
    fetchXML+= "<condition attribute='contactid' operator='eq' value='"+guid+"' />";
    fetchXML+= "</filter>";
    fetchXML+=  "</link-entity>";
    fetchXML+=  "</link-entity>";
    fetchXML+= "</link-entity>";
    fetchXML+=  "</link-entity>";
    fetchXML+= "</link-entity>";
    fetchXML+=  "</link-entity>";
    fetchXML+=  "</entity>";
    fetchXML+=  "</fetch>";

    var grid = formContext.getControl("relatedTrainings");

    if (grid == null) {
        setTimeout(function () {
            filterTrainings(executionContext);
        }, 2000);
        return;
    } else {
        grid.getGrid().setParameter("fetchXml", filterTrainings); //set the fetch xml to the sub grid
        console.log("refresh............")
    }
}
</code>```

答:
Managed to figure that one out. I am getting all required ID's that should be displayed in subgrid by subsequently sending get requests. Most important here is to manage async nature of promises. Then I build a filter that forces subgrid to show only entities, that are in related ID collection

Posting my solution:

```<code>function filterTrainings(executionContext) {
var formContext = executionContext.getFormContext();
var trainigsControl = formContext.getControl("relatedTrainings").getGrid();
var guid = Xrm.Page.data.entity.getId();
console.log(guid);

var relatedProfiles = [];
var relatedTatigkeiten = [];
var relatedBetriebsmittelGruppen = [];
var unterweisungTypen = [];
var xml;

GetRelatedProfiles()
    .then(() => GetRelatedTatigkeiten().then(GetTatigkeitenRelatedUnterweisungTypen).then(() => GetRelatedBetriebsmittel().then(GetBetriebsmittelRelatedUnterweisungTypen).then(buildFetchXMLAndUpdateGrid)));

function buildFetchXMLAndUpdateGrid() {
    getUniques(unterweisungTypen);
    var values = unterweisungTypen.map(val => `<value>${val}</value>`);
    console.log(values);

    xml = `<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
    <entity name="new_schulungstyp">
        <attribute name="new_name" />
        <attribute name="createdon" />
        <attribute name="new_schulungstypid" />
        <attribute name="new_typ" />
        <attribute name="new_intervall" />
        <order attribute="createdon" descending="false" />
        <filter type="and">
            <condition attribute="new_schulungstypid" operator="in">${values.join('')}</condition>
        </filter>
    </entity>
</fetch>`;
    console.log(xml);
    trainigsControl.setParameter("fetchXML", xml);
    trainigsControl.refresh();
    return xml;
}

function GetRelatedProfiles() {
    return Xrm.WebApi.online.retrieveMultipleRecords("new_contact_new_profil", "?$select=new_profilid&$filter=contactid eq " + guid).then(
        function success(result) {
            for (var i = 0; i < result.entities.length; i++) {
                relatedProfiles.push(result.entities[i]["new_profilid"]);
            }
        },
        function (error) {
            console.log(error.message);
            // handle error conditions
        }
    );
}

function getUniques(arr) {
    var uniques = [];
    arr.forEach(item => {
        if (uniques.indexOf(item) === -1) {
            uniques.push(item);
        }
    });
    arr = uniques;
}

function GetRelatedTatigkeiten() {
    return Promise.all(relatedProfiles.map(profile =>
        Xrm.WebApi.online.retrieveMultipleRecords("new_new_profil_new_azttigkeit", `?$select=new_azttigkeitid&$filter=new_profilid eq ${profile}`).then(
            function success(result) {
                for (var i = 0; i < result.entities.length; i++) {
                    relatedTatigkeiten.push(result.entities[i]["new_azttigkeitid"]);
                }
            }, function (error) {
                console.log(error.message);
                // handle error conditions
            }
        )
    )).then(() => getUniques(relatedTatigkeiten));
}

function GetRelatedBetriebsmittel() {
    return Promise.all(relatedProfiles.map(profile =>
        Xrm.WebApi.online.retrieveMultipleRecords("new_new_betriebsmittel_new_profil", "?$select=new_betriebsmittelid&$filter=new_profilid eq " + profile).then(
            function success(result) {
                for (var i = 0; i < result.entities.length; i++) {
                        relatedBetriebsmittelGruppen.push(result.entities[i]["new_betriebsmittelid"])
                }
            }, function (error) {
                console.log(error.message);
                // handle error conditions
            }
        )
    )).then(() => getUniques(relatedTatigkeiten));
}

function GetBetriebsmittelRelatedUnterweisungTypen() {
    return Promise.all(relatedBetriebsmittelGruppen.map(betriebsmittel =>
        Xrm.WebApi.online.retrieveMultipleRecords("new_new_betriebsmittel_new_schulungstyp", "?$select=new_schulungstypid&$filter=new_betriebsmittelid eq " + betriebsmittel).then(
            function success(result) {
                for (var i = 0; i < result.entities.length; i++) {
                    unterweisungTypen.push(result.entities[i]["new_schulungstypid"]);
                }
            }, function (error) {
                console.log(error.message);
                // handle error conditions
            }
        )
    )).then(() => getUniques(unterweisungTypen));
}

function GetTatigkeitenRelatedUnterweisungTypen() {
    return Promise.all(relatedTatigkeiten.map(tatigkeiten =>
        Xrm.WebApi.online.retrieveMultipleRecords("new_new_schulungstyp_new_azttigkeit", "?$select=new_schulungstypid&$filter=new_azttigkeitid eq " + tatigkeiten).then(
            function success(result) {
                for (var i = 0; i < result.entities.length; i++) {
                        unterweisungTypen.push(result.entities[i]["new_schulungstypid"]);
                }
            }, function (error) {
                console.log(error.message);
                // handle error conditions
            }
        ))).then(() => getUniques(unterweisungTypen));
    }
</code>```

}

ContentLicense: CC BY-SA 4.0

Body:
Have a requirement to show list of Unterweisung (trainings) titles in Contact's form as a subgrid. Please, look at:

Is there a way to display those?

I have tried to append fetchXML to form grid vie JS, but no success there by two reasons:

1) FetchXML is not valid, because of twin-linked entity search, i suppose. If it is not supported, the whole approach is wrong.

2) Even if leaving filtering only for one entity, d365 drops an error Invalid FetchXML on opening Contact form. FetchXML validators are stating opposite.

Estimated full fetchXML (not valid):

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">
  <entity name="new_schulungstyp">
    <attribute name="new_name" />
    <attribute name="createdon" />
    <attribute name="new_schulungstypid" />
    <attribute name="new_typ" />
    <attribute name="new_intervall" />
    <order attribute="createdon" descending="false" />
    <filter type="and">
      <condition attribute="statecode" operator="eq" value="0" />
    </filter>
    <link-entity name="new_new_schulungstyp_new_azttigkeit" from="new_schulungstypid" to="new_schulungstypid" visible="false" intersect="true">
      <link-entity name="new_azttigkeit" from="new_azttigkeitid" to="new_azttigkeitid" alias="aa">
        <link-entity name="new_new_profil_new_azttigkeit" from="new_azttigkeitid" to="new_azttigkeitid" visible="false" intersect="true">
          <link-entity name="new_profil" from="new_profilid" to="new_profilid" alias="ab">
            <link-entity name="new_contact_new_profil" from="new_profilid" to="new_profilid" visible="false" intersect="true">
              <link-entity name="contact" from="contactid" to="contactid" alias="ac">
                <filter type="or">
                  <condition attribute="contactid" operator="eq" value="currentContactIdInsertedViaJs" />
                </filter>
              </link-entity>
            </link-entity>
          </link-entity>
        </link-entity>
      </link-entity>
    </link-entity>
    <link-entity name="new_new_betriebsmittel_new_schulungstyp" from="new_schulungstypid" to="new_schulungstypid" visible="false" intersect="true">
      <link-entity name="new_betriebsmittel" from="new_betriebsmittelid" to="new_betriebsmittelid" alias="ad">
        <link-entity name="new_new_betriebsmittel_new_profil" from="new_betriebsmittelid" to="new_betriebsmittelid" visible="false" intersect="true">
          <link-entity name="new_profil" from="new_profilid" to="new_profilid" alias="ae">
            <link-entity name="new_contact_new_profil" from="new_profilid" to="new_profilid" visible="false" intersect="true">
              <link-entity name="contact" from="contactid" to="contactid" alias="af">
                <filter type="or">
                  <condition attribute="contactid" operator="eq" value="currentContactIdInsertedViaJs" />
                </filter>
              </link-entity>
            </link-entity>
          </link-entity>
        </link-entity>
      </link-entity>
    </link-entity>
  </entity>
</fetch>

JS code with single entity filter:

function filterTrainings(executionContext) {
    var formContext = executionContext.getFormContext();
    var guid = Xrm.Page.data.entity.getId();
    var fullname = formContext.getAttribute("fullname").getValue();

    //var fullName = formContext.getAttribute("fullname_d").getValue();
var fetchXML = "<fetch>";
    fetchXML+=  "<entity name='new_schulungstyp'>";
    fetchXML+= "<attribute name='new_name' />";
    fetchXML+= "<attribute name='createdon' />";
    fetchXML+= "<attribute name='new_schulungstypid' />";
    fetchXML+= "<attribute name='new_typ' />";
    fetchXML+= "<attribute name='new_intervall' />";
    fetchXML+= "<order attribute='createdon' descending='false' />";
    fetchXML+= "<filter type='and'>";
    fetchXML+= "<condition attribute='statecode' operator='eq' value='0' />";
    fetchXML+=  "</filter>";
    fetchXML+= "<link-entity name='new_new_schulungstyp_new_azttigkeit' from='new_schulungstypid' to='new_schulungstypid' visible='false' intersect='true'>";
    fetchXML+= "<link-entity name='new_azttigkeit' from='new_azttigkeitid' to='new_azttigkeitid' alias='aj'>";
    fetchXML+= "<link-entity name='new_new_profil_new_azttigkeit' from='new_azttigkeitid' to='new_azttigkeitid' visible='false' intersect='true'>";
    fetchXML+= "<link-entity name='new_profil' from='new_profilid' to='new_profilid' alias='ak'>";
    fetchXML+= "<link-entity name='new_contact_new_profil' from='new_profilid' to='new_profilid' visible='false' intersect='true'>";
    fetchXML+= "<link-entity name='contact' from='contactid' to='contactid' alias='al'>";
    fetchXML+= "<filter type='and'>";
    fetchXML+= "<condition attribute='contactid' operator='eq' value='"+guid+"' />";
    fetchXML+= "</filter>";
    fetchXML+=  "</link-entity>";
    fetchXML+=  "</link-entity>";
    fetchXML+= "</link-entity>";
    fetchXML+=  "</link-entity>";
    fetchXML+= "</link-entity>";
    fetchXML+=  "</link-entity>";
    fetchXML+=  "</entity>";
    fetchXML+=  "</fetch>";

    var grid = formContext.getControl("relatedTrainings");

    if (grid == null) {
        setTimeout(function () {
            filterTrainings(executionContext);
        }, 2000);
        return;
    } else {
        grid.getGrid().setParameter("fetchXml", filterTrainings); //set the fetch xml to the sub grid
        console.log("refresh............")
    }
}

Body:
Managed to figure that one out. I am getting all required ID's that should be displayed in subgrid by subsequently sending get requests. Most important here is to manage async nature of promises. Then I build a filter that forces subgrid to show only entities, that are in related ID collection

Posting my solution:

function filterTrainings(executionContext) {
var formContext = executionContext.getFormContext();
var trainigsControl = formContext.getControl("relatedTrainings").getGrid();
var guid = Xrm.Page.data.entity.getId();
console.log(guid);

var relatedProfiles = [];
var relatedTatigkeiten = [];
var relatedBetriebsmittelGruppen = [];
var unterweisungTypen = [];
var xml;

GetRelatedProfiles()
    .then(() => GetRelatedTatigkeiten().then(GetTatigkeitenRelatedUnterweisungTypen).then(() => GetRelatedBetriebsmittel().then(GetBetriebsmittelRelatedUnterweisungTypen).then(buildFetchXMLAndUpdateGrid)));

function buildFetchXMLAndUpdateGrid() {
    getUniques(unterweisungTypen);
    var values = unterweisungTypen.map(val => `<value>${val}</value>`);
    console.log(values);

    xml = `<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
    <entity name="new_schulungstyp">
        <attribute name="new_name" />
        <attribute name="createdon" />
        <attribute name="new_schulungstypid" />
        <attribute name="new_typ" />
        <attribute name="new_intervall" />
        <order attribute="createdon" descending="false" />
        <filter type="and">
            <condition attribute="new_schulungstypid" operator="in">${values.join('')}</condition>
        </filter>
    </entity>
</fetch>`;
    console.log(xml);
    trainigsControl.setParameter("fetchXML", xml);
    trainigsControl.refresh();
    return xml;
}

function GetRelatedProfiles() {
    return Xrm.WebApi.online.retrieveMultipleRecords("new_contact_new_profil", "?$select=new_profilid&$filter=contactid eq " + guid).then(
        function success(result) {
            for (var i = 0; i < result.entities.length; i++) {
                relatedProfiles.push(result.entities[i]["new_profilid"]);
            }
        },
        function (error) {
            console.log(error.message);
            // handle error conditions
        }
    );
}

function getUniques(arr) {
    var uniques = [];
    arr.forEach(item => {
        if (uniques.indexOf(item) === -1) {
            uniques.push(item);
        }
    });
    arr = uniques;
}

function GetRelatedTatigkeiten() {
    return Promise.all(relatedProfiles.map(profile =>
        Xrm.WebApi.online.retrieveMultipleRecords("new_new_profil_new_azttigkeit", `?$select=new_azttigkeitid&$filter=new_profilid eq ${profile}`).then(
            function success(result) {
                for (var i = 0; i < result.entities.length; i++) {
                    relatedTatigkeiten.push(result.entities[i]["new_azttigkeitid"]);
                }
            }, function (error) {
                console.log(error.message);
                // handle error conditions
            }
        )
    )).then(() => getUniques(relatedTatigkeiten));
}

function GetRelatedBetriebsmittel() {
    return Promise.all(relatedProfiles.map(profile =>
        Xrm.WebApi.online.retrieveMultipleRecords("new_new_betriebsmittel_new_profil", "?$select=new_betriebsmittelid&$filter=new_profilid eq " + profile).then(
            function success(result) {
                for (var i = 0; i < result.entities.length; i++) {
                        relatedBetriebsmittelGruppen.push(result.entities[i]["new_betriebsmittelid"])
                }
            }, function (error) {
                console.log(error.message);
                // handle error conditions
            }
        )
    )).then(() => getUniques(relatedTatigkeiten));
}

function GetBetriebsmittelRelatedUnterweisungTypen() {
    return Promise.all(relatedBetriebsmittelGruppen.map(betriebsmittel =>
        Xrm.WebApi.online.retrieveMultipleRecords("new_new_betriebsmittel_new_schulungstyp", "?$select=new_schulungstypid&$filter=new_betriebsmittelid eq " + betriebsmittel).then(
            function success(result) {
                for (var i = 0; i < result.entities.length; i++) {
                    unterweisungTypen.push(result.entities[i]["new_schulungstypid"]);
                }
            }, function (error) {
                console.log(error.message);
                // handle error conditions
            }
        )
    )).then(() => getUniques(unterweisungTypen));
}

function GetTatigkeitenRelatedUnterweisungTypen() {
    return Promise.all(relatedTatigkeiten.map(tatigkeiten =>
        Xrm.WebApi.online.retrieveMultipleRecords("new_new_schulungstyp_new_azttigkeit", "?$select=new_schulungstypid&$filter=new_azttigkeitid eq " + tatigkeiten).then(
            function success(result) {
                for (var i = 0; i < result.entities.length; i++) {
                        unterweisungTypen.push(result.entities[i]["new_schulungstypid"]);
                }
            }, function (error) {
                console.log(error.message);
                // handle error conditions
            }
        ))).then(() => getUniques(unterweisungTypen));
    }

}


问:
Copy part of json key-values in javascript
Given a json like this

```<code>  var json1 = {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": null
      };

  var json2 = {
                "key3": {
                  "index": "3",
                  "value": "value3"
                },
                "key4": {
                  "index": "4",
                  "value": 'value4'
              }
        };
</code>```

how to get a new json like this, it will only copy the same key to the first one.

```<code>json3= {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": 'value3'
      }
};
</code>```

I've tried on Object.assign  or _.assign of lodash

```<code> Object.assign(json1,json2)
 _.assign(json1,json2)
</code>```

but it will copy all the objects of json2 to json1.

答:
You can use Object.keys to get all the keys from json1 then check if the key exist in json2,if it exists then get the value corresponding to that key from json2

var json1 = {
  "key1": {
    "index": "1",
    "value": null
  },
  "key2": {
    "index": "2",
    "value": null
  },
  "key3": {
    "index": "3",
    "value": null
  }
}

var json2 = {
  "key3": {
    "index": "3",
    "value": "value3"
  },
  "key4": {
    "index": "4",
    "value": 'value4'
  }
};

Object.keys(json1).forEach((item) => {
  if (json2.hasOwnProperty(item)) {
    json1[item].value = json2[item].value
  }
})
console.log(json1)```

Body:
Given a json like this

  var json1 = {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": null
      };

  var json2 = {
                "key3": {
                  "index": "3",
                  "value": "value3"
                },
                "key4": {
                  "index": "4",
                  "value": 'value4'
              }
        };

how to get a new json like this, it will only copy the same key to the first one.

json3= {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": 'value3'
      }
};

I've tried on Object.assign  or _.assign of lodash

 Object.assign(json1,json2)
 _.assign(json1,json2)

but it will copy all the objects of json2 to json1.


问:
SQL Request with LEFT JOIN not able to find data
I'm working on my C# project and I have to get data from database thanks to .sql procedures.

Synthesis :

Table ProprietesCourantes is linked to table Entite.

Table Archive is linked to table EntiteArchive

==> I would like to make a link between ProprietesCourantes and Archive thanks to field Libellé

Table ProprietesCourantes

I have several tables in my case :

```<code>SELECT TOP (1000) [IdEntite]
      ,[Libelle]
      ,[EstActif]
      , ...
      , ...
  FROM [Database].[dbo].[ProprietesCourantes]
  WHERE [Libelle] = 'DELTA SERVICE AUTO';
</code>```

Table Entite

```<code>SELECT TOP (1000) [IdEntite]
      ,[TypeEntite]
      ,[CodeEntite]
      ,[TypeCodeEntite]
  FROM [Database].[dbo].[Entite]
  WHERE IdEntite = '165';
</code>```

Table Archive

```<code>SELECT TOP (1000) [IdArchive]
      ,[IdEntite]
      ,[NoteFinale]
      ,[EstValide]
  FROM [Database].[dbo].[Archive]
  WHERE IdEntite = '33' and EstValide = '1';
</code>```

Table EntiteArchive

```<code>SELECT TOP (1000) [IdEntite]
      ,[TypeEntite]
      ,[CodeEntite]
      ,[Libelle]
      ,...
  FROM [Database].[dbo].[EntiteArchive]
</code>```

MY SQL REQUEST :

```<code>SELECT
            ProprietesCourantes.IdEntite                                                                    as IdEntite,
            ProprietesCourantes.Libelle                                                                     as RaisonSociale,
            Entite.CodeEntite                                                                               as IdCMCIC,
            ProprietesCourantes.NomParent                                                                   as NomGN,
            Archive.NoteFinale                                                                              as Cotation,
            Archive.DateValiditeQuestionnaireDeSoutien                                                      as DateValiditeQuestionnaireDeSoutien,
            ProprietesCourantes.CodePays                                                                    as Pays,
            ProprietesCourantes.EstActif                                                                    as Statut,
            CAST(CASE WHEN Entite.CodeEntite = ProprietesCourantes.IdSocMere THEN 1 ELSE 0 END AS BIT)      as EstMaisonMere,
            ProprietesCourantes.IdCMCICParent                                                               as IdCMCICParent,
            ProprietesCourantesGN.CodeAlgo                                                                  as CodeAlgoParent

    FROM ProprietesCourantes

    LEFT JOIN Archive   ON (Archive.IdEntite  = ProprietesCourantes.IdEntite and Archive.EstValide=1)
    LEFT JOIN Entite ON Entite.IdEntite = ProprietesCourantes.IdEntite
    LEFT JOIN Entite as EntiteGN ON EntiteGN.CodeEntite = ProprietesCourantes.IdCMCICParent
    LEFT JOIN ProprietesCourantes as ProprietesCourantesGN ON ProprietesCourantesGN.IdEntite = EntiteGN.IdEntite

    WHERE Entite.TypeEntite = 1
        AND   (ProprietesCourantes.Libelle LIKE '%'+'DELTA SERVICE'+'%' )
</code>```

As you can see : Cotation and DateValiditeQuestionnaireDeSoutien are NULL because LEFT JOIN Archive   ON (Archive.IdEntite  = ProprietesCourantes.IdEntite can't work (different IDEntite).

I tried to replace by this, but it doesn't work, any idea ?

```<code>LEFT JOIN Archive   ON ((select EntiteArchive.Libelle from EntiteArchive LEFT JOIN Archive ON (EntiteArchive.IdEntite = Archive.IdEntite)) = ProprietesCourantes.Libelle and Archive.EstValide=1)
</code>```

答:
It is not easy to see how your tables are... could it be possible that Archive table has no rows for IdEntite='165'? Are the two keys of the same format? You are showing the output for IdEntite='165' but the 4 example tables are for 2 different IdEntite. Can you provide more insights?

Edited:
For what I understand, you want to join by Libelle field both ProprietesCourantes and Archive but your join is based on IdEntite?

If so, use an intermediate table join ```...</p>

```Archive.NoteFinale                                   as Cotation,
Archive.DateValiditeQuestionnaireDeSoutien           as DateValiditeQuestionnaireDeSoutien,
...
LEFT JOIN EntiteArchive ON (EntiteArchive.Libelle = ProprietesCourantes.Libelle )
LEFT JOIN Archive ON (EntiteArchive.IdEntite = Archive.IdEntite)
...
```
</code>```

Body:
I'm working on my C# project and I have to get data from database thanks to .sql procedures.

Synthesis :

Table ProprietesCourantes is linked to table Entite.

Table Archive is linked to table EntiteArchive

==> I would like to make a link between ProprietesCourantes and Archive thanks to field Libellé

Table ProprietesCourantes

I have several tables in my case :

SELECT TOP (1000) [IdEntite]
      ,[Libelle]
      ,[EstActif]
      , ...
      , ...
  FROM [Database].[dbo].[ProprietesCourantes]
  WHERE [Libelle] = 'DELTA SERVICE AUTO';

Table Entite

SELECT TOP (1000) [IdEntite]
      ,[TypeEntite]
      ,[CodeEntite]
      ,[TypeCodeEntite]
  FROM [Database].[dbo].[Entite]
  WHERE IdEntite = '165';

Table Archive

SELECT TOP (1000) [IdArchive]
      ,[IdEntite]
      ,[NoteFinale]
      ,[EstValide]
  FROM [Database].[dbo].[Archive]
  WHERE IdEntite = '33' and EstValide = '1';

Table EntiteArchive

SELECT TOP (1000) [IdEntite]
      ,[TypeEntite]
      ,[CodeEntite]
      ,[Libelle]
      ,...
  FROM [Database].[dbo].[EntiteArchive]

MY SQL REQUEST :

SELECT
            ProprietesCourantes.IdEntite                                                                    as IdEntite,
            ProprietesCourantes.Libelle                                                                     as RaisonSociale,
            Entite.CodeEntite                                                                               as IdCMCIC,
            ProprietesCourantes.NomParent                                                                   as NomGN,
            Archive.NoteFinale                                                                              as Cotation,
            Archive.DateValiditeQuestionnaireDeSoutien                                                      as DateValiditeQuestionnaireDeSoutien,
            ProprietesCourantes.CodePays                                                                    as Pays,
            ProprietesCourantes.EstActif                                                                    as Statut,
            CAST(CASE WHEN Entite.CodeEntite = ProprietesCourantes.IdSocMere THEN 1 ELSE 0 END AS BIT)      as EstMaisonMere,
            ProprietesCourantes.IdCMCICParent                                                               as IdCMCICParent,
            ProprietesCourantesGN.CodeAlgo                                                                  as CodeAlgoParent

    FROM ProprietesCourantes

    LEFT JOIN Archive   ON (Archive.IdEntite  = ProprietesCourantes.IdEntite and Archive.EstValide=1)
    LEFT JOIN Entite ON Entite.IdEntite = ProprietesCourantes.IdEntite
    LEFT JOIN Entite as EntiteGN ON EntiteGN.CodeEntite = ProprietesCourantes.IdCMCICParent
    LEFT JOIN ProprietesCourantes as ProprietesCourantesGN ON ProprietesCourantesGN.IdEntite = EntiteGN.IdEntite

    WHERE Entite.TypeEntite = 1
        AND   (ProprietesCourantes.Libelle LIKE '%'+'DELTA SERVICE'+'%' )

As you can see : Cotation and DateValiditeQuestionnaireDeSoutien are NULL because LEFT JOIN Archive   ON (Archive.IdEntite  = ProprietesCourantes.IdEntite can't work (different IDEntite).

I tried to replace by this, but it doesn't work, any idea ?

LEFT JOIN Archive   ON ((select EntiteArchive.Libelle from EntiteArchive LEFT JOIN Archive ON (EntiteArchive.IdEntite = Archive.IdEntite)) = ProprietesCourantes.Libelle and Archive.EstValide=1)

Body:
It is not easy to see how your tables are... could it be possible that Archive table has no rows for IdEntite='165'? Are the two keys of the same format? You are showing the output for IdEntite='165' but the 4 example tables are for 2 different IdEntite. Can you provide more insights?

Edited:
For what I understand, you want to join by Libelle field both ProprietesCourantes and Archive but your join is based on IdEntite?

If so, use an intermediate table join ```...</p>

<pre><code>Archive.NoteFinale                                   as Cotation,
Archive.DateValiditeQuestionnaireDeSoutien           as DateValiditeQuestionnaireDeSoutien,
...
LEFT JOIN EntiteArchive ON (EntiteArchive.Libelle = ProprietesCourantes.Libelle )
LEFT JOIN Archive ON (EntiteArchive.IdEntite = Archive.IdEntite)
...
```


问:
Morphtext jQuery plugin not working
I've linked jQuery, animate.css, and morphtext.js in my document's header.

Within h1 I've created a span with the id 'js-rotating'. I've then called it directly in the html like so

```<code><script>
$("#js-rotating").Morphext({
animation: "bounceIn",
separator: ",",
speed: 2000,
complete: function () {
}
});
</script>
</code>```

However, the plugin is not responding. I've verified that I can access the linked css and js files via the direct links. What could cause this issue?

答:
Your Theme is enqueueing jQuery 1.7.2:

And WordPress is enqueueing jQuery 1.8.3:

See also, Frank's answer regarding jQuery no-conflict mode.

Edit
WordPress bundles a version of jQuery. You will inevitably encounter problems if your Theme (or a Plugin) enqueues a separate version of jQuery - whether by enqueueing that separate jQuery version along side the WordPress-bundled version, or else by deregistering the core-bundled version, and enqueueing a custom version.

Don't register a custom version of jQuery via your Theme or any Plugins. If you need to use jQuery, just use the core-bundled version, via:

wp_enqueue_script( 'jquery' );

ContentLicense: CC BY-SA 3.0

Title: Morphtext jQuery plugin not working

Body:
I've linked jQuery, animate.css, and morphtext.js in my document's header.

Within h1 I've created a span with the id 'js-rotating'. I've then called it directly in the html like so

However, the plugin is not responding. I've verified that I can access the linked css and js files via the direct links. What could cause this issue?


问:
Remove gap between widget
I want to close the gap between the lists but its just not working. the only option i have is to increase the gap : Sizedbox,spacer,divider

screenshot of my problem

code:

body: Container(
        child: Column(
          children: <Widget>[
            _mainList(Icon(Icons.cached), "Erste", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Zweite", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Dritte", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Vierte", "21:13 pm"),
          ]
        )
  )```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>  Widget _mainList(Icon symbol, String name, String time){
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: ListTile(
        leading: symbol,
        title: Text(name, textScaleFactor: 1.2),
        trailing: Text(time, textScaleFactor: 1.3),
      ),
    );
  }</code>```

答:
i found a fix (kinda). just add:

dense: true

inside ListTile() it will reduce the gap a bit but thats all i can do for now. I'll keep looking for a better solution if anyone has any.

Title: Remove gap between widget

Body:
I want to close the gap between the lists but its just not working. the only option i have is to increase the gap : Sizedbox,spacer,divider

screenshot of my problem

code:

body: Container(
        child: Column(
          children: <Widget>[
            _mainList(Icon(Icons.cached), "Erste", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Zweite", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Dritte", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Vierte", "21:13 pm"),
          ]
        )
  )

  Widget _mainList(Icon symbol, String name, String time){
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: ListTile(
        leading: symbol,
        title: Text(name, textScaleFactor: 1.2),
        trailing: Text(time, textScaleFactor: 1.3),
      ),
    );
  }


问:
H2 database - Update from select sets out-of-date data after h2database upgrade to version 1.4.198
We have a simple counter in out project database. Until now we were using version 1.4.197 of H2 database. Executing below example snippet with this version always imply counter to be 5000. Upgrade to version 1.4.198 or above makes below code returning inconsistent results, usually between 1500 and 2000.

```<code>public static void main(String[] args) throws SQLException, InterruptedException {
        String url = "jdbc:h2:mem:testdb";

        Connection connection = DriverManager.getConnection(url);
        connection.prepareStatement("CREATE TABLE t1 (id INT PRIMARY KEY, counter INT)").execute();
        connection.prepareStatement("INSERT INTO t1 (id, counter) VALUES (1, 0)").execute();

        int threads = 10;
        int times = 500;

        ExecutorService service = Executors.newFixedThreadPool(threads);
        ExecutorCompletionService<Void> cs = new ExecutorCompletionService<>(service);

        for (int i = 0; i < threads; i++) {
            cs.submit(() -> {
                Connection conn = DriverManager.getConnection(url);
                IntStream.range(0, times).forEach($ -> {
                    try {
                        conn.prepareStatement("UPDATE t1 SET counter = (SELECT counter FROM t1 WHERE id = 1) + 1 WHERE id = 1").executeUpdate();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                });
                return null;
            });
        }

        for (int i = 0; i < threads; i++) {
            cs.take();
        }

        ResultSet resultSet = connection.prepareStatement("SELECT counter FROM t1 WHERE id = 1").executeQuery();
        resultSet.next();
        System.out.println("counter: " + resultSet.getInt("counter"));

    }
</code>```

My assumption is that the select statement from below SQL is executed before other transaction release lock from the table, and then update is performed with out-of-date data from select statement.

```<code>"UPDATE t1 SET counter = (SELECT counter FROM t1 WHERE id = 1) + 1 WHERE id = 1"
</code>```

Have anyone had similar issue?

答:
Normal SELECT statement does not lock selected rows by itself and can read committed (old) values from locked rows. You don't have a barrier around the whole command in your code, that's why newer versions of H2 with their multi-threaded execution can perform such commands concurrently. Multiple commands may read the same old value and try to update the row. UPDATE locks the row, but subquery was already evaluated and the lock is released immediately after execution of the command due to auto-commit. You need to use SELECT … FOR UPDATE in the subquery.

UPDATE t1 SET counter = (SELECT counter FROM t1 WHERE id = 1 FOR UPDATE) + 1 WHERE id = 1
```

BTW, H2 1.4.198 is a beta-quality version with many known problems. It's more safe to use 1.4.199 or 1.4.200 instead of it.

Body:
We have a simple counter in out project database. Until now we were using version 1.4.197 of H2 database. Executing below example snippet with this version always imply counter to be 5000. Upgrade to version 1.4.198 or above makes below code returning inconsistent results, usually between 1500 and 2000.

public static void main(String[] args) throws SQLException, InterruptedException {
        String url = "jdbc:h2:mem:testdb";

        Connection connection = DriverManager.getConnection(url);
        connection.prepareStatement("CREATE TABLE t1 (id INT PRIMARY KEY, counter INT)").execute();
        connection.prepareStatement("INSERT INTO t1 (id, counter) VALUES (1, 0)").execute();

        int threads = 10;
        int times = 500;

        ExecutorService service = Executors.newFixedThreadPool(threads);
        ExecutorCompletionService<Void> cs = new ExecutorCompletionService<>(service);

        for (int i = 0; i < threads; i++) {
            cs.submit(() -> {
                Connection conn = DriverManager.getConnection(url);
                IntStream.range(0, times).forEach($ -> {
                    try {
                        conn.prepareStatement("UPDATE t1 SET counter = (SELECT counter FROM t1 WHERE id = 1) + 1 WHERE id = 1").executeUpdate();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                });
                return null;
            });
        }

        for (int i = 0; i < threads; i++) {
            cs.take();
        }

        ResultSet resultSet = connection.prepareStatement("SELECT counter FROM t1 WHERE id = 1").executeQuery();
        resultSet.next();
        System.out.println("counter: " + resultSet.getInt("counter"));

    }

My assumption is that the select statement from below SQL is executed before other transaction release lock from the table, and then update is performed with out-of-date data from select statement.

"UPDATE t1 SET counter = (SELECT counter FROM t1 WHERE id = 1) + 1 WHERE id = 1"

Have anyone had similar issue?

Body:
Normal SELECT statement does not lock selected rows by itself and can read committed (old) values from locked rows. You don't have a barrier around the whole command in your code, that's why newer versions of H2 with their multi-threaded execution can perform such commands concurrently. Multiple commands may read the same old value and try to update the row. UPDATE locks the row, but subquery was already evaluated and the lock is released immediately after execution of the command due to auto-commit. You need to use SELECT … FOR UPDATE in the subquery.

UPDATE t1 SET counter = (SELECT counter FROM t1 WHERE id = 1 FOR UPDATE) + 1 WHERE id = 1

BTW, H2 1.4.198 is a beta-quality version with many known problems. It's more safe to use 1.4.199 or 1.4.200 instead of it.


问:
apache drill "no current connection" error
I am using the most recent version of drill on windows machines in embedded mode. However, I always get "no current connection" errors when sending any queries. Also, the web server localhost:8047 does not work either. Here is what I see when I try to start drill.

I have tried both Java JDK 8 and 9, on two separate windows machines and got the same error. I searched about this matter but could not get any workarounds so far.

Any fix to this? Thanks a lot!!

答:
Hadoop-3.1.2: Datanode and Nodemanager shuts down

Stuxen in the above thread provided the exact solution and it worked for me.


问:
unable to retrieve link params when opening branch link inside app
Our android app is a chat app. Users can paste a branch link in a chat message. When another user taps on it, we want to retrieve the link parameters to take the user to another screen.

Unfortunately, we are unable to retrieve the link parameters when we tap on such link inside the app (note that we are not using a webview), we are getting the error "Warning. Session initialisation already happened.

To force a new session, set intent extra, branch_force_new_session, to true in the onInitFinished(@Nullable JSONObject referringParams, @Nullable BranchError error) method.

How can we solve this? It's not obvious to me how I could pass a new intent param in that use case.

Notes:

Our launcher activity is singleTask
We are on branch.io sdk 4.3.2
onNewIntent() does not seem to be called (in the code below), maybe that is the root cause for our issue.

sample code:

```<code>private Branch.BranchReferralInitListener branchReferralInitListener =
            new Branch.BranchReferralInitListener() {

                @Override
                public void onInitFinished(@Nullable JSONObject referringParams, @Nullable BranchError error) {
                    ...
}

@Override
    protected void onStart() {
        super.onStart();
        Branch.getInstance().initSession(branchReferralInitListener, getIntent() != null ?
                getIntent().getData() : null, this);
    }
@Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        this.setIntent(intent);
        // activity will skip onStart, handle this case with reInitSession
        Branch.getInstance().reInitSession(this, branchReferralInitListener);
    }
</code>```

答:
This is a known issue with the Android SDK v4.3.2 and we are working on a resolution.
Would suggest you to try the following in the meanwhile:
When the user tries to open an app that is running in the background, we get an error for set branch_force_new_session to true.
Branch SDK gets initialised on onStart for the Launcher Activity and when the app comes foreground from the background, its on onResume.
In this scenario, we could need to re-initialise the SDK here.
Would request you to implement the below snippet as per Branch docs (https://docs.branch.io/apps/android/#initialize-branch)
       // activity will skip onStart, handle this case with reInitSession
        Branch.getInstance().reInitSession(this, branchReferralInitListener);

Alternatively, would suggest you to install Branch SDK v4.3.1.

Body:
Our android app is a chat app. Users can paste a branch link in a chat message. When another user taps on it, we want to retrieve the link parameters to take the user to another screen.

Unfortunately, we are unable to retrieve the link parameters when we tap on such link inside the app (note that we are not using a webview), we are getting the error "Warning. Session initialisation already happened.

To force a new session, set intent extra, branch_force_new_session, to true in the onInitFinished(@Nullable JSONObject referringParams, @Nullable BranchError error) method.

How can we solve this? It's not obvious to me how I could pass a new intent param in that use case.

Notes:

Our launcher activity is singleTask
We are on branch.io sdk 4.3.2
onNewIntent() does not seem to be called (in the code below), maybe that is the root cause for our issue.

sample code:

private Branch.BranchReferralInitListener branchReferralInitListener =
            new Branch.BranchReferralInitListener() {

                @Override
                public void onInitFinished(@Nullable JSONObject referringParams, @Nullable BranchError error) {
                    ...
}

@Override
    protected void onStart() {
        super.onStart();
        Branch.getInstance().initSession(branchReferralInitListener, getIntent() != null ?
                getIntent().getData() : null, this);
    }
@Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        this.setIntent(intent);
        // activity will skip onStart, handle this case with reInitSession
        Branch.getInstance().reInitSession(this, branchReferralInitListener);
    }


问:
Adding a separator line under custom tableview cell in UITableViewCell
I am trying to add a separator to my uitableview cell. i tried this.

```<code>let separator = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 8.0))
cell.contentView.addSubview(separator)
</code>```

But this adds the separator view on top of the cell, i need it to the bottom.

I also tried this way.

```<code>let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(view)
view.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor).isActive = true
view.heightAnchor.constraint(equalToConstant: 8.0).isActive = true
view.topAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true
</code>```

But this gives me no common ancestor error. and i don't want to use storyboard. i need it because i am using same cell at different places, somewhere i need the separator somewhere not. what should i do?

答:
Here is a better way to use separators:

First enable separators in your UITableView by:

```<code>myTableView.separatorStyle = .singleLine
</code>```

Then at your cellForRowAt function:

```<code>// Create your cell
// if you want to show the separator then
cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
// if you want to hide the separator then
self.separatorInset = UIEdgeInsets(top: 0, left: UIScreen.main.bounds.width, bottom: 0, right: 0)
</code>```

This would work for cells in the same UITableView as well. Because by adding a left inset of screen width then it won't show on screen and if you set it to 0 it'll be displyed from left edge to right edge of the screen.

Also you can change the color or the insets of the separator by using other properties without using storyboards or xibs.

Body:
I am trying to add a separator to my uitableview cell. i tried this.

let separator = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 8.0))
cell.contentView.addSubview(separator)

But this adds the separator view on top of the cell, i need it to the bottom.

I also tried this way.

let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(view)
view.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor).isActive = true
view.heightAnchor.constraint(equalToConstant: 8.0).isActive = true
view.topAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true

But this gives me no common ancestor error. and i don't want to use storyboard. i need it because i am using same cell at different places, somewhere i need the separator somewhere not. what should i do?

Body:
Here is a better way to use separators:

First enable separators in your UITableView by:

myTableView.separatorStyle = .singleLine

Then at your cellForRowAt function:

// Create your cell
// if you want to show the separator then
cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
// if you want to hide the separator then
self.separatorInset = UIEdgeInsets(top: 0, left: UIScreen.main.bounds.width, bottom: 0, right: 0)

This would work for cells in the same UITableView as well. Because by adding a left inset of screen width then it won't show on screen and if you set it to 0 it'll be displyed from left edge to right edge of the screen.

Also you can change the color or the insets of the separator by using other properties without using storyboards or xibs.


问:
Daily Coding Problem 260 : Reconstruct a jumbled array - Intuition?
I'm going through the question below.

The sequence [0, 1, ..., N] has been jumbled, and the only clue you have for its order is an array representing whether each number is larger or smaller than the last. Given this information, reconstruct an array that is consistent with it.

For example, given [None, +, +, -, +], you could return [1, 2, 3, 0, 4].

I went through the solution on this post but still unable to understand it as to why this solution works. I don't think I would be able to come up with the solution if I had this in front of me during an interview. Can anyone explain the intuition behind it? Thanks in advance!

答:
Let's look at first to a solution which (I think) is easier to understand, formalize and demonstrate for correctness (but I will only explain it and not demonstrate in a formal way):

We name A[0..N] our input array (where A[k] is None if k = 0 and is + or - otherwise) and B[0..N] our output array (where B[k] is in the range [0, N] and all values are unique)

At first we see that our problem (find B such that B[k] > B[k-1] if A[k] == + and B[k] < B[k-1] if A[k] == -) is only a special case of another problem:

Find B such that B[k] == max(B[0..k]) if A[k] == + and B[k] == min(B[0..k]) if A[k] == -.

Which generalize from "A value must larger or smaller than the last" to "A value must be larger or smaller than everyone before it"

So a solution to this problem is a solution to the original one as well.

Now how do we approach this problem?

A greedy solution will be sufficient, indeed is easy to demonstrate that the value associated with the last + will be the biggest number in absolute (which is N), the one associated with the second last + will be the second biggest number in absolute (which is N-1) ecc...

And in the same time the value associated with the last - will be the smallest number in absolute (which is 0), the one associated with the second last - will be the second smallest (which is 1) ecc...

So we can start filling B from right to left remembering how many + we have seen (let's call this value X), how many - we have seen (let's call this value Y) and looking at what is the current symbol, if it is a + in B we put N-X and we increase X by 1 and if it is a - in B we put 0+Y and we increase Y by 1.

In the end we'll need to fill B[0] with the only remaining value which is equal to Y+1 and to N-X-1.

An interesting property of this solution is that if we look to only the values associated with a - they will be all the values from 0 to Y (where in this case Y is the total number of -) sorted in reverse order; if we look to only the values associated with a + they will be all the values from N-X to N (where in this case X is the total number of +) sorted and if we look at B[0] it will always be Y+1 and N-X-1 (which are equal).

So the - will have all the values strictly smaller than B[0] and reverse sorted and the + will have all the values strictly bigger than B[0] and sorted.

This property is the key to understand why the solution proposed here works:

It consider B[0] equals to 0 and than it fills B following the property, this isn't a solution because the values are not in the range [0, N], but it is possible with a simple translation to move the range and arriving to [0, N]


问:
Why does 11010100 << 1 equal 110101000, not 10101000?
Why when I try to shift bits for 110101002, the result is 1101010002, not 101010002.

```<code>int a = Integer.parseInt("11010100", 2) << 1;
</code>```

I try to do this:

```<code>int a = (byte)(Integer.parseInt("11010100", 2) << 1);
</code>```

But if the output value is greater than 128, everything goes into minus, which is logical.
How can I make that number of bits does not change?

答:
Let's take it one step at a time.

Integer.parseInt("11010100", 2) - this is the int value 212. This is, by the way, needless; you can just write: 0b11010100.

0b11010100 << 1 is the same as 0b110101000, and is 424.

You then cast it to a byte: (byte)(0b11010100 << 1). The bits beyond the first 8 all get lopped off, which leaves 0b10101000, which is -88. Minus, yes, because in java bytes are signed.

You then silently cast this -88 back up to int, as you assign it to an int value. It remains -88, which means all the top bits are all 1s.

Hence, the final value is -88.

If you want to see 168 instead (which is the exact same bits, but shown unsigned instead of signed), the usual trick is to use & 0xFF, which sets all bits except the first 8 to 0, thus guaranteeing a positive number:

byte b = (byte) (0b11010100 << 1);
System.out.println(b); // -88. It is not possible to print 168 when printing a byte.
int asUnsigned = b & 0xFF;
System.out.println(asUnsigned); // 168.

// or in one go:

System.out.println(((byte) (0b11010100 << 1)) & 0xFF); // 168

```

Body:
Why when I try to shift bits for 110101002, the result is 1101010002, not 101010002.

int a = Integer.parseInt("11010100", 2) << 1;

I try to do this:

int a = (byte)(Integer.parseInt("11010100", 2) << 1);

But if the output value is greater than 128, everything goes into minus, which is logical.
How can I make that number of bits does not change?


问:
Build loop to use increasing part of dataframe in R as input to function
I'm using the first principal component from a PCA analysis as an explanatory variable in a forecasting model that forecasts recursively using Kalman filtering. In other words, at each point in time, the model updates and produces a new forecast based on the new observation included into the model. Since PCA uses data from all observations included in the model for its calculations, I need to run also the PCAs recursively, using only the observations prior to the point in time that I am forecasting (otherwise, the PCA-result could reveal information about the future, and help the model produce a more accurate answer than it would have otherwise). I think a loop might be the solution, but I am struggling with how to formulate the code.

As a more specific example, consider if I have the following data.frame

```<code>data <- as.data.frame(rbind(c(6,15,23),c(9,11,22), c(7,13,23), c(6,12,25),c(7,13,23)))
names(data) <- c("V1","V2","V3")

> data
  V1 V2 V3
1  6 15 23
2  9 11 22
3  7 13 23
4  6 12 25
5  7 13 23
</code>```

At each observation date, I wish to run a PCA (function prcomp() from the stats-package) for all observations up to, and including, that observation. So I want to first run PCA for the two first observation

```<code>pca2 <- prcomp(data[1:2,], scale = TRUE)
</code>```

next I want to run PCA with the first, second and third observation as input

```<code>pca3 <- prcomp(data[1:3,], scale = TRUE)
</code>```

next I want to run PCA with the first, second, third and fourth observation as input

```<code>pca4 <- prcomp(data[1:4,], scale = TRUE)
</code>```

and so on, until the last run of the PCA, which includes all observations in the dataframe. For each of these "runs" of the PCA, I wish to extract the last value (though for pca2, I use both the first and second value) of the first principal component (PC1), and merge these into a final dataframe, where each monthly observation is the last value of the first principal component of PCA results for each of the runs.

The principal component outputs are:

```<code>> my_pca2 <- as.data.frame(pca2$x)
> my_pca2
        PC1           PC2
1 -1.224745 -5.551115e-17
2  1.224745  5.551115e-17

> my_pca3 <- as.data.frame(pca3$x)
> my_pca3
         PC1        PC2          PC3
1 -1.4172321 -0.2944338 6.106227e-16
2  1.8732448 -0.1215046 3.330669e-16
3 -0.4560127  0.4159384 4.163336e-16

> my_pca4 <- as.data.frame(pca4$x)
> my_pca4
          PC1         PC2          PC3
1 -1.03030993 -1.10154914  0.015457199
2  2.00769890  0.07649216  0.011670433
3  0.03301806 -0.24226508 -0.033461874
4 -1.01040702  1.26732205  0.006334242
</code>```

So I want my final output to be a dataframe to look like

```<code>>final.output
         PC1
1  -1.224745
2   1.224745
3 -0.4560127
4 -1.01040702
</code>```

Comment: yes, it looks a bit weird with the two first values, but please don't pay too much attention to that. My point is that I wish to build a dataframe that consists of the last calculated value for the first principal component for each of the PCA runs.

I am thinking that a for.loop might be the best solution here, but I have not been successful in finding any threads that might guide me closer to a coding solution. How can I make the loop use an increasing amount of the dataframe in the calculations? Does anyone have any suggestions/tips/links? Any help on this is much appreciated!

答:
You can use a for loop. It's maybe not the most efficient solution, but it will work.

First, you create an empty list to store your results:

```<code>all_results <- list()
</code>```

Next, you iterate from 2 to the number of rows of data with a loop. For each iteration of the loop, run prcomp on data[1:i,]. You can directly create your pca data frame and extract PC1from it as a vector. Now you store it in the list at index i - 1

```<code>for(i in 2:nrow(data))
{
  all_results[[i - 1]] <- as.data.frame(prcomp(data[1:i,], scale = TRUE)$x)$PC1
}
</code>```

Now to extract all the results, you use lapply (list apply) to extract only the last element from each PC1 vector:

```<code>PC1 <- lapply(all_results, function(pca) pca[length(pca)] )
</code>```

Now you convert these from a list of single elements to a vector:

```<code>PC1 <- do.call("c", PC1)
</code>```

Finally, you want to stick the first value of the first analysis back on to the front of this vector:

```<code>PC1 <- c(all_results[[1]][1], PC1)
</code>```

Body:
I'm using the first principal component from a PCA analysis as an explanatory variable in a forecasting model that forecasts recursively using Kalman filtering. In other words, at each point in time, the model updates and produces a new forecast based on the new observation included into the model. Since PCA uses data from all observations included in the model for its calculations, I need to run also the PCAs recursively, using only the observations prior to the point in time that I am forecasting (otherwise, the PCA-result could reveal information about the future, and help the model produce a more accurate answer than it would have otherwise). I think a loop might be the solution, but I am struggling with how to formulate the code.

As a more specific example, consider if I have the following data.frame

data <- as.data.frame(rbind(c(6,15,23),c(9,11,22), c(7,13,23), c(6,12,25),c(7,13,23)))
names(data) <- c("V1","V2","V3")

> data
  V1 V2 V3
1  6 15 23
2  9 11 22
3  7 13 23
4  6 12 25
5  7 13 23

At each observation date, I wish to run a PCA (function prcomp() from the stats-package) for all observations up to, and including, that observation. So I want to first run PCA for the two first observation

pca2 <- prcomp(data[1:2,], scale = TRUE)

next I want to run PCA with the first, second and third observation as input

pca3 <- prcomp(data[1:3,], scale = TRUE)

next I want to run PCA with the first, second, third and fourth observation as input

pca4 <- prcomp(data[1:4,], scale = TRUE)

and so on, until the last run of the PCA, which includes all observations in the dataframe. For each of these "runs" of the PCA, I wish to extract the last value (though for pca2, I use both the first and second value) of the first principal component (PC1), and merge these into a final dataframe, where each monthly observation is the last value of the first principal component of PCA results for each of the runs.

The principal component outputs are:

> my_pca2 <- as.data.frame(pca2$x)
> my_pca2
        PC1           PC2
1 -1.224745 -5.551115e-17
2  1.224745  5.551115e-17

> my_pca3 <- as.data.frame(pca3$x)
> my_pca3
         PC1        PC2          PC3
1 -1.4172321 -0.2944338 6.106227e-16
2  1.8732448 -0.1215046 3.330669e-16
3 -0.4560127  0.4159384 4.163336e-16

> my_pca4 <- as.data.frame(pca4$x)
> my_pca4
          PC1         PC2          PC3
1 -1.03030993 -1.10154914  0.015457199
2  2.00769890  0.07649216  0.011670433
3  0.03301806 -0.24226508 -0.033461874
4 -1.01040702  1.26732205  0.006334242

So I want my final output to be a dataframe to look like

>final.output
         PC1
1  -1.224745
2   1.224745
3 -0.4560127
4 -1.01040702

Comment: yes, it looks a bit weird with the two first values, but please don't pay too much attention to that. My point is that I wish to build a dataframe that consists of the last calculated value for the first principal component for each of the PCA runs.

I am thinking that a for.loop might be the best solution here, but I have not been successful in finding any threads that might guide me closer to a coding solution. How can I make the loop use an increasing amount of the dataframe in the calculations? Does anyone have any suggestions/tips/links? Any help on this is much appreciated!

Body:
You can use a for loop. It's maybe not the most efficient solution, but it will work.

First, you create an empty list to store your results:

all_results <- list()

Next, you iterate from 2 to the number of rows of data with a loop. For each iteration of the loop, run prcomp on data[1:i,]. You can directly create your pca data frame and extract PC1from it as a vector. Now you store it in the list at index i - 1

for(i in 2:nrow(data))
{
  all_results[[i - 1]] <- as.data.frame(prcomp(data[1:i,], scale = TRUE)$x)$PC1
}

Now to extract all the results, you use lapply (list apply) to extract only the last element from each PC1 vector:

PC1 <- lapply(all_results, function(pca) pca[length(pca)] )

Now you convert these from a list of single elements to a vector:

PC1 <- do.call("c", PC1)

Finally, you want to stick the first value of the first analysis back on to the front of this vector:

PC1 <- c(all_results[[1]][1], PC1)


问:
Regular Expression to Replace xxx(zzz)xxx format in c#
I need a regular expression to replace xxx()xxx in this format xxx(zzz)xxx with nothing.

here is example:  Sara(56)Gorge => 56

Body:
C#:

var result = Regex.Replace("Sara(56)Gorge", @"[^(]*\(([^)]*)\)[^(]*", "$1");


问:
Intellisense error when passing vector by const reference (but project builds)
While attempting to pass a vector by const reference I'm receiving the following intellisense error (project builds successfully):

```<code>no instance of constructor "ObjOne::ObjOne" matches the argument list
argument types are: (std::vector<int, std::allocator<int>>)
</code>```

I have commented in the below minimal reproducible example where the error occurs. Is there a known way to resolve issues such as these within visual studio 2017?

```<code>#include <vector>
#include <string>
#include <optional>

class ObjOne
{
public:
    ObjOne(const std::vector<int>& p1) {}
};

class ObjTwo
{
private:
    std::vector<int> testVec = { 1,2,3,4,5 };
    std::optional<ObjOne> optObjOne;
public:
    ObjTwo() {}
    void makeObjOne()
    {
        this->optObjOne = ObjOne(this->testVec); // Issue arises here
    }
};

int main()
{
    auto myObjTwo = ObjTwo();
    myObjTwo.makeObjOne();

    return 0;
}
</code>```

答:
Intellisense error when passing vector by const reference (but project
  builds)

I have tested your sample in my latest VS2017 and Intellisense works well as expected. So l wonder there are some problems with your VS environment and Intellisnese.

My environment-- OS: win10 1903  VS:VS2017 Community 19.9.20

You could try my suggestions to troubleshoot your issue:

As a suggestion, if your VS2017 is not the latest version, you could update it to the latest version which may have a newer fix.

1) close VS instance, delete the .vs hidden folder, bin folder and obj folder

2) clean the VS Component Cache under C:\Users\user\AppData\Local\Microsoft\VisualStudio\15.0_xxxxx\ComponentModelCache

3) open your project in VS and right-click on your project-->Properties-->C/C++-->Language-->set C++ Language Standard to ISO C++ 17 Standard(/std:c++17)

In addition, if these does not work ,please try to do a repair in VS Installer in case the Intellisense is broken.

Hope it could help you.

Body:
While attempting to pass a vector by const reference I'm receiving the following intellisense error (project builds successfully):

no instance of constructor "ObjOne::ObjOne" matches the argument list
argument types are: (std::vector<int, std::allocator<int>>)

I have commented in the below minimal reproducible example where the error occurs. Is there a known way to resolve issues such as these within visual studio 2017?

#include <vector>
#include <string>
#include <optional>

class ObjOne
{
public:
    ObjOne(const std::vector<int>& p1) {}
};

class ObjTwo
{
private:
    std::vector<int> testVec = { 1,2,3,4,5 };
    std::optional<ObjOne> optObjOne;
public:
    ObjTwo() {}
    void makeObjOne()
    {
        this->optObjOne = ObjOne(this->testVec); // Issue arises here
    }
};

int main()
{
    auto myObjTwo = ObjTwo();
    myObjTwo.makeObjOne();

    return 0;
}


答:
Try something like this:

```<code>int anInt = Integer.parseInt("11010100", 2) << 1;
int asUnsignedInt= Byte.toUnsignedInt((byte) anInt);
</code>```

toUnsignedInt has been introduced in Java SE 8.

Title: Why does 11010100 << 1 equal 110101000, not 10101000?

Body:
Try something like this:

int anInt = Integer.parseInt("11010100", 2) << 1;
int asUnsignedInt= Byte.toUnsignedInt((byte) anInt);

toUnsignedInt has been introduced in Java SE 8.


问:
How to calculate a time between two times with one day off?
I have a Do Not Disturb system that mutes the sounds of my android app if the current time is in Do not disturb range time.
It works fine if I use a range time just between a day, but I dont know how to write it with one day off, For example at 11:00 pm to 1:00 am of the next day.

This is method that I used for detecting DND time:

```<code>private boolean isInDNDTime() {
    Calendar now = Calendar.getInstance();
    Calendar startTime = Calendar.getInstance();
    Calendar endTime = Calendar.getInstance();
    MyDate myDate = new MyDate(new Date());

    if (isDNDTwoDays()) {
        startTime.setTime(myDate.getYesterday().toDate());
        startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
        startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());

        endTime.setTime(myDate.getTomorrow().toDate());
        endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
        endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());

    } else {
        startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
        startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());

        endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
        endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());
    }

    return now.after(startTime) && now.before(endTime);
}
</code>```

答:
Pls try below code</p>

```<code> private boolean isInDNDTime() {
        Calendar now = Calendar.getInstance();
        Calendar startTime = Calendar.getInstance();
        Calendar endTime = Calendar.getInstance();
        MyDate myDate = new MyDate(new Date());

        if (isDNDTwoDays()) {
            startTime.add(Calendar.DATE, 1);
            endTime.add(Calendar.DATE, 1);

           // startTime.setTime(myDate.getYesterday().toDate());
            startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
            startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());

           // endTime.setTime(myDate.getTomorrow().toDate());
            endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
            endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());

        } else {
            startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
            startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());

            endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
            endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());
        }

        return now.after(startTime) && now.before(endTime);
    }
</code>```

Body:
I have a Do Not Disturb system that mutes the sounds of my android app if the current time is in Do not disturb range time.
It works fine if I use a range time just between a day, but I dont know how to write it with one day off, For example at 11:00 pm to 1:00 am of the next day.

This is method that I used for detecting DND time:

private boolean isInDNDTime() {
    Calendar now = Calendar.getInstance();
    Calendar startTime = Calendar.getInstance();
    Calendar endTime = Calendar.getInstance();
    MyDate myDate = new MyDate(new Date());

    if (isDNDTwoDays()) {
        startTime.setTime(myDate.getYesterday().toDate());
        startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
        startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());

        endTime.setTime(myDate.getTomorrow().toDate());
        endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
        endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());

    } else {
        startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
        startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());

        endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
        endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());
    }

    return now.after(startTime) && now.before(endTime);
}

Body:
Pls try below code

 private boolean isInDNDTime() {
        Calendar now = Calendar.getInstance();
        Calendar startTime = Calendar.getInstance();
        Calendar endTime = Calendar.getInstance();
        MyDate myDate = new MyDate(new Date());

        if (isDNDTwoDays()) {
            startTime.add(Calendar.DATE, 1);
            endTime.add(Calendar.DATE, 1);

           // startTime.setTime(myDate.getYesterday().toDate());
            startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
            startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());

           // endTime.setTime(myDate.getTomorrow().toDate());
            endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
            endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());

        } else {
            startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
            startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());

            endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
            endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());
        }

        return now.after(startTime) && now.before(endTime);
    }


问:
My Webview Reloads When I Change From Portrait To Landscape
I have a simple WebView that runs a web application on an Android. The problem is when I rotate the phone to change it to landscape the webview reloads and goes back to the beginning.

How can I prevent this action?

Ron

答:
Add the following to your AndroidManifest:

```<code>android:configChanges="orientation|keyboard|keyboardHidden"
</code>```

So it should look something like this:

```<code><activity android:name=".MyActivity"
          android:label="@string/app_name"
          android:configChanges="orientation|keyboard|keyboardHidden">
</code>```

Obviously, if your WebView needs keyboard support then don't include the keyboard options.

Body:
Add the following to your AndroidManifest:

android:configChanges="orientation|keyboard|keyboardHidden"

So it should look something like this:

<activity android:name=".MyActivity"
          android:label="@string/app_name"
          android:configChanges="orientation|keyboard|keyboardHidden">

Obviously, if your WebView needs keyboard support then don't include the keyboard options.


问:
How do you get the nth child of a class in jquery
Normally I would do this in the console:

```<code>$('element:nth-child(which child)')
</code>```

For a class selector I have tried this:

```<code>$('.class:nth-child(2)')
</code>```

This doesn't seem to work, is it even possible to get an nth class? It's just that there are 4 lots with the same class name, and there is no way to select it to then get the button I wish to get.

答:
If my assumption is correct, you are wanting to look at a group of sibling elements, and get the 2nd instance containing a certain class. As an example, let's say you have the following markup:

```<code><div class="class1" id="id1">One</div>
<div class="class888" id="id2">Two</div>
<div class="class1" id="id3">Three</div>
<div class="class1" id="id4">Four</div>
</code>```

And of those siblings, you want to get the 2nd one that contains the class .class1 (which here would be #id3 - we skip #id2 since that does not contain the class .class1). In this case, you can not use the nth-child() selector - this can only be used with all elements (as in :nth-child(2)) or specific element types (as in tr:nth-child(2)).

The way to do what you want is to first filter by class selector, and then use the eq method. So in your case you'd want:

```<code>$('.class').eq(1); // note eq() is zero-based - hence, 1 represents the 2nd child
</code>```

Note that eq() is zero-based, so eq(1) represents the 2nd child.

Body:
Normally I would do this in the console:

$('element:nth-child(which child)')

For a class selector I have tried this:

$('.class:nth-child(2)')

This doesn't seem to work, is it even possible to get an nth class? It's just that there are 4 lots with the same class name, and there is no way to select it to then get the button I wish to get.

Body:
If my assumption is correct, you are wanting to look at a group of sibling elements, and get the 2nd instance containing a certain class. As an example, let's say you have the following markup:

<div class="class1" id="id1">One</div>
<div class="class888" id="id2">Two</div>
<div class="class1" id="id3">Three</div>
<div class="class1" id="id4">Four</div>

And of those siblings, you want to get the 2nd one that contains the class .class1 (which here would be #id3 - we skip #id2 since that does not contain the class .class1). In this case, you can not use the nth-child() selector - this can only be used with all elements (as in :nth-child(2)) or specific element types (as in tr:nth-child(2)).

The way to do what you want is to first filter by class selector, and then use the eq method. So in your case you'd want:

$('.class').eq(1); // note eq() is zero-based - hence, 1 represents the 2nd child

Note that eq() is zero-based, so eq(1) represents the 2nd child.


问:
Is there a way to rescale the axes of a plot produced by plot.clusterlm (R)?
I have run cluster analysis on some time series data using permuco in R. (Permutes the labels of control/treatment conditions and calculates the F statistic as to how likely it is that these time clusters of significant differences occurred by chance.)
So far so good.

I have produced a number of plots using the inbuilt function plot.clusterlm that comes with this package. However, the data come from different groups, and the F values on the y axis get rescaled in each plot, i.e. the values and ticks are reset depending on how strong the effects are.

This is problematic, because the different plots based on different cluster analyses are not visually comparable.
I would like to rescale the y axis, so that all clusters are visualised along the same F values (0-10 for example).

I haven't been able to do that, and I was wondering if there is a way to pass any additional functions into the plot.clusterlm to do this.
This is the usage of the function, but I don't see a way to rescale the y axis. (Although rescaling the x axis is possible by manipulating the nbbaselinepts & nbptsperunit, but that's not what I want...)

```<code>    plot(x, effect = "all", type = "statistic",
    multcomp = "clustermass", alternative = "two.sided",
    enhanced_stat = FALSE, nbbaselinepts = 0, nbptsperunit = 1, ...)
</code>```

If you have any ideas on this, please let me know.
Thank you!

答:
Thanks for using permuco! I opened an issue on GitHub to have a solution for implementing these features. You can expect changes in further releases of permuco.

However, the plot() method shows the F statistic which is not a good measure of effect size. A better measure of effect size is the partial-eta square which is implemented in the afex package

Body:
I have run cluster analysis on some time series data using permuco in R. (Permutes the labels of control/treatment conditions and calculates the F statistic as to how likely it is that these time clusters of significant differences occurred by chance.)
So far so good.

I have produced a number of plots using the inbuilt function plot.clusterlm that comes with this package. However, the data come from different groups, and the F values on the y axis get rescaled in each plot, i.e. the values and ticks are reset depending on how strong the effects are.

This is problematic, because the different plots based on different cluster analyses are not visually comparable.
I would like to rescale the y axis, so that all clusters are visualised along the same F values (0-10 for example).

I haven't been able to do that, and I was wondering if there is a way to pass any additional functions into the plot.clusterlm to do this.
This is the usage of the function, but I don't see a way to rescale the y axis. (Although rescaling the x axis is possible by manipulating the nbbaselinepts & nbptsperunit, but that's not what I want...)

    plot(x, effect = "all", type = "statistic",
    multcomp = "clustermass", alternative = "two.sided",
    enhanced_stat = FALSE, nbbaselinepts = 0, nbptsperunit = 1, ...)

If you have any ideas on this, please let me know.
Thank you!


问:
Adafruit MMA8451 accelerometer giving my Raspberry Pi osError [Errno 121] Remote I/O error
I am running python3.5 on a Raspberry Pi 3 B+. With a display.

My project is getting a simple accelerometer to print its values.
I am following the following tutorial: I even added dtoverlay=spi1-3cs to the end of /boot/config.txt to activate another hardware SPI port as I am using my Pi with a display.

I am trying to run the following code and am having the following errors.

I have run i2cdetect -y -1. It showed a device with address of 1d.

I have checked my connection and everything, not sure what I am doing wrong.

```<code>    # Simple demo of reading the MMA8451 orientation every second.
# Author: Tony DiCola
import time

import board
import busio
import adafruit_mma8451
# Initialize I2C bus.
i2c = busio.I2C(board.SCL, board.SDA)

# Initialize MMA8451 module.
sensor = adafruit_mma8451.MMA8451(i2c)
# Optionally change the address if it's not the default:
##sensor = adafruit_mma8451.MMA8451(i2c, address=0x1d)

# Main loop to print the acceleration and orientation every second.
while True:
    x, y, z = sensor.acceleration
    print('Acceleration: x={0:0.3f}m/s^2 y={1:0.3f}m/s^2 z={2:0.3f}m/s^2'.format(x, y, z))
    orientation = sensor.orientation

    print('Orientation: ', end='')
    if orientation == adafruit_mma8451.PL_PUF:
        print('Portrait, up, front')
    elif orientation == adafruit_mma8451.PL_PUB:
        print('Portrait, up, back')
    elif orientation == adafruit_mma8451.PL_PDF:
        print('Portrait, down, front')
    elif orientation == adafruit_mma8451.PL_PDB:
        print('Portrait, down, back')
    elif orientation == adafruit_mma8451.PL_LRF:
        print('Landscape, right, front')
    elif orientation == adafruit_mma8451.PL_LRB:
        print('Landscape, right, back')
    elif orientation == adafruit_mma8451.PL_LLF:
        print('Landscape, left, front')
    elif orientation == adafruit_mma8451.PL_LLB:
        print('Landscape, left, back')
    time.sleep(1.0)
</code>```

The Errors are as follows:

```<code>Traceback (most recent call last):
  File "simpletest.py", line 15, in <module>
    sensor = adafruit_mma8451.MMA8451(i2c)
  File "/usr/local/lib/python3.5/dist-packages/adafruit_mma8451.py", line 103, in __init__
    while self._read_u8(_MMA8451_REG_CTRL_REG2) & 0x40 > 0:
  File "/usr/local/lib/python3.5/dist-packages/adafruit_mma8451.py", line 134, in _read_u8
    self._read_into(address, self._BUFFER, count=1)
  File "/usr/local/lib/python3.5/dist-packages/adafruit_mma8451.py", line 130, in _read_into
    in_end=count, stop=False)
  File "/usr/local/lib/python3.5/dist-packages/adafruit_bus_device/i2c_device.py", line 149, in write_then_readinto
    in_start=in_start, in_end=in_end, stop=stop)
  File "/home/pi/.local/lib/python3.5/site-packages/busio.py", line 68, in writeto_then_readfrom
    in_start=in_start, in_end=in_end, stop=stop)
  File "/home/pi/.local/lib/python3.5/site-packages/adafruit_blinka/microcontroller/generic_linux/i2c.py", line 63, in writeto_then_readfrom
    readin = self._i2c_bus.read_i2c_block_data(address, buffer_out[out_start:out_end][0], in_end-in_start)
  File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_PureIO/smbus.py", line 215, in read_i2c_block_data
    ioctl(self._device.fileno(), I2C_RDWR, request)
OSError: [Errno 121] Remote I/O error
</code>```

答: I had the same problem with my Pi & accelerometer - device showing when using i2cdetect, but unable to get data with either Adafruit's code or i2cget. i2cdump showed garbage/corrupted data. The solution was that the ground wire between the Pi and the accelerometer was faulty. Once this was fixed, the device responded correctly.

Body:
I am running python3.5 on a Raspberry Pi 3 B+. With a display.

My project is getting a simple accelerometer to print its values.
I am following the following tutorial: I even added dtoverlay=spi1-3cs to the end of /boot/config.txt to activate another hardware SPI port as I am using my Pi with a display.

I am trying to run the following code and am having the following errors.

I have run i2cdetect -y -1. It showed a device with address of 1d.

I have checked my connection and everything, not sure what I am doing wrong.

    # Simple demo of reading the MMA8451 orientation every second.
# Author: Tony DiCola
import time

import board
import busio
import adafruit_mma8451
# Initialize I2C bus.
i2c = busio.I2C(board.SCL, board.SDA)

# Initialize MMA8451 module.
sensor = adafruit_mma8451.MMA8451(i2c)
# Optionally change the address if it's not the default:
##sensor = adafruit_mma8451.MMA8451(i2c, address=0x1d)

# Main loop to print the acceleration and orientation every second.
while True:
    x, y, z = sensor.acceleration
    print('Acceleration: x={0:0.3f}m/s^2 y={1:0.3f}m/s^2 z={2:0.3f}m/s^2'.format(x, y, z))
    orientation = sensor.orientation

    print('Orientation: ', end='')
    if orientation == adafruit_mma8451.PL_PUF:
        print('Portrait, up, front')
    elif orientation == adafruit_mma8451.PL_PUB:
        print('Portrait, up, back')
    elif orientation == adafruit_mma8451.PL_PDF:
        print('Portrait, down, front')
    elif orientation == adafruit_mma8451.PL_PDB:
        print('Portrait, down, back')
    elif orientation == adafruit_mma8451.PL_LRF:
        print('Landscape, right, front')
    elif orientation == adafruit_mma8451.PL_LRB:
        print('Landscape, right, back')
    elif orientation == adafruit_mma8451.PL_LLF:
        print('Landscape, left, front')
    elif orientation == adafruit_mma8451.PL_LLB:
        print('Landscape, left, back')
    time.sleep(1.0)

The Errors are as follows:

Traceback (most recent call last):
  File "simpletest.py", line 15, in <module>
    sensor = adafruit_mma8451.MMA8451(i2c)
  File "/usr/local/lib/python3.5/dist-packages/adafruit_mma8451.py", line 103, in __init__
    while self._read_u8(_MMA8451_REG_CTRL_REG2) & 0x40 > 0:
  File "/usr/local/lib/python3.5/dist-packages/adafruit_mma8451.py", line 134, in _read_u8
    self._read_into(address, self._BUFFER, count=1)
  File "/usr/local/lib/python3.5/dist-packages/adafruit_mma8451.py", line 130, in _read_into
    in_end=count, stop=False)
  File "/usr/local/lib/python3.5/dist-packages/adafruit_bus_device/i2c_device.py", line 149, in write_then_readinto
    in_start=in_start, in_end=in_end, stop=stop)
  File "/home/pi/.local/lib/python3.5/site-packages/busio.py", line 68, in writeto_then_readfrom
    in_start=in_start, in_end=in_end, stop=stop)
  File "/home/pi/.local/lib/python3.5/site-packages/adafruit_blinka/microcontroller/generic_linux/i2c.py", line 63, in writeto_then_readfrom
    readin = self._i2c_bus.read_i2c_block_data(address, buffer_out[out_start:out_end][0], in_end-in_start)
  File "/home/pi/.local/lib/python3.5/site-packages/Adafruit_PureIO/smbus.py", line 215, in read_i2c_block_data
    ioctl(self._device.fileno(), I2C_RDWR, request)
OSError: [Errno 121] Remote I/O error


问:
Why this code works well in MySQL but not in SQL Server?
This is a question in Leetcode: https://leetcode.com/problems/delete-duplicate-emails/solution/

Basically the question asks to delete duplicate emails and keep the one that has the minumal index.

My code is the following one, and I firstly ran it in SQL Server mode, and it shows "Internal Error". But it has passed in MySQL mode. Why does this happen? Are there any syntax differences between them shown in this case? Thanks.

```<code>delete from Person
where Id not in (
select temp.minimum from
(select min(Id) as minimum from Person group by Email) as temp
);
</code>```

答:
In SQL Server you use CTE with ROW_NUMBER() :

```<code>WITH cte AS (
     SELECT P.*, ROW_NUMBER() OVER (PARTITION BY p.email ORDER BY id) AS seq
     FROM Person P
)
DELETE
FROM cte c
WHERE c.seq > 1;
</code>```

However, your original version of query should also work in SQL Server.

Body:
This is a question in Leetcode: https://leetcode.com/problems/delete-duplicate-emails/solution/

Basically the question asks to delete duplicate emails and keep the one that has the minumal index.

My code is the following one, and I firstly ran it in SQL Server mode, and it shows "Internal Error". But it has passed in MySQL mode. Why does this happen? Are there any syntax differences between them shown in this case? Thanks.

delete from Person
where Id not in (
select temp.minimum from
(select min(Id) as minimum from Person group by Email) as temp
);

Body:
In SQL Server you use CTE with ROW_NUMBER() :

WITH cte AS (
     SELECT P.*, ROW_NUMBER() OVER (PARTITION BY p.email ORDER BY id) AS seq
     FROM Person P
)
DELETE
FROM cte c
WHERE c.seq > 1;

However, your original version of query should also work in SQL Server.


问:
How to use activerecord alone?
I prepare to develop one project, which has no UI. The project just need to interact with database, so is there any example for reference ？</p>

答:
Does your app have ties to a Rails-based app and need to read the Rails configuration files? Or, is it entirely stand-alone and have no Rails interaction?

ActiveRecord is OK for that, but if I don't need Rails compatibility I use Sequel. It's a great ORM that I find to be much more flexible.

If you need Rails compatibility and want to use ActiveRecord, look into using rails runner. From the docs:

runner runs Ruby code in the context of Rails non-interactively. For instance:

```<code>$ rails runner "Model.long_running_method"
</code>```

Rails runner is for command-line apps that don't need the HTTPd server or user-interface of Rails. I use them for things like an app that runs daily to ftp files from a site for analysis. It has to write to the database, so it has access to all the models I've defined, but it never needs to present anything to the user since it is invisible to them.

Title: How to use activerecord alone?

Body:
Does your app have ties to a Rails-based app and need to read the Rails configuration files? Or, is it entirely stand-alone and have no Rails interaction?

ActiveRecord is OK for that, but if I don't need Rails compatibility I use Sequel. It's a great ORM that I find to be much more flexible.

If you need Rails compatibility and want to use ActiveRecord, look into using rails runner. From the docs:

runner runs Ruby code in the context of Rails non-interactively. For instance:

$ rails runner "Model.long_running_method"

Rails runner is for command-line apps that don't need the HTTPd server or user-interface of Rails. I use them for things like an app that runs daily to ftp files from a site for analysis. It has to write to the database, so it has access to all the models I've defined, but it never needs to present anything to the user since it is invisible to them.


问:
Copy part of json key-values in javascript
Given a json like this

```<code>  var json1 = {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": null
      };

  var json2 = {
                "key3": {
                  "index": "3",
                  "value": "value3"
                },
                "key4": {
                  "index": "4",
                  "value": 'value4'
              }
        };
</code>```

how to get a new json like this, it will only copy the same key to the first one.

```<code>json3= {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": 'value3'
      }
};
</code>```

I've tried on Object.assign  or _.assign of lodash

```<code> Object.assign(json1,json2)
 _.assign(json1,json2)
</code>```

but it will copy all the objects of json2 to json1.

答:
const json1 = {
    "key1": {
      "index": "1",
      "value": null
    },
    "key2": {
      "index": "2",
      "value": null
    },
    "key3": {
      "index": "3",
      "value": null
  }
};

const json2 = {
        "key3": {
          "index": "3",
          "value": "value3"
        },
        "key4": {
          "index": "4",
          "value": 'value4'
      }
};

const result = {};
for(const key in json1) {
  result[key] = json2[key] ? json2[key] : json1[key];
};

console.log(result);```

You can use a for in for it.

Body:
Given a json like this

  var json1 = {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": null
      };

  var json2 = {
                "key3": {
                  "index": "3",
                  "value": "value3"
                },
                "key4": {
                  "index": "4",
                  "value": 'value4'
              }
        };

how to get a new json like this, it will only copy the same key to the first one.

json3= {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": 'value3'
      }
};

I've tried on Object.assign  or _.assign of lodash

 Object.assign(json1,json2)
 _.assign(json1,json2)

but it will copy all the objects of json2 to json1.

Body:
const json1 = {
    "key1": {
      "index": "1",
      "value": null
    },
    "key2": {
      "index": "2",
      "value": null
    },
    "key3": {
      "index": "3",
      "value": null
  }
};

const json2 = {
        "key3": {
          "index": "3",
          "value": "value3"
        },
        "key4": {
          "index": "4",
          "value": 'value4'
      }
};

const result = {};
for(const key in json1) {
  result[key] = json2[key] ? json2[key] : json1[key];
};

console.log(result);

You can use a for in for it.


问:
Latest git hash needs to be speicified in installer's name
Consider a situation in which Git is installed in Windows and is available only in Git Bash, not Windows cmd environment. Having a vdproj to create installer for an application, but need to intercalate the latest git hash to the MSI package's name. For example, at the moment it produces:
Behnama.msi
But we need it to produce:
Behnama_49ee23d3b33ba0fa5ce0ac128f50ed00345e9ce3.msi
The hash 49ee... is what in top when I enter 'git log' in Git Bash. When a new commit is created, then come and build the vdproj, I want the hash to be changed in the name of the msi file.</p>

答:
You need a few steps

Get the last git commit ID

Write the ID to a wxi-file

Include the wxi-file to original wxs-file

Use the value as variable

For 1) you can use git log -1 --pretty=format:"%h" (short hash) or git log -1 --pretty=format:"%H" (long hash) to get the last commit id.

For 2) On a Windows System type git log -1 --pretty=format:"%H" > gitLastCommit.wxi to store the last commit as a wxi-file. HINT: You need to wrap the simple ID with<include><?define mylastGitCommit = "VALUE OF COMMT ID" ?></include>

For 3) Add a similar line <?include .\gitLastCommit.wxi ?> to your wxs file.

For 4) Use the defined variable $(var.mylastGitCommit) in your wxs file where it is needed


问:
Unable to use only Light or Dark theme on Nativescript
I'm developing a Nativescript (version 6.3.3) app with Angular 8.2 and @nativescript/theme 2.2.1 with scss themes.
I'm trying to use only Dark (or only Light) theme regardless of system mode (Dark/Light) but nothing seems to work.
I followed this guide https://github.com/NativeScript/theme and I used custom color variables setting the dark ones equal to the light ones but it doesnt' work.
Can someone support me?</p>

答:
If you want to force Light or Dark mode only on iOS you can add the following to your Info.plist file.

For light mode:

```<code>    <key>UIUserInterfaceStyle</key>
    <string>Light</string>
</code>```

For dark mode:

```<code>    <key>UIUserInterfaceStyle</key>
    <string>Dark</string>
</code>```

Hope this helps!

Body:
If you want to force Light or Dark mode only on iOS you can add the following to your Info.plist file.

For light mode:

    <key>UIUserInterfaceStyle</key>
    <string>Light</string>

For dark mode:

    <key>UIUserInterfaceStyle</key>
    <string>Dark</string>

Hope this helps!