问:
want to execute change event inside the for loop
I am trying to select the zip code which is in input tag and once it is selected the onchange event in the span should be executed.I am using tampermonkey and trying to call onchange event from there. it executes fine when there is one zip code selected at a time. However, selecting multiple zip code is not working. it selects all zip code but when onchange event calls, it deselect all zip code.

```<code><table>
  <tr>
    <td>
      <span id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_lblDistribRegionName"><span class="indentation"></span> 76511Z </span>
    </td>
    <td>
      <div class="right">
        <span id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_lblEstimatedCirculationFormatted" class="dimmedItem">13</span>
      </div>
    </td>
    <td>
      <input name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$tbQuantityOrdered" type="text" value="0" size="6" onchange="javascript:setTimeout('__doPostBack(\'ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$tbQuantityOrdered\',\'\')', 0)"
        onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_tbQuantityOrdered" disabled="disabled" class="aspNetDisabled read-only right" class="right" />
      <!- comment to prevent PlaceHolder eating whitespaces -->
      <span class="mandatory" title="Mandatory field">*</span> <span data-val-controltovalidate="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_tbQuantityOrdered" data-val-errormessage="Fill-in ordered quantity" data-val-display="Dynamic" data-val-validationGroup="AdInsertRegionsNumber"
        id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_reqQuantityOrdered" class="validation-error" data-val="true" data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid" data-val-initialvalue="" style="display:none;">Fill-in ordered quantity</span>
      <span data-val-controltovalidate="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_tbQuantityOrdered" data-val-errormessage="Fill-in number in valid format." data-val-display="Dynamic" data-val-validationGroup="AdInsertRegionsNumber" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cvQuantityOrderedInt"
        class="validation-error" data-val="true" data-val-type="Integer" data-val-evaluationfunction="CompareValidatorEvaluateIsValid" data-val-operator="DataTypeCheck" style="display:none;">Fill-in number in valid format.</span>
      <span data-val-controltovalidate="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_tbQuantityOrdered" data-val-errormessage="Fill-in whole number greater or equal to 0." data-val-display="Dynamic" data-val-validationGroup="AdInsertRegionsNumber" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cvQuantityOrderedZero"
        class="validation-error" data-val="true" data-val-type="Integer" data-val-evaluationfunction="CompareValidatorEvaluateIsValid" data-val-valuetocompare="0" data-val-operator="GreaterThanEqual" style="display:none;">Fill-in whole number greater or equal to 0.</span>
      <span data-val-controltovalidate="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_tbQuantityOrdered" data-val-errormessage="Quantity cannot exceed circulation" data-val-display="Dynamic" data-val-validationGroup="AdInsertRegionsNumber" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cvQuanityOrderedLessThanCirculation"
        class="validation-error" data-val="true" data-val-type="Integer" data-val-evaluationfunction="CompareValidatorEvaluateIsValid" data-val-valuetocompare="13" data-val-operator="LessThanEqual" style="display:none;">Quantity cannot exceed circulation</span>
    </td>
    <td><span class="checkbox" onchange="document.getElementById('ctl00_body_AdInsRegionsLightCtrl_hfDummy').value='7140532;1;'+document.getElementById('ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cbDeliveryTypeQuantity1').checked; __doPostBack('ctl00$body$AdInsRegionsLightCtrl$lbtnDummy','')"><input id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cbDeliveryTypeQuantity1" type="checkbox" name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$cbDeliveryTypeQuantity1" /><label for="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cbDeliveryTypeQuantity1">0</label></span>
      <span
        id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_lblDeliveryTypeQuantity1" title="13"> (13)</span>
    </td>
    <td><span class="aspNetDisabled checkbox" onchange="document.getElementById('ctl00_body_AdInsRegionsLightCtrl_hfDummy').value='7140532;2;'+document.getElementById('ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cbDeliveryTypeQuantity2').checked; __doPostBack('ctl00$body$AdInsRegionsLightCtrl$lbtnDummy','')"><input id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cbDeliveryTypeQuantity2" type="checkbox" name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$cbDeliveryTypeQuantity2" disabled="disabled" /><label for="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cbDeliveryTypeQuantity2">0</label></span>
      <span
        id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_lblDeliveryTypeQuantity2" title="0"> (0)</span>
    </td>
    <td>
      <input name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$tbRunOutOfSequence" type="text" maxlength="1" size="2" onchange="javascript:setTimeout('__doPostBack(\'ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$tbRunOutOfSequence\',\'\')', 0)"
        onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_tbRunOutOfSequence" />
      <span data-val-controltovalidate="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_tbRunOutOfSequence" data-val-errormessage="Only number 1-9 is allowed or empty field." data-val-display="Dynamic" data-val-validationGroup="AdInsertRegionsNumber" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_regRunOutOfSequence"
        class="validation-error" data-val="true" data-val-evaluationfunction="RegularExpressionValidatorEvaluateIsValid" data-val-validationexpression="[1-9]" style="display:none;">Only number 1-9 is allowed or empty field.</span>
    </td>
    <td>
      <div style="text-align: center;">
        <a id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_lbtnEdit" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$lbtnEdit", "", true, "", "", false, true))">Edit</a>
      </div>
    </td>
    <td>
      <div style="text-align: center;">
        <input id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cbSelect" type="checkbox" name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$cbSelect" />
      </div>
    </td>
  </tr>
  <tr>
    <td>
      <span id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_lblDistribRegionName"><span class="indentation">..</span> 76511 </span>
    </td>
    <td>
      <div class="right">
        <span id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_lblEstimatedCirculationFormatted">13</span>
      </div>
    </td>
    <td>
      <input name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl03$tbQuantityOrdered" type="text" value="0" size="6" onchange="javascript:setTimeout('__doPostBack(\'ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl03$tbQuantityOrdered\',\'\')', 0)"
        onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_tbQuantityOrdered" disabled="disabled" class="aspNetDisabled read-only right" class="right" />
      <!- comment to prevent PlaceHolder eating whitespaces -->
    </td>
    <td><span class="aspNetDisabled checkbox" onchange="document.getElementById('ctl00_body_AdInsRegionsLightCtrl_hfDummy').value='7140533;1;'+document.getElementById('ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_cbDeliveryTypeQuantity1').checked; __doPostBack('ctl00$body$AdInsRegionsLightCtrl$lbtnDummy','')"><input id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_cbDeliveryTypeQuantity1" type="checkbox" name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl03$cbDeliveryTypeQuantity1" disabled="disabled" /><label for="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_cbDeliveryTypeQuantity1">0</label></span>
      <span
        id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_lblDeliveryTypeQuantity1" title="13" class="aspNetDisabled"> (13)</span>
    </td>
    <td><span class="aspNetDisabled checkbox" onchange="document.getElementById('ctl00_body_AdInsRegionsLightCtrl_hfDummy').value='7140533;2;'+document.getElementById('ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_cbDeliveryTypeQuantity2').checked; __doPostBack('ctl00$body$AdInsRegionsLightCtrl$lbtnDummy','')"><input id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_cbDeliveryTypeQuantity2" type="checkbox" name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl03$cbDeliveryTypeQuantity2" disabled="disabled" /><label for="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_cbDeliveryTypeQuantity2">0</label></span>
      <span
        id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_lblDeliveryTypeQuantity2" title="0" class="aspNetDisabled"> (0)</span>
    </td>
    <td>
      <input name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl03$tbRunOutOfSequence" type="text" maxlength="1" size="2" onchange="javascript:setTimeout('__doPostBack(\'ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl03$tbRunOutOfSequence\',\'\')', 0)"
        onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_tbRunOutOfSequence" />
      <span data-val-controltovalidate="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_tbRunOutOfSequence" data-val-errormessage="Only number 1-9 is allowed or empty field." data-val-display="Dynamic" data-val-validationGroup="AdInsertRegionsNumber" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_regRunOutOfSequence"
        class="validation-error" data-val="true" data-val-evaluationfunction="RegularExpressionValidatorEvaluateIsValid" data-val-validationexpression="[1-9]" style="display:none;">Only number 1-9 is allowed or empty field.</span>
    </td>
    <td>
      <div style="text-align: center;">
        <a id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_lbtnEdit" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl03$lbtnEdit", "", true, "", "", false, true))">Edit</a>
      </div>
    </td>
    <td>
      <div style="text-align: center;">

      </div>
    </td>
  </tr>
</table>
</code>```

Javascript Code:

```<code>var url = location.protocol + '//' + location.host + 'Booking/AdInsert.aspx?OrderItemID=' + orderitemid + '&OrderID=' + orderid;
for (i = 0; i <= getzip.length - 1; i++) {

  $('span:contains(' + getzip[i] + ')').parent().parent().find('td:nth-child(4) > Span > input').not('[disabled="disabled"]').attr('checked', true);
  $('span:contains(' + getzip[i] + ')').parent().parent().find('td:nth-child(4) > Span > input').not('[disabled="disabled"]').parent().trigger('change');
  check_http_request(url);
}

function check_http_request(url)
{
  var xmlHttp = new XMLHttpRequest(url);
  console.log(url)
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      callback(xmlHttp.responseText);
    }
    xmlHttp.open("POST", url, true); // true for asynchronous
    xmlHttp.send(null);
  }
}
</code>```

