问:
Calling ConfigureAwait with false in DAL Layer
This article explains the usage of Dapper.

In the ExecuteAsync section the author writes after this example:

```<code>public async Task<int> UpdateSalesOrder(int salesOrderId, byte status)
{
const string sql = @"
    UPDATE Sales.SalesOrderHeader
    SET STATUS = @status
    WHERE SalesOrderID = @salesOrderId";

var param = new {status, salesOrderId};
using var conn = _db.GetAdventureWorksConnection();

return await conn.ExecuteAsync(sql, param)
    .ConfigureAwait(false);
}
</code>```

It is best to nuke any synchronization with the main thread at the data access layer because this can affect scalability. Therefore, it is a good idea to set configure await to false, so this does not wait on the main thread. Unfortunately, C# does not do this automatically for the developer, so it must come from muscle memory. A good rule of thumb is if you are working in the DAL, put ConfigureAwait(false) in every call stack method.

Does this advice apply only to code that interacts with Db in the way that Dapper does?
Can someone please explain in which scenario C# does this automatically?

If this code is part of a class library which would then be used in any type of .Net Application what would be the implications?

Regards.

Body:
This article explains the usage of Dapper.

In the ExecuteAsync section the author writes after this example:

public async Task<int> UpdateSalesOrder(int salesOrderId, byte status)
{
const string sql = @"
    UPDATE Sales.SalesOrderHeader
    SET STATUS = @status
    WHERE SalesOrderID = @salesOrderId";

var param = new {status, salesOrderId};
using var conn = _db.GetAdventureWorksConnection();

return await conn.ExecuteAsync(sql, param)
    .ConfigureAwait(false);
}

It is best to nuke any synchronization with the main thread at the data access layer because this can affect scalability. Therefore, it is a good idea to set configure await to false, so this does not wait on the main thread. Unfortunately, C# does not do this automatically for the developer, so it must come from muscle memory. A good rule of thumb is if you are working in the DAL, put ConfigureAwait(false) in every call stack method.

Does this advice apply only to code that interacts with Db in the way that Dapper does?
Can someone please explain in which scenario C# does this automatically?

If this code is part of a class library which would then be used in any type of .Net Application what would be the implications?

Regards.


来源: stackexchange

问:
case_when function just returning first line of code and not creating/recoding to a new variable
I'm very new to all of this and am (trying!) to complete an assignment for a quantitative methods module at uni. I want to recode a quantitative variable measuring number of minutes spent doing an activity. I want to create a new variable with five categories up to 1300 minutes using the case_when function.

I've tried numerous times to do this and it's just not working. R is only reading the first line of code and wont create a new variable.

Here's my code:

```<code>italy$nwspol_re <- case_when(italy$nwspol < 260 ~ "0-260 mins",
                             italy$nwspol >= 261 & italy$nwspol < 520 ~ "261-520",
                             italy$nwspol >= 521 & italy$nwspol < 780 ~ "521-780",
                             italy$nwspol >= 781 & italy$nwspol < 1040 ~ "781-1040",
                             italy$nwspol >= 1041 & italy$nwspol < 1300 ~ "1041-1300")

</code>```

in the console, R just returns the first line and nothing else happens.

I have also tried the mutate function as shown, however R just returns the first line containing italy and nothing else happens, i.e., no new variable is created.

```<code>italy %\>%
mutate(nwspol_re = case_when(nwspol \>= 260 \~ '0-260 minutes'
,nwspol \>= 520 & nwspol \< 780 \~ '521-780'
,nwspol \>= 781 & nwspol \< 1040 \~ '781-1040'
,nwspol \>= 1041 & nwspol \< 1285 \~ '1041-1300'
,TRUE \~ 'F'
)
)

</code>```

Any help would be appreciated.

ContentLicense: CC BY-SA 4.0

Body:
I'm very new to all of this and am (trying!) to complete an assignment for a quantitative methods module at uni. I want to recode a quantitative variable measuring number of minutes spent doing an activity. I want to create a new variable with five categories up to 1300 minutes using the case_when function.

I've tried numerous times to do this and it's just not working. R is only reading the first line of code and wont create a new variable.

Here's my code:

italy$nwspol_re <- case_when(italy$nwspol < 260 ~ "0-260 mins",
                             italy$nwspol >= 261 & italy$nwspol < 520 ~ "261-520",
                             italy$nwspol >= 521 & italy$nwspol < 780 ~ "521-780",
                             italy$nwspol >= 781 & italy$nwspol < 1040 ~ "781-1040",
                             italy$nwspol >= 1041 & italy$nwspol < 1300 ~ "1041-1300")

in the console, R just returns the first line and nothing else happens.

I have also tried the mutate function as shown, however R just returns the first line containing italy and nothing else happens, i.e., no new variable is created.

italy %\>%
mutate(nwspol_re = case_when(nwspol \>= 260 \~ '0-260 minutes'
,nwspol \>= 520 & nwspol \< 780 \~ '521-780'
,nwspol \>= 781 & nwspol \< 1040 \~ '781-1040'
,nwspol \>= 1041 & nwspol \< 1285 \~ '1041-1300'
,TRUE \~ 'F'
)
)

Any help would be appreciated.


问:
How can i get the current URL (its dynamic, because of a blog) to a Schema.org File?
I want to create a Schema.org for our blog. Unfortunately I don't have a placeholder for the corresponding URL. Can someone help me?

```<code><script type="application/ld+json">
  {
  "@context": "https://schema.org/",
  "@type": "BreadcrumbList",
  "itemListElement": [{
    "@type": "ListItem",
    "position": 1,
    "name": "netpulse.ch",
    "item": "https://www.netpulse.ch"
  },{
    "@type": "ListItem",
    "position": 2,
    "name": "Online Marketing News",
    "item": "https://www.netpulse.ch/blog/"
  },{
    "@type": "ListItem",
    "position": 3,
    "name": "{{blog.title}}",
    "item": "{{InitialPostAlias}}"
  }]
}
 </script>
</code>```


问:
Nativescript android:exported android-12 compatibility error even after adding android:exported in all activity, service and receiver tags

{
    "version": "2.10.1",
    "description": "NativeScript Application",
    "license": "SEE LICENSE IN <your-license-filename>",
    "repository": "<fill-your-repository-here>",
    "scripts": {
        "lint": "tslint \"src/**/*.ts\"",
        "code-clean": "prettier --write \"src\"",
        "ngcc": "ngcc",
        "postinstall": "patch-package"
    },
    "dependencies": {
        "@angular/animations": "~12.2.5",
        "@angular/common": "~12.2.5",
        "@angular/compiler": "~12.2.5",
        "@angular/core": "~12.2.5",
        "@angular/forms": "~12.2.5",
        "@angular/platform-browser": "~12.2.5",
        "@angular/platform-browser-dynamic": "~12.2.5",
        "@angular/router": "~12.2.5",
        "@mapo80/nativescript-ngx-shadow": "file:packages/mapo80-nativescript-ngx-shadow-7.0.1.tgz",
        "@nativescript-community/ui-image": "4.0.20",
        "@nativescript-community/ui-material-bottom-navigation": "^7.0.25",
        "@nativescript-community/ui-material-bottomsheet": "^7.0.28",
        "@nativescript-community/ui-pager": "13.0.31",
        "@nativescript/angular": "^12.2.0",
        "@nativescript/appversion": "~2.0.0",
        "@nativescript/camera": "^5.0.13",
        "@nativescript/core": "~8.1.1",
        "@nativescript/fingerprint-auth": "^8.1.0",
        "@nativescript/firebase": "^11.1.3",
        "@nativescript/geolocation": "8.0.2",
        "@nativescript/imagepicker": "~1.0.0",
        "@nativescript/iqkeyboardmanager": "~2.0.0",
        "@nativescript/social-share": "^2.0.4",
        "@nativescript/theme": "^3.0.2",
        "@ngrx/effects": "^9.2.0",
        "@ngrx/entity": "^12.2.0",
        "@ngrx/store": "^9.2.0",
        "@nstudio/nativescript-exoplayer": "~5.0.0",
        "@nstudio/nativescript-pulltorefresh": "^3.0.2",
        "@sergeymell/nativescript-svg": "^1.1.2",
        "@sonnytrujillojr/tokenizerjs": "^1.0.1",
        "ALAssetsLibrary-CustomPhotoAlbum": "file:packages/ALAssetsLibrary-CustomPhotoAlbum",
        "deep-diff": "^1.0.2",
        "immer": "^7.0.9",
        "lodash": "^4.17.20",
        "moment-timezone": "^0.5.31",
        "nativescript-drop-down": "^6.0.2",
        "nativescript-google-maps-sdk": "^3.0.2",
        "nativescript-gradient": "^2.0.1",
        "nativescript-image-swipe": "^5.0.1",
        "nativescript-masked-text-field": "file:packages/nativescript-masked-text-field-4.0.3.tgz",
        "nativescript-mediafilepicker": "4.0.2",
        "nativescript-push-notifications": "^1.1.6",
        "nativescript-status-bar": "file:nativescript-status-bar",
        "nativescript-ui-listview": "^9.1.0",
        "ngrx-store-logger": "^0.2.4",
        "normalizr": "^3.6.1",
        "reflect-metadata": "^0.1.13",
        "rxjs": "^7.4.0",
        "zone.js": "^0.11.4"
    },
    "devDependencies": {
        "@angular-devkit/build-angular": "^12.2.18",
        "@angular/compiler-cli": "^12.2.5",
        "@nativescript/android": "8.1.1",
        "@nativescript/ios": "8.1.0",
        "@nativescript/types": "~8.1.0",
        "@nativescript/webpack": "^5.0.8",
        "@ngtools/webpack": "^12.2.5",
        "@types/lodash": "^4.14.161",
        "babel-traverse": "6.26.0",
        "babel-types": "6.26.0",
        "babylon": "6.18.0",
        "codelyzer": "~4.0.2",
        "commitizen": "^4.2.3",
        "cz-conventional-changelog": "^3.3.0",
        "patch-package": "^6.4.7",
        "prettier": "2.0.5",
        "prettier-tslint": "^0.4.2",
        "tslint": "~5.8.0",
        "typescript": "~4.3.5"
    },
    "readme": "NativeScript Application",
    "config": {
        "commitizen": {
            "path": "./node_modules/cz-conventional-changelog"
        }
    },
    "main": "./src/main.ts"
}```
</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><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="__PACKAGE__" android:versionCode="1" android:versionName="1.0.0">

    <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true"/>

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
      <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:name="android.hardware.location.gps" android:required="false" />

    <application android:name="com.tns.NativeScriptApplication" android:allowBackup="true" android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@style/AppTheme" android:requestLegacyExternalStorage="true" android:exported="true">

        <activity android:name="net.demo.Activity" android:label="@string/title_activity_kimera" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|smallestScreenSize|screenLayout|locale|uiMode" android:theme="@style/LaunchScreenTheme" android:screenOrientation="portrait" android:windowSoftInputMode="stateHidden | adjustPan" android:exported="true">

            <meta-data android:name="SET_THEME_ON_LAUNCH" android:resource="@style/AppTheme" />

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="http" android:host="link.demo.com" />
                <data android:scheme="https" android:host="link.demo.com" />
                <data android:scheme="net.demo" android:host="demo.com" />
            </intent-filter>
        </activity>
        <activity android:name="com.tns.ErrorReportActivity" android:exported="true"/>

        <service android:name="org.nativescript.plugins.firebase.MyFirebaseInstanceIDService" android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

        <service android:name="org.nativescript.plugins.firebase.MyFirebaseMessagingService" android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

        <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/nativescript_google_maps_api_key"/>
    </application>
</manifest></code>```

