问:
Android app icon doesn't show after adding aar to project
I converted an app to aar (com.aar.lib) and added it to my main project (com.main.app). At first there were 2 icons shown on the phone but after some changes in manifest both are gone! I managed to get only one icon at some points and copied that working manifest as a backup until I completely figure out the problem which I didn't succeed. The strange thing was that using the backup manifest didn't work after I copied!

I tried these but no luck:

regenerating icons

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

removing label from activity

Here is my merged manifest:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.main.app"
    android:versionCode="100320"
    android:versionName="1.3.2" >

    <uses-sdk
        android:minSdkVersion="21"
        android:targetSdkVersion="31" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />

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

    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera.autofocus"
        android:required="false" /> <!-- https://developer.android.com/about/versions/11/privacy/package-visibility -->
    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />

    <permission
        android:name="com.main.app.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.main.app.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION" />

    <application
        android:name="com.main.app.MyApplication"
        android:allowBackup="true"
        android:appComponentFactory="androidx.core.app.CoreComponentFactory"
        android:debuggable="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:testOnly="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.main.app.myactivity1"
            android:exported="false" >
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>

        <activity
            android:name="com.main.app.MainActivity"
            android:exported="true"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <activity
            android:name="com.main.app.SettingsActivity"
            android:label="@string/title_activity_settings"
            android:parentActivityName="com.main.app.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.main.app.MainActivity" />
        </activity>

        <service
            android:name="com.main.app.service.Tun2HttpVpnService"
            android:exported="true"
            android:permission="android.permission.BIND_VPN_SERVICE" >
            <intent-filter>
                <action android:name="android.net.VpnService" />
            </intent-filter>
        </service>
        <service
            android:name="com.main.app.V2rayCustomVpnService"
            android:exported="true"
            android:permission="android.permission.BIND_VPN_SERVICE" >
            <intent-filter>
                <action android:name="android.net.VpnService" />
            </intent-filter>
        </service>

        <receiver
            android:name="com.main.app.receiver.BootReceiver"
            android:exported="true"
            android:label="@string/app_name" >
            <intent-filter android:priority="999" >
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <activity
            android:name="com.aar.lib.ui.ServerActivity"
            android:exported="false"
            android:windowSoftInputMode="stateUnchanged" />
        <activity
            android:name="com.aar.lib.ui.ServerCustomConfigActivity"
            android:exported="false"
            android:windowSoftInputMode="stateUnchanged" />
        <activity
            android:name="com.aar.lib.ui.SettingsActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.PerAppProxyActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.ScannerActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.LogcatActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.RoutingSettingsActivity"
            android:exported="false"
            android:windowSoftInputMode="stateUnchanged" />
        <activity
            android:name="com.aar.lib.ui.SubSettingActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.UserAssetActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.SubEditActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.ScScannerActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.ScSwitchActivity"
            android:excludeFromRecents="true"
            android:exported="false"
            android:process=":RunSoLibV2RayDaemon"
            android:theme="@style/AppTheme.NoActionBar.Translucent" />
        <activity
            android:name="com.aar.lib.ui.UrlSchemeActivity"
            android:exported="true" >
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="text/plain" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.BROWSABLE" />
                <category android:name="android.intent.category.DEFAULT" />

                <data
                    android:host="install-config"
                    android:scheme="v2rayng" />
            </intent-filter>
        </activity>

        <service
            android:name="com.aar.lib.service.V2RayVpnService"
            android:enabled="true"
            android:exported="false"
            android:label="@string/app_name"
            android:permission="android.permission.BIND_VPN_SERVICE"
            android:process=":RunSoLibV2RayDaemon" >
            <intent-filter>
                <action android:name="android.net.VpnService" />
            </intent-filter>

            <meta-data
                android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
                android:value="true" />
        </service>
        <service
            android:name="com.aar.lib.service.V2RayProxyOnlyService"
            android:exported="false"
            android:label="@string/app_name"
            android:process=":RunSoLibV2RayDaemon" >
        </service>
        <service
            android:name="com.aar.lib.service.V2RayTestService"
            android:exported="false"
            android:process=":RunSoLibV2RayDaemon" >
        </service>

        <receiver
            android:name="com.aar.lib.receiver.WidgetProvider"
            android:exported="true"
            android:process=":RunSoLibV2RayDaemon" >
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/app_widget_provider" />

            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <action android:name="com.aar.lib.action.widget.click" />
                <action android:name="com.aar.lib.action.activity" />
            </intent-filter>
        </receiver>

        <service
            android:name="com.aar.lib.service.QSTileService"
            android:exported="true"
            android:icon="@drawable/ic_stat_name"
            android:label="@string/app_tile_name"
            android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"
            android:process=":RunSoLibV2RayDaemon" >
            <intent-filter>
                <action android:name="android.service.quicksettings.action.QS_TILE" />
            </intent-filter>
        </service> <!-- =====================Tasker===================== -->
        <activity
            android:name="com.aar.lib.ui.TaskerActivity"
            android:exported="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="com.twofortyfouram.locale.intent.action.EDIT_SETTING" />
            </intent-filter>
        </activity>

        <receiver
            android:name="com.aar.lib.receiver.TaskerReceiver"
            android:exported="true"
            android:process=":RunSoLibV2RayDaemon" >
            <intent-filter>
                <action android:name="com.twofortyfouram.locale.intent.action.FIRE_SETTING" />
            </intent-filter>
        </receiver>

        <uses-library
            android:name="androidx.window.extensions"
            android:required="false" />
        <uses-library
            android:name="androidx.window.sidecar"
            android:required="false" />
    </application>