Body:
I am trying to select the zip code which is in input tag and once it is selected the onchange event in the span should be executed.I am using tampermonkey and trying to call onchange event from there. it executes fine when there is one zip code selected at a time. However, selecting multiple zip code is not working. it selects all zip code but when onchange event calls, it deselect all zip code.

       76511Z

        13

      <input name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$tbQuantityOrdered" type="text" value="0" size="6" onchange="javascript:setTimeout('__doPostBack(\'ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$tbQuantityOrdered\',\'\')', 0)"
        onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_tbQuantityOrdered" disabled="disabled" class="aspNetDisabled read-only right" class="right" />
      <!- comment to prevent PlaceHolder eating whitespaces -->
      * Fill-in ordered quantity
      <span data-val-controltovalidate="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_tbQuantityOrdered" data-val-errormessage="Fill-in number in valid format." data-val-display="Dynamic" data-val-validationGroup="AdInsertRegionsNumber" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cvQuantityOrderedInt"
        class="validation-error" data-val="true" data-val-type="Integer" data-val-evaluationfunction="CompareValidatorEvaluateIsValid" data-val-operator="DataTypeCheck" style="display:none;">Fill-in number in valid format.
      <span data-val-controltovalidate="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_tbQuantityOrdered" data-val-errormessage="Fill-in whole number greater or equal to 0." data-val-display="Dynamic" data-val-validationGroup="AdInsertRegionsNumber" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cvQuantityOrderedZero"
        class="validation-error" data-val="true" data-val-type="Integer" data-val-evaluationfunction="CompareValidatorEvaluateIsValid" data-val-valuetocompare="0" data-val-operator="GreaterThanEqual" style="display:none;">Fill-in whole number greater or equal to 0.
      <span data-val-controltovalidate="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_tbQuantityOrdered" data-val-errormessage="Quantity cannot exceed circulation" data-val-display="Dynamic" data-val-validationGroup="AdInsertRegionsNumber" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cvQuanityOrderedLessThanCirculation"
        class="validation-error" data-val="true" data-val-type="Integer" data-val-evaluationfunction="CompareValidatorEvaluateIsValid" data-val-valuetocompare="13" data-val-operator="LessThanEqual" style="display:none;">Quantity cannot exceed circulation

    <input id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cbDeliveryTypeQuantity1" type="checkbox" name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$cbDeliveryTypeQuantity1" />0
       (13)

    <input id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cbDeliveryTypeQuantity2" type="checkbox" name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$cbDeliveryTypeQuantity2" disabled="disabled" />0
       (0)

      <input name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$tbRunOutOfSequence" type="text" maxlength="1" size="2" onchange="javascript:setTimeout('__doPostBack(\'ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$tbRunOutOfSequence\',\'\')', 0)"
        onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_tbRunOutOfSequence" />
      <span data-val-controltovalidate="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_tbRunOutOfSequence" data-val-errormessage="Only number 1-9 is allowed or empty field." data-val-display="Dynamic" data-val-validationGroup="AdInsertRegionsNumber" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_regRunOutOfSequence"
        class="validation-error" data-val="true" data-val-evaluationfunction="RegularExpressionValidatorEvaluateIsValid" data-val-validationexpression="[1-9]" style="display:none;">Only number 1-9 is allowed or empty field.

        Edit

        <input id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl02_cbSelect" type="checkbox" name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl02$cbSelect" />

      .. 76511

        13

      <input name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl03$tbQuantityOrdered" type="text" value="0" size="6" onchange="javascript:setTimeout('__doPostBack(\'ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl03$tbQuantityOrdered\',\'\')', 0)"
        onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_tbQuantityOrdered" disabled="disabled" class="aspNetDisabled read-only right" class="right" />
      <!- comment to prevent PlaceHolder eating whitespaces -->

    <input id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_cbDeliveryTypeQuantity1" type="checkbox" name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl03$cbDeliveryTypeQuantity1" disabled="disabled" />0
       (13)

    <input id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_cbDeliveryTypeQuantity2" type="checkbox" name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl03$cbDeliveryTypeQuantity2" disabled="disabled" />0
       (0)

      <input name="ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl03$tbRunOutOfSequence" type="text" maxlength="1" size="2" onchange="javascript:setTimeout('__doPostBack(\'ctl00$body$AdInsRegionsLightCtrl$gvListRegions$ctl03$tbRunOutOfSequence\',\'\')', 0)"
        onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_tbRunOutOfSequence" />
      <span data-val-controltovalidate="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_tbRunOutOfSequence" data-val-errormessage="Only number 1-9 is allowed or empty field." data-val-display="Dynamic" data-val-validationGroup="AdInsertRegionsNumber" id="ctl00_body_AdInsRegionsLightCtrl_gvListRegions_ctl03_regRunOutOfSequence"
        class="validation-error" data-val="true" data-val-evaluationfunction="RegularExpressionValidatorEvaluateIsValid" data-val-validationexpression="[1-9]" style="display:none;">Only number 1-9 is allowed or empty field.

        Edit

Javascript Code:

var url = location.protocol + '//' + location.host + 'Booking/AdInsert.aspx?OrderItemID=' + orderitemid + '&OrderID=' + orderid;
for (i = 0; i <= getzip.length - 1; i++) {

  $('span:contains(' + getzip[i] + ')').parent().parent().find('td:nth-child(4) > Span > input').not('[disabled="disabled"]').attr('checked', true);
  $('span:contains(' + getzip[i] + ')').parent().parent().find('td:nth-child(4) > Span > input').not('[disabled="disabled"]').parent().trigger('change');
  check_http_request(url);
}

function check_http_request(url)
{
  var xmlHttp = new XMLHttpRequest(url);
  console.log(url)
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      callback(xmlHttp.responseText);
    }
    xmlHttp.open("POST", url, true); // true for asynchronous
    xmlHttp.send(null);
  }
}


来源: stackexchange

问:
Missing type information in Redux reducer

The basics

I want to create a Redux action for a HTTP PATCH operation. Suppose we have a simple type

interface SimpleEntity {
  foo: string;
  bar: number;
}
```
<p>To carry out a PATCH, we need to have the entity to patch, the property to change and the new value that needs to be set. Since we have more types than just <code>SimpleEntity</code> we have a generic interface describing a parameter to a PATCH operation:</p>
<pre class="lang-js prettyprint-override"><code>export interface PatchOperation<Entity, Property extends keyof Entity> {
  entity: Entity,
  propertyName: Property,
  newValue: Entity[Property]
}
</code>```

This makes it possible to describe a PATCH operation as follows:

const thing: SimpleEntity = {
    foo: "abc",
    bar: 1337
}

const patchOperation: PatchOperation<SimpleEntity, "foo"> = {
  entity: thing,
  propertyName: "foo",
  newValue: "8"
}
```
<p>And we are even able to apply that change:</p>
<pre class="lang-js prettyprint-override"><code>thing[patchOperation.propertyName] = patchOperation.newValue;
</code>```

The issue

But if we want to create a Redux action for such a PATCH operation, we lose some type information.

Here is the action:

const patchEntity = createAsyncThunk<SomeReturnType, PatchOperation<SimpleEntity, keyof SimpleEntity>>(
    "exampleSlice/patchEntity",
    ({entity, propertyName, newValue}) => {
        return api.patch(entity, propertyName, newValue);
    },
    {
        condition: api.isPatchNeeded
    }
);
```
<p>As one can see, we are not able to specify a certain property when defining the action. We need to pass <code>keyof SimpleEntity</code> as second type parameter to <code>PatchOperation</code>.</p>
<p>This leads to an issue in the reducer:</p>
<pre class="lang-js prettyprint-override"><code>  .addCase(
    patchEntity.fulfilled,
    (state, action) => {
      state.selectedEntity[action.meta.arg.propertyName] = action.meta.arg.newValue;
    //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    //TS2322: Type 'string | number' is not assignable to type 'never'.
    //  Type 'string' is not assignable to type 'never'.
    })
</code>```

TypeScript just can't narrow done the newValue type based on the value of propertyName here and thus uses the union of the types of all properties of the given Entity, just like keyof Entity instructs.

The solution?

Pass type information

I'm currently wondering if I missed some feature in Redux or TypeScript to be able to let the caller of patchEntity. If it was possible to add some type parameter to patchEntity like patchEntity<"foo">({entity, propertyName: "foo", newValue: "baz"}) and connect that one to the createAsyncThunk call, this issue should be gone.

But I doubt this was possible.

Extend TypeScript

Wouldn't it be great if it was possible to define PatchOperation like

export interface PatchOperation<Entity> {
  entity: Entity,
  propertyName: Property,
  newValue: Entity[propertyName] // Maybe "Entity[this.propertyName]"?
}
```
<p>This would allow a developer to add a "constraint" to the <code>PatchOperation</code> type which was previously manually defined by the <code>extends keyof</code> constraint.</p>
<h3>Extend the PATCH</h3>
<p>This one actually works:</p>
<pre class="lang-js prettyprint-override"><code>  .addCase(
    patchEntity.fulfilled,
    (state, action) => {
      state.selectedEntity = {...state.selectedEntity, ...action.payload.entities.SimpleEntity};
    })
</code>```

(Here we make use of the fact that our PATCH endpoint returns the PATCHed entity, but we could easily create that second parameter out of action.meta.arg.entity ourselves.)

It's not as precise as just using the parameters which were passed to the patchEntity call, but there is no type error.

The question

Does anybody see another approach than the third one? I would be happy if someone would know how to "pass type information".

Does it make sense to request a TypeScript feature like the following?

export interface PatchOperation<Entity> {
  entity: Entity,
  propertyName: Property,
  newValue: Entity[propertyName] // Maybe "Entity[this.propertyName]"?
}
```

ContentLicense: CC BY-SA 4.0

Body:
The basics

I want to create a Redux action for a HTTP PATCH operation. Suppose we have a simple type

interface SimpleEntity {
  foo: string;
  bar: number;
}

To carry out a PATCH, we need to have the entity to patch, the property to change and the new value that needs to be set. Since we have more types than just SimpleEntity we have a generic interface describing a parameter to a PATCH operation:

export interface PatchOperation<Entity, Property extends keyof Entity> {
  entity: Entity,
  propertyName: Property,
  newValue: Entity[Property]
}

This makes it possible to describe a PATCH operation as follows:

const thing: SimpleEntity = {
    foo: "abc",
    bar: 1337
}

const patchOperation: PatchOperation<SimpleEntity, "foo"> = {
  entity: thing,
  propertyName: "foo",
  newValue: "8"
}

And we are even able to apply that change:

thing[patchOperation.propertyName] = patchOperation.newValue;

The issue

But if we want to create a Redux action for such a PATCH operation, we lose some type information.

Here is the action:

const patchEntity = createAsyncThunk<SomeReturnType, PatchOperation<SimpleEntity, keyof SimpleEntity>>(
    "exampleSlice/patchEntity",
    ({entity, propertyName, newValue}) => {
        return api.patch(entity, propertyName, newValue);
    },
    {
        condition: api.isPatchNeeded
    }
);

As one can see, we are not able to specify a certain property when defining the action. We need to pass keyof SimpleEntity as second type parameter to PatchOperation.

This leads to an issue in the reducer:

  .addCase(
    patchEntity.fulfilled,
    (state, action) => {
      state.selectedEntity[action.meta.arg.propertyName] = action.meta.arg.newValue;
    //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    //TS2322: Type 'string | number' is not assignable to type 'never'.
    //  Type 'string' is not assignable to type 'never'.
    })

TypeScript just can't narrow done the newValue type based on the value of propertyName here and thus uses the union of the types of all properties of the given Entity, just like keyof Entity instructs.

The solution?

Pass type information

I'm currently wondering if I missed some feature in Redux or TypeScript to be able to let the caller of patchEntity. If it was possible to add some type parameter to patchEntity like patchEntity<"foo">({entity, propertyName: "foo", newValue: "baz"}) and connect that one to the createAsyncThunk call, this issue should be gone.

But I doubt this was possible.

Extend TypeScript

Wouldn't it be great if it was possible to define PatchOperation like

export interface PatchOperation<Entity> {
  entity: Entity,
  propertyName: Property,
  newValue: Entity[propertyName] // Maybe "Entity[this.propertyName]"?
}

This would allow a developer to add a "constraint" to the PatchOperation type which was previously manually defined by the extends keyof constraint.

Extend the PATCH

This one actually works:

  .addCase(
    patchEntity.fulfilled,
    (state, action) => {
      state.selectedEntity = {...state.selectedEntity, ...action.payload.entities.SimpleEntity};
    })

(Here we make use of the fact that our PATCH endpoint returns the PATCHed entity, but we could easily create that second parameter out of action.meta.arg.entity ourselves.)

It's not as precise as just using the parameters which were passed to the patchEntity call, but there is no type error.

The question

Does anybody see another approach than the third one? I would be happy if someone would know how to "pass type information".

Does it make sense to request a TypeScript feature like the following?

export interface PatchOperation<Entity> {
  entity: Entity,
  propertyName: Property,
  newValue: Entity[propertyName] // Maybe "Entity[this.propertyName]"?
}


问:
Php checkdnsrr function returns incorrect result for blacklist search
I have a function that checking if IP in known blacklists and it returning incorrect data.

```<code>  $ip = '185.91.153.27';
  $host = 'zen.spamhaus.org';
  $reverse_ip = implode(".", array_reverse(explode(".", $ip)));
  if (checkdnsrr($reverse_ip . "." . $host . ".", "A")) {
     return true;
  }
  return false;