I am working on a nativescript project. The app is working perfectly fine in development mode but as soon as I am creating a .aab file and trying to upload the bundle to the play store I am getting the following error regarding android 12 compatibility

Error - You uploaded an APK or Android App Bundle which has an activity, activity alias, service or broadcast receiver with intent filter, but without the 'android:exported' property set. This file can't be installed on Android 12 or higher. See: developer.android.com/about/versions/12/behavior-changes-12#exported

I tried following the doc link specified in the error message and also tried solutions that stated things like adding android:exported in all activity, service and receiver tags in which intent-filter is there. I tried these solutions but nothing worked. Can someone help me or guide me with tackling this issue?

Body:
{
    "version": "2.10.1",
    "description": "NativeScript Application",
    "license": "SEE LICENSE IN <your-license-filename>",
    "repository": "<fill-your-repository-here>",
    "scripts": {
        "lint": "tslint \"src/**/*.ts\"",
        "code-clean": "prettier --write \"src\"",
        "ngcc": "ngcc",
        "postinstall": "patch-package"
    },
    "dependencies": {
        "@angular/animations": "~12.2.5",
        "@angular/common": "~12.2.5",
        "@angular/compiler": "~12.2.5",
        "@angular/core": "~12.2.5",
        "@angular/forms": "~12.2.5",
        "@angular/platform-browser": "~12.2.5",
        "@angular/platform-browser-dynamic": "~12.2.5",
        "@angular/router": "~12.2.5",
        "@mapo80/nativescript-ngx-shadow": "file:packages/mapo80-nativescript-ngx-shadow-7.0.1.tgz",
        "@nativescript-community/ui-image": "4.0.20",
        "@nativescript-community/ui-material-bottom-navigation": "^7.0.25",
        "@nativescript-community/ui-material-bottomsheet": "^7.0.28",
        "@nativescript-community/ui-pager": "13.0.31",
        "@nativescript/angular": "^12.2.0",
        "@nativescript/appversion": "~2.0.0",
        "@nativescript/camera": "^5.0.13",
        "@nativescript/core": "~8.1.1",
        "@nativescript/fingerprint-auth": "^8.1.0",
        "@nativescript/firebase": "^11.1.3",
        "@nativescript/geolocation": "8.0.2",
        "@nativescript/imagepicker": "~1.0.0",
        "@nativescript/iqkeyboardmanager": "~2.0.0",
        "@nativescript/social-share": "^2.0.4",
        "@nativescript/theme": "^3.0.2",
        "@ngrx/effects": "^9.2.0",
        "@ngrx/entity": "^12.2.0",
        "@ngrx/store": "^9.2.0",
        "@nstudio/nativescript-exoplayer": "~5.0.0",
        "@nstudio/nativescript-pulltorefresh": "^3.0.2",
        "@sergeymell/nativescript-svg": "^1.1.2",
        "@sonnytrujillojr/tokenizerjs": "^1.0.1",
        "ALAssetsLibrary-CustomPhotoAlbum": "file:packages/ALAssetsLibrary-CustomPhotoAlbum",
        "deep-diff": "^1.0.2",
        "immer": "^7.0.9",
        "lodash": "^4.17.20",
        "moment-timezone": "^0.5.31",
        "nativescript-drop-down": "^6.0.2",
        "nativescript-google-maps-sdk": "^3.0.2",
        "nativescript-gradient": "^2.0.1",
        "nativescript-image-swipe": "^5.0.1",
        "nativescript-masked-text-field": "file:packages/nativescript-masked-text-field-4.0.3.tgz",
        "nativescript-mediafilepicker": "4.0.2",
        "nativescript-push-notifications": "^1.1.6",
        "nativescript-status-bar": "file:nativescript-status-bar",
        "nativescript-ui-listview": "^9.1.0",
        "ngrx-store-logger": "^0.2.4",
        "normalizr": "^3.6.1",
        "reflect-metadata": "^0.1.13",
        "rxjs": "^7.4.0",
        "zone.js": "^0.11.4"
    },
    "devDependencies": {
        "@angular-devkit/build-angular": "^12.2.18",
        "@angular/compiler-cli": "^12.2.5",
        "@nativescript/android": "8.1.1",
        "@nativescript/ios": "8.1.0",
        "@nativescript/types": "~8.1.0",
        "@nativescript/webpack": "^5.0.8",
        "@ngtools/webpack": "^12.2.5",
        "@types/lodash": "^4.14.161",
        "babel-traverse": "6.26.0",
        "babel-types": "6.26.0",
        "babylon": "6.18.0",
        "codelyzer": "~4.0.2",
        "commitizen": "^4.2.3",
        "cz-conventional-changelog": "^3.3.0",
        "patch-package": "^6.4.7",
        "prettier": "2.0.5",
        "prettier-tslint": "^0.4.2",
        "tslint": "~5.8.0",
        "typescript": "~4.3.5"
    },
    "readme": "NativeScript Application",
    "config": {
        "commitizen": {
            "path": "./node_modules/cz-conventional-changelog"
        }
    },
    "main": "./src/main.ts"
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="__PACKAGE__" android:versionCode="1" android:versionName="1.0.0">

    <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true"/>

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
      <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:name="android.hardware.location.gps" android:required="false" />

    <application android:name="com.tns.NativeScriptApplication" android:allowBackup="true" android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@style/AppTheme" android:requestLegacyExternalStorage="true" android:exported="true">

        <activity android:name="net.demo.Activity" android:label="@string/title_activity_kimera" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|smallestScreenSize|screenLayout|locale|uiMode" android:theme="@style/LaunchScreenTheme" android:screenOrientation="portrait" android:windowSoftInputMode="stateHidden | adjustPan" android:exported="true">

            <meta-data android:name="SET_THEME_ON_LAUNCH" android:resource="@style/AppTheme" />

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="http" android:host="link.demo.com" />
                <data android:scheme="https" android:host="link.demo.com" />
                <data android:scheme="net.demo" android:host="demo.com" />
            </intent-filter>
        </activity>
        <activity android:name="com.tns.ErrorReportActivity" android:exported="true"/>

        <service android:name="org.nativescript.plugins.firebase.MyFirebaseInstanceIDService" android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

        <service android:name="org.nativescript.plugins.firebase.MyFirebaseMessagingService" android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

        <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/nativescript_google_maps_api_key"/>
    </application>
</manifest>

I am working on a nativescript project. The app is working perfectly fine in development mode but as soon as I am creating a .aab file and trying to upload the bundle to the play store I am getting the following error regarding android 12 compatibility

Error - You uploaded an APK or Android App Bundle which has an activity, activity alias, service or broadcast receiver with intent filter, but without the 'android:exported' property set. This file can't be installed on Android 12 or higher. See: developer.android.com/about/versions/12/behavior-changes-12#exported

I tried following the doc link specified in the error message and also tried solutions that stated things like adding android:exported in all activity, service and receiver tags in which intent-filter is there. I tried these solutions but nothing worked. Can someone help me or guide me with tackling this issue?


问:
Online contact form | Send email message using php | HTTP ERROR 405
I am trying to submit an online contact form by using PHP but I get error message "HTTP ERROR 405" in submission.

Hello everyone!

I am trying to setup an Online Contact Form by using PHP. You can see the code here:

https://codepen.io/p_demetriou/pen/mdjRvJz

Below you can see the code of PHP file send-email.php :

```<code><?php
  // Get the form data
  $name = $_POST['name'];
  $surname = $_POST['surname'];
  $company = $_POST['company'];
  $email = $_POST['email'];
  $message = $_POST['message'];

  // Set the recipient email address
  $to = "contactvenusproperties@gmail.com";
  // $to = 'recipient@example.com';

  // Set the email subject
  $subject = 'Venus Holdings | New Message from Online Contact Form';

  // Build the email content
  $email_content = "Name: $name\n";
  $email_content = "Surname: $surname\n";
  $email_content = "Company: $company\n";
  $email_content .= "Email: $email\n\n";
  $email_content .= "Message:\n$message\n";

  // Build the email headers
  $email_headers = "From: $name <$email>";

  // Send the email
  mail($to, $subject, $email_content, $email_headers);
?>
</code>```

When i submit the form, i get the following error message:

*This page isn’t working
If the problem continues, contact the site owner.

HTTP ERROR 405*

Any ideas on how to solve this issue?

Many thanks!

Body:
I am trying to submit an online contact form by using PHP but I get error message "HTTP ERROR 405" in submission.

Hello everyone!

I am trying to setup an Online Contact Form by using PHP. You can see the code here:

https://codepen.io/p_demetriou/pen/mdjRvJz

Below you can see the code of PHP file send-email.php :

<?php
  // Get the form data
  $name = $_POST['name'];
  $surname = $_POST['surname'];
  $company = $_POST['company'];
  $email = $_POST['email'];
  $message = $_POST['message'];

  // Set the recipient email address
  $to = "contactvenusproperties@gmail.com";
  // $to = 'recipient@example.com';

  // Set the email subject
  $subject = 'Venus Holdings | New Message from Online Contact Form';

  // Build the email content
  $email_content = "Name: $name\n";
  $email_content = "Surname: $surname\n";
  $email_content = "Company: $company\n";
  $email_content .= "Email: $email\n\n";
  $email_content .= "Message:\n$message\n";

  // Build the email headers
  $email_headers = "From: $name <$email>";

  // Send the email
  mail($to, $subject, $email_content, $email_headers);
?>

When i submit the form, i get the following error message:

*This page isn’t working
If the problem continues, contact the site owner.

HTTP ERROR 405*

Any ideas on how to solve this issue?

Many thanks!


问:
Updating ticks when using blit with Matplotlib
This is my first time asking a question on this platform. Sorry if I make any mistakes.

Some context: I have a figure with three axes. The first one holds the video sequence, the second, the estimation computed by my visual odometry system, the third, the ground truth. It looks something like this:
image1
To get this, I first create the subplots:

```<code>fig, (ax_image, ax_odom, ax_gt) = plt.subplots(1, 3)

line_image = ax_image.imshow(cv_image)
ax_image.set_title("Original sequence")

line_odom, = ax_odom.plot(estimated_x, estimated_y, animated=False, color='black', marker='o', markersize=3)
ax_odom.set_title("Estimation")

line_gt, = ax_gt.plot(gt_x, gt_y, animated=False, color='red', marker='o', markersize=3)
ax_gt.set_title("Ground truth")

fig.canvas.draw()
plt.show(block=False)
</code>```

And, everytime I read an image from the bag file and its corresponding ground truth, I update the plots by calling this function.

```<code>def update_plot(fig, ax_image, line_image, ax_odom, line_odom, ax_gt, line_gt, cv_image, estimated_x, estimated_y, gt_x, gt_y):

    ax_image.imshow(cv_image)
    line_image.set_data(cv_image)
    ax_image.draw_artist(ax_image.patch)
    ax_image.draw_artist(line_image)

    line_odom.set_data(estimated_x, estimated_y)
    ax_odom.draw_artist(ax_odom.axes)
    ax_odom.draw_artist(ax_odom.patch)
    ax_odom.draw_artist(line_odom)
    ax_odom.relim()
    ax_odom.autoscale_view()

    line_gt.set_data(gt_y, gt_x)
    ax_gt.draw_artist(ax_gt.patch)
    ax_gt.draw_artist(line_gt)
    ax_gt.relim()
    ax_gt.autoscale_view()

    fig.canvas.blit(ax_image.bbox)
    fig.canvas.blit(ax_odom.clipbox)
    fig.canvas.blit(ax_gt.bbox)
    fig.canvas.flush_events()
</code>```

That works well so far. The problem comes when I try to update the axis ticks. I've read several questions/answers regarding this topic, also Matplotlib documentation but the solution evades me. Instead of replacing the ticks (xticks for the Estimation plot in this example), it gets overwritten.
image2

I avoid the calling of plt.show(), fig.canvas.draw() or plt.pause(x) because it reduces the frame rate significantly.

Any help will be appreciated.

Body:
This is my first time asking a question on this platform. Sorry if I make any mistakes.

Some context: I have a figure with three axes. The first one holds the video sequence, the second, the estimation computed by my visual odometry system, the third, the ground truth. It looks something like this:
image1
To get this, I first create the subplots:

fig, (ax_image, ax_odom, ax_gt) = plt.subplots(1, 3)

line_image = ax_image.imshow(cv_image)
ax_image.set_title("Original sequence")

line_odom, = ax_odom.plot(estimated_x, estimated_y, animated=False, color='black', marker='o', markersize=3)
ax_odom.set_title("Estimation")

line_gt, = ax_gt.plot(gt_x, gt_y, animated=False, color='red', marker='o', markersize=3)
ax_gt.set_title("Ground truth")

fig.canvas.draw()
plt.show(block=False)

And, everytime I read an image from the bag file and its corresponding ground truth, I update the plots by calling this function.

def update_plot(fig, ax_image, line_image, ax_odom, line_odom, ax_gt, line_gt, cv_image, estimated_x, estimated_y, gt_x, gt_y):

    ax_image.imshow(cv_image)
    line_image.set_data(cv_image)
    ax_image.draw_artist(ax_image.patch)
    ax_image.draw_artist(line_image)

    line_odom.set_data(estimated_x, estimated_y)
    ax_odom.draw_artist(ax_odom.axes)
    ax_odom.draw_artist(ax_odom.patch)
    ax_odom.draw_artist(line_odom)
    ax_odom.relim()
    ax_odom.autoscale_view()

    line_gt.set_data(gt_y, gt_x)
    ax_gt.draw_artist(ax_gt.patch)
    ax_gt.draw_artist(line_gt)
    ax_gt.relim()
    ax_gt.autoscale_view()

    fig.canvas.blit(ax_image.bbox)
    fig.canvas.blit(ax_odom.clipbox)
    fig.canvas.blit(ax_gt.bbox)
    fig.canvas.flush_events()

That works well so far. The problem comes when I try to update the axis ticks. I've read several questions/answers regarding this topic, also Matplotlib documentation but the solution evades me. Instead of replacing the ticks (xticks for the Estimation plot in this example), it gets overwritten.
image2

I avoid the calling of plt.show(), fig.canvas.draw() or plt.pause(x) because it reduces the frame rate significantly.

Any help will be appreciated.


问:
How to put the legend that group by color in Poly3DCollection in python
I'd like to add the legend for each rectangular box that plot by Poly3DCollection like "yellow" for "level1", "blue" for "level2"
figure with no legend

Here is the source code:

```<code>import numpy as np
from bin import Bin
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
from constants import *

class Plot:
    def data(self,o, size=(1,1,1)):
        X = [[[0, 1, 0], [0, 0, 0], [1, 0, 0], [1, 1, 0]],
            [[0, 0, 0], [0, 0, 1], [1, 0, 1], [1, 0, 0]],
            [[1, 0, 1], [1, 0, 0], [1, 1, 0], [1, 1, 1]],
            [[0, 0, 1], [0, 0, 0], [0, 1, 0], [0, 1, 1]],
            [[0, 1, 0], [0, 1, 1], [1, 1, 1], [1, 1, 0]],
            [[0, 1, 1], [0, 0, 1], [1, 0, 1], [1, 1, 1]]]
        X = np.array(X).astype(float)
        for i in range(3):
            X[:,:,i] *= size[i]
        X += np.array(o)
        return X

    def plot(self,positions,sizes=None,colors=None, **kwargs):
        if not isinstance(colors,(list,np.ndarray)): colors=["C0"]*len(positions)
        if not isinstance(sizes,(list,np.ndarray)): sizes=[(1,1,1)]*len(positions)
        g = []
        for p,s,c in zip(positions,sizes,colors):
            g.append(self.data(p, size=s) )
        return Poly3DCollection(np.concatenate(g),facecolors=np.repeat(colors,6), **kwargs)

    def draw(self,bin:Bin):
        bdx,bdy,bdz = bin.dimension
        positions:list[int] = [[0,0,0]]
        sizes = [[bdx,bdy,bdz]]
        list_colors = ["limegreen"]
        list_name = ["Box"]

        for item in bin.items:
            positions.append(item.position)
            sizes.append(item.get_dimension())
            list_colors.append(item.color)
            list_name.append(item.name)

        fig = plt.figure()
        ax = fig.gca(projection='3d')

        pc = self.plot(positions,sizes,colors=list_colors, edgecolor="k",alpha = 0.25,)
        ax.add_collection3d(pc)

        ax.set_xlim([0,MAX_DIMENSION[0]])
        ax.set_ylim([0,MAX_DIMENSION[1]])
        ax.set_zlim([0,MAX_DIMENSION[2]])
        ax.set_xlabel('X')
        ax.set_ylabel('Y')
        ax.set_zlabel('Z')
        ax.set_title(bin.size + " " + str(bin.dimension))
        plt.show()
</code>```

I tried to set the legend like a scatter or line, but it doesn't work. And I also tried to read the doc but it so hard for me to understand.

expected result some kind like this
expected result

Body:
I'd like to add the legend for each rectangular box that plot by Poly3DCollection like "yellow" for "level1", "blue" for "level2"
figure with no legend

Here is the source code:

import numpy as np
from bin import Bin
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
from constants import *

class Plot:
    def data(self,o, size=(1,1,1)):
        X = [[[0, 1, 0], [0, 0, 0], [1, 0, 0], [1, 1, 0]],
            [[0, 0, 0], [0, 0, 1], [1, 0, 1], [1, 0, 0]],
            [[1, 0, 1], [1, 0, 0], [1, 1, 0], [1, 1, 1]],
            [[0, 0, 1], [0, 0, 0], [0, 1, 0], [0, 1, 1]],
            [[0, 1, 0], [0, 1, 1], [1, 1, 1], [1, 1, 0]],
            [[0, 1, 1], [0, 0, 1], [1, 0, 1], [1, 1, 1]]]
        X = np.array(X).astype(float)
        for i in range(3):
            X[:,:,i] *= size[i]
        X += np.array(o)
        return X

    def plot(self,positions,sizes=None,colors=None, **kwargs):
        if not isinstance(colors,(list,np.ndarray)): colors=["C0"]*len(positions)
        if not isinstance(sizes,(list,np.ndarray)): sizes=[(1,1,1)]*len(positions)
        g = []
        for p,s,c in zip(positions,sizes,colors):
            g.append(self.data(p, size=s) )
        return Poly3DCollection(np.concatenate(g),facecolors=np.repeat(colors,6), **kwargs)

    def draw(self,bin:Bin):
        bdx,bdy,bdz = bin.dimension
        positions:list[int] = [[0,0,0]]
        sizes = [[bdx,bdy,bdz]]
        list_colors = ["limegreen"]
        list_name = ["Box"]

        for item in bin.items:
            positions.append(item.position)
            sizes.append(item.get_dimension())
            list_colors.append(item.color)
            list_name.append(item.name)

        fig = plt.figure()
        ax = fig.gca(projection='3d')

        pc = self.plot(positions,sizes,colors=list_colors, edgecolor="k",alpha = 0.25,)
        ax.add_collection3d(pc)

        ax.set_xlim([0,MAX_DIMENSION[0]])
        ax.set_ylim([0,MAX_DIMENSION[1]])
        ax.set_zlim([0,MAX_DIMENSION[2]])
        ax.set_xlabel('X')
        ax.set_ylabel('Y')
        ax.set_zlabel('Z')
        ax.set_title(bin.size + " " + str(bin.dimension))
        plt.show()

I tried to set the legend like a scatter or line, but it doesn't work. And I also tried to read the doc but it so hard for me to understand.

expected result some kind like this
expected result


问:
difference between graphql datastore and dynamodb items in a table in aws amplify
difference between records created using  graphql datastore  from a form (created using aws amplify UI Library) and dynamodb items created through an API and Lambda function) in a table. the problem is that when using the form Datastore automatically assigns an id but when trying to create record using dynamoDB in the lambda function you have to manually assign an ID and the data type is not int or string it's ID... and when trying to fetch the records and show them on the frontend using datastore it only get the items created using datastore or auto populated data