</manifest>
</code>```

Body:
I converted an app to aar (com.aar.lib) and added it to my main project (com.main.app). At first there were 2 icons shown on the phone but after some changes in manifest both are gone! I managed to get only one icon at some points and copied that working manifest as a backup until I completely figure out the problem which I didn't succeed. The strange thing was that using the backup manifest didn't work after I copied!

I tried these but no luck:

regenerating icons

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

removing label from activity

Here is my merged manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.main.app"
    android:versionCode="100320"
    android:versionName="1.3.2" >

    <uses-sdk
        android:minSdkVersion="21"
        android:targetSdkVersion="31" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />

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

    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera.autofocus"
        android:required="false" />
    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />

    <permission
        android:name="com.main.app.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.main.app.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION" />

    <application
        android:name="com.main.app.MyApplication"
        android:allowBackup="true"
        android:appComponentFactory="androidx.core.app.CoreComponentFactory"
        android:debuggable="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:testOnly="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.main.app.myactivity1"
            android:exported="false" >
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>

        <activity
            android:name="com.main.app.MainActivity"
            android:exported="true"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <activity
            android:name="com.main.app.SettingsActivity"
            android:label="@string/title_activity_settings"
            android:parentActivityName="com.main.app.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.main.app.MainActivity" />
        </activity>

        <service
            android:name="com.main.app.service.Tun2HttpVpnService"
            android:exported="true"
            android:permission="android.permission.BIND_VPN_SERVICE" >
            <intent-filter>
                <action android:name="android.net.VpnService" />
            </intent-filter>
        </service>
        <service
            android:name="com.main.app.V2rayCustomVpnService"
            android:exported="true"
            android:permission="android.permission.BIND_VPN_SERVICE" >
            <intent-filter>
                <action android:name="android.net.VpnService" />
            </intent-filter>
        </service>

        <receiver
            android:name="com.main.app.receiver.BootReceiver"
            android:exported="true"
            android:label="@string/app_name" >
            <intent-filter android:priority="999" >
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <activity
            android:name="com.aar.lib.ui.ServerActivity"
            android:exported="false"
            android:windowSoftInputMode="stateUnchanged" />
        <activity
            android:name="com.aar.lib.ui.ServerCustomConfigActivity"
            android:exported="false"
            android:windowSoftInputMode="stateUnchanged" />
        <activity
            android:name="com.aar.lib.ui.SettingsActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.PerAppProxyActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.ScannerActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.LogcatActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.RoutingSettingsActivity"
            android:exported="false"
            android:windowSoftInputMode="stateUnchanged" />
        <activity
            android:name="com.aar.lib.ui.SubSettingActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.UserAssetActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.SubEditActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.ScScannerActivity"
            android:exported="false" />
        <activity
            android:name="com.aar.lib.ui.ScSwitchActivity"
            android:excludeFromRecents="true"
            android:exported="false"
            android:process=":RunSoLibV2RayDaemon"
            android:theme="@style/AppTheme.NoActionBar.Translucent" />
        <activity
            android:name="com.aar.lib.ui.UrlSchemeActivity"
            android:exported="true" >
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="text/plain" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.BROWSABLE" />
                <category android:name="android.intent.category.DEFAULT" />

                <data
                    android:host="install-config"
                    android:scheme="v2rayng" />
            </intent-filter>
        </activity>

        <service
            android:name="com.aar.lib.service.V2RayVpnService"
            android:enabled="true"
            android:exported="false"
            android:label="@string/app_name"
            android:permission="android.permission.BIND_VPN_SERVICE"
            android:process=":RunSoLibV2RayDaemon" >
            <intent-filter>
                <action android:name="android.net.VpnService" />
            </intent-filter>

            <meta-data
                android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
                android:value="true" />
        </service>
        <service
            android:name="com.aar.lib.service.V2RayProxyOnlyService"
            android:exported="false"
            android:label="@string/app_name"
            android:process=":RunSoLibV2RayDaemon" >
        </service>
        <service
            android:name="com.aar.lib.service.V2RayTestService"
            android:exported="false"
            android:process=":RunSoLibV2RayDaemon" >
        </service>

        <receiver
            android:name="com.aar.lib.receiver.WidgetProvider"
            android:exported="true"
            android:process=":RunSoLibV2RayDaemon" >
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/app_widget_provider" />

            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <action android:name="com.aar.lib.action.widget.click" />
                <action android:name="com.aar.lib.action.activity" />
            </intent-filter>
        </receiver>

        <service
            android:name="com.aar.lib.service.QSTileService"
            android:exported="true"
            android:icon="@drawable/ic_stat_name"
            android:label="@string/app_tile_name"
            android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"
            android:process=":RunSoLibV2RayDaemon" >
            <intent-filter>
                <action android:name="android.service.quicksettings.action.QS_TILE" />
            </intent-filter>
        </service>
        <activity
            android:name="com.aar.lib.ui.TaskerActivity"
            android:exported="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="com.twofortyfouram.locale.intent.action.EDIT_SETTING" />
            </intent-filter>
        </activity>

        <receiver
            android:name="com.aar.lib.receiver.TaskerReceiver"
            android:exported="true"
            android:process=":RunSoLibV2RayDaemon" >
            <intent-filter>
                <action android:name="com.twofortyfouram.locale.intent.action.FIRE_SETTING" />
            </intent-filter>
        </receiver>

        <uses-library
            android:name="androidx.window.extensions"
            android:required="false" />
        <uses-library
            android:name="androidx.window.sidecar"
            android:required="false" />
    </application>

</manifest>


来源: stackexchange

问:
Urlfetch with OAuth2 on same domain with Apps Script
I have this situation :

2 accounts on the same domain

Each account have the two sames Apps Scripts functions (basically: fetch and doGet)

function doGet() is deployed as Web App, access only for domain

Problem: I can only fetch the function doGet() from the same user

I did a plan to understand easier:

test_doGet:

```<code>function doGet(e) {

  var output = ContentService.createTextOutput(JSON.stringify({"code": 200, "data": "aaaa"})).setMimeType(ContentService.MimeType.JSON);
  return output;

}
//deployed as Web App, only domain to access
</code>```

test_fetch:

```<code>function fetch() {

  let options = {
    muteHttpExceptions: true,
    method: 'GET',
    headers: {
      Authorization: `Bearer ${ScriptApp.getOAuthToken()}`
    }
  };
  //DEPLOYMENT_ID is changing if we fetch test_doGet() from USER 1 or USER 2
  var url = "https://script.google.com/a/macros/<DOMAIN>/s/<DEPLOYMENT_ID>/exec";
  var r = UrlFetchApp.fetch(url, options);
  Logger.log(r.getContentText()); //return error if test_doGet() from different user
}
</code>```

Note: if i'm logged into user 1, and I enter manually the URL in the browser of test_doGet() from User 2, it's working fine!

What am I doing wrong?

ContentLicense: CC BY-SA 4.0

Body:
I have this situation :

2 accounts on the same domain

Each account have the two sames Apps Scripts functions (basically: fetch and doGet)

function doGet() is deployed as Web App, access only for domain

Problem: I can only fetch the function doGet() from the same user

I did a plan to understand easier:

test_doGet:

function doGet(e) {

  var output = ContentService.createTextOutput(JSON.stringify({"code": 200, "data": "aaaa"})).setMimeType(ContentService.MimeType.JSON);
  return output;

}
//deployed as Web App, only domain to access

test_fetch:

function fetch() {

  let options = {
    muteHttpExceptions: true,
    method: 'GET',
    headers: {
      Authorization: `Bearer ${ScriptApp.getOAuthToken()}`
    }
  };
  //DEPLOYMENT_ID is changing if we fetch test_doGet() from USER 1 or USER 2
  var url = "https://script.google.com/a/macros/<DOMAIN>/s/<DEPLOYMENT_ID>/exec";
  var r = UrlFetchApp.fetch(url, options);
  Logger.log(r.getContentText()); //return error if test_doGet() from different user
}

Note: if i'm logged into user 1, and I enter manually the URL in the browser of test_doGet() from User 2, it's working fine!

What am I doing wrong?


问:
How to confine grid for kriging to shapefile or polygon boundaries? Help needed
I'm working on creating a grid for kriging in R. I am trying to limit my prediction grid to the water, and not include anything outside of it. I have a shape file for the water shoreline. I've only been able to create a convex shape from my data points, and grid within it.</p>
```<code>  xgrid=seq(min(fXloc),max(fXloc),length=100),
  ygrid=seq(min(fYloc),max(fYloc),length=100),
  cbind(
    fXloc[fsite.chull],
    fYloc[fsite.chull]))
names(fsite.grid)=c("fXloc","fYloc")
coordinates(fsite.grid)=c("fXloc","fYloc")
fsite.grid = as(fsite.grid, "SpatialPixels")

plot(fYloc~fXloc,cex=1.2,pch=20,col=2)
points(data.frame(fsite.grid)$fXloc,data.frame(fsite.grid)$fYloc,pch="+")```

[![Creates a grid based on a convex shape.](https://i.stack.imgur.com/5cs76.png)](https://i.stack.imgur.com/5cs76.png)

```shp <- readOGR....
shp <- spTransform(shp,"+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
shp_fortified <- tidy(shp)
data <- as.data.frame(Data)

ggplot() +
  geom_polygon(data = shp_fortified, aes( x = long, y = lat, group = group), fill="#69b3a2", color="white") +
  theme_void() +
  geom_point(data=data, aes(x=fXloc, y = fYloc), color="red", linewidth=.2, alpha=.2) ```

[![I'd like to restrict this grid to just the green polygon shown here (shp)](https://i.stack.imgur.com/Jpg7R.png)](https://i.stack.imgur.com/Jpg7R.png)

I've searched all over online and can't find a solution!

</code>```

Body:
I'm working on creating a grid for kriging in R. I am trying to limit my prediction grid to the water, and not include anything outside of it. I have a shape file for the water shoreline. I've only been able to create a convex shape from my data points, and grid within it.

  xgrid=seq(min(fXloc),max(fXloc),length=100),
  ygrid=seq(min(fYloc),max(fYloc),length=100),
  cbind(
    fXloc[fsite.chull],
    fYloc[fsite.chull]))
names(fsite.grid)=c("fXloc","fYloc")
coordinates(fsite.grid)=c("fXloc","fYloc")
fsite.grid = as(fsite.grid, "SpatialPixels")