</code>```

It retruns true but in spamhaus website it shows that ip isn't in blacklist.
What's wrong with this method or does exists any other solutions?

Body:
I have a function that checking if IP in known blacklists and it returning incorrect data.

  $ip = '185.91.153.27';
  $host = 'zen.spamhaus.org';
  $reverse_ip = implode(".", array_reverse(explode(".", $ip)));
  if (checkdnsrr($reverse_ip . "." . $host . ".", "A")) {
     return true;
  }
  return false;

It retruns true but in spamhaus website it shows that ip isn't in blacklist.
What's wrong with this method or does exists any other solutions?


问:
maui: showing picture from gallery not working
Im grabbing a picture from the gallery like described in the docs. that works, I can pick the pictures in my ios gallery and I am getting a full stream:

```<code>        string localFilePath = System.IO.Path.Combine(FileSystem.CacheDirectory, photo.FileName);

        using Stream sourceStream = await photo.OpenReadAsync();
        using FileStream localFileStream = File.OpenWrite(localFilePath);

         await sourceStream.CopyToAsync(localFileStream);

        MainThread.BeginInvokeOnMainThread(() =>
        {
            img_profilePic.Source = ImageSource.FromStream(() => localFileStream);
            img_profilePic.IsVisible = true;
        });
</code>```

But when I try to set the image to the imagesource of my image from xaml, nothing changes in the UI.

If I change the image to a local image however, it updates the UI. So it must be something with the stream.

Anyone got any idea?

Body:
Im grabbing a picture from the gallery like described in the docs. that works, I can pick the pictures in my ios gallery and I am getting a full stream:

        string localFilePath = System.IO.Path.Combine(FileSystem.CacheDirectory, photo.FileName);

        using Stream sourceStream = await photo.OpenReadAsync();
        using FileStream localFileStream = File.OpenWrite(localFilePath);

         await sourceStream.CopyToAsync(localFileStream);

        MainThread.BeginInvokeOnMainThread(() =>
        {
            img_profilePic.Source = ImageSource.FromStream(() => localFileStream);
            img_profilePic.IsVisible = true;
        });

But when I try to set the image to the imagesource of my image from xaml, nothing changes in the UI.

If I change the image to a local image however, it updates the UI. So it must be something with the stream.

Anyone got any idea?


问:
converting the 1D np array to 2D np array
The nPhotonDesity is 1 D <class 'numpy.ndarray'> , How can I convert it to 2D <class 'numpy.ndarray'> ?
#######################################################</p>
```<code>def getPhotonDensity( pulseWidth, PhotonsTotalNumber, pulseShapeName, xPosition=0):
z = []

if pulseShapeName == ePulseShape.RECT:
    Io = PhotonsTotalNumber/len(x);
    z =  getTransmitedPulse(ePulseShape.RECT.name, T, Io, 0, pulseWidth)(t)
elif pulseShapeName == ePulseShape.GAUSSIAN:
    Io = PhotonsTotalNumber;
    z = getTransmitedPulse(ePulseShape.GAUSSIAN.name, T, Io, 0, pulseWidth)(t)

return z;

def getTransmitedPulse(name, T, Io,  mu=0, pulseWidth = 0, rolloff=None ):
def rc(t, beta):
    import warnings
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        return np.sinc(t)*np.cos(np.pi*beta*t)/(1-(2*beta*t)**2)
def rrc(t, beta):
    return (np.sin(np.pi*t*(1-beta))+4*beta*t*np.cos(np.pi*t*(1+beta)))/(np.pi*t*(1-(4*beta*t)**2))

# rolloff is ignored for triang and rect
if name == ePulseShape.RECT.name:
    return lambda t: Io*(abs(t/T) < pulseWidth).astype(int)
elif name == 'triang':
    return lambda t: (1-abs(t/T)) * (abs(t/T) <  pulseWidth ).astype(float)
elif name == 'rc':
    return lambda t: rc(t/T, rolloff)
elif name == 'rrc':
    return lambda t: rrc(t/T, rolloff)
elif name == ePulseShape.GAUSSIAN.name:
   return lambda t: Io/(pulseWidth * np.sqrt(2 * np.pi)) *  np.exp( - (t/T - mu)**2 / (2 * pulseWidth**2) )

nPhotonDesity = getPhotonDensity(pulseWidth, PhotonsTotalNumber, pulseShapeName)
</code>```

Body:
The nPhotonDesity is 1 D <class 'numpy.ndarray'> , How can I convert it to 2D <class 'numpy.ndarray'> ?
#######################################################

def getPhotonDensity( pulseWidth, PhotonsTotalNumber, pulseShapeName, xPosition=0):
z = []

if pulseShapeName == ePulseShape.RECT:
    Io = PhotonsTotalNumber/len(x);
    z =  getTransmitedPulse(ePulseShape.RECT.name, T, Io, 0, pulseWidth)(t)
elif pulseShapeName == ePulseShape.GAUSSIAN:
    Io = PhotonsTotalNumber;
    z = getTransmitedPulse(ePulseShape.GAUSSIAN.name, T, Io, 0, pulseWidth)(t)

return z;

def getTransmitedPulse(name, T, Io,  mu=0, pulseWidth = 0, rolloff=None ):
def rc(t, beta):
    import warnings
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        return np.sinc(t)*np.cos(np.pi*beta*t)/(1-(2*beta*t)**2)
def rrc(t, beta):
    return (np.sin(np.pi*t*(1-beta))+4*beta*t*np.cos(np.pi*t*(1+beta)))/(np.pi*t*(1-(4*beta*t)**2))

# rolloff is ignored for triang and rect
if name == ePulseShape.RECT.name:
    return lambda t: Io*(abs(t/T) < pulseWidth).astype(int)
elif name == 'triang':
    return lambda t: (1-abs(t/T)) * (abs(t/T) <  pulseWidth ).astype(float)
elif name == 'rc':
    return lambda t: rc(t/T, rolloff)
elif name == 'rrc':
    return lambda t: rrc(t/T, rolloff)
elif name == ePulseShape.GAUSSIAN.name:
   return lambda t: Io/(pulseWidth * np.sqrt(2 * np.pi)) *  np.exp( - (t/T - mu)**2 / (2 * pulseWidth**2) )

nPhotonDesity = getPhotonDensity(pulseWidth, PhotonsTotalNumber, pulseShapeName)


问:
How to check the usage / interaction with jitpack / maven library?
Is it possible to find any statistics regarding the implementation, usage and interaction with a published library on nitpick or maven or whatever central repository there is? If yes, please give some details</p>


问:
Suddenly these lines appeared and it no longer accepts anything that I modify in the code and gives an error sign
this is my code

(send_keys and click) stoped from work after this line appeared

I tried to update the library, I also deleted the VS and re-downloaded it. I also deleted and re-downloaded the extensions , but nothing works .help me please


问:
Installing vue-strap with Node 16 and NPM 7
A legacy project is using wffranco/vue-strap with Node 8. We are trying to migrate to Node v16.4.2 with NPM 7.18.1, but I can't seem to figure a way to install it:

```<code>npm install --save-dev wffranco/vue-strap
</code>```

I believe it's because of the version of node-sass which is set to be 3.10.1 and node-sass requires to be 6.0 in order to work with Node 16 (according to this table).

So I tried to override the version. I followed this topic: How do I override nested NPM dependency versions?

I created npm-shrinkwrap.json:

{
  "lockfileVersion": 2,
  "requires": true,
  "packages": {},
  "dependencies": {
    "wffranco/vue-strap": {
      "version": "2.0.2",
      "from": "wffranco/vue-strap@2.0.2",
      "dependencies": {
        "node-sass": {
          "version": "6.0.0",
          "from": "node-sass@~3.10.1"
        }
      }
    }
  }
}
```
<p>But it didn't work. Is it possible to make it work?</p>
<p>The full log if needed:</p>
```npm ERR! npm ERR! src/libsass.target.mk:153: recipe for target 'Release/obj.target/libsass/src/libsass/src/ast.o' failed
npm ERR! npm ERR! make: Leaving directory '/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass/build'
npm ERR! npm ERR! gyp info it worked if it ends with ok
npm ERR! npm ERR! gyp verb cli [
npm ERR! npm ERR! gyp verb cli   '/usr/nodejs/16.4.2/bin/node',
npm ERR! npm ERR! gyp verb cli   '/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-gyp/bin/node-gyp.js',
npm ERR! npm ERR! gyp verb cli   'rebuild',
npm ERR! npm ERR! gyp verb cli   '--verbose',
npm ERR! npm ERR! gyp verb cli   '--libsass_ext=',
npm ERR! npm ERR! gyp verb cli   '--libsass_cflags=',
npm ERR! npm ERR! gyp verb cli   '--libsass_ldflags=',
npm ERR! npm ERR! gyp verb cli   '--libsass_library='
npm ERR! npm ERR! gyp verb cli ]
npm ERR! npm ERR! gyp info using node-gyp@3.8.0
npm ERR! npm ERR! gyp info using node@16.4.2 | linux | x64
npm ERR! npm ERR! gyp verb command rebuild []
npm ERR! npm ERR! gyp verb command clean []
npm ERR! npm ERR! gyp verb clean removing "build" directory
npm ERR! npm ERR! gyp verb command configure []
npm ERR! npm ERR! gyp verb check python checking for Python executable "python2" in the PATH
npm ERR! npm ERR! gyp verb `which` succeeded python2 /usr/bin/python2
npm ERR! npm ERR! gyp verb check python version `/usr/bin/python2 -c "import sys; print "2.7.18
npm ERR! npm ERR! gyp verb check python version .%s.%s" % sys.version_info[:3];"` returned: %j
npm ERR! npm ERR! gyp verb get node dir no --target version specified, falling back to host node version: 16.4.2
npm ERR! npm ERR! gyp verb command install [ '16.4.2' ]
npm ERR! npm ERR! gyp verb install input version string "16.4.2"
npm ERR! npm ERR! gyp verb install installing version: 16.4.2
npm ERR! npm ERR! gyp verb install --ensure was passed, so won't reinstall if already installed
npm ERR! npm ERR! gyp verb install version is already installed, need to check "installVersion"
npm ERR! npm ERR! gyp verb got "installVersion" 9
npm ERR! npm ERR! gyp verb needs "installVersion" 9
npm ERR! npm ERR! gyp verb install version is good
npm ERR! npm ERR! gyp verb get node dir target node version installed: 16.4.2
npm ERR! npm ERR! gyp verb build dir attempting to create "build" dir: /tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass/build
npm ERR! npm ERR! gyp verb build dir "build" dir needed to be created? /tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass/build
npm ERR! npm ERR! gyp verb build/config.gypi creating config file
npm ERR! npm ERR! gyp verb build/config.gypi writing out config file: /tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass/build/config.gypi
npm ERR! npm ERR! (node:10075) [DEP0150] DeprecationWarning: Setting process.config is deprecated. In the future the property will be read-only.
npm ERR! npm ERR! (Use `node --trace-deprecation ...` to show where the warning was created)
npm ERR! npm ERR! gyp verb config.gypi checking for gypi file: /tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass/config.gypi
npm ERR! npm ERR! gyp verb common.gypi checking for gypi file: /tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass/common.gypi
npm ERR! npm ERR! gyp verb gyp gyp format was not specified; forcing "make"
npm ERR! npm ERR! gyp info spawn /usr/bin/python2
npm ERR! npm ERR! gyp info spawn args [
npm ERR! npm ERR! gyp info spawn args   '/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! npm ERR! gyp info spawn args   '-f',
npm ERR! npm ERR! gyp info spawn args   'make',
npm ERR! npm ERR! gyp info spawn args   '-I',
npm ERR! npm ERR! gyp info spawn args   '/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass/build/config.gypi',
npm ERR! npm ERR! gyp info spawn args   '-I',
npm ERR! npm ERR! gyp info spawn args   '/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-gyp/addon.gypi',
npm ERR! npm ERR! gyp info spawn args   '-I',
npm ERR! npm ERR! gyp info spawn args   '/tmp/.node-gyp/16.4.2/include/node/common.gypi',
npm ERR! npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! npm ERR! gyp info spawn args   '-Dnode_root_dir=/tmp/.node-gyp/16.4.2',
npm ERR! npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-gyp',
npm ERR! npm ERR! gyp info spawn args   '-Dnode_lib_file=/tmp/.node-gyp/16.4.2/<(target_arch)/node.lib',
npm ERR! npm ERR! gyp info spawn args   '-Dmodule_root_dir=/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass',
npm ERR! npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! npm ERR! gyp info spawn args   '--depth=.',
npm ERR! npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! npm ERR! gyp info spawn args   '--generator-output',
npm ERR! npm ERR! gyp info spawn args   'build',
npm ERR! npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! npm ERR! gyp info spawn args ]
npm ERR! npm ERR! gyp verb command build []
npm ERR! npm ERR! gyp verb build type Release
npm ERR! npm ERR! gyp verb architecture x64
npm ERR! npm ERR! gyp verb node dev dir /tmp/.node-gyp/16.4.2
npm ERR! npm ERR! gyp verb `which` succeeded for `make` /usr/bin/make
npm ERR! npm ERR! gyp info spawn make
npm ERR! npm ERR! gyp info spawn args [ 'V=1', 'BUILDTYPE=Release', '-C', 'build' ]
npm ERR! npm ERR! g++: error: unrecognized command line option '-std=gnu++14'
npm ERR! npm ERR! make: *** [Release/obj.target/libsass/src/libsass/src/ast.o] Error 1
npm ERR! npm ERR! gyp ERR! build error
npm ERR! npm ERR! gyp ERR! stack Error: `make` failed with exit code: 2
npm ERR! npm ERR! gyp ERR! stack     at ChildProcess.onExit (/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-gyp/lib/build.js:262:23)
npm ERR! npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:394:28)
npm ERR! npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
npm ERR! npm ERR! gyp ERR! System Linux 4.12.14-122.60-default
npm ERR! npm ERR! gyp ERR! command "/usr/nodejs/16.4.2/bin/node" "/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
npm ERR! npm ERR! gyp ERR! cwd /tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass
npm ERR! npm ERR! gyp ERR! node -v v16.4.2
npm ERR! npm ERR! gyp ERR! node-gyp -v v3.8.0
npm ERR! npm ERR! gyp ERR! not ok
npm ERR! npm ERR! Build failed with error code: 1
npm ERR!
npm ERR! npm ERR! A complete log of this run can be found in:
npm ERR! npm ERR!     /tmp/.npm/_logs/2022-12-19T14_25_19_038Z-debug.log

npm ERR! A complete log of this run can be found in:
npm ERR!     /tmp/.npm/_logs/2022-12-19T14_25_19_181Z-debug.log
```