tried everything, i need help either being able to create record using dynamoDB with the same type of ID or get all the records using Datastore and graphql


问:
I need to override the class Magento/FunctionalTestingFramework/Util/ModuleResolver/ModuleResolverService.php
I was trying to override the Class Magento/FunctionalTestingFramework/DataTransport/Auth/WebApiAuth.php function getAdminToken() but this particular function is a static function so it can't be override so I tried overriding the class
Magento/FunctionalTestingFramework/Util/ModuleResolver/ModuleResolverService.php from where this function getAdminToken() is called so that I can call the function getAdminToken() of my custom class WebApiAuth.php.
I tried overriding the class by preference

but the class is not getting override ,I need to make change in this function

public function getAdminToken(): string rather than calling the function getAdminToken() of class
Magento\FunctionalTestingFramework\DataTransport\Auth\WebApiAuth; I want to call my custom file.

I tried using the preference

but was unable to get die inside my custom file when I am running the command in the Terminal
php -d memory_limit=-1 vendor/bin/mftf generate:tests AdminLoginSuccessfulTest, it is getting die in the core file but not in my custom override file.


问:
Wordpress Multisite Language Switcher with Alll Import plugin not working
I'm trying to use Multisite language switcher 2.5.8 with all import like so:

I'm importing a product through XML in English then I'm importing the same product's translation with the ID as a common reference. The translation should show up in the box but I see nothing. Anybody has experienced similar issues?


问:
Can't see project explorer in STM32CubeIDE
I have a little newbie problem here, I was working whit STM32CubeIDE, then (I guess I press some button or something like that) the project Explorer disappeared, currently I'm only able to open in if I open the debug perspective, If I open the C/C++ perspective the project explorer don't show up, I tried to open it by going to Windows -> Show view -> Project explorer, but when I click on it, anything happens.

This is getting frustrating because I have to switch to debug perspective every time I want to open or add a file

Any help would be very much appreciated


问:
Is it possible to get the exact pixel size of (css) zoomed text?
I have some text that is set to 17 pixels.
I then have some css setting the zoom of this text to zoom: 1.1

```<code><div class="text">This is some text</div>
.text {
  font-size: 17px;
  zoom: 1.1;
}
</code>```

Is it possible to work out exactly how big the font is in the browser? (In the 'computed' section it is still telling me it is 17px)

Or is there a calculation that will allow me to work it out?
Will the font size simply be 17 * 1.1 = 18.7px?

Body:
I have some text that is set to 17 pixels.
I then have some css setting the zoom of this text to zoom: 1.1

This is some text

.text {
  font-size: 17px;
  zoom: 1.1;
}

Is it possible to work out exactly how big the font is in the browser? (In the 'computed' section it is still telling me it is 17px)

Or is there a calculation that will allow me to work it out?
Will the font size simply be 17 * 1.1 = 18.7px?