plot(fYloc~fXloc,cex=1.2,pch=20,col=2)
points(data.frame(fsite.grid)$fXloc,data.frame(fsite.grid)$fYloc,pch="+")```

[![Creates a grid based on a convex shape.](https://i.stack.imgur.com/5cs76.png)](https://i.stack.imgur.com/5cs76.png)

```shp <- readOGR....
shp <- spTransform(shp,"+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
shp_fortified <- tidy(shp)
data <- as.data.frame(Data)

ggplot() +
  geom_polygon(data = shp_fortified, aes( x = long, y = lat, group = group), fill="#69b3a2", color="white") +
  theme_void() +
  geom_point(data=data, aes(x=fXloc, y = fYloc), color="red", linewidth=.2, alpha=.2) ```

[![I'd like to restrict this grid to just the green polygon shown here (shp)](https://i.stack.imgur.com/Jpg7R.png)](https://i.stack.imgur.com/Jpg7R.png)

I've searched all over online and can't find a solution!


问:
Testing `(?=\d)\w(?=\d)` on `123abc456`
I was testing the regex (?=\d)\w(?=\d) on the string 123abc456. My expectation was that the positive lookahead (?=\d) should match 1 and discard it ( since lookaheads are zero length assertions) and then \w should match2 and the second positive look ahead should just match3 and discard it. Thus, we have an overall match of just 2.

However, pythex yields the match as 12 and 45 . Where could I be going wrong? Thanks!

Title: Testing `(?=\d)\w(?=\d)` on `123abc456`


问:
Vaadin 14 async update to component send during refresh
i want to make update in my component after getting event which can be executed during refreshing the page so component can be detached. So the problem is that when i'm using

```<code>comp.getUI().get().access(() -> makeAction());
</code>```

my component can by detached because of reloading the page with PreserveOnRefresh annotation so it throw a error that UI is detached. But after reloading ends then component will be attached again and i would like to get result of the view which should be after firing makeAction function. So my question is what is the best way to make async updates which can by fired during when component is detached but will be attached again.

I made something like that:

```<code>public static void doCommandWhenCompUIAccessIsAvailable(Component c, final Command command){
    if(c.getUI().isPresent() && c.isAttached()){
        c.getUI().get().access(command);
    }else{
        c.addAttachListener(evt -> {
            evt.getUI().access(command);
            evt.unregisterListener();
        });
    }
}
</code>```

but i'm getting error because of attach listener functionality like the one from this thread.

I'm using Vaadin 14.8.14.

Body:
i want to make update in my component after getting event which can be executed during refreshing the page so component can be detached. So the problem is that when i'm using

comp.getUI().get().access(() -> makeAction());

my component can by detached because of reloading the page with PreserveOnRefresh annotation so it throw a error that UI is detached. But after reloading ends then component will be attached again and i would like to get result of the view which should be after firing makeAction function. So my question is what is the best way to make async updates which can by fired during when component is detached but will be attached again.

I made something like that:

public static void doCommandWhenCompUIAccessIsAvailable(Component c, final Command command){
    if(c.getUI().isPresent() && c.isAttached()){
        c.getUI().get().access(command);
    }else{
        c.addAttachListener(evt -> {
            evt.getUI().access(command);
            evt.unregisterListener();
        });
    }
}

but i'm getting error because of attach listener functionality like the one from this thread.

I'm using Vaadin 14.8.14.


问:
How do I extend StackProps in cdk using Java?
I was trying to implement something similar to this example.

 public class StackUnderTestProps extends StackProps {
     private Architecture architecture;
     public Architecture getArchitecture() {
         return this.architecture;
     }
     public StackUnderTestProps architecture(Architecture architecture) {
         this.architecture = architecture;
         return this;
     }
 }
```

I get an error with the extends because StackProps is an interface not a class. I am unable to find any examples extending StackProps using Java. Not quite sure how to do it considering that StackProps proxy is a final class. Thoughts?

Body:
I was trying to implement something similar to this example.

 public class StackUnderTestProps extends StackProps {
     private Architecture architecture;
     public Architecture getArchitecture() {
         return this.architecture;
     }
     public StackUnderTestProps architecture(Architecture architecture) {
         this.architecture = architecture;
         return this;
     }
 }

I get an error with the extends because StackProps is an interface not a class. I am unable to find any examples extending StackProps using Java. Not quite sure how to do it considering that StackProps proxy is a final class. Thoughts?


问:
VBA Dir function with username and password
I'm trying to use the Dir function in VBA. Something like

```<code>file = Dir("\\pca410\c$\Automation\CoaqLog\")
</code>```

The problem is the folder that I'm trying to access is protected with username and password. I can manually access the folder by input username and password in the prompt window. Is there a way that I can include those information with the Dir function? Searched everywhere with no luck. Thank you.

Online search with no luck

Body:
I'm trying to use the Dir function in VBA. Something like

file = Dir("\\pca410\c$\Automation\CoaqLog\")

The problem is the folder that I'm trying to access is protected with username and password. I can manually access the folder by input username and password in the prompt window. Is there a way that I can include those information with the Dir function? Searched everywhere with no luck. Thank you.

Online search with no luck


问:
aws cloudformation apigatwayv2 leads to different links depend on the stage
I am trying to create an AWS apigateway v2 with the stages dev and production that both lead to different ec2 instances using the URL:Port. But it is giving an error with the routekey. i cant figure out why it is not creating the apigateway, i follwed the manal steps and tried converting it to cloudformation but it is not accepting it.</p>
```<code>AWSTemplateFormatVersion: '2010-09-09'
Resources:
  MyApi:
    Type: AWS::ApiGatewayV2::Api
    Properties:
      Name: MyApi
      ProtocolType: HTTP

  MyApiStage:
    Type: AWS::ApiGatewayV2::Stage
    Properties:
      StageName: dev
      Description: Development stage for MyApi
      DeploymentId: !Ref MyApiDeployment
      ApiId: !Ref MyApi

  MyApiProdStage:
    Type: AWS::ApiGatewayV2::Stage
    Properties:
      StageName: production
      Description: Production stage for MyApi
      DeploymentId: !Ref MyApiProdDeployment
      ApiId: !Ref MyApi

  MyApiDeployment:
    Type: AWS::ApiGatewayV2::Deployment
    Properties:
      Description: Deployment for MyApi stage
      StageName: dev
      ApiId: !Ref MyApi

  MyApiProdDeployment:
    Type: AWS::ApiGatewayV2::Deployment
    Properties:
      Description: Deployment for MyApi production stage
      StageName: production
      ApiId: !Ref MyApi

  MyApiRoute:
    Type: AWS::ApiGatewayV2::Route
    Properties:
      ApiId: !Ref MyApi
      RouteKey: '/{proxy+}'
      Target:
        Type: HTTP
        Integration:
          Type: HTTP_PROXY
          Uri: http://10.128.12.8:8080
          IntegrationHttpMethod: ANY

  MyApiProdRoute:
    Type: AWS::ApiGatewayV2::Route
    Properties:
      ApiId: !Ref MyApi
      RouteKey: '/{proxy+}'
      Target:
        Type: HTTP
        Integration:
          Type: HTTP_PROXY
          Uri: http://10.128.12.9:8080
          IntegrationHttpMethod: ANY
```
</code>```

Body:
I am trying to create an AWS apigateway v2 with the stages dev and production that both lead to different ec2 instances using the URL:Port. But it is giving an error with the routekey. i cant figure out why it is not creating the apigateway, i follwed the manal steps and tried converting it to cloudformation but it is not accepting it.

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  MyApi:
    Type: AWS::ApiGatewayV2::Api
    Properties:
      Name: MyApi
      ProtocolType: HTTP

  MyApiStage:
    Type: AWS::ApiGatewayV2::Stage
    Properties:
      StageName: dev
      Description: Development stage for MyApi
      DeploymentId: !Ref MyApiDeployment
      ApiId: !Ref MyApi

  MyApiProdStage:
    Type: AWS::ApiGatewayV2::Stage
    Properties:
      StageName: production
      Description: Production stage for MyApi
      DeploymentId: !Ref MyApiProdDeployment
      ApiId: !Ref MyApi

  MyApiDeployment:
    Type: AWS::ApiGatewayV2::Deployment
    Properties:
      Description: Deployment for MyApi stage
      StageName: dev
      ApiId: !Ref MyApi

  MyApiProdDeployment:
    Type: AWS::ApiGatewayV2::Deployment
    Properties:
      Description: Deployment for MyApi production stage
      StageName: production
      ApiId: !Ref MyApi

  MyApiRoute:
    Type: AWS::ApiGatewayV2::Route
    Properties:
      ApiId: !Ref MyApi
      RouteKey: '/{proxy+}'
      Target:
        Type: HTTP
        Integration:
          Type: HTTP_PROXY
          Uri: http://10.128.12.8:8080
          IntegrationHttpMethod: ANY

  MyApiProdRoute:
    Type: AWS::ApiGatewayV2::Route
    Properties:
      ApiId: !Ref MyApi
      RouteKey: '/{proxy+}'
      Target:
        Type: HTTP
        Integration:
          Type: HTTP_PROXY
          Uri: http://10.128.12.9:8080
          IntegrationHttpMethod: ANY
```


问:
Continuously hold a button CGEvent
This question is a follow up from a very old post:

CGEventPost - hold a key (shift)

I am building a SwiftUI virtual keyboard. Like a real keyboard, I have UIButtons that resemble the hardware buttons ( key a, s, d, etc ) which the user can click with their mouse. The user can also toggle to keep a button pressed.

I can send keyDown events using a function below, but an unable to keep a keyboard key held down. Inferring that my users want to hold every button until released, how would I send a CGEvent that would tell the macOS that the key with keyCode == a is being held by the user?

```<code>private func pressButton(_ keyCode: UInt16) {
    // create a key down event
    let eventDown = CGEvent(keyboardEventSource: nil, virtualKey: keyCode, keyDown: true)
    // post the key down event
    eventDown?.post(tap: .cghidEventTap)
}
</code>```

I tried intentionally only setting the keyDown event without the keyUp event ( as seen in the above function ), but I get an equivalent of a button press as opposed to hold. I also tried to use timers to fire the pressButton method periodically to keep sending button down events, but ran into the issue of "the events are being sent too fast or too slow", in comparison what would happen if i were to hold that specific button on my keyboard.

A useful thread: Simulate keypress using Swift

Title: Continuously hold a button CGEvent

Body:
This question is a follow up from a very old post:

CGEventPost - hold a key (shift)

I am building a SwiftUI virtual keyboard. Like a real keyboard, I have UIButtons that resemble the hardware buttons ( key a, s, d, etc ) which the user can click with their mouse. The user can also toggle to keep a button pressed.

I can send keyDown events using a function below, but an unable to keep a keyboard key held down. Inferring that my users want to hold every button until released, how would I send a CGEvent that would tell the macOS that the key with keyCode == a is being held by the user?

private func pressButton(_ keyCode: UInt16) {
    // create a key down event
    let eventDown = CGEvent(keyboardEventSource: nil, virtualKey: keyCode, keyDown: true)
    // post the key down event
    eventDown?.post(tap: .cghidEventTap)
}

I tried intentionally only setting the keyDown event without the keyUp event ( as seen in the above function ), but I get an equivalent of a button press as opposed to hold. I also tried to use timers to fire the pressButton method periodically to keep sending button down events, but ran into the issue of "the events are being sent too fast or too slow", in comparison what would happen if i were to hold that specific button on my keyboard.

A useful thread: Simulate keypress using Swift


问:
python socket package [WinError 10022] , invalid argument was supplied
```<code>import socket
from _thread import *    #setting up a connection or using a port on
import sys         # our network to look for certain connections
#34:06
server = "redacted IP"
port = 5555

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # "AF_INET" is the type of socket and "SOCK STREAM" is how the data comes in

try:
    s.bind((str ("redacted IP"), 5555))

except socket.error as e:
    str(e) #check for errors

s.listen(2)               # only want two port connections "player 1" and "player 2" therefore only 2 client on the socket
</code>```

i've tried running this part of a server python file to create an online connection however i keep getting this error.

```<code>Traceback (most recent call last):
  File "C:\Users\Phoen\PycharmProjects\chessProject1\server.py", line 16, in <module>
    s.listen(2)               # only want two port connections "player 1" and "player 2" therefore only 2 client on the socket
OSError: [WinError 10022] An invalid argument was supplied
</code>```

i can't find an invalid argument in my code

Body:
import socket
from _thread import *    #setting up a connection or using a port on
import sys         # our network to look for certain connections
#34:06
server = "redacted IP"
port = 5555

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # "AF_INET" is the type of socket and "SOCK STREAM" is how the data comes in

try:
    s.bind((str ("redacted IP"), 5555))

except socket.error as e:
    str(e) #check for errors

s.listen(2)               # only want two port connections "player 1" and "player 2" therefore only 2 client on the socket

i've tried running this part of a server python file to create an online connection however i keep getting this error.

Traceback (most recent call last):
  File "C:\Users\Phoen\PycharmProjects\chessProject1\server.py", line 16, in <module>
    s.listen(2)               # only want two port connections "player 1" and "player 2" therefore only 2 client on the socket
OSError: [WinError 10022] An invalid argument was supplied

i can't find an invalid argument in my code


问:
Even if peer connection is establish but not getting the remote stream?
```<code>import React, { useEffect, useContext, useRef } from 'react';
import { SocketContext } from "../../contexts/socketContext";

const Call = ({ myId, otherId, init }) => {
    const socket = useContext(SocketContext);

    const localStream = useRef();
    const remoteStream = useRef();
    const _pc = useRef(new RTCPeerConnection());

    useEffect(() => {

        navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then((stream) => {
            localStream.current.srcObject = stream;

            stream.getTracks().forEach((track) => {
                _pc.current.addTrack(track, stream);
            });

        }).catch((err) => {
            console.log(err);
        });

        if (init) {
            createAndSendOffer()
        }

        _pc.current.onicecandidate = (e) => {
            if (e.candidate) {
                socket.emit("candidate", { from: myId, to: otherId, candidate: e.candidate });
            }
        }

        _pc.current.ontrack = (e) => {
            console.log("Hello");
            if (e.streams) {
                console.log(e.streams);
            }
        }
    });

    useEffect(() => {
        socket.on("offer", (data) => {
            createAndSendAnswer(data);
        });

        socket.on("answer", (data) => {
            setAnswer(data.answer);
        });

        socket.on("candidate", (data) => {
            _pc.current.addIceCandidate(new RTCIceCandidate(data.candidate));
        });
    });

    async function setAnswer(answer) {
        _pc.current.setRemoteDescription(new RTCSessionDescription(answer));
    }

    async function createAndSendOffer() {
        const offer = await _pc.current.createOffer({ offerToReceiveAudio: true, offerToReceiveVideo: true });
        socket.emit("offer", { from: myId, to: otherId, offer });
        _pc.current.setLocalDescription(new RTCSessionDescription(offer));
    }

    async function createAndSendAnswer({ from, to, offer }) {

        _pc.current.setRemoteDescription(new RTCSessionDescription(offer));
        const answer = await _pc.current.createAnswer();
        _pc.current.setLocalDescription(new RTCSessionDescription(answer));
        socket.emit("answer", { from: myId, to: otherId, answer });
    }

    return (
        <div>
            <video autoPlay muted ref={localStream} />
            <video autoPlay muted ref={remoteStream} />
        </div>
    )
}

export default Call
``

I am trying to make a video calling app but remote peer video is not getting.
</code>```

Body:
import React, { useEffect, useContext, useRef } from 'react';
import { SocketContext } from "../../contexts/socketContext";

const Call = ({ myId, otherId, init }) => {
    const socket = useContext(SocketContext);

    const localStream = useRef();
    const remoteStream = useRef();
    const _pc = useRef(new RTCPeerConnection());

    useEffect(() => {

        navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then((stream) => {
            localStream.current.srcObject = stream;

            stream.getTracks().forEach((track) => {
                _pc.current.addTrack(track, stream);
            });

        }).catch((err) => {
            console.log(err);
        });

        if (init) {
            createAndSendOffer()
        }

        _pc.current.onicecandidate = (e) => {
            if (e.candidate) {
                socket.emit("candidate", { from: myId, to: otherId, candidate: e.candidate });
            }
        }

        _pc.current.ontrack = (e) => {
            console.log("Hello");
            if (e.streams) {
                console.log(e.streams);
            }
        }
    });

    useEffect(() => {
        socket.on("offer", (data) => {
            createAndSendAnswer(data);
        });

        socket.on("answer", (data) => {
            setAnswer(data.answer);
        });

        socket.on("candidate", (data) => {
            _pc.current.addIceCandidate(new RTCIceCandidate(data.candidate));
        });
    });

    async function setAnswer(answer) {
        _pc.current.setRemoteDescription(new RTCSessionDescription(answer));
    }

    async function createAndSendOffer() {
        const offer = await _pc.current.createOffer({ offerToReceiveAudio: true, offerToReceiveVideo: true });
        socket.emit("offer", { from: myId, to: otherId, offer });
        _pc.current.setLocalDescription(new RTCSessionDescription(offer));
    }

    async function createAndSendAnswer({ from, to, offer }) {

        _pc.current.setRemoteDescription(new RTCSessionDescription(offer));
        const answer = await _pc.current.createAnswer();
        _pc.current.setLocalDescription(new RTCSessionDescription(answer));
        socket.emit("answer", { from: myId, to: otherId, answer });
    }

    return (

            <video autoPlay muted ref={localStream} />
            <video autoPlay muted ref={remoteStream} />

    )
}

export default Call
``

I am trying to make a video calling app but remote peer video is not getting.


问:
Use ODBC connection to managed Azure SQL Database
I need to run a SQL query on Azure SQL Database from an Ansible playbook.
My task is:

```<code>- name: Sql server - rights
  vars:
    sql_groups:
      - { group_name: "{{ reader_group }}", db_access: "db_datareader" }
      - { group_name: "{{ contributer_group }}", db_access: "db_datawriter" }
      - { group_name: "{{ owner_group }}", db_access: "db_owner" }
  community.general.odbc:
    dsn: "Driver={ODBC Driver 13 for SQL Server};Server=tcp:{{ sql_server_host }},1433;Database={{ sql_server_db }};Uid={{ mssql_login_user }};Pwd={{ mssql_login_password }};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;Authentication=ActiveDirectoryPassword"
    query: |
      CREATE USER ["{{ group_name }}"] FROM EXTERNAL PROVIDER
      EXEC sp_addrolemember '{{ db_access }}', '{{ group_name }}'
  loop: "{{ sql_groups }}"
</code>```

When I run the playbook with the following command, Ansible tries to communicate via SSH.

```<code>ansible-playbook -i inventory.yml playbook.yml --check
</code>```

The error is :

```<code>[WARNING]: Unhandled error in Python interpreter discovery for host XXXXXX: Failed to connect to the host via ssh: ssh: Could not resolve hostname XXXXXX: Name
or service not known
fatal: [XXXXXX]: UNREACHABLE! => {"changed": false, "msg": "Data could not be sent to remote host \"XXXXXX\". Make sure this host can be reached over ssh: ssh: Could not resolve hostname XXXXXX: Name or service not known\r\n", "unreachable": true}
</code>```

I think I need to force the use of an ODBC connection with something like below (example is for Windows server) :

```<code>ansible_connection: winrm
ansible_port: 5986
ansible_winrm_transport: credssp
ansible_winrm_server_cert_validation: ignore
</code>```

What should I do ?
ansible_port: 1433 ? And what other parameters ?
I don't see how to communicate via ODBC.

Body:
I need to run a SQL query on Azure SQL Database from an Ansible playbook.
My task is:

- name: Sql server - rights
  vars:
    sql_groups:
      - { group_name: "{{ reader_group }}", db_access: "db_datareader" }
      - { group_name: "{{ contributer_group }}", db_access: "db_datawriter" }
      - { group_name: "{{ owner_group }}", db_access: "db_owner" }
  community.general.odbc:
    dsn: "Driver={ODBC Driver 13 for SQL Server};Server=tcp:{{ sql_server_host }},1433;Database={{ sql_server_db }};Uid={{ mssql_login_user }};Pwd={{ mssql_login_password }};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;Authentication=ActiveDirectoryPassword"
    query: |
      CREATE USER ["{{ group_name }}"] FROM EXTERNAL PROVIDER
      EXEC sp_addrolemember '{{ db_access }}', '{{ group_name }}'
  loop: "{{ sql_groups }}"

When I run the playbook with the following command, Ansible tries to communicate via SSH.

ansible-playbook -i inventory.yml playbook.yml --check

The error is :

[WARNING]: Unhandled error in Python interpreter discovery for host XXXXXX: Failed to connect to the host via ssh: ssh: Could not resolve hostname XXXXXX: Name
or service not known
fatal: [XXXXXX]: UNREACHABLE! => {"changed": false, "msg": "Data could not be sent to remote host \"XXXXXX\". Make sure this host can be reached over ssh: ssh: Could not resolve hostname XXXXXX: Name or service not known\r\n", "unreachable": true}

I think I need to force the use of an ODBC connection with something like below (example is for Windows server) :

ansible_connection: winrm
ansible_port: 5986
ansible_winrm_transport: credssp
ansible_winrm_server_cert_validation: ignore

What should I do ?
ansible_port: 1433 ? And what other parameters ?
I don't see how to communicate via ODBC.


问:
peewee problem: No module named 'playhouse' when deploying using AWS Chalice
I am working on an AWS Chalice project, and I chose peewee as the ORM for the DB we have.

When I run things locally with chalice local I can run my api with no problem, I'm able to CRUD normally.

When I deploy my microservice using chalice deploy and I go test it out on the live url, I encounter an error 500. When looking into the logs I see this message multiple times:

```<code>Traceback (most recent call last):
2023-01-03 22:39:57.665000 s98frt [ERROR] Runtime.ImportModuleError: Unable to import module 'app': No module named 'playhouse'
</code>```

I cannot do poetry add playhouse, because I get the following error: Could not find a matching version of package playhouse. Strange because playhouse comes with peewee.

What can you suggest me to do to fix this?

Thank you so much

Body:
I am working on an AWS Chalice project, and I chose peewee as the ORM for the DB we have.

When I run things locally with chalice local I can run my api with no problem, I'm able to CRUD normally.

When I deploy my microservice using chalice deploy and I go test it out on the live url, I encounter an error 500. When looking into the logs I see this message multiple times:

Traceback (most recent call last):
2023-01-03 22:39:57.665000 s98frt [ERROR] Runtime.ImportModuleError: Unable to import module 'app': No module named 'playhouse'

I cannot do poetry add playhouse, because I get the following error: Could not find a matching version of package playhouse. Strange because playhouse comes with peewee.

What can you suggest me to do to fix this?

Thank you so much


问:
Using VS2022, I cannot change C# code in debug mode (ENC1002)
Any code modification is forbidding me to continue debugging, raising this error:

ENC1002    Cannot apply changes -- unexpected error: 'The given key 'TSUNAMI, Version=1.0.0.65535, Culture=neutral, PublicKeyToken=null' was not present in the dictionary.'

What is this dictionary?
Tsunami is the name of my project in version 1.0.0.

I couldn't find something related to this dictionary anywhere.


问:
java.sql.SQLIntegrityConstraintViolationException: Column 'prenom' cannot be null
I'm new in Java programming so that's why I'm here seeking your kind help stackoverflowers.

I have this problem which I could not find the solution on internet, I hope someone could inform me where is my mistake and how can I fix it.

My problem is that when I try to insert the data, everything goes fine, the window opens, I can insert the data, button looks just fine.

But it gives me this message

java.sql.SQLIntegrityConstraintViolationException: Column 'prenom' cannot be null

Which I assume was a problem with php mySQL, then I changed all variables to NULL, activating the button "Null" for all of them.

It then WORKED, but all informations were saved as "null" in my database, which didn't really solve my problem.

My goal is to insert data (name, lastname, phone, email) into a data base (php mySQL) through eclipse. I did a program which I'm obliged to use window builder to insert that data, so graphical user interface MUST be used

What I expect to happen is to save data normally. Like, name = Mike, lastname = Tyson, phone = +55555, email = mtyson@gmail.com
And it shows in my database, not null message.

Thank you everyone

```<code>package interfaceGraphique;

import accesBaseDeDonnees.ClientsBDD;
import entites.Clients;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Color;

public class InterfaceClients extends JFrame {

    static InterfaceClients window;

    private JPanel contentPane;
    private JTextField txtPrenom;
    private JTextField txtNom;
    private JTextField txtTelephone;
    private JTextField txtEmail;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    InterfaceClients frame = new InterfaceClients();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public InterfaceClients() {
        setBackground(new Color(0, 0, 0));
        setOpacity(1.0f);
        setTitle("Ajouter un client");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnNewButton = new JButton("Enregistrer");
        btnNewButton.addActionListener(new ActionListener() {
            private AbstractButton labelResult;

            @Override
            public void actionPerformed(ActionEvent e) {
                String prenom = txtPrenom.getText();
                String nom = txtNom.getText();
                String telephone = txtTelephone.getText();
                String email = txtEmail.getText();

                Clients Clients = new Clients(prenom, nom, telephone, email);
                ClientsBDD clientsBDD = new ClientsBDD();
                Connection cn = clientsBDD.makeConnection();
                clientsBDD.insert(Clients, cn);
                clientsBDD.closeConnection(cn);

                //labelResult = null;
                //labelResult.setText("Client ajoute avec succes");
                }
        });
        btnNewButton.setBounds(45, 227, 112, 23);
        contentPane.add(btnNewButton);

        txtPrenom = new JTextField();
        txtPrenom.setBounds(124, 39, 258, 20);
        contentPane.add(txtPrenom);
        txtPrenom.setColumns(10);

        txtNom = new JTextField();
        txtNom.setColumns(10);
        txtNom.setBounds(124, 82, 258, 20);
        contentPane.add(txtNom);

        txtTelephone = new JTextField();
        txtTelephone.setColumns(10);
        txtTelephone.setBounds(124, 125, 258, 20);
        contentPane.add(txtTelephone);

        txtEmail = new JTextField();
        txtEmail.setColumns(10);
        txtEmail.setBounds(124, 166, 258, 20);
        contentPane.add(txtEmail);

        JLabel lblNewLabel = new JLabel("Prenom");
        lblNewLabel.setBounds(45, 42, 67, 14);
        contentPane.add(lblNewLabel);

        JLabel lblMarque = new JLabel("Nom");
        lblMarque.setBounds(45, 85, 46, 14);
        contentPane.add(lblMarque);

        JLabel lblNewLabel_1_1 = new JLabel("Telephone");
        lblNewLabel_1_1.setBounds(45, 128, 67, 14);
        contentPane.add(lblNewLabel_1_1);

        JLabel lblNewLabel_1_1_1 = new JLabel("Email");
        lblNewLabel_1_1_1.setBounds(45, 169, 89, 14);
        contentPane.add(lblNewLabel_1_1_1);

        JLabel labelResult = new JLabel("");
        labelResult.setBounds(194, 229, 227, 16);
        contentPane.add(labelResult);
    }
}
</code>```

Body:
I'm new in Java programming so that's why I'm here seeking your kind help stackoverflowers.

I have this problem which I could not find the solution on internet, I hope someone could inform me where is my mistake and how can I fix it.

My problem is that when I try to insert the data, everything goes fine, the window opens, I can insert the data, button looks just fine.

But it gives me this message

java.sql.SQLIntegrityConstraintViolationException: Column 'prenom' cannot be null

Which I assume was a problem with php mySQL, then I changed all variables to NULL, activating the button "Null" for all of them.

It then WORKED, but all informations were saved as "null" in my database, which didn't really solve my problem.

My goal is to insert data (name, lastname, phone, email) into a data base (php mySQL) through eclipse. I did a program which I'm obliged to use window builder to insert that data, so graphical user interface MUST be used

What I expect to happen is to save data normally. Like, name = Mike, lastname = Tyson, phone = +55555, email = mtyson@gmail.com
And it shows in my database, not null message.

Thank you everyone

package interfaceGraphique;

import accesBaseDeDonnees.ClientsBDD;
import entites.Clients;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Color;

public class InterfaceClients extends JFrame {

    static InterfaceClients window;

    private JPanel contentPane;
    private JTextField txtPrenom;
    private JTextField txtNom;
    private JTextField txtTelephone;
    private JTextField txtEmail;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    InterfaceClients frame = new InterfaceClients();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public InterfaceClients() {
        setBackground(new Color(0, 0, 0));
        setOpacity(1.0f);
        setTitle("Ajouter un client");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnNewButton = new JButton("Enregistrer");
        btnNewButton.addActionListener(new ActionListener() {
            private AbstractButton labelResult;

            @Override
            public void actionPerformed(ActionEvent e) {
                String prenom = txtPrenom.getText();
                String nom = txtNom.getText();
                String telephone = txtTelephone.getText();
                String email = txtEmail.getText();

                Clients Clients = new Clients(prenom, nom, telephone, email);
                ClientsBDD clientsBDD = new ClientsBDD();
                Connection cn = clientsBDD.makeConnection();
                clientsBDD.insert(Clients, cn);
                clientsBDD.closeConnection(cn);

                //labelResult = null;
                //labelResult.setText("Client ajoute avec succes");
                }
        });
        btnNewButton.setBounds(45, 227, 112, 23);
        contentPane.add(btnNewButton);

        txtPrenom = new JTextField();
        txtPrenom.setBounds(124, 39, 258, 20);
        contentPane.add(txtPrenom);
        txtPrenom.setColumns(10);

        txtNom = new JTextField();
        txtNom.setColumns(10);
        txtNom.setBounds(124, 82, 258, 20);
        contentPane.add(txtNom);

        txtTelephone = new JTextField();
        txtTelephone.setColumns(10);
        txtTelephone.setBounds(124, 125, 258, 20);
        contentPane.add(txtTelephone);

        txtEmail = new JTextField();
        txtEmail.setColumns(10);
        txtEmail.setBounds(124, 166, 258, 20);
        contentPane.add(txtEmail);

        JLabel lblNewLabel = new JLabel("Prenom");
        lblNewLabel.setBounds(45, 42, 67, 14);
        contentPane.add(lblNewLabel);

        JLabel lblMarque = new JLabel("Nom");
        lblMarque.setBounds(45, 85, 46, 14);
        contentPane.add(lblMarque);

        JLabel lblNewLabel_1_1 = new JLabel("Telephone");
        lblNewLabel_1_1.setBounds(45, 128, 67, 14);
        contentPane.add(lblNewLabel_1_1);

        JLabel lblNewLabel_1_1_1 = new JLabel("Email");
        lblNewLabel_1_1_1.setBounds(45, 169, 89, 14);
        contentPane.add(lblNewLabel_1_1_1);

        JLabel labelResult = new JLabel("");
        labelResult.setBounds(194, 229, 227, 16);
        contentPane.add(labelResult);
    }
}


问:
"The file is not displayed in the editor because it is either binary or uses an unsupported text encoding"
I want to open a HTML file on VSCode but in the editor, there is a sentence like this:

I don't know how to fix it.

I tried to open it anyway but the file looks like this:


问:
Not able to Sumit data from Vue Js to Django Rest
I built a web app with Vue js and Django, django rest framework , I am only able to post data from the backend. When I try and fill in the data from the form with vue js nothing posts. here is my code hope someone smart can solve this. Thank you for your help it is appreciated. I followed the tutorial from: https://blog.logrocket.com/how-to-build-vue-js-app-django-rest-framework/
I attempted it twice there may be some code issues with her code. but I am open for anyone to help thank you.</p>
```<code>Tasks.vue
<template>
  <div class="tasks_container">
    <div class="add_task">
      <form v-on:submit.prevent="submitForm">
        <div class="form-group">
          <label for="title">Title</label>
          <input type="text" class="form-control" id="title" v-model="title" />
        </div>
        <div class="form-group">
          <label for="description">Description</label>
          <textarea
            class="form-control"
            id="description"
            v-model="description"
          ></textarea>
        </div>
        <div class="form-group">
          <button type="submit">Add Task</button>
        </div>
      </form>
    </div>
    <div class="tasks_content">
      <h1>Tasks</h1>
      <ul class="tasks_list">
        <li v-for="task in tasks" :key="task.id">
          <h2>{{ task.title }}</h2>
          <p>{{ task.description }}</p>
          <button @click="toggleTask(task)">
            {{ task.completed ? "Undo" : "Complete" }}
          </button>
          <button @click="deleteTask(task)">Delete</button>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tasks: [],
      title: "",
      description: "",
    };
  },
  methods: {
    async getData() {
      try {
        // fetch tasks
        const response = await this.$http.get(
          "http://localhost:8000/api/tasks/"
        );
        // set the data returned as tasks
        this.tasks = response.data;
      } catch (error) {
        // log the error
        console.log(error);
      }
    },
  },
  async submitForm() {
    try {
      // Send a POST request to the API
      const response = await this.$http.post(
        "http://localhost:8000/api/tasks/",
        {
          title: this.title,
          description: this.description,
          completed: false,
        }
      );
      // Append the returned data to the tasks array
      this.tasks.push(response.data);
      // Reset the title and description field values.
      this.title = "";
      this.description = "";
    } catch (error) {
      // Log the error
      console.log(error);
    }
  },
  async toggleTask(task) {
    try {
      // Send a request to API to update the task
      const response = await this.$http.put(
        `http://localhost:8000/api/tasks/${task.id}/`,
        {
          completed: !task.completed,
          title: task.title,
          description: task.description,
        }
      );

      // Get the index of the task being updated
      let taskIndex = this.tasks.findIndex((t) => t.id === task.id);

      // Reset the tasks array with the new data of the updated task

      this.tasks = this.tasks.map((task) => {
        if (this.tasks.findIndex((t) => t.id === task.id) === taskIndex) {
          return response.data;
        }
        return task;
      });
    } catch (error) {
      // Log any error
      console.log(error);
    }
  },
  async deleteTask(task) {
    // Confirm if one wants to delete the task
    let confirmation = confirm("Do you want to delete this task?");

    if (confirmation) {
      try {
        // Send a request to delete the task
        await this.$http.delete(`http://localhost:8000/api/tasks/${task.id}`);

        // Refresh the tasks
        this.getData();
      } catch (error) {
        // Log any error

        console.log(error);
      }
    }
  },
  created() {
    // Fetch tasks on page load
    this.getData();
  },
};
</script>