Body:
A legacy project is using wffranco/vue-strap with Node 8. We are trying to migrate to Node v16.4.2 with NPM 7.18.1, but I can't seem to figure a way to install it:

npm install --save-dev wffranco/vue-strap

I believe it's because of the version of node-sass which is set to be 3.10.1 and node-sass requires to be 6.0 in order to work with Node 16 (according to this table).

So I tried to override the version. I followed this topic: How do I override nested NPM dependency versions?

I created npm-shrinkwrap.json:

{
  "lockfileVersion": 2,
  "requires": true,
  "packages": {},
  "dependencies": {
    "wffranco/vue-strap": {
      "version": "2.0.2",
      "from": "wffranco/vue-strap@2.0.2",
      "dependencies": {
        "node-sass": {
          "version": "6.0.0",
          "from": "node-sass@~3.10.1"
        }
      }
    }
  }
}

But it didn't work. Is it possible to make it work?

The full log if needed:

npm ERR! npm ERR! src/libsass.target.mk:153: recipe for target 'Release/obj.target/libsass/src/libsass/src/ast.o' failed
npm ERR! npm ERR! make: Leaving directory '/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass/build'
npm ERR! npm ERR! gyp info it worked if it ends with ok
npm ERR! npm ERR! gyp verb cli [
npm ERR! npm ERR! gyp verb cli   '/usr/nodejs/16.4.2/bin/node',
npm ERR! npm ERR! gyp verb cli   '/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-gyp/bin/node-gyp.js',
npm ERR! npm ERR! gyp verb cli   'rebuild',
npm ERR! npm ERR! gyp verb cli   '--verbose',
npm ERR! npm ERR! gyp verb cli   '--libsass_ext=',
npm ERR! npm ERR! gyp verb cli   '--libsass_cflags=',
npm ERR! npm ERR! gyp verb cli   '--libsass_ldflags=',
npm ERR! npm ERR! gyp verb cli   '--libsass_library='
npm ERR! npm ERR! gyp verb cli ]
npm ERR! npm ERR! gyp info using node-gyp@3.8.0
npm ERR! npm ERR! gyp info using node@16.4.2 | linux | x64
npm ERR! npm ERR! gyp verb command rebuild []
npm ERR! npm ERR! gyp verb command clean []
npm ERR! npm ERR! gyp verb clean removing "build" directory
npm ERR! npm ERR! gyp verb command configure []
npm ERR! npm ERR! gyp verb check python checking for Python executable "python2" in the PATH
npm ERR! npm ERR! gyp verb `which` succeeded python2 /usr/bin/python2
npm ERR! npm ERR! gyp verb check python version `/usr/bin/python2 -c "import sys; print "2.7.18
npm ERR! npm ERR! gyp verb check python version .%s.%s" % sys.version_info[:3];"` returned: %j
npm ERR! npm ERR! gyp verb get node dir no --target version specified, falling back to host node version: 16.4.2
npm ERR! npm ERR! gyp verb command install [ '16.4.2' ]
npm ERR! npm ERR! gyp verb install input version string "16.4.2"
npm ERR! npm ERR! gyp verb install installing version: 16.4.2
npm ERR! npm ERR! gyp verb install --ensure was passed, so won't reinstall if already installed
npm ERR! npm ERR! gyp verb install version is already installed, need to check "installVersion"
npm ERR! npm ERR! gyp verb got "installVersion" 9
npm ERR! npm ERR! gyp verb needs "installVersion" 9
npm ERR! npm ERR! gyp verb install version is good
npm ERR! npm ERR! gyp verb get node dir target node version installed: 16.4.2
npm ERR! npm ERR! gyp verb build dir attempting to create "build" dir: /tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass/build
npm ERR! npm ERR! gyp verb build dir "build" dir needed to be created? /tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass/build
npm ERR! npm ERR! gyp verb build/config.gypi creating config file
npm ERR! npm ERR! gyp verb build/config.gypi writing out config file: /tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass/build/config.gypi
npm ERR! npm ERR! (node:10075) [DEP0150] DeprecationWarning: Setting process.config is deprecated. In the future the property will be read-only.
npm ERR! npm ERR! (Use `node --trace-deprecation ...` to show where the warning was created)
npm ERR! npm ERR! gyp verb config.gypi checking for gypi file: /tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass/config.gypi
npm ERR! npm ERR! gyp verb common.gypi checking for gypi file: /tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass/common.gypi
npm ERR! npm ERR! gyp verb gyp gyp format was not specified; forcing "make"
npm ERR! npm ERR! gyp info spawn /usr/bin/python2
npm ERR! npm ERR! gyp info spawn args [
npm ERR! npm ERR! gyp info spawn args   '/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! npm ERR! gyp info spawn args   '-f',
npm ERR! npm ERR! gyp info spawn args   'make',
npm ERR! npm ERR! gyp info spawn args   '-I',
npm ERR! npm ERR! gyp info spawn args   '/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass/build/config.gypi',
npm ERR! npm ERR! gyp info spawn args   '-I',
npm ERR! npm ERR! gyp info spawn args   '/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-gyp/addon.gypi',
npm ERR! npm ERR! gyp info spawn args   '-I',
npm ERR! npm ERR! gyp info spawn args   '/tmp/.node-gyp/16.4.2/include/node/common.gypi',
npm ERR! npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! npm ERR! gyp info spawn args   '-Dnode_root_dir=/tmp/.node-gyp/16.4.2',
npm ERR! npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-gyp',
npm ERR! npm ERR! gyp info spawn args   '-Dnode_lib_file=/tmp/.node-gyp/16.4.2/<(target_arch)/node.lib',
npm ERR! npm ERR! gyp info spawn args   '-Dmodule_root_dir=/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass',
npm ERR! npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! npm ERR! gyp info spawn args   '--depth=.',
npm ERR! npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! npm ERR! gyp info spawn args   '--generator-output',
npm ERR! npm ERR! gyp info spawn args   'build',
npm ERR! npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! npm ERR! gyp info spawn args ]
npm ERR! npm ERR! gyp verb command build []
npm ERR! npm ERR! gyp verb build type Release
npm ERR! npm ERR! gyp verb architecture x64
npm ERR! npm ERR! gyp verb node dev dir /tmp/.node-gyp/16.4.2
npm ERR! npm ERR! gyp verb `which` succeeded for `make` /usr/bin/make
npm ERR! npm ERR! gyp info spawn make
npm ERR! npm ERR! gyp info spawn args [ 'V=1', 'BUILDTYPE=Release', '-C', 'build' ]
npm ERR! npm ERR! g++: error: unrecognized command line option '-std=gnu++14'
npm ERR! npm ERR! make: *** [Release/obj.target/libsass/src/libsass/src/ast.o] Error 1
npm ERR! npm ERR! gyp ERR! build error
npm ERR! npm ERR! gyp ERR! stack Error: `make` failed with exit code: 2
npm ERR! npm ERR! gyp ERR! stack     at ChildProcess.onExit (/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-gyp/lib/build.js:262:23)
npm ERR! npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:394:28)
npm ERR! npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
npm ERR! npm ERR! gyp ERR! System Linux 4.12.14-122.60-default
npm ERR! npm ERR! gyp ERR! command "/usr/nodejs/16.4.2/bin/node" "/tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
npm ERR! npm ERR! gyp ERR! cwd /tmp/.npm/_cacache/tmp/git-clone-3f5c1536/node_modules/node-sass
npm ERR! npm ERR! gyp ERR! node -v v16.4.2
npm ERR! npm ERR! gyp ERR! node-gyp -v v3.8.0
npm ERR! npm ERR! gyp ERR! not ok
npm ERR! npm ERR! Build failed with error code: 1
npm ERR!
npm ERR! npm ERR! A complete log of this run can be found in:
npm ERR! npm ERR!     /tmp/.npm/_logs/2022-12-19T14_25_19_038Z-debug.log

npm ERR! A complete log of this run can be found in:
npm ERR!     /tmp/.npm/_logs/2022-12-19T14_25_19_181Z-debug.log