问:
How to apply MinMaxScaler to several columns using absolute max and min values for every column (unknown)?
I have a pandas DataFrame with several columns representing quantity of water at different points in time:

```<code>df = pd.DataFrame(data = [[1, 5, 4],
                          [3, 1, 4],
                          [2, 2, 3],
                          [6, 1, 5]],
                          columns=['dep1', 'dep2', 'dep3'])
</code>```

and I want to scale it using the MinMaxScaler but with the absolute minimum and maximum of the data, without calculating them previously (as MinMaxScaler works normally).

I have tried transforming into one column:

```<code>X = df.values.reshape(-1, 1)

scaler = MinMaxScaler()
scaler.fit(X)

X_scaled = scaler.transform(X).reshape(-1, len(df.columns))
</code>```

Is there a way to perform this operation directly with MinMaxScaler?

My final aim is to include it as a step in a pipeline and currently I do not know how to.

Thanks in advance.

Body:
I have a pandas DataFrame with several columns representing quantity of water at different points in time:

df = pd.DataFrame(data = [[1, 5, 4],
                          [3, 1, 4],
                          [2, 2, 3],
                          [6, 1, 5]],
                          columns=['dep1', 'dep2', 'dep3'])

and I want to scale it using the MinMaxScaler but with the absolute minimum and maximum of the data, without calculating them previously (as MinMaxScaler works normally).

I have tried transforming into one column:

X = df.values.reshape(-1, 1)

scaler = MinMaxScaler()
scaler.fit(X)

X_scaled = scaler.transform(X).reshape(-1, len(df.columns))

Is there a way to perform this operation directly with MinMaxScaler?

My final aim is to include it as a step in a pipeline and currently I do not know how to.

Thanks in advance.


问:
Get Dynamic Windows Download Folder Path with Javascript
I would like to get the path to the windows download folder of the user. So it needs to be dynamic. I want to store it in a local variable und use it inside Adobe Acrobat Reader.

var filePath = "PATH"

I have tried the following two but unfortunately it did not work

%userprofile%/Downloads

C:\Users%username%\Downloads

This did not work either from Acrobat Reader
var filePath = '"C:\Users" & Environ("UserName") & "\Downloads"'


问:
Deployed react app on cpannel but it shows black white page
I build an node and react app that are connected with each other I have deployed both on cPanel but for some reason react app only showing blank white page with react app as title and in console I can see my custom styling but for some reason I cant able to see content
"Screenshot of React App"(https://i.stack.imgur.com/M7MuD.png)

My settings for react app
"Screenshot of react package.json file setting"(https://i.stack.imgur.com/t8dOq.png)
proxy is URL where node app is deployed


问:
Nginx close connection when the plain HTTP request is sent to HTTPS port
I want to close connection when someone try to access my app via HTTP instead of HTTPS.

Now my app returns 400:

So first question is why is status code 400 instead of 497?

Here is my config where I try to close connection for status code 400:

```<code>server {
        listen 2053 ssl http2;
        listen [::]:2053 ssl http2;

        server_name mydomain.com www.mydomain.com;

        error_page 400 @custom_error_400;

        location @custom_error_400 {
                return 444;
        }

        location / {
                proxy_pass http://localhost:5001/;

                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $host;

                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
        }

        ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;
        include /etc/letsencrypt/options-ssl-nginx.conf;
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

        access_log /var/log/nginx/custom.access.log combined_realip if=$should_log;
        error_log /var/log/nginx/custom.error.log;
}
</code>```

Nginx ignores all my config for error pages, even when I try to set error page for 497 also. Has anyone had similar problem?

Body:
I want to close connection when someone try to access my app via HTTP instead of HTTPS.

Now my app returns 400:

So first question is why is status code 400 instead of 497?

Here is my config where I try to close connection for status code 400:

server {
        listen 2053 ssl http2;
        listen [::]:2053 ssl http2;

        server_name mydomain.com www.mydomain.com;

        error_page 400 @custom_error_400;

        location @custom_error_400 {
                return 444;
        }

        location / {
                proxy_pass http://localhost:5001/;

                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $host;

                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
        }

        ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;
        include /etc/letsencrypt/options-ssl-nginx.conf;
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

        access_log /var/log/nginx/custom.access.log combined_realip if=$should_log;
        error_log /var/log/nginx/custom.error.log;
}

Nginx ignores all my config for error pages, even when I try to set error page for 497 also. Has anyone had similar problem?


问:
TypeError: Cannot set properties of undefined (setting 'name')
This TypeError

I want to set properties of undefined (setting 'name')


问:
Is there a way to use pg_dump with a query filter on the table?
I would like to export a set of INSERT commands with pg_dump. I do not want to dump the full table though. I want to filter the table for specific rows with:

SELECT * FROM table where col=4

Is there a way to pass this information to pg_dump something like:

```<code>pg_dump db_name --column-inserts --data-only --table='(SELECT * FROM table WHERE col=5)' > test.sql
</code>```

The above is a pseudo example. It does not really work. But is there such functionality like this without having to create a secondary table with the data out of that query?

Body:
I would like to export a set of INSERT commands with pg_dump. I do not want to dump the full table though. I want to filter the table for specific rows with:

SELECT * FROM table where col=4

Is there a way to pass this information to pg_dump something like:

pg_dump db_name --column-inserts --data-only --table='(SELECT * FROM table WHERE col=5)' > test.sql

The above is a pseudo example. It does not really work. But is there such functionality like this without having to create a secondary table with the data out of that query?


问:
Child entity not auto generating id in mongo db
When I try to persist the data in mongo db the child entity(departments) is not generating ObjectId.

The persisted data in mongodb, the  departmentId auto generated id is not generated automatically

```<code>@org.springframework.data.mongodb.core.mapping.Document(collection="stores")
  public class StoresEntity extends BaseEntityEntity implements java.io.Serializable {

 private static final long serialVersionUID = 1L;

@org.springframework.data.annotation.Id
private java.lang.String storeId;

@org.springframework.data.mongodb.core.mapping.Field(name ="store_name")
private java.lang.String storeName;

@org.springframework.data.mongodb.core.mapping.Field(name ="store_location")
private java.lang.String storeLocation;

private java.util.List<com.mt.mtamp.employees.entity.DepartmentsEntity> departments;

public java.lang.String getStoreId() {
    return storeId;
 }

public java.lang.String setStoreId(java.lang.String  storeId) {
    return this.storeId = storeId;
 }

public java.lang.String getStoreName() {
    return storeName;
 }

public java.lang.String setStoreName(java.lang.String  storeName) {
    return this.storeName = storeName;
 }

public java.lang.String getStoreLocation() {
    return storeLocation;
 }

public java.lang.String setStoreLocation(java.lang.String  storeLocation) {
    return this.storeLocation = storeLocation;
 }

public java.util.List<com.mt.mtamp.employees.entity.DepartmentsEntity> getDepartments() {
    return departments;
 }

public java.util.List<com.mt.mtamp.employees.entity.DepartmentsEntity> setDepartments(java.util.List<com.mt.mtamp.employees.entity.DepartmentsEntity>  departments) {
    return this.departments = departments;
 }
</code>```

}

```<code>@org.springframework.data.mongodb.core.mapping.Document(collection="departments")
 public class DepartmentsEntity extends BaseEntityEntity implements java.io.Serializable {

 private static final long serialVersionUID = 1L;

@org.springframework.data.annotation.Id
private java.lang.String departmentId;

@org.springframework.data.mongodb.core.mapping.Field(name ="department_name")
private java.lang.String departmentName;

public java.lang.String getDepartmentId() {
    return departmentId;
 }

public java.lang.String setDepartmentId(java.lang.String  departmentId) {
    return this.departmentId = departmentId;
 }

public java.lang.String getDepartmentName() {
    return departmentName;
 }

public java.lang.String setDepartmentName(java.lang.String  departmentName) {
    return this.departmentName = departmentName;
 }
</code>```

}

Body:
When I try to persist the data in mongo db the child entity(departments) is not generating ObjectId.

The persisted data in mongodb, the  departmentId auto generated id is not generated automatically

@org.springframework.data.mongodb.core.mapping.Document(collection="stores")
  public class StoresEntity extends BaseEntityEntity implements java.io.Serializable {

 private static final long serialVersionUID = 1L;

@org.springframework.data.annotation.Id
private java.lang.String storeId;

@org.springframework.data.mongodb.core.mapping.Field(name ="store_name")
private java.lang.String storeName;

@org.springframework.data.mongodb.core.mapping.Field(name ="store_location")
private java.lang.String storeLocation;

private java.util.List<com.mt.mtamp.employees.entity.DepartmentsEntity> departments;

public java.lang.String getStoreId() {
    return storeId;
 }

public java.lang.String setStoreId(java.lang.String  storeId) {
    return this.storeId = storeId;
 }

public java.lang.String getStoreName() {
    return storeName;
 }

public java.lang.String setStoreName(java.lang.String  storeName) {
    return this.storeName = storeName;
 }

public java.lang.String getStoreLocation() {
    return storeLocation;
 }

public java.lang.String setStoreLocation(java.lang.String  storeLocation) {
    return this.storeLocation = storeLocation;
 }

public java.util.List<com.mt.mtamp.employees.entity.DepartmentsEntity> getDepartments() {
    return departments;
 }

public java.util.List<com.mt.mtamp.employees.entity.DepartmentsEntity> setDepartments(java.util.List<com.mt.mtamp.employees.entity.DepartmentsEntity>  departments) {
    return this.departments = departments;
 }

}

@org.springframework.data.mongodb.core.mapping.Document(collection="departments")
 public class DepartmentsEntity extends BaseEntityEntity implements java.io.Serializable {

 private static final long serialVersionUID = 1L;

@org.springframework.data.annotation.Id
private java.lang.String departmentId;

@org.springframework.data.mongodb.core.mapping.Field(name ="department_name")
private java.lang.String departmentName;

public java.lang.String getDepartmentId() {
    return departmentId;
 }

public java.lang.String setDepartmentId(java.lang.String  departmentId) {
    return this.departmentId = departmentId;
 }

public java.lang.String getDepartmentName() {
    return departmentName;
 }

public java.lang.String setDepartmentName(java.lang.String  departmentName) {
    return this.departmentName = departmentName;
 }

}


问:
Embedding Flutter app from external source in Android app at runtime
I am trying to embed a Flutter app into an existing Android app at runtime. The Flutter app is hosted on an EC2 server and can be downloaded as a zip file from a CDN.

I have been looking at the FlutterActivity class as a potential solution, but have not been able to find any methods or properties that allow me to achieve this. Is it possible to embed a Flutter app from an external source in this way, and if so, what is the recommended approach? Any guidance or suggestions would be greatly appreciated.

I have been trying to use the FlutterActivity class to embed the Flutter app into my Android app, but have not been able to find any methods or properties that allow me to do so. I have not yet tried any other approaches, as I was hoping to use the FlutterActivity class to achieve this.

I was expecting to be able to use the FlutterActivity class to load the Flutter app from the EC2 server and display it within my Android app at runtime. However, I have not been able to find any documentation or examples that demonstrate how to do this using the FlutterActivity class.


问:
Creating graphs in for-loop stores in environment only last graph
I know this question has been asked before, but I found none of the answers where clear enough for me to understand how to solve my problem.
I am looping over several variables to create graphs. The thing is, I want to save each of the graphs in the environment and combine them using ggsave. The problem I have is that all the graphs stored in the R environment are the same and correspond to the last graph in the loop.