App.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <Tasks />
  </div>
</template>

<script>
import Tasks from "./components/Tasks.vue";
export default {
  name: "App",
  components: {
    Tasks,
  },
};
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

main.js

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'

// set a prototype for http
Vue.prototype.$http = axios;
Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

vies.py

# parsing data from the client
from rest_framework.parsers import JSONParser
# To bypass having a CSRF token
from django.views.decorators.csrf import csrf_exempt
# for sending response to the client
from django.http import HttpResponse, JsonResponse
# API definition for task
from .serializers import TaskSerializer
# Task model
from .models import Task

@csrf_exempt
def tasks(request):
    '''
    List all task snippets
    '''
    if(request.method == 'GET'):
        # get all the tasks
        tasks = Task.objects.all()
        # serialize the task data
        serializer = TaskSerializer(tasks, many=True)
        # return a Json response
        return JsonResponse(serializer.data,safe=False)
    elif(request.method == 'POST'):
        # parse the incoming information
        data = JSONParser().parse(request)
        # instanciate with the serializer
        serializer = TaskSerializer(data=data)
        # check if the sent information is okay
        if(serializer.is_valid()):
            # if okay, save it on the database
            serializer.save()
            # provide a Json Response with the data that was saved
            return JsonResponse(serializer.data, status=201)
            # provide a Json Response with the necessary error information
        return JsonResponse(serializer.errors, status=400)