问:
Run npm install in remote server with capistrano 3
i have a problem when i try to deploy my symfony application with in front angular.

When I run the following code on capistrano, I end up with the following error when I run the npm install :

```<code>cd /var/www/oasis/current/angular && npm install stderr: bash: line 1: npm: command not found
</code>```

npm is of course installed on my remote server !
I even specified the npm path but without success.

```<code>set :default_env, { path: "PATH=$PATH:/home/oasis/.nvm/versions/node/v8.9.4/bin"}

namespace :npm do
    desc 'Run npm install (locally project)'
    task :install do
      puts "--> Installing npm install (middle) "
      on roles(:app) do
        execute "cd #{release_path}/angular && npm install"
      end
    end
end
</code>```

Body:
i have a problem when i try to deploy my symfony application with in front angular.

When I run the following code on capistrano, I end up with the following error when I run the npm install :

cd /var/www/oasis/current/angular && npm install stderr: bash: line 1: npm: command not found

npm is of course installed on my remote server !
I even specified the npm path but without success.

set :default_env, { path: "PATH=$PATH:/home/oasis/.nvm/versions/node/v8.9.4/bin"}

namespace :npm do
    desc 'Run npm install (locally project)'
    task :install do
      puts "--> Installing npm install (middle) "
      on roles(:app) do
        execute "cd #{release_path}/angular && npm install"
      end
    end
end


问:
While respecting the order of a hierarchical clustering output, how can one order a vector?
I am looking for the python's equivalent of the reorder.dendrogram function from R.

From the R's documentations:

This function takes a dendrogram and a vector of values and reorders
the dendrogram in the order of the supplied vector, maintaining the
constraints on the dendrogram.

I am aware on how to order a given vector using the hierarchical clustering results (e.g. this nice example) - the operation I am looking for is more subtle.

An interesting option on a similar direction is the optimal_ordering function/argument from scipy. However, it represents an individual solution based on the algorithm behind the "optimal" arrangement and doesn't really provide any level of control for arbitrary ordering vectors.


问:
Flutter Open Multiple Drawers
Im looking for a way to open multiple drawers in flutter to display different data depending on which list tile I clicked.
So I have a ListView which has multiple ListTiles - Asset Code, Asset Name etc.
I want to display different data inside the drawer itself depending on which ListTile I have clicked so if I clicked the asset code tile I would get asset code data and so on.
I was wanting to display all of this inside drawers only but cannot understand how to do so; Any help is appreciated!
This is my code:

```<code>
List filterType = ['Asset Code', 'Name', 'Description', 'Location'];

class FilterTerms extends StatefulWidget {
  const FilterTerms({Key? key}) : super(key: key);

  @override
  State<FilterTerms> createState() => _FilterTermsState();
}

class _FilterTermsState extends State<FilterTerms> {
  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: Scaffold(
        endDrawer: filterCodeData(context),
        body: Builder(builder: (context) {
          return ListView(padding: EdgeInsets.zero, children: [
            DrawerHeader(
              decoration: BoxDecoration(color: Colors.blue[900]),
              padding: const EdgeInsets.all(8.0),
              child: const Center(
                child: Text(
                  'First Drawer',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 40,
                      fontWeight: FontWeight.bold),
                ),
              ),
            ),
            SizedBox(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              child: drawerCodeData(context, filterCodeData(context)),
            ),
            SizedBox(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              child: drawerNameData(context, filterNameData(context)),
            )]);
        }),
      ),
    );
  }
}

Drawer drawerCodeData(BuildContext context, Widget drawerName) {
  return Drawer(
      child: Scaffold(
    endDrawer: filterCodeData(context),
    body: ListTile(
      title: Text(filterType[0]),
      onTap: () {
        Scaffold.of(context).openEndDrawer();
      },
    ),
  ));
}

Drawer drawerNameData(BuildContext context, Widget drawerName) {
  return Drawer(
      child: Scaffold(
        endDrawer: filterNameData(context),
        body: ListTile(
          title: Text(filterType[1]),
          onTap: () {
            Scaffold.of(context).openEndDrawer();
          },
        ),
      ));
}

Widget filterCodeData(BuildContext context) => const Drawer(
      child: Center(child: Text('Code Data')),
    );

Widget filterNameData(BuildContext context) => const Drawer(
  child: Center(child: Text('Name Data')),
);

</code>```

FilterTerms is also being called in a drawer in a previous widget.
Thanks!

Title: Flutter Open Multiple Drawers

Body:
Im looking for a way to open multiple drawers in flutter to display different data depending on which list tile I clicked.
So I have a ListView which has multiple ListTiles - Asset Code, Asset Name etc.
I want to display different data inside the drawer itself depending on which ListTile I have clicked so if I clicked the asset code tile I would get asset code data and so on.
I was wanting to display all of this inside drawers only but cannot understand how to do so; Any help is appreciated!
This is my code:

List filterType = ['Asset Code', 'Name', 'Description', 'Location'];

class FilterTerms extends StatefulWidget {
  const FilterTerms({Key? key}) : super(key: key);

  @override
  State<FilterTerms> createState() => _FilterTermsState();
}

class _FilterTermsState extends State<FilterTerms> {
  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: Scaffold(
        endDrawer: filterCodeData(context),
        body: Builder(builder: (context) {
          return ListView(padding: EdgeInsets.zero, children: [
            DrawerHeader(
              decoration: BoxDecoration(color: Colors.blue[900]),
              padding: const EdgeInsets.all(8.0),
              child: const Center(
                child: Text(
                  'First Drawer',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 40,
                      fontWeight: FontWeight.bold),
                ),
              ),
            ),
            SizedBox(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              child: drawerCodeData(context, filterCodeData(context)),
            ),
            SizedBox(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              child: drawerNameData(context, filterNameData(context)),
            )]);
        }),
      ),
    );
  }
}

Drawer drawerCodeData(BuildContext context, Widget drawerName) {
  return Drawer(
      child: Scaffold(
    endDrawer: filterCodeData(context),
    body: ListTile(
      title: Text(filterType[0]),
      onTap: () {
        Scaffold.of(context).openEndDrawer();
      },
    ),
  ));
}

Drawer drawerNameData(BuildContext context, Widget drawerName) {
  return Drawer(
      child: Scaffold(
        endDrawer: filterNameData(context),
        body: ListTile(
          title: Text(filterType[1]),
          onTap: () {
            Scaffold.of(context).openEndDrawer();
          },
        ),
      ));
}

Widget filterCodeData(BuildContext context) => const Drawer(
      child: Center(child: Text('Code Data')),
    );

Widget filterNameData(BuildContext context) => const Drawer(
  child: Center(child: Text('Name Data')),
);

FilterTerms is also being called in a drawer in a previous widget.
Thanks!


问:
Update DefaultUri using AnalyticsAdminServiceClient(GA4) .NET C# not updating?
I wanted to update the default uri for the already created datastream using .NET library Google.Analytics.Admin.V1Beta, but it only updates the name the stream url don't get updated. And I am getting no errors at all.

```<code>public static void UpdateMydatastream()
{
    GoogleCredential credential = GoogleCredential.GetApplicationDefault();
    var client = new AnalyticsAdminServiceClientBuilder()
    {
        CredentialsPath = "fifth-bonito-371514-0e10258585f4.json"
    }.Build();

    // filtered the property I wanted by the project-id
    var req = new ListPropertiesRequest
    {
        Filter = $"firebase_project:{CloudManager.ProjectId}"
    };
    var res1 = client.ListProperties(req, null);
    foreach (var property in res1)
    {

        var request = new ListDataStreamsRequest {
           Parent = property.PropertyName.ToString()
        };

        // filtered the data stream I wanted that need to be updated
        var response = client.ListDataStreams(request, null);
        foreach(var res2 in response){

            // I want to update the default uri as well for the data stream
            var mydataStream = new DataStream {
                Name = res2.DataStreamName.ToString(),
                DisplayName = res2.DisplayName,
                WebStreamData = new DataStream.Types.WebStreamData
                {
                    DefaultUri = "https://www.google.com"
                }
            };

            var dStream = new DataStream{
                DisplayName = res2.DisplayName,
                Type = DataStream.Types.DataStreamType.WebDataStream
            };

            var updatemask = new Google.Protobuf.WellKnownTypes.FieldMask {
                Paths = { "*" }
            };

            var req2 = client.UpdateDataStream(dStream, updatemask, null);

        }

    }

}
</code>```

In the google doc it says that default uri is immutable, is that why I am not able to change the stream url ?
https://cloud.google.com/php/docs/reference/analytics-admin/latest/V1beta.DataStream.WebStreamData#_Google_Analytics_Admin_V1beta_DataStream_WebStreamData__setDefaultUri__

Body:
I wanted to update the default uri for the already created datastream using .NET library Google.Analytics.Admin.V1Beta, but it only updates the name the stream url don't get updated. And I am getting no errors at all.

public static void UpdateMydatastream()
{
    GoogleCredential credential = GoogleCredential.GetApplicationDefault();
    var client = new AnalyticsAdminServiceClientBuilder()
    {
        CredentialsPath = "fifth-bonito-371514-0e10258585f4.json"
    }.Build();

    // filtered the property I wanted by the project-id
    var req = new ListPropertiesRequest
    {
        Filter = $"firebase_project:{CloudManager.ProjectId}"
    };
    var res1 = client.ListProperties(req, null);
    foreach (var property in res1)
    {

        var request = new ListDataStreamsRequest {
           Parent = property.PropertyName.ToString()
        };

        // filtered the data stream I wanted that need to be updated
        var response = client.ListDataStreams(request, null);
        foreach(var res2 in response){

            // I want to update the default uri as well for the data stream
            var mydataStream = new DataStream {
                Name = res2.DataStreamName.ToString(),
                DisplayName = res2.DisplayName,
                WebStreamData = new DataStream.Types.WebStreamData
                {
                    DefaultUri = "https://www.google.com"
                }
            };

            var dStream = new DataStream{
                DisplayName = res2.DisplayName,
                Type = DataStream.Types.DataStreamType.WebDataStream
            };

            var updatemask = new Google.Protobuf.WellKnownTypes.FieldMask {
                Paths = { "*" }
            };

            var req2 = client.UpdateDataStream(dStream, updatemask, null);

        }

    }

}

In the google doc it says that default uri is immutable, is that why I am not able to change the stream url ?
https://cloud.google.com/php/docs/reference/analytics-admin/latest/V1beta.DataStream.WebStreamData#_Google_Analytics_Admin_V1beta_DataStream_WebStreamData__setDefaultUri__


问:
How to generate/export RSA public keys in Swift including SubjectPublicKeyInfo (SPKI-format) in iOS?

Objective

A RSA-4096 key pair is generated and the public key shall be send in order to ecrypt some payload.

The microservice executing the encryption is written in Java 17.

Note:

Java 17, more specific the 'java.security'-library accepts keys which look alike the PKCS#1-format but are slightly different. They are using the SubjectPublicKeyInfo (or SPKI) specification.

The SPKI specification follows the RFC 5280.

It is not possible to change the microservice.

It is searched for a solution to generate a RSA key pair in swift (iOS) following the SPKI specification.

Transformation from a PKCS#1-format is preferred.

An external library (such as OpenSSL) may be used. Still, native swift code is in favor to prevent weakness in "security"-related functions.

Setup

Swift in Xcode (IDE)

Emulator for iPhone14