Here is the data I am using.
My code is the following:

```<code># DEFINING VARIABLES
varnames <- c("firstborn", "gradet0", "p_educ")

 #LOOPING OVER THEM:
 for (var in varnames) {

 var_m <- data[[paste(var,"m", sep="_")]]
 var_se <- data[[paste(var,"se", sep="_")]]
 varf <- data[[var]]

   #CREATING GRAPHS:
    plot <- ggplot(data, aes(x=var1_, y=var_m, fill=factor(varf))) +
    geom_bar(stat = "identity", color="black",
             position=position_dodge()) +
    geom_errorbar(aes(ymin=var_m-1.96*var_se, ymax=var_m+1.96*var_se), width=.2,
                  position=position_dodge(.9))   +
    theme_classic() +
    labs(x =var, y = "Predicted values") +
    scale_x_discrete(limits = c("noteen_female", "noteen_male", "teen_female",
                                "teen_male"),
                     labels = c("Female", "Male",
                                "Teen Mother", "Teen Father")) +
    scale_fill_brewer(palette="Oranges") +
    theme(legend.title = element_blank())

    # TRYING TO SAVE TO THE R ENVIRONMENT
    plot_var_name <- str_c(c("plot", var), collapse = "_")
    assign(plot_var_name, plot)

    # SAVING TO THE PC:
    ggsave(paste("graph_",var,".png",sep=""), width = 200,
           height = 100,
           units = c("mm"),)

}

# COMBINING GRAPHS:
ggarrange(plot_firstborn, plot_gradet0, plot_p_educ,
          ncol = 2, nrow = 2)
</code>```

Whilst ggsave works well, the stored graphics in R environment are all the same. I am still an R newbie, so kind help/explanation would be greatly appreciated.

Body:
I know this question has been asked before, but I found none of the answers where clear enough for me to understand how to solve my problem.
I am looping over several variables to create graphs. The thing is, I want to save each of the graphs in the environment and combine them using ggsave. The problem I have is that all the graphs stored in the R environment are the same and correspond to the last graph in the loop.

Here is the data I am using.
My code is the following:

# DEFINING VARIABLES
varnames <- c("firstborn", "gradet0", "p_educ")

 #LOOPING OVER THEM:
 for (var in varnames) {

 var_m <- data[[paste(var,"m", sep="_")]]
 var_se <- data[[paste(var,"se", sep="_")]]
 varf <- data[[var]]

   #CREATING GRAPHS:
    plot <- ggplot(data, aes(x=var1_, y=var_m, fill=factor(varf))) +
    geom_bar(stat = "identity", color="black",
             position=position_dodge()) +
    geom_errorbar(aes(ymin=var_m-1.96*var_se, ymax=var_m+1.96*var_se), width=.2,
                  position=position_dodge(.9))   +
    theme_classic() +
    labs(x =var, y = "Predicted values") +
    scale_x_discrete(limits = c("noteen_female", "noteen_male", "teen_female",
                                "teen_male"),
                     labels = c("Female", "Male",
                                "Teen Mother", "Teen Father")) +
    scale_fill_brewer(palette="Oranges") +
    theme(legend.title = element_blank())

    # TRYING TO SAVE TO THE R ENVIRONMENT
    plot_var_name <- str_c(c("plot", var), collapse = "_")
    assign(plot_var_name, plot)

    # SAVING TO THE PC:
    ggsave(paste("graph_",var,".png",sep=""), width = 200,
           height = 100,
           units = c("mm"),)

}

# COMBINING GRAPHS:
ggarrange(plot_firstborn, plot_gradet0, plot_p_educ,
          ncol = 2, nrow = 2)

Whilst ggsave works well, the stored graphics in R environment are all the same. I am still an R newbie, so kind help/explanation would be greatly appreciated.


问:
Elastic 8.5.3 is not starting
After I used elastic 8.2 successful I delete it, also the elasticsearch folder in C:\Users\me\AppData\Local\Temp, than I downloaded the current version 8.5.3 and start the bin/elasticsearch.bat. On the end I don't get the password and fingerprint and I can't reach via https://localhost:9200/ .

I'm using the current version of Java.
I restart the computer.

The console text I linked on my private page and
the log file you find here, because it is to long for this forum. (It will both open in your Browser.)

At the log is a Memory error. But I got around 22 GB free RAM.
Further there is a "exception during geoip databases update". But I think this is not important, also because I don't need the geo locations.

What could be the reason that it is not proper installing elasticsearch on my device (Windows 11)?

Title: Elastic 8.5.3 is not starting


问:
Is it possible to forbid foreign keys in different tables to reference the same row?
I have two 3 tables:

CREATE TABLE "items" (
    "key"   TEXT NOT NULL UNIQUE,
    "name_key"  TEXT,
    "base_price"    INTEGER,
    "description_key"   TEXT,
    PRIMARY KEY("key")
)
```
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE "consumable_items" (
    "key"   TEXT NOT NULL UNIQUE,
    "item_key"  TEXT NOT NULL,
    "scope" TEXT NOT NULL,
    "only_menu" BOOLEAN NOT NULL,
    PRIMARY KEY("key"),
    FOREIGN KEY("item_key") REFERENCES "items"("key")
)
</code>```

CREATE TABLE "weapons" (
    "key"   TEXT NOT NULL UNIQUE,
    "item_key"  TEXT NOT NULL,
    "name_key"  TEXT,
    "type"  TEXT,
    FOREIGN KEY("item_key") REFERENCES "items"("key"),
    FOREIGN KEY("type") REFERENCES "weapon_types"("key"),
    PRIMARY KEY("key")
)
```
<p>I have some kind of "inheritance" relationship here.</p>
<p><code>consumable_items</code> references <code>items</code> and <code>weapons</code> also references <code>items</code> for storing common properties. between all items.</p>
<p>I would like to forbid the creation of a <code>consumable_item</code> if a <code>weapon</code> already exists with the same foreign key and vice versa</p>
<p>For example:</p>
<p>If I have the following item:</p>
```INSERT INTO "main"."items" ("key", "name_key", "base_price", "description_key") VALUES ('excalibur', 'excalibur', '800000', 'excalibur');
```

EITHER consumable_items can reference excalibur OR weapons can reference it, but not both at the same time.

Is that possible with SQL(ite)?

Body:
I have two 3 tables:

CREATE TABLE "items" (
    "key"   TEXT NOT NULL UNIQUE,
    "name_key"  TEXT,
    "base_price"    INTEGER,
    "description_key"   TEXT,
    PRIMARY KEY("key")
)

CREATE TABLE "consumable_items" (
    "key"   TEXT NOT NULL UNIQUE,
    "item_key"  TEXT NOT NULL,
    "scope" TEXT NOT NULL,
    "only_menu" BOOLEAN NOT NULL,
    PRIMARY KEY("key"),
    FOREIGN KEY("item_key") REFERENCES "items"("key")
)

CREATE TABLE "weapons" (
    "key"   TEXT NOT NULL UNIQUE,
    "item_key"  TEXT NOT NULL,
    "name_key"  TEXT,
    "type"  TEXT,
    FOREIGN KEY("item_key") REFERENCES "items"("key"),
    FOREIGN KEY("type") REFERENCES "weapon_types"("key"),
    PRIMARY KEY("key")
)

I have some kind of "inheritance" relationship here.

consumable_items references items and weapons also references items for storing common properties. between all items.

I would like to forbid the creation of a consumable_item if a weapon already exists with the same foreign key and vice versa

For example:

If I have the following item:

INSERT INTO "main"."items" ("key", "name_key", "base_price", "description_key") VALUES ('excalibur', 'excalibur', '800000', 'excalibur');

EITHER consumable_items can reference excalibur OR weapons can reference it, but not both at the same time.

Is that possible with SQL(ite)?


问:
Copy-webpack-plugin [INFO] error <e> cannot locate '\**\*' in '\**\*' - Windows [closed
I have been dealing with this for several days, when I want to generate the war of a project in Windows I find this error when executing mvn clean package Error de copy-webpack-plugin [INFO] no se puede localizar '' en ''. I paste that path that the terminal gives me in the explorer and it exists.

I have tried several things but they did not work, I know that it is a problem with the paths in Windows because it is looking for a list of directories that is not working because it does not find anything and it cannot generate the copy of the files, in Linux it works and compile normally. Has anyone had the same problem and can help me with this? I am attaching some images for reference, thank you very much.

Error Terminal
Path of the webpack.config.js file]


问:
Create a BCF file from a three.js scene with an IFC file using javascript
I'm trying to create a BCF file from a three.js scene with an IFC model loaded in it. The BCF file should contain the IFC and issues created by the user. I have been looking into it but I am not really sure how to proceed.

Any help would be appreciated.

I tried finding libraries to do so and to create the file from scratch myself.


问:
Buffer jpeg in zip
basically what doesn't work is inside the for loop.
what I have to do is, for each data.id present in reportData (10 numbers if I'm not mistaken) create a Qr (qrCodeGenerator function)

the files are written, but the zip file that should contain them won't open it for me.. what am I doing wrong?

```<code>      try {
    const zip = new ZIP()
    //, ou.store_name, ou.address
    const queryCompanies = `
    SELECT id
    From orga_unita ou
    where created_at < '${dateToReport.utc().endOf('days').toISOString()}'
    and created_at >= '${dateToReport.utc().endOf('days').subtract(7, 'days').toISOString()}'
    AND scope_id = ${unitScopes.MERCHANT}
  `

    let [numCompanies] =
      (await Promise.all([
        mySQLPrisma.$queryRawUnsafe(queryCompanies),
      ])) as [
        any,
      ]

    var reportData: any = []

    numCompanies.map(async (data: any) => {
      reportData.push([
        data.id,
      ])

      for (let i = 0; i < data.id; i++) {
        var proca = await qrCodeGenerator(data.id)

        var rere = await fs.writeFile(`./crono/logo${data.id}.jpg`, rer)
        zip.addFile({ name: `logo${data.id}.jpg`, content: proca })
      }
    })

    const zipBuffer = await zip.writeToBuffer()
    await fs.writeFile(`./crono/logo.zip`, zipBuffer)

    /*
    slack.api = 'https://slack.com/api/files.upload'

    const zipBuffer = await zip.writeToBuffer()

    await client.files.upload({
      channels: 'dqwdqe',
      title: `prova`,
      file: zipBuffer,
      filetype: 'zip',
      filename: 'Registrazione.zip',
    })*/
  } catch (err) {
    console.error(err)
  }