@csrf_exempt
def task_detail(request, pk):
    try:
        # obtain the task with the passed id.
        task = Task.objects.get(pk=pk)
    except:
        # respond with a 404 error message
        return HttpResponse(status=404)
    if(request.method == 'PUT'):
        # parse the incoming information
        data = JSONParser().parse(request)
        # instanciate with the serializer
        serializer = TaskSerializer(task, data=data)
        # check whether the sent information is okay
        if(serializer.is_valid()):
            # if okay, save it on the database
            serializer.save()
            # provide a JSON response with the data that was submitted
            return JsonResponse(serializer.data, status=201)
        # provide a JSON response with the necessary error information
        return JsonResponse(serializer.errors, status=400)
    elif(request.method == 'DELETE'):
        # delete the task
        task.delete()
        # return a no content response.
        return HttpResponse(status=204)

serializers.py

from rest_framework import routers,serializers,viewsets
from .models import Task
class TaskSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Task
        fields = ['id', 'title', 'description', 'completed', 'created_at']
</code>```

Body:
I built a web app with Vue js and Django, django rest framework , I am only able to post data from the backend. When I try and fill in the data from the form with vue js nothing posts. here is my code hope someone smart can solve this. Thank you for your help it is appreciated. I followed the tutorial from: https://blog.logrocket.com/how-to-build-vue-js-app-django-rest-framework/
I attempted it twice there may be some code issues with her code. but I am open for anyone to help thank you.

Tasks.vue
<template>

      <form v-on:submit.prevent="submitForm">

          Title
          <input type="text" class="form-control" id="title" v-model="title" />

          Description
          <textarea
            class="form-control"
            id="description"
            v-model="description"
          ></textarea>

          <button type="submit">Add Task</button>

      </form>

Tasks

{{ task.title }}

{{ task.description }}

          <button @click="toggleTask(task)">
            {{ task.completed ? "Undo" : "Complete" }}
          </button>
          <button @click="deleteTask(task)">Delete</button>

</template>

App.vue

<template>

    <Tasks />

</template>

main.js

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'

// set a prototype for http
Vue.prototype.$http = axios;
Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

vies.py

# parsing data from the client
from rest_framework.parsers import JSONParser
# To bypass having a CSRF token
from django.views.decorators.csrf import csrf_exempt
# for sending response to the client
from django.http import HttpResponse, JsonResponse
# API definition for task
from .serializers import TaskSerializer
# Task model
from .models import Task

@csrf_exempt
def tasks(request):
    '''
    List all task snippets
    '''
    if(request.method == 'GET'):
        # get all the tasks
        tasks = Task.objects.all()
        # serialize the task data
        serializer = TaskSerializer(tasks, many=True)
        # return a Json response
        return JsonResponse(serializer.data,safe=False)
    elif(request.method == 'POST'):
        # parse the incoming information
        data = JSONParser().parse(request)
        # instanciate with the serializer
        serializer = TaskSerializer(data=data)
        # check if the sent information is okay
        if(serializer.is_valid()):
            # if okay, save it on the database
            serializer.save()
            # provide a Json Response with the data that was saved
            return JsonResponse(serializer.data, status=201)
            # provide a Json Response with the necessary error information
        return JsonResponse(serializer.errors, status=400)

@csrf_exempt
def task_detail(request, pk):
    try:
        # obtain the task with the passed id.
        task = Task.objects.get(pk=pk)
    except:
        # respond with a 404 error message
        return HttpResponse(status=404)
    if(request.method == 'PUT'):
        # parse the incoming information
        data = JSONParser().parse(request)
        # instanciate with the serializer
        serializer = TaskSerializer(task, data=data)
        # check whether the sent information is okay
        if(serializer.is_valid()):
            # if okay, save it on the database
            serializer.save()
            # provide a JSON response with the data that was submitted
            return JsonResponse(serializer.data, status=201)
        # provide a JSON response with the necessary error information
        return JsonResponse(serializer.errors, status=400)
    elif(request.method == 'DELETE'):
        # delete the task
        task.delete()
        # return a no content response.
        return HttpResponse(status=204)

serializers.py

from rest_framework import routers,serializers,viewsets
from .models import Task
class TaskSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Task
        fields = ['id', 'title', 'description', 'completed', 'created_at']


问:
PowerShell script to deploy model metadata from *bim files to SQL Server Analysis Services
I have a remote server that will be used as Power BI and Analytics Services on premises
Everything necessary is installed there (SQL + SSAS +PBIRS + Kerberos)
One of my challenges is to deploy model metadata from *.bim files (that are stored in GitLab) to SSAS with the help of PowerShell

I would like to write a PowerShell script that would be executed from GitLab CI pipeline (note that I can only build Linux based containers that can run PowerShell scripts) which would grab specific .bim file and deployed it to SSAS (TabularEditor might be used?!)
Any help would be much appreciated!


问:
Is there a way to have successive pandas accessor
We can create custom pandas accessor by registering a class with the decorator:

```<code>@pd.api.extensions.register_dataframe_accessor("my_accessor")
</code>```

Is there a way to have successive accessor, in a such a way that it could be used as such:

```<code>df.my_accessor_1.my_accessor_2., ...,.my_accessor_n
</code>```

The idea is to have a hierarchical ordering of my accessor.

I can't really find out how accessor are implemented.

Body:
We can create custom pandas accessor by registering a class with the decorator:

@pd.api.extensions.register_dataframe_accessor("my_accessor")

Is there a way to have successive accessor, in a such a way that it could be used as such:

df.my_accessor_1.my_accessor_2., ...,.my_accessor_n

The idea is to have a hierarchical ordering of my accessor.

I can't really find out how accessor are implemented.


问:
PostgreSQL in Memory (with docker compose) - validate if its working?
I tried this approach from here: https://stackoverflow.com/a/42239760/1455384

So I have this kind of db setup:

```<code>  db:
    # 15.1-alpine3.16
    image: postgres@sha256:44b4073d487d0f9baf82bc95d10e2b1f161b18dcc52cfbd0eb2a894b5e2cd513
    environment:
      <<: *common-variables
      PGDATA: /pgtmpfs
    tmpfs:
      - /run:size=131072k
      - /var/cache:size=65536k
    networks:
      - backend