Sample Code: Generating a KeyPair (Swift - iOS)

// Keypair attributes
let tag = "my_personal_keystore_keypair_alias".data(using: .utf8)!
let attributes: [String: Any] =
    [kSecAttrKeyType as String:            kSecAttrKeyTypeRSA,
     kSecAttrKeySizeInBits as String:      "4096",
     kSecPrivateKeyAttrs as String:
        [kSecAttrIsPermanent as String:    true,
         kSecAttrApplicationTag as String: tag]
]
var error: Unmanaged<CFError>?

// Generate PrivateKey / Keypair
guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
    throw error!.takeRetainedValue() as Error
}

// Extract PublicKey
guard let publicKey = SecKeyCopyPublicKey(privateKey),
      let publicKeyOptional = SecKeyCopyExternalRepresentation(publicKey, nil) else {
    return "PublicKey could not be accessed."
}
let publicKeyData = publicKeyOptional as Data
let base64PublicKey = publicKeyData.base64EncodedString()
print("PublicKey, base64:   ", base64PublicKey)
```
<p>The given swift-code generates a RSA key pair in PKCS#1-format.
Details on the key-formats may be retrieved from this question:</p>
<ul>
<li>Why do PKCS#1 PublicKeys from 'Java17 KeyFactory' and Swift (iOS) differ?</li>
</ul>
<h1>Problem</h1>
<p>Still the wrong format (ÜKCS#1) is retrieved.</p>
<h2>Not the objective</h2>
<p>This section shall <strong>prevent typical mistakes</strong> along the research.
The following mistakes can be excluded:</p>
<p><strong>A)</strong> The key provided by iOS is BASE64 encoded - it has <strong>been handeled already</strong> .. :)</p>
<ul>
<li>RSA public key created in iOS/Swift and exported as base64 not recognized in Java</li>
</ul>
<p><strong>B)</strong> The code transforming the public key is in Objective-C.
This till <strong>remains a legit alternative</strong> to the primary objective of this question .. ^.^</p>
<ul>
<li>RSA public key generation -- Swift</li>
</ul>
<p><strong>C)</strong> Swift/iOS hates Keys (KeyPairs) to be overwritten. If you need a new KeyPair, delete the old one using its ALIAS and thereafter create a new KeyPair. <strong>Already solved for this question</strong> .. :D</p>
<ul>
<li>RSA public key created in iOS/Swift and exported as base64 not recognized in Java</li>
</ul>
<p><strong>D)</strong> Other standards/formats are explicitly not included in the solution space <strong>although they may implicitly be containers</strong> for the <em>desired SPKI-Format</em>.
To mention left outs: ASN.1, DER, PEM, x509, PKCS#1 etc. .. :)</p>
<ul>
<li>Especially PEM: https://developer.apple.com/forums/thread/85915</li>
<li>https://www.cryptologie.net/article/260/asn1-vs-der-vs-pem-vs-x509-vs-pkcs7-vs/</li>
</ul>
<p><strong>E)</strong> <em>Things & Links</em> that may come into my mind later on .. ;-)</p>
<h2>Sample Java code for testing</h2>
<p>Sample keys can be found in the <strong>Appendix</strong> below.</p>
<p>Parsing the key(s) generated by Java 17:</p>
<pre class="lang-java prettyprint-override"><code>public Optional<PublicKey> validateKeyFromJava(String publicKey) {
    try {
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKey);
        KeyFactory keyFactory = KeyFactory.getInstance(EncryptionProperties.ALGORITHM);
        EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
        return Optional.ofNullable(keyFactory.generatePublic(publicKeySpec));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException | NullPointerException e) {
        return Optional.empty();
    }
}
</code>```

The error to be overcome