</code>```

Title: Buffer jpeg in zip

Body:
basically what doesn't work is inside the for loop.
what I have to do is, for each data.id present in reportData (10 numbers if I'm not mistaken) create a Qr (qrCodeGenerator function)

the files are written, but the zip file that should contain them won't open it for me.. what am I doing wrong?

      try {
    const zip = new ZIP()
    //, ou.store_name, ou.address
    const queryCompanies = `
    SELECT id
    From orga_unita ou
    where created_at < '${dateToReport.utc().endOf('days').toISOString()}'
    and created_at >= '${dateToReport.utc().endOf('days').subtract(7, 'days').toISOString()}'
    AND scope_id = ${unitScopes.MERCHANT}
  `

    let [numCompanies] =
      (await Promise.all([
        mySQLPrisma.$queryRawUnsafe(queryCompanies),
      ])) as [
        any,
      ]

    var reportData: any = []

    numCompanies.map(async (data: any) => {
      reportData.push([
        data.id,
      ])

      for (let i = 0; i < data.id; i++) {
        var proca = await qrCodeGenerator(data.id)

        var rere = await fs.writeFile(`./crono/logo${data.id}.jpg`, rer)
        zip.addFile({ name: `logo${data.id}.jpg`, content: proca })
      }
    })

    const zipBuffer = await zip.writeToBuffer()
    await fs.writeFile(`./crono/logo.zip`, zipBuffer)

    /*
    slack.api = 'https://slack.com/api/files.upload'

    const zipBuffer = await zip.writeToBuffer()

    await client.files.upload({
      channels: 'dqwdqe',
      title: `prova`,
      file: zipBuffer,
      filetype: 'zip',
      filename: 'Registrazione.zip',
    })*/
  } catch (err) {
    console.error(err)
  }


问:
Chrome SameSite cookie not working for
As per my understanding, if I login to site A, the browser will store site A cookies locally.
Now, I open a new tab in the browser and visit Site B. In the Site B, I have a link to Site A.

Now, when I click on the link, I am redirected to Site A with all the cookies for Site A.
But if SameSite=Strict is set for a cookie, it should not have been passed when coming from Site B to Site A.

To test this, I created a html page with a simple href="link to site A> and opened it in the browser.

```<code><html>
<body>
<a href="https://hac-1/ui/#/dashboard">Dashboard</a>
</body>
</html>
</code>```

When I click on the Dashboard, I am redirected to hac-1 dashboard and all the cookies (including Strict SameSite) are shown in Application tab in the developer's tool.

Why chrome is not considering SameSite flag?

Also, why does browser not send cookies of Site B to Site A when I navigate from Site B to Site A using the above link ?

Title: Chrome SameSite cookie not working for <a href>

Body:
As per my understanding, if I login to site A, the browser will store site A cookies locally.
Now, I open a new tab in the browser and visit Site B. In the Site B, I have a link to Site A.

Now, when I click on the link, I am redirected to Site A with all the cookies for Site A.
But if SameSite=Strict is set for a cookie, it should not have been passed when coming from Site B to Site A.

To test this, I created a html page with a simple  and opened it in the browser.

Dashboard

When I click on the Dashboard, I am redirected to hac-1 dashboard and all the cookies (including Strict SameSite) are shown in Application tab in the developer's tool.

Why chrome is not considering SameSite flag?

Also, why does browser not send cookies of Site B to Site A when I navigate from Site B to Site A using the above link ?


问:
Print style issue occurred after chromium upgrade to 108

Description

My application could simulate a series of printable A4 standard pages by HTML, and then print them to pdf via puppeteer. Just like this:

Click to see the image

Before chromium 108, the page style was standard A4 format both in the browser tab and in the print preview.

After the browser was updated to chromium 108, the style of the page in the print preview was messed up, but it was still OK in the browser tab, and I didn't change any code !!! Just like this:

Click to see the image

Code

The html roughly looks like:

  ...
  <link rel="stylesheet" href="css/base.css" />
  <link rel="stylesheet" href="css/fancy.css" />
  <link rel="stylesheet" href="css/print.css" />
  ...

content

content

```
<p>There are 3 CSS files:</p>
<pre class="lang-css prettyprint-override"><code>base.css

/*!
 * Base CSS for pdf2htmlEX
 * Copyright 2012,2013 Lu Wang <coolwanglu@gmail.com>
 * https://github.com/coolwanglu/pdf2htmlEX/blob/master/share/LICENSE
 */

@media print {
  @page {
    margin: 0;
  }
  html {
    margin: 0;
  }
  body {
    margin: 0;
    -webkit-print-color-adjust: exact;
  }
  #sidebar {
    display: none;
  }
  #page-container {
    width: auto;
    height: auto;
    overflow: visible;
    background-color: transparent;
  }
  .d {
    display: none;
  }
}

.pf {
  position: relative;
  background-color: white;
  overflow: hidden;
  margin: 0;
  border: 0;
}

@media print {
  .pf {
    margin: 0;
    box-shadow: none;
    page-break-after: always;
    page-break-inside: avoid;
  }
  @-moz-document url-prefix() {
    .pf {
      overflow: visible;
      border: 1px solid #fff;
    }
    .pc {
      overflow: visible;
    }
  }
}
</code>```

fancy.css

/*!
 * Fancy styles for pdf2htmlEX
 * Copyright 2012,2013 Lu Wang <coolwanglu@gmail.com>
 * https://github.com/coolwanglu/pdf2htmlEX/blob/master/share/LICENSE
 */
@media screen {
  .pf {
    margin: 13px auto;
    box-shadow: 1px 1px 3px 1px #333;
    border-collapse: separate;
  }
}
```
<pre class="lang-css prettyprint-override"><code>print.css

.w0 {
    width: 8.27in;
}

.h0 {
    height: 11.69in;
}

.page {
    position: absolute;
    top: 0;
    bottom: 0;
}
</code>```

What I Want

I want to know if there is any major modification of the rendering engine in chromium 108, and how can I fix this issue to make the print style work properly back to A4 format ?

Body:
Description

My application could simulate a series of printable A4 standard pages by HTML, and then print them to pdf via puppeteer. Just like this:

Click to see the image

Before chromium 108, the page style was standard A4 format both in the browser tab and in the print preview.

After the browser was updated to chromium 108, the style of the page in the print preview was messed up, but it was still OK in the browser tab, and I didn't change any code !!! Just like this:

Click to see the image

Code

The html roughly looks like:

  ...
  <link rel="stylesheet" href="css/base.css" />
  <link rel="stylesheet" href="css/fancy.css" />
  <link rel="stylesheet" href="css/print.css" />
  ...

content

content

There are 3 CSS files:

base.css

/*!
 * Base CSS for pdf2htmlEX
 * Copyright 2012,2013 Lu Wang <coolwanglu@gmail.com>
 * https://github.com/coolwanglu/pdf2htmlEX/blob/master/share/LICENSE
 */

@media print {
  @page {
    margin: 0;
  }
  html {
    margin: 0;
  }
  body {
    margin: 0;
    -webkit-print-color-adjust: exact;
  }
  #sidebar {
    display: none;
  }
  #page-container {
    width: auto;
    height: auto;
    overflow: visible;
    background-color: transparent;
  }
  .d {
    display: none;
  }
}

.pf {
  position: relative;
  background-color: white;
  overflow: hidden;
  margin: 0;
  border: 0;
}

@media print {
  .pf {
    margin: 0;
    box-shadow: none;
    page-break-after: always;
    page-break-inside: avoid;
  }
  @-moz-document url-prefix() {
    .pf {
      overflow: visible;
      border: 1px solid #fff;
    }
    .pc {
      overflow: visible;
    }
  }
}

fancy.css

/*!
 * Fancy styles for pdf2htmlEX
 * Copyright 2012,2013 Lu Wang <coolwanglu@gmail.com>
 * https://github.com/coolwanglu/pdf2htmlEX/blob/master/share/LICENSE
 */
@media screen {
  .pf {
    margin: 13px auto;
    box-shadow: 1px 1px 3px 1px #333;
    border-collapse: separate;
  }
}

print.css

.w0 {
    width: 8.27in;
}

.h0 {
    height: 11.69in;
}

.page {
    position: absolute;
    top: 0;
    bottom: 0;
}

What I Want

I want to know if there is any major modification of the rendering engine in chromium 108, and how can I fix this issue to make the print style work properly back to A4 format ?


问:
Finding number of unread emails in Squirrelmail via JavaScript
I am trying to create a recipe for Ferdium to access an online webmail page and get notifications. The webmail works with Squirrelmail.

I need to write a JavaScript function that accesses the number of unread emails.

I tried navigating the DOM but I failed. The page consists of two frames, a sidebar and the main page. I would like to read the number from the sidebar:

```<code><frameset cols="150, *" id="fs1">
<frame src="left_main.php" name="left" frameborder="1">
<frame src="right_main.php" name="right" frameborder="1">
</frameset>
</code>```

And in left_main.php:

```<code>...
<body>
<table width="99%" cellspacing="0" cellpadding="0" border="0" align="left">
  <tbody>
    <tr>
      <td align="left">
        ...
        <a target="left" style="text-decoration:none" href="...">-</a> </tt><b><a href="..." target="right" title="INBOX" style="text-decoration:none"><font color="#770000">INBOX</font></a></b> <small>(8)</small></span><br>
        </td>
    </tr>
  </tbody>
</table>
</code>```

As you can see, there is (8) in there, but I do not know how to get this element and parse it.

Body:
I am trying to create a recipe for Ferdium to access an online webmail page and get notifications. The webmail works with Squirrelmail.

I need to write a JavaScript function that accesses the number of unread emails.

I tried navigating the DOM but I failed. The page consists of two frames, a sidebar and the main page. I would like to read the number from the sidebar:

<frameset cols="150, *" id="fs1">
<frame src="left_main.php" name="left" frameborder="1">
<frame src="right_main.php" name="right" frameborder="1">
</frameset>

And in left_main.php:

...

        ...
        - </tt>INBOX (8)

As you can see, there is (8) in there, but I do not know how to get this element and parse it.


问:
argument "" is missing, with no default when using map_dfc in R
I am trying to modify Monte Carlo code from Reproduceable Finance with R to handle withdrawals and inflation of these withdrawals.

to do so I have changed a simulation accumulate function to subtract a withdrawl amount that has been increased do to inflation prior to calling the function.

```<code> simulation_accum_withdrawls <- function(init_value, N, mean, stdev, wAmt) {
    tibble(c(init_value, 1 + rnorm(N, mean, stdev),wAmt)) %>%
    `colnames<-`("returns") %>%
    mutate(growth =
             accumulate(returns, function(x, y, wAmt) x * y - wAmt)) %>%
    select(growth)
  }
</code>```

the function is run from the following code

```<code>monte_carlo_sim <-
    map_dfc(starts, simulation_accum_withdrawls,
      N = sim_duration_months,
      mean = geo_mean_port_return,
      stdev = geo_stddev_port_return,
      wAmt = inflated_withdrawls)
</code>```

which throws off the following error.

Error in map():
ℹ In index: 1.
Caused by error in mutate():
! Problem while computing growth = accumulate(returns, function(x, y, wAmt) x * y - wAmt).
Caused by error in fn():
! argument "wAmt" is missing, with no default
Backtrace:

purrr::map_dfc(...)

purrr::accumulate(returns, function(x, y, wAmt) x * y - wAmt)

purrr:::reduce_impl(...)

fn(out, elt, ...)
Error in map(.x, .f, ...) :

The inflated_withdrawls data frame does exist and is not empty i.e. see below

```<code>str(inflated_withdrawls)
'data.frame':   38 obs. of  1 variable:
 $ wAmt: num  1805391 0 0 0 0 ...
</code>```

Any advice or insight on how to debug this would be appreciated.

Thanks

Here is an executable example per the request.

```<code>library(tidyverse)
library(highcharter)
library(tidyquant)
library(timetk)
library(broom)
library(highcharter)
library(purrr)
library(knitr)
library(readxl)

accum_inflation <- function(init_value, inflation=0.0) {
    tibble(c(init_value, 1 + inflation)) %>%
    `colnames<-`("acc_inf") %>%
    mutate(acc_inf =
             accumulate(acc_inf, function(x, y) x * y ))
}

accum_wd <- function(wAmt, acc_inf=0.0) {
     growth =  wAmt * acc_inf
}