</code>```

When I run my application with this kind of postgres setup, I don't really notice any difference in speed (for example when I run various tests that hit database, they finish in about 2 minutes, whether tmpfs is used or not).

Also if I run: docker exec -it demo-db-1 df /run

I see:

```<code>Filesystem           1K-blocks      Used Available Use% Mounted on
tmpfs                   131072         4    131068   0% /run
</code>```

Does 0% Use mean, postgres does not actually use that memory "block" from tmpfs?

Update

Changing to:

tmpfs:
  - /pgtmpfs:size=131072k
```

makes it properly use memory, but speed is not changed. Not sure if thats, because postgres does not really benefit from this or because something else is wrong?

Body:
I tried this approach from here: https://stackoverflow.com/a/42239760/1455384

So I have this kind of db setup:

  db:
    # 15.1-alpine3.16
    image: postgres@sha256:44b4073d487d0f9baf82bc95d10e2b1f161b18dcc52cfbd0eb2a894b5e2cd513
    environment:
      <<: *common-variables
      PGDATA: /pgtmpfs
    tmpfs:
      - /run:size=131072k
      - /var/cache:size=65536k
    networks:
      - backend

When I run my application with this kind of postgres setup, I don't really notice any difference in speed (for example when I run various tests that hit database, they finish in about 2 minutes, whether tmpfs is used or not).