The PKCS#1-format can not be read by the Java 17 microservice.

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException:
IOException: algid parse error, not a sequence
at java.base/sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:241)
at java.base/java.security.KeyFactory.generatePublic(KeyFactory.java:351)
```

Therefore the SPKI-format is needed to be used by Swift (iOS).

Hope

In case there is no solution using native Swift, the following approach using OpenSSL may be tried (not happened, yet).

https://medium.com/@joncardasis/openssl-swift-everything-you-need-to-know-2a4f9f256462

Anyways

Thanks for reading & sharing - any help is appreciated :)

Appendix

All keys may be analyzed:

https://8gwifi.org/PemParserFunctions.jsp

Multiple keys are given to prevent 'lucky shots' ..  ;-)

Sample keys - Swift iOS (PKCS#1)

First:

MIICCgKCAgEAl0HYn9IdRmexAR9dSh3SxmFazWF0RV2TKmtRxGySvCA+aHZ/Dp+8tC0YDWpQzP+tZdlDWNOBj/D7i1z4b+UZk8F9ZEoi+w61kYQz+KjMkRuYrPBFi4A/gsS2qGeFJ4OvLQzGObZ0C+5/E+wunUWyQCVjgjTHKH8yqfVXeWYFKmaSSZblSZJAObE8Ao5J38DMINF1oWG+GdZt8RTLf35ULLEa8zKvFXrfBkDjiQH90WKPwDxWwvFInqZhjpsFxLytiKW+iBLqa4+0P7uwXVodFXa38RW9dk9mEsLvj6764BKtPAaWym9XZfEZNBu0jwlfO07k0augynGps6bsSIyYglDImlTRagdA/e+1AMBlSxEFVO4NpCjEpMT7rNX/LYPeEaJ8fTC3axOM1yEntcwUfSSCDulVPGlWlFbPxt29y1RrGtMmwfbTlbOQf2okMf0mGx9Ytd9HWadIdWh4FqDVWA8MF82PP1YsOW5TA0hkprK1qJwfkaLRKnmpfL5a7gWn4HWzpdDqrezhbc/zTCeHbX5c61mgWsAIWnB3fyXsJHpR62+QtBEznwhDxafVCQyUmsDqbncBxilEnFIn08G+6ox2PQC8GhNdpFVGsSoqpDfctsm51/tUYLpyeIBdzw/3nMLL1J5jL3yWr7ZKgnzNwjpC8l6c6gpsF3NRodeVhp8CAwEAAQ==

Second:

MIICCgKCAgEAlSbN7rlX6EMCDGuxQm9G6qqXIWshDvI5VaN4QPNCFcFzPjI/FyaHqi43+mxTyKGycT6TNqvanSu67yoIA80tSlFH2LndWv6sPQeHKxNwwFKU98Y/uL3M6hKIVXDwa6kZGM58dfY9qMWEOPXB4AwZtVaxJ4ePHFAR0kEOAHLCPpQxFkNlkg9FlCwlBzZbhHkI5uhCmlGEiLpLaJNJzjn7yo33m65189J6tIh3vopZ2ahFHb/vo6SVSbtS7Y0YlinJwH3MCGLm5+pKBpE64t5lgEhDPYSF7pKpLhEVqC5ETaya3mYTkXPSCiY/9Mo5zddniUGrxAJaY940jY3QNYeFmWPEEdhhIW2tUbuiM3IlHAqk4Du5p/2o1QcSVZdBsHStSGdcWqs00Z+ooxXwrOpMOUnZeb8Jt5dGDyHwjOmPf0N8dDQwz+5pgOoTkxd/z5cTK9tMv/nC+Mbbt8LRsct16M3LYrRAYnA8unX1ZD3eXTJPOSB/fM9Hmf1ObxQro9tatC5RaJjS0Xg5aepUsey62BW9lj4kHCkRPD4w1OmjDWGUCOSEhwy0KwqFyRBppYUMndEbJb3GKEjpekcQYwjERPtH/vEVxaN5gGYaCORancUaNH+d03zAmi0G830QXQvyohyKUkGw5qljEBH5R5Wqu7YLTlUes0rQEx8DpLVclaMCAwEAAQ==

Sample keys - Java 17 (SPKI-format)

First:

MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAqwMRLS3hhNuVBQTqRT4714fbl4h3PtrSZQ8Ry1qMCefFOLzmLmLD/VdnFoHj3QiqlZMlajvVuJonprhOy911aNW2Qs2VZ+zoMkLRjah9gqg00dLVtdWa2FXjAX6bh/rSR6jmF1hzfLPs/CqOKyDpX003AUF/WvgHkuAizQjZeskEDKawbExs6RSSFHNycrGwB9hBhAwGvyZpC2+fqPN/93W2NZ8xyb5H6CmM7pCpG+sTcsEEYOZjjq2HV8vYdM9KHi7O+nmY0MJxjLJ5JOv5oLqPXFt4Epezz4v2C3oE3Leu4gIy1r1D2xHuxu0pyQ9F2nI7a+6mGZbRAYDA8Yq2oidqBDC9pKogoHcMYhXj/G0WNEhE9ODuHg+GkiiGc3zysuKwfKu1Z5ZmUtlI1kVFqUEEi81smylTXtkU/oEf7P0OX94XcNTq1N3iO+nuFayAhINlvLUXwyO4JQUsmCyu0bH17XuNUfbnSCmOfGhFSjpyU0PthW9Qtf9yY9MmyZz9c9T2kfxoUxBnNRhVUZ+Kg8oA6kkNJp/ac+AdZzkPZFev91ZKYCbyI+rcakJ4KBQ5YoprDtpHmAQZ5E3/rWcq1Tis0yiomE2+natrzaO4aQbrljOHEgB6arbMkeu7/sZHEvYfK7ilH7tsZfDdU2DVOV0yxNReYwOHAFgFMTNQvBsCAwEAAQ==

Second:

MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAs9ywiZnmv9Ewf+dIsmwV8ZlZKQNg4lbVLpNptb3pftnoukvBjak1rDqb6GcxXtM+UuBgr4Wigi0TI+vItzWv6QlBB8HShA4WImKrOCD3+U1fFdDpwCxQO+oHqTqeNKhRcKcM0e0C/c88hJo8l9G2OCjIANW3O+pGeMirB/XjPdcQ+d37TFGpRs83wPR8gUFQsH8qQMkS7uOtTCZHfcK6UzbvJB3Gf/llcCSfPYKUMY9SXIc5K9hpI0E1v5EdEUvdbhiilZI0esntr5BzeO5AxH/m9fFPH9ekZZyc9nXsHY7tPOJMD+wsTad4D9NBGi9x+lzxZRdxyDLote4ix+aHSqMgcdtOyJ69WFym2Ty1VfCgrmG8fhC/PZBEzk6obK5uJD4mO3owrKgYsmJgZHO3CbVkmv04+EEPpQLippQu8uCl+2KO480EvjSco5ryVH3XEsAGokBLCsZviBtntY/Ia0OLXPmy7WWXigxsVQkgPZ1SyZa3FUp/Zuwtoo0BWDI/9JdUZPfKhbQkcxtnKbCe8QXf51YUgIfKXPTBlmk/Zj931EzXdQCZFMvgK+I5p79DqCsD9yKbiUnfK9tXJ4SzMfuiLd4pqB0UIMVMQEj5SZPYn7eHRZyje4v96FDwtj56NQ/kZPYXKqLoOv5nvMALZngzJ6aFaGjkWZX9RNQLfA8CAwEAAQ==

Body:
Objective

A RSA-4096 key pair is generated and the public key shall be send in order to ecrypt some payload.

The microservice executing the encryption is written in Java 17.

Note:

Java 17, more specific the 'java.security'-library accepts keys which look alike the PKCS#1-format but are slightly different. They are using the SubjectPublicKeyInfo (or SPKI) specification.

The SPKI specification follows the RFC 5280.

It is not possible to change the microservice.

It is searched for a solution to generate a RSA key pair in swift (iOS) following the SPKI specification.

Transformation from a PKCS#1-format is preferred.

An external library (such as OpenSSL) may be used. Still, native swift code is in favor to prevent weakness in "security"-related functions.

Setup

Swift in Xcode (IDE)

Emulator for iPhone14

Sample Code: Generating a KeyPair (Swift - iOS)

// Keypair attributes
let tag = "my_personal_keystore_keypair_alias".data(using: .utf8)!
let attributes: [String: Any] =
    [kSecAttrKeyType as String:            kSecAttrKeyTypeRSA,
     kSecAttrKeySizeInBits as String:      "4096",
     kSecPrivateKeyAttrs as String:
        [kSecAttrIsPermanent as String:    true,
         kSecAttrApplicationTag as String: tag]
]
var error: Unmanaged<CFError>?

// Generate PrivateKey / Keypair
guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
    throw error!.takeRetainedValue() as Error
}

// Extract PublicKey
guard let publicKey = SecKeyCopyPublicKey(privateKey),
      let publicKeyOptional = SecKeyCopyExternalRepresentation(publicKey, nil) else {
    return "PublicKey could not be accessed."
}
let publicKeyData = publicKeyOptional as Data
let base64PublicKey = publicKeyData.base64EncodedString()
print("PublicKey, base64:   ", base64PublicKey)

The given swift-code generates a RSA key pair in PKCS#1-format.
Details on the key-formats may be retrieved from this question:

Why do PKCS#1 PublicKeys from 'Java17 KeyFactory' and Swift (iOS) differ?

Problem

Still the wrong format (ÜKCS#1) is retrieved.

Not the objective

This section shall prevent typical mistakes along the research.
The following mistakes can be excluded:

A) The key provided by iOS is BASE64 encoded - it has been handeled already .. :)

RSA public key created in iOS/Swift and exported as base64 not recognized in Java

B) The code transforming the public key is in Objective-C.
This till remains a legit alternative to the primary objective of this question .. ^.^

RSA public key generation -- Swift

C) Swift/iOS hates Keys (KeyPairs) to be overwritten. If you need a new KeyPair, delete the old one using its ALIAS and thereafter create a new KeyPair. Already solved for this question .. :D

RSA public key created in iOS/Swift and exported as base64 not recognized in Java

D) Other standards/formats are explicitly not included in the solution space although they may implicitly be containers for the desired SPKI-Format.
To mention left outs: ASN.1, DER, PEM, x509, PKCS#1 etc. .. :)

Especially PEM: https://developer.apple.com/forums/thread/85915

https://www.cryptologie.net/article/260/asn1-vs-der-vs-pem-vs-x509-vs-pkcs7-vs/

E) Things & Links that may come into my mind later on .. ;-)

Sample Java code for testing

Sample keys can be found in the Appendix below.

Parsing the key(s) generated by Java 17:

public Optional<PublicKey> validateKeyFromJava(String publicKey) {
    try {
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKey);
        KeyFactory keyFactory = KeyFactory.getInstance(EncryptionProperties.ALGORITHM);
        EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
        return Optional.ofNullable(keyFactory.generatePublic(publicKeySpec));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException | NullPointerException e) {
        return Optional.empty();
    }
}

The error to be overcome

The PKCS#1-format can not be read by the Java 17 microservice.

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException:
IOException: algid parse error, not a sequence
at java.base/sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:241)
at java.base/java.security.KeyFactory.generatePublic(KeyFactory.java:351)

Therefore the SPKI-format is needed to be used by Swift (iOS).

Hope

In case there is no solution using native Swift, the following approach using OpenSSL may be tried (not happened, yet).

https://medium.com/@joncardasis/openssl-swift-everything-you-need-to-know-2a4f9f256462

Anyways

Thanks for reading & sharing - any help is appreciated :)

Appendix

All keys may be analyzed:

https://8gwifi.org/PemParserFunctions.jsp

Multiple keys are given to prevent 'lucky shots' ..  ;-)

Sample keys - Swift iOS (PKCS#1)

First:

MIICCgKCAgEAl0HYn9IdRmexAR9dSh3SxmFazWF0RV2TKmtRxGySvCA+aHZ/Dp+8tC0YDWpQzP+tZdlDWNOBj/D7i1z4b+UZk8F9ZEoi+w61kYQz+KjMkRuYrPBFi4A/gsS2qGeFJ4OvLQzGObZ0C+5/E+wunUWyQCVjgjTHKH8yqfVXeWYFKmaSSZblSZJAObE8Ao5J38DMINF1oWG+GdZt8RTLf35ULLEa8zKvFXrfBkDjiQH90WKPwDxWwvFInqZhjpsFxLytiKW+iBLqa4+0P7uwXVodFXa38RW9dk9mEsLvj6764BKtPAaWym9XZfEZNBu0jwlfO07k0augynGps6bsSIyYglDImlTRagdA/e+1AMBlSxEFVO4NpCjEpMT7rNX/LYPeEaJ8fTC3axOM1yEntcwUfSSCDulVPGlWlFbPxt29y1RrGtMmwfbTlbOQf2okMf0mGx9Ytd9HWadIdWh4FqDVWA8MF82PP1YsOW5TA0hkprK1qJwfkaLRKnmpfL5a7gWn4HWzpdDqrezhbc/zTCeHbX5c61mgWsAIWnB3fyXsJHpR62+QtBEznwhDxafVCQyUmsDqbncBxilEnFIn08G+6ox2PQC8GhNdpFVGsSoqpDfctsm51/tUYLpyeIBdzw/3nMLL1J5jL3yWr7ZKgnzNwjpC8l6c6gpsF3NRodeVhp8CAwEAAQ==

Second:

MIICCgKCAgEAlSbN7rlX6EMCDGuxQm9G6qqXIWshDvI5VaN4QPNCFcFzPjI/FyaHqi43+mxTyKGycT6TNqvanSu67yoIA80tSlFH2LndWv6sPQeHKxNwwFKU98Y/uL3M6hKIVXDwa6kZGM58dfY9qMWEOPXB4AwZtVaxJ4ePHFAR0kEOAHLCPpQxFkNlkg9FlCwlBzZbhHkI5uhCmlGEiLpLaJNJzjn7yo33m65189J6tIh3vopZ2ahFHb/vo6SVSbtS7Y0YlinJwH3MCGLm5+pKBpE64t5lgEhDPYSF7pKpLhEVqC5ETaya3mYTkXPSCiY/9Mo5zddniUGrxAJaY940jY3QNYeFmWPEEdhhIW2tUbuiM3IlHAqk4Du5p/2o1QcSVZdBsHStSGdcWqs00Z+ooxXwrOpMOUnZeb8Jt5dGDyHwjOmPf0N8dDQwz+5pgOoTkxd/z5cTK9tMv/nC+Mbbt8LRsct16M3LYrRAYnA8unX1ZD3eXTJPOSB/fM9Hmf1ObxQro9tatC5RaJjS0Xg5aepUsey62BW9lj4kHCkRPD4w1OmjDWGUCOSEhwy0KwqFyRBppYUMndEbJb3GKEjpekcQYwjERPtH/vEVxaN5gGYaCORancUaNH+d03zAmi0G830QXQvyohyKUkGw5qljEBH5R5Wqu7YLTlUes0rQEx8DpLVclaMCAwEAAQ==

Sample keys - Java 17 (SPKI-format)

First:

MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAqwMRLS3hhNuVBQTqRT4714fbl4h3PtrSZQ8Ry1qMCefFOLzmLmLD/VdnFoHj3QiqlZMlajvVuJonprhOy911aNW2Qs2VZ+zoMkLRjah9gqg00dLVtdWa2FXjAX6bh/rSR6jmF1hzfLPs/CqOKyDpX003AUF/WvgHkuAizQjZeskEDKawbExs6RSSFHNycrGwB9hBhAwGvyZpC2+fqPN/93W2NZ8xyb5H6CmM7pCpG+sTcsEEYOZjjq2HV8vYdM9KHi7O+nmY0MJxjLJ5JOv5oLqPXFt4Epezz4v2C3oE3Leu4gIy1r1D2xHuxu0pyQ9F2nI7a+6mGZbRAYDA8Yq2oidqBDC9pKogoHcMYhXj/G0WNEhE9ODuHg+GkiiGc3zysuKwfKu1Z5ZmUtlI1kVFqUEEi81smylTXtkU/oEf7P0OX94XcNTq1N3iO+nuFayAhINlvLUXwyO4JQUsmCyu0bH17XuNUfbnSCmOfGhFSjpyU0PthW9Qtf9yY9MmyZz9c9T2kfxoUxBnNRhVUZ+Kg8oA6kkNJp/ac+AdZzkPZFev91ZKYCbyI+rcakJ4KBQ5YoprDtpHmAQZ5E3/rWcq1Tis0yiomE2+natrzaO4aQbrljOHEgB6arbMkeu7/sZHEvYfK7ilH7tsZfDdU2DVOV0yxNReYwOHAFgFMTNQvBsCAwEAAQ==

Second:

MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAs9ywiZnmv9Ewf+dIsmwV8ZlZKQNg4lbVLpNptb3pftnoukvBjak1rDqb6GcxXtM+UuBgr4Wigi0TI+vItzWv6QlBB8HShA4WImKrOCD3+U1fFdDpwCxQO+oHqTqeNKhRcKcM0e0C/c88hJo8l9G2OCjIANW3O+pGeMirB/XjPdcQ+d37TFGpRs83wPR8gUFQsH8qQMkS7uOtTCZHfcK6UzbvJB3Gf/llcCSfPYKUMY9SXIc5K9hpI0E1v5EdEUvdbhiilZI0esntr5BzeO5AxH/m9fFPH9ekZZyc9nXsHY7tPOJMD+wsTad4D9NBGi9x+lzxZRdxyDLote4ix+aHSqMgcdtOyJ69WFym2Ty1VfCgrmG8fhC/PZBEzk6obK5uJD4mO3owrKgYsmJgZHO3CbVkmv04+EEPpQLippQu8uCl+2KO480EvjSco5ryVH3XEsAGokBLCsZviBtntY/Ia0OLXPmy7WWXigxsVQkgPZ1SyZa3FUp/Zuwtoo0BWDI/9JdUZPfKhbQkcxtnKbCe8QXf51YUgIfKXPTBlmk/Zj931EzXdQCZFMvgK+I5p79DqCsD9yKbiUnfK9tXJ4SzMfuiLd4pqB0UIMVMQEj5SZPYn7eHRZyje4v96FDwtj56NQ/kZPYXKqLoOv5nvMALZngzJ6aFaGjkWZX9RNQLfA8CAwEAAQ==


问:
How do I properly type nested React Navigation navigators?
For my top level navigator, I have:

```<code>type NavigationParamList = {
  Instances: undefined;
  Default: undefined;
  Settings: undefined;
  Compose: undefined;
};

const AppStack = createNativeStackNavigator<NavigationParamList>();

<NavigationContainer theme={NavTheme}>
      <AppStack.Navigator initialRouteName="Default">
        <AppStack.Screen
          name="Instances"
          component={InstancesScreen}
        />