simulation_accum_1 <- function(init_value, N, mean, stdev,inf_wd) {
    tibble(c(init_value, 1 + rnorm(N, mean, stdev), inf_wd)) %>%
    `colnames<-`("returns") %>%
    mutate(growth =
             accumulate(returns, function(x, y) x * y - inf_wd)) %>%
    select(growth)
}
  simulation_accum_withdrawls <- function(init_value, N, mean, stdev, wAmt=0) {
    tibble(c(init_value, 1 + rnorm(N, mean, stdev),wAmt)) %>%
    `colnames<-`("returns") %>%
    mutate(growth =
             accumulate(returns, function(x, y, wAmt) x * y + wAmt)) %>%
    select(growth)
  }

test_df <- data.frame(wAmt =c(100000,-180000,-180000,-180000),
                  date=seq.Date(as.Date("2024-01-01"), by = "year", length.out = 4)
)

test_df <- test_df %>% pad_by_time(date, .by = "month", .pad_value = 0)

inf_df <- rnorm(nrow(test_df),0.03/12,0.042/12)

inflated_returns <- accum_inflation(1, inf_df)
edatep1 <- ymd(edate)+months(1)
test_df<- rows_append(test_df,tibble(wAmt = 0, date = edatep1))
inflated_withdrawls <- accum_wd(test_df[1], inflated_returns)

nav=1000000
sim_duration_months = 40
total_sims = 10
geo_mean_port_return = 0.00443402454379282
geo_stddev_port_return = 0.0237813751473552
sims <- total_sims
starts <-
 rep(nav, sims) %>%
 set_names(paste("sim", 1:sims, sep = ""))

monte_carlo_sim <-
    map_dfc(starts, simulation_accum_withdrawls,
      N = sim_duration_months,
      mean = geo_mean_port_return,
      stdev = geo_stddev_port_return,
      wAmt = inflated_withdrawls)
</code>```

Body:
I am trying to modify Monte Carlo code from Reproduceable Finance with R to handle withdrawals and inflation of these withdrawals.

to do so I have changed a simulation accumulate function to subtract a withdrawl amount that has been increased do to inflation prior to calling the function.

 simulation_accum_withdrawls <- function(init_value, N, mean, stdev, wAmt) {
    tibble(c(init_value, 1 + rnorm(N, mean, stdev),wAmt)) %>%
    `colnames<-`("returns") %>%
    mutate(growth =
             accumulate(returns, function(x, y, wAmt) x * y - wAmt)) %>%
    select(growth)
  }

the function is run from the following code

monte_carlo_sim <-
    map_dfc(starts, simulation_accum_withdrawls,
      N = sim_duration_months,
      mean = geo_mean_port_return,
      stdev = geo_stddev_port_return,
      wAmt = inflated_withdrawls)

which throws off the following error.

Error in map():
ℹ In index: 1.
Caused by error in mutate():
! Problem while computing growth = accumulate(returns, function(x, y, wAmt) x * y - wAmt).
Caused by error in fn():
! argument "wAmt" is missing, with no default
Backtrace:

purrr::map_dfc(...)

purrr::accumulate(returns, function(x, y, wAmt) x * y - wAmt)

purrr:::reduce_impl(...)

fn(out, elt, ...)
Error in map(.x, .f, ...) :

The inflated_withdrawls data frame does exist and is not empty i.e. see below

str(inflated_withdrawls)
'data.frame':   38 obs. of  1 variable:
 $ wAmt: num  1805391 0 0 0 0 ...

Any advice or insight on how to debug this would be appreciated.

Thanks

Here is an executable example per the request.

library(tidyverse)
library(highcharter)
library(tidyquant)
library(timetk)
library(broom)
library(highcharter)
library(purrr)
library(knitr)
library(readxl)

accum_inflation <- function(init_value, inflation=0.0) {
    tibble(c(init_value, 1 + inflation)) %>%
    `colnames<-`("acc_inf") %>%
    mutate(acc_inf =
             accumulate(acc_inf, function(x, y) x * y ))
}

accum_wd <- function(wAmt, acc_inf=0.0) {
     growth =  wAmt * acc_inf
}

simulation_accum_1 <- function(init_value, N, mean, stdev,inf_wd) {
    tibble(c(init_value, 1 + rnorm(N, mean, stdev), inf_wd)) %>%
    `colnames<-`("returns") %>%
    mutate(growth =
             accumulate(returns, function(x, y) x * y - inf_wd)) %>%
    select(growth)
}
  simulation_accum_withdrawls <- function(init_value, N, mean, stdev, wAmt=0) {
    tibble(c(init_value, 1 + rnorm(N, mean, stdev),wAmt)) %>%
    `colnames<-`("returns") %>%
    mutate(growth =
             accumulate(returns, function(x, y, wAmt) x * y + wAmt)) %>%
    select(growth)
  }

test_df <- data.frame(wAmt =c(100000,-180000,-180000,-180000),
                  date=seq.Date(as.Date("2024-01-01"), by = "year", length.out = 4)
)

test_df <- test_df %>% pad_by_time(date, .by = "month", .pad_value = 0)

inf_df <- rnorm(nrow(test_df),0.03/12,0.042/12)

inflated_returns <- accum_inflation(1, inf_df)
edatep1 <- ymd(edate)+months(1)
test_df<- rows_append(test_df,tibble(wAmt = 0, date = edatep1))
inflated_withdrawls <- accum_wd(test_df[1], inflated_returns)

nav=1000000
sim_duration_months = 40
total_sims = 10
geo_mean_port_return = 0.00443402454379282
geo_stddev_port_return = 0.0237813751473552
sims <- total_sims
starts <-
 rep(nav, sims) %>%
 set_names(paste("sim", 1:sims, sep = ""))

monte_carlo_sim <-
    map_dfc(starts, simulation_accum_withdrawls,
      N = sim_duration_months,
      mean = geo_mean_port_return,
      stdev = geo_stddev_port_return,
      wAmt = inflated_withdrawls)


问:
Mlflow model signature in R API
Can somebody show how to specify inputs/outputs for mlflow_log_model (R API). Seems like it's model_spec param, but i'm not sure
For instance, let's take following columns:

```<code>input = c("international_plan","total_day_minutes","total_day_charge")
output="churn"

mlflow_log_model(model_glm,"churn-glm",
                 registered_model_name="churn-glm-model")
</code>```

Thank you in advance

Title: Mlflow model signature in R API

Body:
Can somebody show how to specify inputs/outputs for mlflow_log_model (R API). Seems like it's model_spec param, but i'm not sure
For instance, let's take following columns:

input = c("international_plan","total_day_minutes","total_day_charge")
output="churn"

mlflow_log_model(model_glm,"churn-glm",
                 registered_model_name="churn-glm-model")

Thank you in advance


问:
How to make a loop to get an audio (.wav) fragment in Python
If the segment length is shorter than the fragment length, no fragments are created.

If the segment length is an exact multiple of the fragment length, then there is no overlap between fragments and the number of fragments is equal to the segment length divided by the fragment length.

If the segment length is not an exact multiple of the fragment length, then the number of fragments is set to one more than the number of non-overlapping fragments which could be made from the segment. These fragments are then distributed evenly along the length of the segment, ensuring that the first and last points in the segment are included in the first and last fragments, respectively.

```<code>import wave
import audioop

wav = wave.open("piano2.wav")
print(audioop.avg(wav.readframes(wav.getnframes()), wav.getsampwidth()))
</code>```

With this I can get a fragment. How can I implement the loop?

Body:
If the segment length is shorter than the fragment length, no fragments are created.

If the segment length is an exact multiple of the fragment length, then there is no overlap between fragments and the number of fragments is equal to the segment length divided by the fragment length.

If the segment length is not an exact multiple of the fragment length, then the number of fragments is set to one more than the number of non-overlapping fragments which could be made from the segment. These fragments are then distributed evenly along the length of the segment, ensuring that the first and last points in the segment are included in the first and last fragments, respectively.

import wave
import audioop

wav = wave.open("piano2.wav")
print(audioop.avg(wav.readframes(wav.getnframes()), wav.getsampwidth()))

With this I can get a fragment. How can I implement the loop?


问:
Expected Returns in risk parity method allocation method
The HRP method of the risk allocation just takes the input of the Covariance matrix for solving the asset allocation.

How can we say or define a way to HRP that it should also allocate the weights according to some factor.

For example:

Lets say we have a very simple mean reversion factor which says TESLA stock is expected to move up.

How can we allocate the weight to TESLA considering that information.

I thought rather than passing the price return covariance matrix, i pass the expected returns covariance matrix but i'm not sure this is right way at all.


问:
How do I read an Excel Web Page?
Excel gives you the option to save as Web Page (*.html, *.html) which will convert your spreadsheet from the binary format to html.

It creates the html with the header:

```<code><html
    xmlns:v="urn:schemas-microsoft-com:vml"
    xmlns:v="urn:schemas-microsoft-com:office:office"
    xmlns:x="urn:schemas-microsoft-com:office:excel"
</code>```

A legacy third-party system being used is generating this html and saving it with the extension xls. Excel will open the file and although it gives a warning about "The file format and extension don't match" it opens the file just fine.

Currently, some VBA on on the end users personal macro workbook is reading these files and saving them to the binary Excel format.

```<code>Sub Convert()
      Const FOLDER_PATH As String = "Z:\reports\"
      Dim wb As Workbook
      Set wb = Workbooks.Open(FOLDER_PATH & "input.html.xls")
      wb.SaveAs Filename:=FOLDER_PATH & "output.xls", FileFormat:=xlExcel8
End Sub
</code>```

However, the files are now being fed through a centralised process that handles all the report feeds.

The existing process reads reports in Java using poi. However, the process fails when being sent this Excel file as it is expecting xls and not html renamed as xls.

How do I read/convert these files in Java?

Title: How do I read an Excel Web Page?

Body:
Excel gives you the option to save as Web Page (*.html, *.html) which will convert your spreadsheet from the binary format to html.

It creates the html with the header:

<html
    xmlns:v="urn:schemas-microsoft-com:vml"
    xmlns:v="urn:schemas-microsoft-com:office:office"
    xmlns:x="urn:schemas-microsoft-com:office:excel"

A legacy third-party system being used is generating this html and saving it with the extension xls. Excel will open the file and although it gives a warning about "The file format and extension don't match" it opens the file just fine.

Currently, some VBA on on the end users personal macro workbook is reading these files and saving them to the binary Excel format.

Sub Convert()
      Const FOLDER_PATH As String = "Z:\reports\"
      Dim wb As Workbook
      Set wb = Workbooks.Open(FOLDER_PATH & "input.html.xls")
      wb.SaveAs Filename:=FOLDER_PATH & "output.xls", FileFormat:=xlExcel8
End Sub

However, the files are now being fed through a centralised process that handles all the report feeds.

The existing process reads reports in Java using poi. However, the process fails when being sent this Excel file as it is expecting xls and not html renamed as xls.

How do I read/convert these files in Java?


问:
in socket.io v4.5 how to get all sockets that connect to particualr room
I try that

```<code>function sockets(io, roomName) {
     const socketIds = io.sockets.adapter.rooms.get(roomName) || new Set();
     return Array.from(socketIds).map(key => o.sockets.sockets.get(key));
}
</code>```

that seems to work, but it feels odd to use io.sockets.sockets and I feel that should be a strait way to do that

Body:
I try that

function sockets(io, roomName) {
     const socketIds = io.sockets.adapter.rooms.get(roomName) || new Set();
     return Array.from(socketIds).map(key => o.sockets.sockets.get(key));
}

that seems to work, but it feels odd to use io.sockets.sockets and I feel that should be a strait way to do that


问:
Camera gliitches when I walk on hill/slope in Unity3D
Good day,

I am making a first-person-view game. That works fine, but whenever I get on a hill/mountain etc. it starts freaking out. The player/camera starts rotating for no reason.

Note: I got some bits of code from external sources, so I don't fully comprehend every bit.

Here is the relevant code:

fpc script:

```<code>    public float turnSpeed = 4.0f;
    public float moveSpeed = 2.0f;
    public float minTurnAngle = -90.0f;
    public float maxTurnAngle = 90.0f;
    private float rotX;
    void Update()
    {
        MouseAiming();
        KeyboardMovement();
    }
    void MouseAiming()
    {
        // get the mouse inputs
        float y = Input.GetAxis("Mouse X") * turnSpeed;
        rotX += Input.GetAxis("Mouse Y") * turnSpeed;
        // clamp the vertical rotation
        rotX = Mathf.Clamp(rotX, minTurnAngle, maxTurnAngle);
        // rotate the camera
        transform.eulerAngles = new Vector3(-rotX, transform.eulerAngles.y + y, 0);
    }
    void KeyboardMovement()
    {
        Vector3 dir = new Vector3(0, 0, 0);
        dir.x = Input.GetAxis("Horizontal");
        dir.z = Input.GetAxis("Vertical");
        transform.Translate(dir * moveSpeed * Time.deltaTime);
    }