Also if I run: docker exec -it demo-db-1 df /run

I see:

Filesystem           1K-blocks      Used Available Use% Mounted on
tmpfs                   131072         4    131068   0% /run

Does 0% Use mean, postgres does not actually use that memory "block" from tmpfs?

Update

Changing to:

tmpfs:
  - /pgtmpfs:size=131072k

makes it properly use memory, but speed is not changed. Not sure if thats, because postgres does not really benefit from this or because something else is wrong?


问:
Open SQL on a search with multiple search factors in any combination
im creating an program, which allows the user to search for movies. The Movies are stored in a database, while the actors are stored in another database.

Each Movie has a unique id and a 1 to n relationship with actors. The Database movie looks like this:

movieid
Moviename
Kategory
year
movieid

x
test
action
2023
69

y
random
thriller
1995
420

The actor database looks like this:

actorid
name

1
Person1

2
Person2

3
Person3

and the relationship Database looks like this:

movieid
actor id

x
1

x
2

y
3

I I want to create a open search function which allows the user to search for the criteria: movieid, moviename, kategory and Actors.

The field can be empty or have value and u should be able to search for any combination.
Does anybody have an Idea?


问:
Getting Feature and Geometry error in Google Earth Engine
This is the code:

```<code>
//print('Amsterdam', Amsterdam)
var Cent_Amsterdam = ee.Feature(geometry);
Map.addLayer(Cent_Amsterdam, {}, 'Cent_Amsterdam');
Map.centerObject(Cent_Amsterdam, 10);

var first = ee.ImageCollection('LANDSAT/LC08/CO2/T1_L2')
  .filterDate('2019-01-01', '2019-12-31')
  .filterBounds(Cent_Amsterdam)
  .sort('CLOUD_COVER')
  .first();

Map.addLayer(first.clip(Cent_Amsterdam), {bands: ['SR_B4', 'SR_B3', 'SR_B2'], min: 7000, max: 15000});
</code>```

This is the error:

```<code>Layer 2: Layer error: Feature, argument 'geometry': Invalid type.
Expected type: Geometry.
Actual type: Feature.
</code>```

Just trying to get a Landsat overlay on Google Earth Engine of Amsterdam.
Please let me know how to fix this.

Body:
This is the code:

//print('Amsterdam', Amsterdam)
var Cent_Amsterdam = ee.Feature(geometry);
Map.addLayer(Cent_Amsterdam, {}, 'Cent_Amsterdam');
Map.centerObject(Cent_Amsterdam, 10);

var first = ee.ImageCollection('LANDSAT/LC08/CO2/T1_L2')
  .filterDate('2019-01-01', '2019-12-31')
  .filterBounds(Cent_Amsterdam)
  .sort('CLOUD_COVER')
  .first();

Map.addLayer(first.clip(Cent_Amsterdam), {bands: ['SR_B4', 'SR_B3', 'SR_B2'], min: 7000, max: 15000});

This is the error:

Layer 2: Layer error: Feature, argument 'geometry': Invalid type.
Expected type: Geometry.
Actual type: Feature.

Just trying to get a Landsat overlay on Google Earth Engine of Amsterdam.
Please let me know how to fix this.


问:
Unable to make any minio operations from a different container to the Minio container
I'm trying to build a containerized application that will basically read from a storage service do some operations and write a "processed" file into the same storage service.
I tried using NFS as a storage service but hit a few bottlenecks which led me to Minio as a storage service, which works out very well for me since I'm already familiar with AWS S3.

So I spun up a Minio container and basically wrote a simple python script which will basically check for .csv files that have been uploaded in the last 60 seconds.
I tested this locally and it worked flawlessly.

This is the sample code -

```<code>
import time
from minio import Minio
from minio.error import ResponseError

# Initialize the Minio client
host = "minio_server:9000"
access_key = "ROOTNAME"
secret_key="CHANGEME123"
client = Minio (host, access_key=access_key,
    secret_key=secret_key, secure=False)
# Set the name of the bucket to monitor
bucket_name = 'my-bucket'

# Set the interval for checking the bucket (in seconds)
check_interval = 60

while True:
  # Get the list of objects in the bucket
  objects = client.list_objects(bucket_name, prefix='', recursive=True)

  # Check the time of each object
  for obj in objects:
    # Check if the object is a CSV file
    if obj.object_name.endswith('.csv'):
      # Check if the object was uploaded in the last 60 seconds
      current_time = time.time()
      if current_time - obj.last_modified.timestamp() < check_interval:
        print(f'Found new CSV file: {obj.object_name}')

  # Sleep for the specified interval before checking again
  time.sleep(check_interval)

</code>```

And this works exactly as intended.

So next I containerized this application and created a Dockerfile

```<code>FROM ubuntu:20.04

RUN apt-get update -y
RUN apt update
RUN apt upgrade -y
RUN apt-get install -y python3
#RUN apt-get install -y python3-pip
RUN apt update
RUN apt upgrade -y
RUN apt-get install -y python3
RUN apt-get install -y python3-pip
RUN DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC apt-get -y install tzdata
RUN apt-get install -y libenchant1c2a

RUN apt install git -y

RUN pip3 install \
  argparse \
  boto3 \
  numpy==1.20.3 \
  scipy \
  pandas \
  scikit-learn \
  matplotlib \
  plotly \
  kaleido \
  fpdf \
  regex \
  pyenchant \
  minio \
  pythonping\
  openpyxl

RUN git clone https://github.com/nedap/dateinfer.git && \
  cd dateinfer && \
  pip3 install .

ADD core.py /core.py

CMD ["/core.py"]

ENTRYPOINT ["python3"]

</code>```

Note- I need the other dependencies for the actual application that I'm going to write once this test passes.

I created a Docker-compose.yaml file to club the two containers.

```<code>version: "2.1"
services:
  minio_server:
    image:  quay.io/minio/minio
    networks:
      - appnet
    container_name: minio_server
    restart: unless-stopped
    privileged: true
    command: server --address ":9000" --console-address ":9001" /data
    environment:
      - MINIO_ROOT_USER=ROOTNAME
      - MINIO_ROOT_PASSWORD=CHANGEME123
    volumes:
      - /minio/data:/data
    ports:
      - 9090:9090
      - 9000:9000

  minio_core_server:
    image: miniocore:latest
    networks:
      - appnet
    depends_on:
      - minio_server

networks:
  appnet:
    name: appnet

</code>```

And obviously I Made some changes to the source code to do something super simple -

```<code>from minio import Minio
from minio.error import ResponseError

# Set the URL of the Minio server

minio_url = "minio_server:9000"

# Set the access key and secret key for the Minio server
access_key = "ROOTNAME"
secret_key = "CHANGEME123"

# Initialize the Minio client
client = Minio(minio_url,
              access_key=access_key,
              secret_key=secret_key,
              secure=True)

# Set the name of the bucket
imput_bucket= client.make_bucket('sample.bucket')

</code>```

But I'm getting the following error:
File "/usr/local/lib/python3.8/dist-packages/urllib3/util/retry.py", line 592, in increment
minio_core_server_1  |     raise MaxRetryError(_pool, url, error or ResponseError(cause))
minio_core_server_1  | urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='minio_server', port=9000): Max retries exceeded with url: /sample.bucket (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1131)')))

Trouble shooting steps that I tried:

I initially thought that the service container is unable to establish a connection between the service container and the Minio container:

So I tried to ping the Minio container from the application from the service container

```<code>from minio import Minio
#from minio.error import ResponseError

# Set the URL of the Minio server
from pythonping import ping

ping("minio_server", verbose=True)
</code>```

and this is the response -

minio_core_server_1  | Reply from 192.168.192.2, 29 bytes in 0.03ms
minio_core_server_1  | Reply from 192.168.192.2, 29 bytes in 0.01ms
minio_core_server_1  | Reply from 192.168.192.2, 29 bytes in 0.01ms
minio_core_server_1  | Reply from 192.168.192.2, 29 bytes in 0.01ms

SO it's in fact able to establish a connection with the Minio container

Body:
I'm trying to build a containerized application that will basically read from a storage service do some operations and write a "processed" file into the same storage service.
I tried using NFS as a storage service but hit a few bottlenecks which led me to Minio as a storage service, which works out very well for me since I'm already familiar with AWS S3.

So I spun up a Minio container and basically wrote a simple python script which will basically check for .csv files that have been uploaded in the last 60 seconds.
I tested this locally and it worked flawlessly.

This is the sample code -

import time
from minio import Minio
from minio.error import ResponseError

# Initialize the Minio client
host = "minio_server:9000"
access_key = "ROOTNAME"
secret_key="CHANGEME123"
client = Minio (host, access_key=access_key,
    secret_key=secret_key, secure=False)
# Set the name of the bucket to monitor
bucket_name = 'my-bucket'

# Set the interval for checking the bucket (in seconds)
check_interval = 60

while True:
  # Get the list of objects in the bucket
  objects = client.list_objects(bucket_name, prefix='', recursive=True)

  # Check the time of each object
  for obj in objects:
    # Check if the object is a CSV file
    if obj.object_name.endswith('.csv'):
      # Check if the object was uploaded in the last 60 seconds
      current_time = time.time()
      if current_time - obj.last_modified.timestamp() < check_interval:
        print(f'Found new CSV file: {obj.object_name}')

  # Sleep for the specified interval before checking again
  time.sleep(check_interval)