....
</code>```

But when I do something like:

```<code>navigation.navigate('Instances')
</code>```

I get:

```<code>No overload matches this call.
  Overload 1 of 2, '(...args: never): void', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'never'.
  Overload 2 of 2, '(options: never): void', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'never'.
</code>```

What am I doing wrong and how do I get TypeScript to finally just be happy?

Body:
For my top level navigator, I have:

type NavigationParamList = {
  Instances: undefined;
  Default: undefined;
  Settings: undefined;
  Compose: undefined;
};

const AppStack = createNativeStackNavigator<NavigationParamList>();

<NavigationContainer theme={NavTheme}>
      <AppStack.Navigator initialRouteName="Default">
        <AppStack.Screen
          name="Instances"
          component={InstancesScreen}
        />
....

But when I do something like:

navigation.navigate('Instances')

I get:

No overload matches this call.
  Overload 1 of 2, '(...args: never): void', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'never'.
  Overload 2 of 2, '(options: never): void', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'never'.

What am I doing wrong and how do I get TypeScript to finally just be happy?


问:
Using Project specific color palette in React and sharing it to child components by a single reference
I have got an SCSS like this

color.scss

```<code>$conifer: #bae659; // Conifer
$apple: #63c532; // Apple
$jungle-green: #00796d; // Jungle Green
$vivid-violet: #a446ba; // Vivid Violet
$dark-violet: #7d3787; // Dark Violet
$gigas: #4f3398; // Gigas
$mercury: #e2e2e2; // Mercury
$monza: #e00716; // Monza
$mirage: #15152b; // Mirage
$athens-gray: #F3F5F8; // Athens gray
$rock-blue: #A3B0CB; // Rock blue
$nobel: #b3b3b3; // Nobel
$gray-nurse: #E1E6EA; //Gray nurse
</code>```

In my App.tsx

```<code>import './color.scss'
const App = () => {

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<RecipeLanding />} />
          <Route path="ManageRecipe" element={<ManageRecipe />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
};

export default App;
</code>```

I need to use these colors in my child components as well. So how can I handle this the best way.

Is there is anyway to use it like this even in child components just by the reference in app.tsx

bgcolor:mystyle.vivid-violet

Body:
I have got an SCSS like this

color.scss

$conifer: #bae659; // Conifer
$apple: #63c532; // Apple
$jungle-green: #00796d; // Jungle Green
$vivid-violet: #a446ba; // Vivid Violet
$dark-violet: #7d3787; // Dark Violet
$gigas: #4f3398; // Gigas
$mercury: #e2e2e2; // Mercury
$monza: #e00716; // Monza
$mirage: #15152b; // Mirage
$athens-gray: #F3F5F8; // Athens gray
$rock-blue: #A3B0CB; // Rock blue
$nobel: #b3b3b3; // Nobel
$gray-nurse: #E1E6EA; //Gray nurse

In my App.tsx

import './color.scss'
const App = () => {

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<RecipeLanding />} />
          <Route path="ManageRecipe" element={<ManageRecipe />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
};

export default App;

I need to use these colors in my child components as well. So how can I handle this the best way.

Is there is anyway to use it like this even in child components just by the reference in app.tsx

bgcolor:mystyle.vivid-violet


问:
Is there a possibility to change tab title when I show an native pdf
I will show an PDF in chrome. Direct (no html). But the tab title in chrome is the last part of my url (https://myservice/foo/baar/generate-pdf).

I send the PDF to the client via HTTP-Header:

```<code>Content-Disposition: inline, filename="test.pdf"
</code>```

Is there a possibility to change tab title when I show an native pdf?

I tried this without success:

Search for title HTML-Header

PDF title Meta-Data (ignored by chrome)

The "Content-Disposition" Filename are ignored by chrome

Has anybody an idea?
Thanks!

Body:
I will show an PDF in chrome. Direct (no html). But the tab title in chrome is the last part of my url (https://myservice/foo/baar/generate-pdf).

I send the PDF to the client via HTTP-Header:

Content-Disposition: inline, filename="test.pdf"

Is there a possibility to change tab title when I show an native pdf?

I tried this without success:

Search for title HTML-Header

PDF title Meta-Data (ignored by chrome)

The "Content-Disposition" Filename are ignored by chrome

Has anybody an idea?
Thanks!


问:
Why is simple C++ OpenMP parallel for loop slower?
I have a relatively simple for loop that I would like to parallelize with OpenMP. For some reason, the parallel version is slower than the serial version. Here is the function and loop in question:

template<typename T, class UnaryOperation>
void State:apply_diagmatrix(const std::vector<T>& matrix, const UnaryOperation& transformation)
{
#pragma omp parallel for
    for (uint64_t i=0; i<dim_; ++i) {
        state_[i] *= transformation(matrix[i]);
    }
}
```
<p>where <code>state_</code> is <code>std::vector<std::complex<double>></code>. This function is called by another function where the <code>UnaryOperation transformation</code> is defined as</p>
<pre class="lang-cpp prettyprint-override"><code>auto exp_func = [dt](double matrix_term) {
    return std::complex<double>{std::cos(dt*matrix_term), -std::sin(dt*matrix_term)};
};
</code>```

However, running the program with this parallel section is actually slower than running the serial version (without the #pragma omp directive). This is the case even when dim_ > 4096, where I would expect the overhead to be much smaller compared to the benefit of parallelizing 4096 executions of exp_func.

Of course, the entire program does much more than just this loop. Nevertheless, from profiling my code I know that the apply_diagmatrix function has significant relative cost. Hence, I would expect measurable benefit after parallelizing it.

I also tried to benchmark the parallel vs the serial version of just the loop in question. In that case, there is a clear benefit of the parallel version once dim_ > 512. Why am I seeing this benefit only when running the loop in isolation. What is the difference when the loop is part of a larger code? Any ideas?

Edit: From the comments it seems clear that the problem is not obvious without some more context. I will go back and look whether I can extract some min. reproducible example without the need to share the entire code.

Body:
I have a relatively simple for loop that I would like to parallelize with OpenMP. For some reason, the parallel version is slower than the serial version. Here is the function and loop in question:

template<typename T, class UnaryOperation>
void State:apply_diagmatrix(const std::vector<T>& matrix, const UnaryOperation& transformation)
{
#pragma omp parallel for
    for (uint64_t i=0; i<dim_; ++i) {
        state_[i] *= transformation(matrix[i]);
    }
}

where state_ is std::vector<std::complex<double>>. This function is called by another function where the UnaryOperation transformation is defined as

auto exp_func = [dt](double matrix_term) {
    return std::complex<double>{std::cos(dt*matrix_term), -std::sin(dt*matrix_term)};
};

However, running the program with this parallel section is actually slower than running the serial version (without the #pragma omp directive). This is the case even when dim_ > 4096, where I would expect the overhead to be much smaller compared to the benefit of parallelizing 4096 executions of exp_func.

Of course, the entire program does much more than just this loop. Nevertheless, from profiling my code I know that the apply_diagmatrix function has significant relative cost. Hence, I would expect measurable benefit after parallelizing it.

I also tried to benchmark the parallel vs the serial version of just the loop in question. In that case, there is a clear benefit of the parallel version once dim_ > 512. Why am I seeing this benefit only when running the loop in isolation. What is the difference when the loop is part of a larger code? Any ideas?

Edit: From the comments it seems clear that the problem is not obvious without some more context. I will go back and look whether I can extract some min. reproducible example without the need to share the entire code.


问:
NYC mocha resulting in 0 coverage
`your

```<code>"test": "nyc --all --reporter=text-summary  mocha --recursive './test/**/*.test.js'  --exit",
</code>```

`this results in no coverage

any ideas

enter image description here

I am expecting to show some code coverage points

Title: NYC mocha resulting in 0 coverage

Body:
`your

"test": "nyc --all --reporter=text-summary  mocha --recursive './test/**/*.test.js'  --exit",

`this results in no coverage

any ideas

enter image description here

I am expecting to show some code coverage points


问:
wordpress current menu item problem? highlighting the menu item when you’re on the Section name?
I have made my website a one-pager with the menu items scrolling down to each section.

The problem is: current-menu-item current_page_item classes are added in all menu items as shown in the screenshot.


问:
AWS RDS Aurora Postgres freeable memory decreasing leads to db restart
I have a RDS Aurora Postgres instance crashing with OOM error when the freeable memory reaches close to 0. This error generates a database restart and once the freeable memory decreases again over the time, a new restart happens. After each new restart, the freeable memory goes back to around 16500MB.

Does anyone has any idea on why this is happening?

Some information:

Number of ongoing IDLE connections: around 450 IDLE connections

Instance class = db.r6g.2xlarge

vCPU = 8

RAM = 64 GB

Engine version = 11.9

```<code>shared_buffers = 43926128kB
work_mem = 4MB
temp_buffers = 8MB
wal_buffers = 16MB
max_connections = 5000
maintenance_work_mem = 1042MB
autovacuum_work_mem = -1
</code>```

These connections are keep alive for application reutilization and when new queries goes to the database, one of those connections are used by the application. This is not a pool of connection implementation, just 100 instances of my application are connected to the database.

It seems some of these connections/processes are "eating" the memory over the time. By checking the OS processes, I saw some of these processes are increasing the RES memory. For example, one idle process had 920.9 MB as RES metric but now it has 3.96 GiB.

RES metric refers to physical memory being used by the process as per this AWS doc: https://docs.amazonaws.cn/en_us/AmazonRDS/latest/AuroraUserGuide/USER_Monitoring.OS.Viewing.html

I'm wondering if this issue is related to these idle connections as described here: https://aws.amazon.com/blogs/database/resources-consumed-by-idle-postgresql-connections/

Maybe I should reduce the number of connections to the database.

Freeable Memory on CloudWatch graph:

General metrics on CloudWatch:

Enhanced monitoring metrics:

OS processes (around 100 ongoing processes):

Body:
I have a RDS Aurora Postgres instance crashing with OOM error when the freeable memory reaches close to 0. This error generates a database restart and once the freeable memory decreases again over the time, a new restart happens. After each new restart, the freeable memory goes back to around 16500MB.

Does anyone has any idea on why this is happening?

Some information:

Number of ongoing IDLE connections: around 450 IDLE connections

Instance class = db.r6g.2xlarge

vCPU = 8

RAM = 64 GB

Engine version = 11.9

shared_buffers = 43926128kB
work_mem = 4MB
temp_buffers = 8MB
wal_buffers = 16MB
max_connections = 5000
maintenance_work_mem = 1042MB
autovacuum_work_mem = -1

These connections are keep alive for application reutilization and when new queries goes to the database, one of those connections are used by the application. This is not a pool of connection implementation, just 100 instances of my application are connected to the database.

It seems some of these connections/processes are "eating" the memory over the time. By checking the OS processes, I saw some of these processes are increasing the RES memory. For example, one idle process had 920.9 MB as RES metric but now it has 3.96 GiB.

RES metric refers to physical memory being used by the process as per this AWS doc: https://docs.amazonaws.cn/en_us/AmazonRDS/latest/AuroraUserGuide/USER_Monitoring.OS.Viewing.html

I'm wondering if this issue is related to these idle connections as described here: https://aws.amazon.com/blogs/database/resources-consumed-by-idle-postgresql-connections/

Maybe I should reduce the number of connections to the database.

Freeable Memory on CloudWatch graph:

General metrics on CloudWatch:

Enhanced monitoring metrics:

OS processes (around 100 ongoing processes):