</code>```

MouseLookScript:

```<code>    private PlayerInputActions controls;
    [SerializeField] float mouseSensivity = 15f;
    private float xRotation = 0f;
    private Vector2 mouseLook;
    private Transform playerBody;

    private void Awake()
    {
        playerBody = transform.parent;
        controls = new PlayerInputActions();
        Cursor.lockState = CursorLockMode.Locked;
    }

    private void Update()
    {
        Look();
    }

    private void Look()
    {
        mouseLook = controls.Player.Look.ReadValue<Vector2>();

        float mouseX = mouseLook.x * mouseSensivity * Time.deltaTime;
        float mouseY = mouseLook.y * mouseSensivity * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);
        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector2.up, mouseX);
    }

    private void OnEnable()
    {
        controls.Enable();
    }

    private void OnDisable()
    {
        controls.Disable();
    }
</code>```

Hopefully someone will be able to help me!

Body:
Good day,

I am making a first-person-view game. That works fine, but whenever I get on a hill/mountain etc. it starts freaking out. The player/camera starts rotating for no reason.

Note: I got some bits of code from external sources, so I don't fully comprehend every bit.

Here is the relevant code:

fpc script:

    public float turnSpeed = 4.0f;
    public float moveSpeed = 2.0f;
    public float minTurnAngle = -90.0f;
    public float maxTurnAngle = 90.0f;
    private float rotX;
    void Update()
    {
        MouseAiming();
        KeyboardMovement();
    }
    void MouseAiming()
    {
        // get the mouse inputs
        float y = Input.GetAxis("Mouse X") * turnSpeed;
        rotX += Input.GetAxis("Mouse Y") * turnSpeed;
        // clamp the vertical rotation
        rotX = Mathf.Clamp(rotX, minTurnAngle, maxTurnAngle);
        // rotate the camera
        transform.eulerAngles = new Vector3(-rotX, transform.eulerAngles.y + y, 0);
    }
    void KeyboardMovement()
    {
        Vector3 dir = new Vector3(0, 0, 0);
        dir.x = Input.GetAxis("Horizontal");
        dir.z = Input.GetAxis("Vertical");
        transform.Translate(dir * moveSpeed * Time.deltaTime);
    }

MouseLookScript:

    private PlayerInputActions controls;
    [SerializeField] float mouseSensivity = 15f;
    private float xRotation = 0f;
    private Vector2 mouseLook;
    private Transform playerBody;

    private void Awake()
    {
        playerBody = transform.parent;
        controls = new PlayerInputActions();
        Cursor.lockState = CursorLockMode.Locked;
    }

    private void Update()
    {
        Look();
    }

    private void Look()
    {
        mouseLook = controls.Player.Look.ReadValue<Vector2>();

        float mouseX = mouseLook.x * mouseSensivity * Time.deltaTime;
        float mouseY = mouseLook.y * mouseSensivity * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);
        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector2.up, mouseX);
    }

    private void OnEnable()
    {
        controls.Enable();
    }

    private void OnDisable()
    {
        controls.Disable();
    }

Hopefully someone will be able to help me!


问:
How to create a child component that opens on the same page?
I have a link on an html page and I want it to open a new component on the same page when it is clicked and it's not working

the link:

```<code></code>```

```<code>            <a (click)="more(item.name)">for more details</a>
</code>```

```<code>
</code>```

The code is in TypeScript:

```<code>  more(name:string){
                  debugger
                  this.route.navigate(['/Cards/MoreDetails',name])
               }
</code>```

app-routing

```<code> {path:"cards",component:CardsComponent,children:[
    {path:"MoreDetails/:name",component:MoreDetailsComponent}
  ]},
];
</code>```

more-details-component(html) 'more' is a variable in the database

```<code><router-outlet></router-outlet>
<p>{{cardFromRoute.more}}</p>

</code>```

more-details-component(typeScript)

```<code>export class MoreDetailsComponent implements OnInit {
  cardFromRoute:any=[];

  constructor(public route:ActivatedRoute,public ser:CardService) { }

  ngOnInit(): void {
    this.route.paramMap.subscribe((c)=>{
      if(c.get("name") && this.ser.cards.find(i=>i.name== c.get("name")))
      {
        this.cardFromRoute=this.ser.cards.find(i=>i.name== c.get("name"))
      }
        })
  }

}
</code>```

cardService

```<code>export class CardService {
  cards:Array<Card>=[];
  env=environment;
  constructor(private http: HttpClient) { }

  Get():Observable<NewCard[]>{
    return this.http.get<Card[]>(this.env.URL+'/Cards');
  }
}
</code>```

Body:
I have a link on an html page and I want it to open a new component on the same page when it is clicked and it's not working

the link:

            for more details

The code is in TypeScript:

  more(name:string){
                  debugger
                  this.route.navigate(['/Cards/MoreDetails',name])
               }

app-routing

 {path:"cards",component:CardsComponent,children:[
    {path:"MoreDetails/:name",component:MoreDetailsComponent}
  ]},
];

more-details-component(html) 'more' is a variable in the database

<router-outlet></router-outlet>

{{cardFromRoute.more}}

more-details-component(typeScript)

export class MoreDetailsComponent implements OnInit {
  cardFromRoute:any=[];

  constructor(public route:ActivatedRoute,public ser:CardService) { }

  ngOnInit(): void {
    this.route.paramMap.subscribe((c)=>{
      if(c.get("name") && this.ser.cards.find(i=>i.name== c.get("name")))
      {
        this.cardFromRoute=this.ser.cards.find(i=>i.name== c.get("name"))
      }
        })
  }

}

cardService

export class CardService {
  cards:Array<Card>=[];
  env=environment;
  constructor(private http: HttpClient) { }

  Get():Observable<NewCard[]>{
    return this.http.get<Card[]>(this.env.URL+'/Cards');
  }
}


问:
Google Pay Angular: Integration type Direct or Gateway?
This is the npm-package "Google Pay Angular button". The integration is extremely simple, just copying a few lines as shown in the linked npm read-me. To deploy it to a production environment, you need to enable your website in the Google Pay console.

There, you need to specify whether the integration type is Gateway or Direct. I would say it is Direct since we do not use one of their supported Payment Service Providers. But on the other hand, no matter where I read, Direct is not recommended and requires a massive amount of additional work, for example:

If completing a DIRECT tokenizationSpecification type integration, you must annually rotate your public encryption key through the Google Pay Developer Profile and provide PCI Attestation to Google. PCI Attestation can be submitted by a third-party or Qualified Security Assessor certified by the PCI Security Standards Council, and approved by an Approved Vendor or Qualified Assessor.

This makes me wonder if the integration type really is Direct, since we do not store (or even receive) any financial info of the users... So this whole PCI Attestation and encryption stuff does not seem to make sense.

So which integration type is it?


问:
Flutter - Skia strange error on text overflow parameter
Skia logs a strange error on the Text overflow parameter. When I commented out the overflow: TextOverflow.ellipsis, the error disappeared.

Here's my code:

```<code>Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8.0),
            child: Text(
              blogData.title ?? '',
              style: AppTextStyle.cardTitleStyle,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
</code>```

Here's the log:

```<code>D/skia    (14184): ASSERT: 143.863403 != 151.829376
</code>```

Body:
Skia logs a strange error on the Text overflow parameter. When I commented out the overflow: TextOverflow.ellipsis, the error disappeared.

Here's my code:

Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8.0),
            child: Text(
              blogData.title ?? '',
              style: AppTextStyle.cardTitleStyle,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),

Here's the log:

D/skia    (14184): ASSERT: 143.863403 != 151.829376


问:
How to avoid the React Datepicker to close when clicking outside
I'm using the react-datepicker component on my application (https://www.npmjs.com/package/react-datepicker).

I want to close the datepicker calendar only when I click on a certain element that I created on the surrounding of the component, but the default behavior of the datepicker is to close when I click in any place outside him.

How can I do this? I tried this:

```<code><ReactDatePicker selected={startDate}
  startOpen
  shouldCloseOnSelect={false}
  withPortal
  onClickOutside={(e: any)=> { e.preventDefault(); e.stopPropagation(); }} />
</code>```

But it didn't worked.

Body:
I'm using the react-datepicker component on my application (https://www.npmjs.com/package/react-datepicker).

I want to close the datepicker calendar only when I click on a certain element that I created on the surrounding of the component, but the default behavior of the datepicker is to close when I click in any place outside him.

How can I do this? I tried this:

<ReactDatePicker selected={startDate}
  startOpen
  shouldCloseOnSelect={false}
  withPortal
  onClickOutside={(e: any)=> { e.preventDefault(); e.stopPropagation(); }} />

But it didn't worked.


问:
Angular: Issue with cdk-virtual-scroll-viewport lazyload data on scroll with variable item size
Working on infinite scroll with cdk-virtual-scroll-viewport and variable item height and At the end of list it will fetch next batch of data from api.

```<code><cdk-virtual-scroll-viewport itemSize="400" (scrolledIndexChange)="onViewerScroll($event)>
     <div *cdkVirtualFor="let data of dataList ; let i = index">
      <app-card [data]="data"></app-card> // This is of variable height from min 100px to atleast 500px
    </div>
</cdk-virtual-scroll-viewport>
</code>```

Due to variable height not able to trigger scrolledIndexChange properly. large space is visible at the end of list before new data is fetched.

Tried with autosize, list displays properly but its not triggers scrolledIndexChange which im using for fetching data.

```<code><cdk-virtual-scroll-viewport autosize>
</code>```

Is there any way I can resolve this issue.

Body:
Working on infinite scroll with cdk-virtual-scroll-viewport and variable item height and At the end of list it will fetch next batch of data from api.

<cdk-virtual-scroll-viewport itemSize="400" (scrolledIndexChange)="onViewerScroll($event)>

      <app-card [data]="data"></app-card> // This is of variable height from min 100px to atleast 500px

</cdk-virtual-scroll-viewport>

Due to variable height not able to trigger scrolledIndexChange properly. large space is visible at the end of list before new data is fetched.

Tried with autosize, list displays properly but its not triggers scrolledIndexChange which im using for fetching data.

<cdk-virtual-scroll-viewport autosize>

Is there any way I can resolve this issue.