And this works exactly as intended.

So next I containerized this application and created a Dockerfile

FROM ubuntu:20.04

RUN apt-get update -y
RUN apt update
RUN apt upgrade -y
RUN apt-get install -y python3
#RUN apt-get install -y python3-pip
RUN apt update
RUN apt upgrade -y
RUN apt-get install -y python3
RUN apt-get install -y python3-pip
RUN DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC apt-get -y install tzdata
RUN apt-get install -y libenchant1c2a

RUN apt install git -y

RUN pip3 install \
  argparse \
  boto3 \
  numpy==1.20.3 \
  scipy \
  pandas \
  scikit-learn \
  matplotlib \
  plotly \
  kaleido \
  fpdf \
  regex \
  pyenchant \
  minio \
  pythonping\
  openpyxl

RUN git clone https://github.com/nedap/dateinfer.git && \
  cd dateinfer && \
  pip3 install .

ADD core.py /core.py

CMD ["/core.py"]

ENTRYPOINT ["python3"]

Note- I need the other dependencies for the actual application that I'm going to write once this test passes.

I created a Docker-compose.yaml file to club the two containers.

version: "2.1"
services:
  minio_server:
    image:  quay.io/minio/minio
    networks:
      - appnet
    container_name: minio_server
    restart: unless-stopped
    privileged: true
    command: server --address ":9000" --console-address ":9001" /data
    environment:
      - MINIO_ROOT_USER=ROOTNAME
      - MINIO_ROOT_PASSWORD=CHANGEME123
    volumes:
      - /minio/data:/data
    ports:
      - 9090:9090
      - 9000:9000

  minio_core_server:
    image: miniocore:latest
    networks:
      - appnet
    depends_on:
      - minio_server

networks:
  appnet:
    name: appnet

And obviously I Made some changes to the source code to do something super simple -

from minio import Minio
from minio.error import ResponseError

# Set the URL of the Minio server

minio_url = "minio_server:9000"

# Set the access key and secret key for the Minio server
access_key = "ROOTNAME"
secret_key = "CHANGEME123"

# Initialize the Minio client
client = Minio(minio_url,
              access_key=access_key,
              secret_key=secret_key,
              secure=True)

# Set the name of the bucket
imput_bucket= client.make_bucket('sample.bucket')

But I'm getting the following error:
File "/usr/local/lib/python3.8/dist-packages/urllib3/util/retry.py", line 592, in increment
minio_core_server_1  |     raise MaxRetryError(_pool, url, error or ResponseError(cause))
minio_core_server_1  | urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='minio_server', port=9000): Max retries exceeded with url: /sample.bucket (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1131)')))

Trouble shooting steps that I tried:

I initially thought that the service container is unable to establish a connection between the service container and the Minio container:

So I tried to ping the Minio container from the application from the service container

from minio import Minio
#from minio.error import ResponseError

# Set the URL of the Minio server
from pythonping import ping

ping("minio_server", verbose=True)

and this is the response -

minio_core_server_1  | Reply from 192.168.192.2, 29 bytes in 0.03ms
minio_core_server_1  | Reply from 192.168.192.2, 29 bytes in 0.01ms
minio_core_server_1  | Reply from 192.168.192.2, 29 bytes in 0.01ms
minio_core_server_1  | Reply from 192.168.192.2, 29 bytes in 0.01ms

SO it's in fact able to establish a connection with the Minio container


问:
How to redirect to the same page without duplicating it when going back in ASP.NET MVC
In one page I have a form that on submit sends data to an action. This action, when finished with its logic, redirects to the same page. The problem is that when I go back in the browser there is a duplicate page. I want to achieve an action like refreshing.

I tried changing the redirect to RedirectToActionPermanent() and Redirect(). Also tried disabling the cache once in the action and once in Program.cs.

```<code>[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
</code>```

```<code>Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
Response.Headers["Pragma"] = "no-cache";
Response.Headers["Expires"] = "0";
</code>```

```<code>app.Use(async (context, next) =>
{
    context.Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
    context.Response.Headers["Pragma"] = "no-cache";
    context.Response.Headers["Expires"] = "0";

    await next();
});
</code>```

Body:
In one page I have a form that on submit sends data to an action. This action, when finished with its logic, redirects to the same page. The problem is that when I go back in the browser there is a duplicate page. I want to achieve an action like refreshing.

I tried changing the redirect to RedirectToActionPermanent() and Redirect(). Also tried disabling the cache once in the action and once in Program.cs.

[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]

Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
Response.Headers["Pragma"] = "no-cache";
Response.Headers["Expires"] = "0";

app.Use(async (context, next) =>
{
    context.Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
    context.Response.Headers["Pragma"] = "no-cache";
    context.Response.Headers["Expires"] = "0";

    await next();
});


问:
Power Apps Set Variable returning date after selected dated
In Power Apps, I am in the process of creating a Custom Form based off a SharePoint List. I added in an additional data source (excel file) that we are able to pull information from to autofill significant portions of the Custom Form. The issue is that it doesn't return the Date Selected but the following day (1/1/22 selected, 1/2/22 returned).

The code I am using is based off two pieces of user-input information. The ID of the individual and the date of the Activity. The code is as the following. It should return a mini table, which is important for further down the survey.

Set(Result, Filter(Table1,ID = ID.Text && (Text(ActivityDate, "mm/dd/yyyy") = Text(SelectedActivityDate.SelectedDate,"mm/dd/yyyy"))))

I do not see why the following date is being returned.


问:
How to trap a Text object selection event in Python3 / tkinter
Per the following Stackoverflow wisdom

Python/Tkinter: Trap text selection via keyboard/mouse as an event?

I tried to detect the creation of a user selection in a Text object as follows

```<code>import tkinter as tk

def handle_selection(e=None):
    print('here')
    try:
        sel_first = input_text.index(tk.SEL_FIRST)
        sel_last = input_text.index(tk.SEL_LAST)
        print(sel_first, sel_last)
    except:
        return

def main():
    window = tk.Tk()
    window.title("Simple Text Editor")

    input_text = tk.Text(window)

    input_text.bind("<<Selection>>", handle_selection)
    input_text.pack()
    window.mainloop()

if __name__ == "__main__":
    main()
</code>```

However the event is triggered (apparently) for each horizontal pixel selected rather than when the selection is completed, which was my intention. I also tried the following

```<code>input_text.bind("<<Selection-ButtonRelease>>", handle_selection)
</code>```

which wasn't triggered at all.

Is there a way to capture the event when the user releases the button after making the selection?

Body:
Per the following Stackoverflow wisdom

Python/Tkinter: Trap text selection via keyboard/mouse as an event?

I tried to detect the creation of a user selection in a Text object as follows

import tkinter as tk

def handle_selection(e=None):
    print('here')
    try:
        sel_first = input_text.index(tk.SEL_FIRST)
        sel_last = input_text.index(tk.SEL_LAST)
        print(sel_first, sel_last)
    except:
        return

def main():
    window = tk.Tk()
    window.title("Simple Text Editor")

    input_text = tk.Text(window)

    input_text.bind("<<Selection>>", handle_selection)
    input_text.pack()
    window.mainloop()

if __name__ == "__main__":
    main()

However the event is triggered (apparently) for each horizontal pixel selected rather than when the selection is completed, which was my intention. I also tried the following

input_text.bind("<<Selection-ButtonRelease>>", handle_selection)

which wasn't triggered at all.

Is there a way to capture the event when the user releases the button after making the selection?


问:
Juypterlab | ipyfilechooser ignores start_path option with UNC paths and also local paths
I started working with Jupyterlab to analyse bunches of CSV files.

It is installed and run within an virtual environment on a windows PC (Windows 10, Python 3.9, JupyterLab 3.5.2).

As the filenames often change and our paths are quite deep I thought a file dialogue would be a good starting point to get data in.

I searched a while and found that ipyfilechooser could be my friend.

So I created a Jupyter Notebook and started with this code block:

import ipywidgets
from ipyfilechooser import FileChooser

chooser = FileChooser(
    accept='.csv',  # only show CSV files
    multiple=False, # allow only one file
    # optional starting path
    start_path=r'\\sglx-srv1\geschaeft\MESSPLATZ'
)

display(chooser)
```

After executing this block a chooser widget appeared and I could select a folder or file, also from a UNC path (network drive).

But the setting of the start_path was always ignored and the dialogue always started from the folder the notebook itself is stored in.

I tried any variant I could find to quote the path, but with no luck.

It was not possible to let the file chooser start from any specified path neither local nor UNC.

What is wrong here? Is it a bug in my code or elsewhere?

Body:
I started working with Jupyterlab to analyse bunches of CSV files.

It is installed and run within an virtual environment on a windows PC (Windows 10, Python 3.9, JupyterLab 3.5.2).

As the filenames often change and our paths are quite deep I thought a file dialogue would be a good starting point to get data in.

I searched a while and found that ipyfilechooser could be my friend.

So I created a Jupyter Notebook and started with this code block:

import ipywidgets
from ipyfilechooser import FileChooser

chooser = FileChooser(
    accept='.csv',  # only show CSV files
    multiple=False, # allow only one file
    # optional starting path
    start_path=r'\\sglx-srv1\geschaeft\MESSPLATZ'
)

display(chooser)

After executing this block a chooser widget appeared and I could select a folder or file, also from a UNC path (network drive).

But the setting of the start_path was always ignored and the dialogue always started from the folder the notebook itself is stored in.

I tried any variant I could find to quote the path, but with no luck.

It was not possible to let the file chooser start from any specified path neither local nor UNC.

What is wrong here? Is it a bug in my code or elsewhere?