问:
Datastream in Project-A, CloudSQL in Project-B
I'm trying to configure Datastream to enable streaming data from CloudSQL to the BigQuery.

Our CloudSQL instance in the project-A, Datastream in the project -B.
Project-A has vpc-A which is peered with vpc-B in the Project-B.
vpc-A has cloudsql_auth proxy and I'm able to ping or login to this database via cloudsql_auth_proxy using psql from VPC-B(Project-B) but I'm not able to connect to the cloudsql_auth_proxy from the Datastream. I need to be able to connect Datastream(Project-A) to the CloudSQL(Project-B) using private connection
Thank you!


来源: stackexchange

问:
Parsing nested objects in JSON objects into multiple, cleaner JSON objects in Python
Is there a best practice for parsing messy JSON objects that have nested objects such that they're stored more cleanly?

I'm wondering if I could use Pyspark to solve this problem

I first extracted the information and loaded it to a s3 bucket, then I used a get function on s3 .Bucket('bucket-name').Object('json-file-name') to load the data.

An example would be trying to find the artist name and the song name (Polo G and RAPSTAR) here:

ContentLicense: CC BY-SA 4.0


问:
Why am I not getting a legend?
I'm plotting two columns in the same histogram plot. Everything is great, but for some reason I got the legend beforew, now after rerunning the code, it's gone. Here is the code:

```<code>plt.hist(sample_200[sample_200['income'] == '<=50K']['hours-per-week'], bins = 25, label = 'Below 50K')
plt.hist(sample_200[sample_200['income'] == '>50K']['hours-per-week'], bins = 25, label = 'Above 50K' )
plt.title('Compare the X feature in the two Y labels')
plt.ylabel('Count')
plt.xlabel('Hours Per Week')
</code>```

The plot:

Title: Why am I not getting a legend?

Body:
I'm plotting two columns in the same histogram plot. Everything is great, but for some reason I got the legend beforew, now after rerunning the code, it's gone. Here is the code:

plt.hist(sample_200[sample_200['income'] == '<=50K']['hours-per-week'], bins = 25, label = 'Below 50K')
plt.hist(sample_200[sample_200['income'] == '>50K']['hours-per-week'], bins = 25, label = 'Above 50K' )
plt.title('Compare the X feature in the two Y labels')
plt.ylabel('Count')
plt.xlabel('Hours Per Week')

The plot:


问:
QSqlTableModel.insertRow() only works once
This must be a beginner error - why does the .insertRow(row) function only add one row, then stop working? I've tried .submitAll(), .select(), and everything else I can think of. Likewise, the .insertRows(row, count) function is only able to add a single row, but nothing happens if the count argument is greater than 1.

```<code>import sys
from PySide6.QtCore import QSize, Qt
from PySide6.QtWidgets import QApplication, QMainWindow, QTableView
from PySide6.QtGui import QAction, QKeySequence
from PySide6.QtSql import QSqlDatabase, QSqlTableModel, QSqlQuery

class SQLTableModel(QSqlTableModel):
    def __init__(self, parent=None):
        super().__init__(parent)

        query = QSqlQuery()
        query.exec(
            "CREATE TABLE data_table"
            "(id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, "
            "name TEXT(40) NOT NULL)"
        )

        self.col_names = ["id", "name"]

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.db = QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("SQLTable.sqlite")
        self.db.open()

        self.table_view = QTableView()
        self.model = SQLTableModel()
        self.table_view.setModel(self.model)
        self.model.setTable("data_table")

        self.setMinimumSize(QSize(250, 250))
        self.setCentralWidget(self.table_view)

        T_action = QAction(self)
        T_action.triggered.connect(self.T_event)
        T_action.setShortcuts([QKeySequence(Qt.Key_T), "Ctrl+T"])
        self.addAction(T_action)

    def T_event(self):
        self.model.insertRow(self.model.rowCount())  # Only "works" once; causes vertical header to display "*"
        # self.model.insertRows(self.model.rowCount(), 3)  # Doesn't do anything

app = QApplication(sys.argv)
mainwindow = MainWindow()
mainwindow.show()
sys.exit(app.exec())
</code>```

Body:
This must be a beginner error - why does the .insertRow(row) function only add one row, then stop working? I've tried .submitAll(), .select(), and everything else I can think of. Likewise, the .insertRows(row, count) function is only able to add a single row, but nothing happens if the count argument is greater than 1.

import sys
from PySide6.QtCore import QSize, Qt
from PySide6.QtWidgets import QApplication, QMainWindow, QTableView
from PySide6.QtGui import QAction, QKeySequence
from PySide6.QtSql import QSqlDatabase, QSqlTableModel, QSqlQuery

class SQLTableModel(QSqlTableModel):
    def __init__(self, parent=None):
        super().__init__(parent)

        query = QSqlQuery()
        query.exec(
            "CREATE TABLE data_table"
            "(id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, "
            "name TEXT(40) NOT NULL)"
        )

        self.col_names = ["id", "name"]

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.db = QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("SQLTable.sqlite")
        self.db.open()

        self.table_view = QTableView()
        self.model = SQLTableModel()
        self.table_view.setModel(self.model)
        self.model.setTable("data_table")

        self.setMinimumSize(QSize(250, 250))
        self.setCentralWidget(self.table_view)

        T_action = QAction(self)
        T_action.triggered.connect(self.T_event)
        T_action.setShortcuts([QKeySequence(Qt.Key_T), "Ctrl+T"])
        self.addAction(T_action)

    def T_event(self):
        self.model.insertRow(self.model.rowCount())  # Only "works" once; causes vertical header to display "*"
        # self.model.insertRows(self.model.rowCount(), 3)  # Doesn't do anything

app = QApplication(sys.argv)
mainwindow = MainWindow()
mainwindow.show()
sys.exit(app.exec())


问:
Insecure browser error in WebView on logging Google
I am trying to make a WebView based Android app. It's found that when ever I try to sign in Google account i get a error.
I am using the default WebView in Java, and has added some additional codes to make it more functional like enabling JS, Cookies, file upload and download.
The code I used in OnCreate also tried this question

```<code>if (query.getString("query", "").contains("https://")) {

    webview1.loadUrl(query.getString("query", ""));

}

else {

    webview1.loadUrl("https://qmamu.com/search?q=".concat(query.getString("query", "").concat("&from=web")));

}

webview1.setWebChromeClient(new WebChromeClient() {

            @Override

            public void onProgressChanged(WebView view, int newProgress) {

                    super.onProgressChanged(view, newProgress);

                    progressBar.setProgress(newProgress);

                }

    ```
            @Override

            public void onReceivedIcon(WebView view, Bitmap icon) {

                    super.onReceivedIcon(view, icon);

                    favicon.setImageBitmap(icon);

                }

        });

webview1.getSettings().setJavaScriptEnabled(true);

webview1.getSettings().setUseWideViewPort(true);

webview1.getSettings().setBuiltInZoomControls(false);

webview1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

webview1.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {

                Intent intent = new Intent(Intent.ACTION_VIEW);

                intent.setData(Uri.parse(url));

                startActivity (intent);

        }

});

webview1.getSettings().setAllowFileAccess(true);

webview1.getSettings().setLoadWithOverviewMode(true);

webview1.getSettings().setUseWideViewPort(true);

webview1.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

webview1.getSettings().setDomStorageEnabled(true);

webview1.getSettings().setSaveFormData(true);

webview1.getSettings().setLoadWithOverviewMode(true); webview1.getSettings().setUseWideViewPort(true); final WebSettings webSettings = webview1.getSettings(); final String newUserAgent; newUserAgent = "Mozilla/5.0 (Android) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"; webSettings.setUserAgentString(newUserAgent);

if (1 == 2) {

        startActivityForResult(cam, REQ_CD_CAM);

        Intent _intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

        _intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());

        _intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

        _intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());

        sp.startListening(_intent);

}

webview1.setWebChromeClient(new WebChromeClient(){

            @Override

            public void onPermissionRequest(PermissionRequest request){

                        // Generally you want to check which permissions you are granting

                        request.grant(request.getResources());

                    }

});

 webSettings.setJavaScriptCanOpenWindowsAutomatically(true); if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { webSettings.setAllowFileAccessFromFileURLs(true); webSettings.setAllowUniversalAccessFromFileURLs(true); }

webview1.getSettings().setSavePassword(true);

webview1.setWebChromeClient(new WebChromeClient() {

    // For 3.0+ Devices

    protected void openFileChooser(ValueCallback uploadMsg, String acceptType) { mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE);

        i.setType("image/*"); startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);

    }

    public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {

        if (uploadMessage != null) {

            uploadMessage.onReceiveValue(null);

            uploadMessage = null; } uploadMessage = filePathCallback; Intent intent = fileChooserParams.createIntent(); try {

            startActivityForResult(intent, REQUEST_SELECT_FILE);

        } catch (ActivityNotFoundException e) {

            uploadMessage = null; Toast.makeText(getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show(); return false; }

        return true; }

    //For Android 4.1 only

    protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {

        mUploadMessage = uploadMsg; Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);

    }

    protected void openFileChooser(ValueCallback<Uri> uploadMsg) {

        mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE);

        i.setType("image/*"); startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

    }

});

CookieManager.getInstance().setAcceptCookie(true);

{

    android.graphics.drawable.GradientDrawable SketchUi = new android.graphics.drawable.GradientDrawable();

    SketchUi.setColor(0xFFFFFFFF);

    float lt = getDip(0);

    float rt = getDip(0);

    float rb = getDip(43);

    float lb = getDip(43);

    SketchUi.setCornerRadii(new float[]{

            lt,lt,rt ,rt,rb,rb ,lb,lb });

    linear7.setElevation(getDip(30));

    linear7.setBackground(SketchUi);

}

webview1.getSettings().setBuiltInZoomControls(true);webview1.getSettings().setDisplayZoomControls(false);
```

The Error message in WebView

Can you tell me a code or any other method to avoid this error without changing whole application program.

Body:
I am trying to make a WebView based Android app. It's found that when ever I try to sign in Google account i get a error.
I am using the default WebView in Java, and has added some additional codes to make it more functional like enabling JS, Cookies, file upload and download.
The code I used in OnCreate also tried this question

if (query.getString("query", "").contains("https://")) {

    webview1.loadUrl(query.getString("query", ""));

}

else {

    webview1.loadUrl("https://qmamu.com/search?q=".concat(query.getString("query", "").concat("&from=web")));

}

webview1.setWebChromeClient(new WebChromeClient() {

            @Override

            public void onProgressChanged(WebView view, int newProgress) {

                    super.onProgressChanged(view, newProgress);

                    progressBar.setProgress(newProgress);

                }

    ```
            @Override

            public void onReceivedIcon(WebView view, Bitmap icon) {

                    super.onReceivedIcon(view, icon);

                    favicon.setImageBitmap(icon);

                }

        });

webview1.getSettings().setJavaScriptEnabled(true);

webview1.getSettings().setUseWideViewPort(true);

webview1.getSettings().setBuiltInZoomControls(false);

webview1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

webview1.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {

                Intent intent = new Intent(Intent.ACTION_VIEW);

                intent.setData(Uri.parse(url));

                startActivity (intent);

        }

});

webview1.getSettings().setAllowFileAccess(true);

webview1.getSettings().setLoadWithOverviewMode(true);

webview1.getSettings().setUseWideViewPort(true);

webview1.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

webview1.getSettings().setDomStorageEnabled(true);

webview1.getSettings().setSaveFormData(true);

webview1.getSettings().setLoadWithOverviewMode(true); webview1.getSettings().setUseWideViewPort(true); final WebSettings webSettings = webview1.getSettings(); final String newUserAgent; newUserAgent = "Mozilla/5.0 (Android) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"; webSettings.setUserAgentString(newUserAgent);

if (1 == 2) {

        startActivityForResult(cam, REQ_CD_CAM);

        Intent _intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

        _intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());

        _intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

        _intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());

        sp.startListening(_intent);

}

webview1.setWebChromeClient(new WebChromeClient(){

            @Override

            public void onPermissionRequest(PermissionRequest request){

                        // Generally you want to check which permissions you are granting

                        request.grant(request.getResources());

                    }

});

 webSettings.setJavaScriptCanOpenWindowsAutomatically(true); if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { webSettings.setAllowFileAccessFromFileURLs(true); webSettings.setAllowUniversalAccessFromFileURLs(true); }

webview1.getSettings().setSavePassword(true);

webview1.setWebChromeClient(new WebChromeClient() {

    // For 3.0+ Devices

    protected void openFileChooser(ValueCallback uploadMsg, String acceptType) { mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE);

        i.setType("image/*"); startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);

    }

    public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {

        if (uploadMessage != null) {

            uploadMessage.onReceiveValue(null);

            uploadMessage = null; } uploadMessage = filePathCallback; Intent intent = fileChooserParams.createIntent(); try {

            startActivityForResult(intent, REQUEST_SELECT_FILE);

        } catch (ActivityNotFoundException e) {

            uploadMessage = null; Toast.makeText(getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show(); return false; }

        return true; }

    //For Android 4.1 only

    protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {

        mUploadMessage = uploadMsg; Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);

    }

    protected void openFileChooser(ValueCallback<Uri> uploadMsg) {

        mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE);

        i.setType("image/*"); startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

    }

});

CookieManager.getInstance().setAcceptCookie(true);

{

    android.graphics.drawable.GradientDrawable SketchUi = new android.graphics.drawable.GradientDrawable();

    SketchUi.setColor(0xFFFFFFFF);

    float lt = getDip(0);

    float rt = getDip(0);

    float rb = getDip(43);

    float lb = getDip(43);

    SketchUi.setCornerRadii(new float[]{

            lt,lt,rt ,rt,rb,rb ,lb,lb });

    linear7.setElevation(getDip(30));

    linear7.setBackground(SketchUi);

}

webview1.getSettings().setBuiltInZoomControls(true);webview1.getSettings().setDisplayZoomControls(false);

The Error message in WebView

Can you tell me a code or any other method to avoid this error without changing whole application program.


问:
Postgress psycopg2 python select - relation "modelo" does not exist
An AWS Aurora Postgress is with some tables, it was just created and i'm testing the psycopg2 connection.

The code bellow returns the tables created.

# Create a cursor
cur = conecta() //cod com login, host, bd name,..
# Query to list all tables
query = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'schema';"
# Execute the query
cur.execute(query)
# Get the result
result = cur.fetchall()
# Iterate over the result and print the table names
for table in result:
    print(table[0])
# Close the cursor and connection
cur.close()
conn.close()
```
<p>But when i make a select,</p>
<pre class="lang-py prettyprint-override"><code># Create a cursor
cur = conecta()
# Execute the SELECT statement
cur.execute("SELECT \* FROM Table_Name")
# Fetch the rows
rows = cur.fetchall()
# Print the rows
for row in rows:
    print(row)
# Close the cursor and connection
cur.close()
conn.close()
</code>```

UndefinedTable

Traceback (most recent call last)
/tmp/ipykernel_196871/3150531950.py in \<module\>
6
7 # Execute the SELECT statement
\----\> 8 cur.execute("SELECT \* FROM Table_Name")
9
10 # Fetch the rows

UndefinedTable: relation "Table_Name" does not exist
LINE 1: SELECT \* FROM Table_Name
```

I try to select from information_schema.tables and a see the table in the result
I try to check the default schema.
Passing the schema in the sql select.
check table permissions.
say a prayer.

Body:
An AWS Aurora Postgress is with some tables, it was just created and i'm testing the psycopg2 connection.

The code bellow returns the tables created.

# Create a cursor
cur = conecta() //cod com login, host, bd name,..
# Query to list all tables
query = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'schema';"
# Execute the query
cur.execute(query)
# Get the result
result = cur.fetchall()
# Iterate over the result and print the table names
for table in result:
    print(table[0])
# Close the cursor and connection
cur.close()
conn.close()

But when i make a select,

# Create a cursor
cur = conecta()
# Execute the SELECT statement
cur.execute("SELECT \* FROM Table_Name")
# Fetch the rows
rows = cur.fetchall()
# Print the rows
for row in rows:
    print(row)
# Close the cursor and connection
cur.close()
conn.close()

UndefinedTable

Traceback (most recent call last)
/tmp/ipykernel_196871/3150531950.py in \<module\>
6
7 # Execute the SELECT statement
\----\> 8 cur.execute("SELECT \* FROM Table_Name")
9
10 # Fetch the rows

UndefinedTable: relation "Table_Name" does not exist
LINE 1: SELECT \* FROM Table_Name

I try to select from information_schema.tables and a see the table in the result
I try to check the default schema.
Passing the schema in the sql select.
check table permissions.
say a prayer.


问:
Cypress can't find Pug module even though Vue finds it just fine
I searched through all the web and seems like no one ever had a problem with Pug while testing with Cypress. Anyone?

I'm using Pug with Vue 3.

```<code>The following error originated from your test code, not from Cypress.

> Module build failed (from ./node_modules/pug-plain-loader/index.js):
Error: Cannot find module 'pug'
</code>```

/cypress/support/component.js

```<code>// ***********************************************************
// This example support/component.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************

// Import commands.js using ES2015 syntax:
import './commands'

// Alternatively you can use CommonJS syntax:
// require('./commands')

import { mount } from 'cypress/vue'

// Cypress.Commands.add('mount', mount)
import App from '@/App.vue'
import { h } from 'vue'
import pugPlainLoader from 'pug-plain-loader'

Cypress.Commands.add('mount', (component, ...args) => {
  args.global = args.global || {}
  args.global.plugins = args.global.plugins || []
  args.global.plugins.push(pugPlainLoader())

  return mount(() => {
    return h(App, {}, component)
  }, ...args)
})

// Example use:
// cy.mount(MyComponent)
</code>```

package.json

```<code> "dependencies": {
    "@cypress/vue": "^3.1.0",
    "@cypress/webpack-dev-server": "^3.2.2",
    "core-js": "^3.8.3",
    "cypress": "^12.3.0",
    "path": "^0.12.7",
    "pug": "^3.0.2",
    "pug-plain-loader": "^1.1.0",
    "vue": "^3.2.13"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-plugin-unit-jest": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "@vue/test-utils": "^2.0.0-0",
    "@vue/vue3-jest": "^28.1.0",
    "babel-jest": "^27.0.6",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3",
    "jest": "^27.0.5",
    "vue-cli-plugin-pug": "^2.0.0"
  },
</code>```

Body:
I searched through all the web and seems like no one ever had a problem with Pug while testing with Cypress. Anyone?

I'm using Pug with Vue 3.

The following error originated from your test code, not from Cypress.

> Module build failed (from ./node_modules/pug-plain-loader/index.js):
Error: Cannot find module 'pug'

/cypress/support/component.js

// ***********************************************************
// This example support/component.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************

// Import commands.js using ES2015 syntax:
import './commands'

// Alternatively you can use CommonJS syntax:
// require('./commands')

import { mount } from 'cypress/vue'

// Cypress.Commands.add('mount', mount)
import App from '@/App.vue'
import { h } from 'vue'
import pugPlainLoader from 'pug-plain-loader'

Cypress.Commands.add('mount', (component, ...args) => {
  args.global = args.global || {}
  args.global.plugins = args.global.plugins || []
  args.global.plugins.push(pugPlainLoader())

  return mount(() => {
    return h(App, {}, component)
  }, ...args)
})

// Example use:
// cy.mount(MyComponent)

package.json

 "dependencies": {
    "@cypress/vue": "^3.1.0",
    "@cypress/webpack-dev-server": "^3.2.2",
    "core-js": "^3.8.3",
    "cypress": "^12.3.0",
    "path": "^0.12.7",
    "pug": "^3.0.2",
    "pug-plain-loader": "^1.1.0",
    "vue": "^3.2.13"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-plugin-unit-jest": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "@vue/test-utils": "^2.0.0-0",
    "@vue/vue3-jest": "^28.1.0",
    "babel-jest": "^27.0.6",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3",
    "jest": "^27.0.5",
    "vue-cli-plugin-pug": "^2.0.0"
  },


问:
Using polling2 module to check for growing files
I'm having trouble working out if I can use the polling2 module to check for growing files in a directory.

I am currently using watchdog to scan a directory for new files then process them, but I need to ensure that the files/folders being copied to the watch directory have finished copying before I allow them to be processed.
I believe polling should be able to do this, from reading the usage docs i'm still unsure how this would be possible.

Any help would be appreciated.


问:
Request API timeout under LAN
Background:

1、All Servers unable to connect to the public network

2、It is expected that all URLs of server B can be normally requested on server A

3、nginx config in ServerB like this：

```<code>server{
  listen 443 ssl;
  ...
  location /api/ {
     proxy_pass http://C:8040/;
  }
}
</code>```

Result：

1、ServerA request https://B:443/ success  ,but request https://B:443/api/... failed; like login api, in F12 console, it shows Error:POST https://B:443/api/user/login net::ERR_CONNECTION_TIMED_OUT

2、In nginx access.log and error.log, it seems not find the content that contains /api/

Question：

1、Is it related to server A unable to access server C？

2、how to solve the ERR_CONNECTION_TIMED_OUT？

Title: Request API timeout under LAN

Body:
Background:

1、All Servers unable to connect to the public network

2、It is expected that all URLs of server B can be normally requested on server A

3、nginx config in ServerB like this：

server{
  listen 443 ssl;
  ...
  location /api/ {
     proxy_pass http://C:8040/;
  }
}

Result：

1、ServerA request https://B:443/ success  ,but request https://B:443/api/... failed; like login api, in F12 console, it shows Error:POST https://B:443/api/user/login net::ERR_CONNECTION_TIMED_OUT

2、In nginx access.log and error.log, it seems not find the content that contains /api/

Question：

1、Is it related to server A unable to access server C？

2、how to solve the ERR_CONNECTION_TIMED_OUT？


问:
how to use mouseDoubleClick in listView and and filter clicks that are not on a specific listViewItem- in WPF
I have a listView in xaml(code below) that displays list of objects,
this listView have event of mouseDoubleClick and the event opens new window with the details of the selected listViewItem.

But when the user presses Accidentally on empty areas on the page the software throws exception,
and I want that when an empty area is clicked the event will not be called
this is the event:(in the c# file)

```<code>private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
            this.Hide();

            new ProductWindow(productSelected.Id).ShowDialog();//after the add window close updating the list
            this.Show();
</code>```

this is my listView:(in the xaml file)

```<code><ListView Grid.Row="1" ItemsSource="{Binding productList }" SelectedItem="{Binding productSelected, Mode=TwoWay}" MouseDoubleClick="ListView_MouseDoubleClick"  >
            <ListView.View>
                <GridView x:Name="GridView1">
                    <GridViewColumn x:Name="idColumn" DisplayMemberBinding= "{Binding Path=Id}"
                                Header="Id" Width="120"/>
                    <GridViewColumn DisplayMemberBinding= "{Binding Path=Name}"
                                Header="Name" Width="120"/>
                    <GridViewColumn DisplayMemberBinding= "{Binding Path=Price}"
                                Header="Price" Width="120"/>
                    <GridViewColumn DisplayMemberBinding= "{Binding Path=Category}"
                                Header="Category" Width="120"/>
                </GridView>
            </ListView.View>
        </ListView>
</code>```

how can I do that?
what do I do in the exception handeling??

Body:
I have a listView in xaml(code below) that displays list of objects,
this listView have event of mouseDoubleClick and the event opens new window with the details of the selected listViewItem.

But when the user presses Accidentally on empty areas on the page the software throws exception,
and I want that when an empty area is clicked the event will not be called
this is the event:(in the c# file)

private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
            this.Hide();

            new ProductWindow(productSelected.Id).ShowDialog();//after the add window close updating the list
            this.Show();

this is my listView:(in the xaml file)

<ListView Grid.Row="1" ItemsSource="{Binding productList }" SelectedItem="{Binding productSelected, Mode=TwoWay}" MouseDoubleClick="ListView_MouseDoubleClick"  >
            <ListView.View>
                <GridView x:Name="GridView1">
                    <GridViewColumn x:Name="idColumn" DisplayMemberBinding= "{Binding Path=Id}"
                                Header="Id" Width="120"/>
                    <GridViewColumn DisplayMemberBinding= "{Binding Path=Name}"
                                Header="Name" Width="120"/>
                    <GridViewColumn DisplayMemberBinding= "{Binding Path=Price}"
                                Header="Price" Width="120"/>
                    <GridViewColumn DisplayMemberBinding= "{Binding Path=Category}"
                                Header="Category" Width="120"/>
                </GridView>
            </ListView.View>
        </ListView>

how can I do that?
what do I do in the exception handeling??


问:
Implementing async retry in Rust with mutable state
I am trying to implement a generic async retry method taking a call with a mutable parameter (in my case database connection), but running into compile errors around lifetimes that I don't completely understand.

Here is a simplified example illustrating the problem:

use std::future::Future;

#[tokio::main]
async fn main() {
    let mut foo = Foo { x: 1 };
    retry(&mut foo, |f| test(f)).await;
}

async fn retry<C, T, F>(foo: &mut Foo, mut call: C) -> Result<T, ()>
where
    C: FnMut(&mut Foo) -> F,
    F: Future<Output=Result<T, ()>>,
{
    for _ in 0..3 {
        match call(foo).await {
            Ok(x) => return Ok(x),
            Err(_) => ()
        }
    }

    Err(())
}

struct Foo {
    x: i32
}

async fn test(foo: &mut Foo) -> Result<i32, ()> {
    Ok(foo.x.clone())
}
```
<p>gives:</p>
```error: lifetime may not live long enough
 --> src/lib.rs:6:25
  |
6 |     retry(&mut foo, |f| test(f)).await;
  |                      -- ^^^^^^^ returning this value requires that `'1` must outlive `'2`
  |                      ||
  |                      |return type of closure `impl Future<Output = Result<i32, ()>>` contains a lifetime `'2`
  |                      has type `&'1 mut Foo`
```
<p>Adding lifetime to <code>foo</code> in <code>retry</code> method doesn't help:</p>
<pre class="lang-rust prettyprint-override"><code>async fn retry<'a, C, T, F>(foo: &'a mut Foo, mut call: C) -> Result<T, ()>
where
    C: FnMut(&'a mut Foo) -> F,
    F: Future<Output=Result<T, ()>>,
{
    for _ in 0..3 {
        match call(foo).await {
            Ok(x) => return Ok(x),
            Err(_) => ()
        }
    }

    Err(())
}
</code>```

gives:

```<code>error[E0499]: cannot borrow `*foo` as mutable more than once at a time
  --> src/lib.rs:15:20
   |
9  | async fn retry<'a, C, T, F>(foo: &'a mut Foo, mut call: C) -> Result<T, ()>
   |                -- lifetime `'a` defined here
...
15 |         match call(foo).await {
   |               -----^^^-
   |               |    |
   |               |    `*foo` was mutably borrowed here in the previous iteration of the loop
   |               argument requires that `*foo` is borrowed for `'a`
</code>```

Body:
I am trying to implement a generic async retry method taking a call with a mutable parameter (in my case database connection), but running into compile errors around lifetimes that I don't completely understand.

Here is a simplified example illustrating the problem:

use std::future::Future;

#[tokio::main]
async fn main() {
    let mut foo = Foo { x: 1 };
    retry(&mut foo, |f| test(f)).await;
}

async fn retry<C, T, F>(foo: &mut Foo, mut call: C) -> Result<T, ()>
where
    C: FnMut(&mut Foo) -> F,
    F: Future<Output=Result<T, ()>>,
{
    for _ in 0..3 {
        match call(foo).await {
            Ok(x) => return Ok(x),
            Err(_) => ()
        }
    }

    Err(())
}

struct Foo {
    x: i32
}

async fn test(foo: &mut Foo) -> Result<i32, ()> {
    Ok(foo.x.clone())
}

gives:

error: lifetime may not live long enough
 --> src/lib.rs:6:25
  |
6 |     retry(&mut foo, |f| test(f)).await;
  |                      -- ^^^^^^^ returning this value requires that `'1` must outlive `'2`
  |                      ||
  |                      |return type of closure `impl Future<Output = Result<i32, ()>>` contains a lifetime `'2`
  |                      has type `&'1 mut Foo`

Adding lifetime to foo in retry method doesn't help:

async fn retry<'a, C, T, F>(foo: &'a mut Foo, mut call: C) -> Result<T, ()>
where
    C: FnMut(&'a mut Foo) -> F,
    F: Future<Output=Result<T, ()>>,
{
    for _ in 0..3 {
        match call(foo).await {
            Ok(x) => return Ok(x),
            Err(_) => ()
        }
    }

    Err(())
}

gives:

error[E0499]: cannot borrow `*foo` as mutable more than once at a time
  --> src/lib.rs:15:20
   |
9  | async fn retry<'a, C, T, F>(foo: &'a mut Foo, mut call: C) -> Result<T, ()>
   |                -- lifetime `'a` defined here
...
15 |         match call(foo).await {
   |               -----^^^-
   |               |    |
   |               |    `*foo` was mutably borrowed here in the previous iteration of the loop
   |               argument requires that `*foo` is borrowed for `'a`


问:
How to generate a dataframe from FeatureUnion in python?
I have some preprocess on my dataframe and write a function to do this.
This function use FeatureUnion from sklearn.pipeline and here we can see it

```<code>def generate_data_transformation_config():
from sklearn.pipeline import FeatureUnion

feature_union = FeatureUnion([
    ('text_features_mapper', text_features_mapper(column_group_1)),
    ('categorical_features_mapper', categorical_fetures_mapper(column_group_2)),
    ('numerical_features_mapper', numerical_features_mapper(column_group_3)),
])

return feature_union
</code>```

(text_features_mapper , categorical_features_mapper , numerical_features_mapper are my another functions)

Now I want to have a dataframe from this function.

Is there any way to do this?

Body:
I have some preprocess on my dataframe and write a function to do this.
This function use FeatureUnion from sklearn.pipeline and here we can see it

def generate_data_transformation_config():
from sklearn.pipeline import FeatureUnion

feature_union = FeatureUnion([
    ('text_features_mapper', text_features_mapper(column_group_1)),
    ('categorical_features_mapper', categorical_fetures_mapper(column_group_2)),
    ('numerical_features_mapper', numerical_features_mapper(column_group_3)),
])

return feature_union

(text_features_mapper , categorical_features_mapper , numerical_features_mapper are my another functions)

Now I want to have a dataframe from this function.

Is there any way to do this?


问:
I know that question has been asked: JEST throws error: Cannot use import statement outside a module in REact app made with CRA, with TS
I have read many possible answers, but none works in my case (so please be no surprised - my config files are now overfilled)
The problem is thrown here:

```<code>import axios from "axios";
</code>```

Here are config files

```<code>import type { Config } from "@jest/types";

const config: Config.InitialOptions = {
    roots: ["<rootDir>/src"],
    transform: {
        "^.+\\.tsx?$": "ts-jest",
        "^.+\\.css$": "<rootDir>/jest-config/style-mock.js",
        "^.+\\.jsx?$": "babel-jest",
    },
    transformIgnorePatterns: [
        "<rootDir>/node_modules/",
        "<rootDir>/node_modules/(?!axios)",
        "node_modules/(?!(@react-native|react-native|react-native-vector-icons)/)",
    ],

    setupFilesAfterEnv: ["@testing-library/jest-dom/extend-expect"],
    testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(tsx|jsx)?$",
    moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
    testEnvironment: "jsdom",
    collectCoverage: false,
    collectCoverageFrom: ["src/**/*.{ts,tsx}"],
    moduleNameMapper: {
        "^.+\\.(css|sass|scss)$": "identity-obj-proxy",
    },
    globals: {
        "ts-jest": {
            isolatedModules: true,
        },
    },
};

export default config;
</code>```

Body:
I have read many possible answers, but none works in my case (so please be no surprised - my config files are now overfilled)
The problem is thrown here:

import axios from "axios";

Here are config files

import type { Config } from "@jest/types";

const config: Config.InitialOptions = {
    roots: ["<rootDir>/src"],
    transform: {
        "^.+\\.tsx?$": "ts-jest",
        "^.+\\.css$": "<rootDir>/jest-config/style-mock.js",
        "^.+\\.jsx?$": "babel-jest",
    },
    transformIgnorePatterns: [
        "<rootDir>/node_modules/",
        "<rootDir>/node_modules/(?!axios)",
        "node_modules/(?!(@react-native|react-native|react-native-vector-icons)/)",
    ],

    setupFilesAfterEnv: ["@testing-library/jest-dom/extend-expect"],
    testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(tsx|jsx)?$",
    moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
    testEnvironment: "jsdom",
    collectCoverage: false,
    collectCoverageFrom: ["src/**/*.{ts,tsx}"],
    moduleNameMapper: {
        "^.+\\.(css|sass|scss)$": "identity-obj-proxy",
    },
    globals: {
        "ts-jest": {
            isolatedModules: true,
        },
    },
};

export default config;


问:
How to program Python to create Microsoft Power Automate Flow
Questions

How do I program Python to create new Microsoft Flows on an ongoing and "ad hoc" basis? (Not sure if "ad hoc" is the correct terminology but hopefully I'm communicating clearly what I mean.)

Is there a better way to achieve my objective?

Background

Dropbox integration automatically syncs certain files from another source to the App folder within Dropbox. The folder organization is Folders/Subfolders/Files.

I'm looking for an automated way to reroute those files to a completely separate directory with different Folder names and file folder directory organization.

I've been manually creating Microsoft Flows for each set of files to reroute them to the correct location outside of the Apps folder of Dropbox. There are hundreds of sets of files and more are added regularly. Files within each set are being added regularly.

Thank you


问:
Gibberish print result on wireless printer from Blazor WASM app on Android
We have developed a Blazor WASM app that is run on Android with a connected wireless printer.
We produce a simple HTML page that is then printed using the native Google Chrome on Android browser functionality. The print preview always looks good on the screen. However, in one out of ten or twenty such printouts, the printer produces some "good" output and some "gibberish".

Here is an example:

We have already tested different brands and different connections (WiFi/Bluetooth), but we haven't been able to get rid of this problem.

I initially suspected a faulty printer, then a faulty connection, then a low-quality brand printer, but swapping neither of these has produced any improvement.

Does anybody have any ideas on how to approach this problem and find the root cause for it?

Thanks for any suggestions you may have!

Best regards,

Joerg.


问:
Exception has occurred: IndexError list index out of range
I have a problem with this code: specifically it returns the error Exception has occurred: IndexError list index out of range even if the whole process is iterated by for loops and therefore it is impossible for the process to go out of the index .
The program in question starts a pool of threads which iterates the chunks list so that operations are performed on the records in that list.
I noticed that the error only comes up when the process moves to the last element of the chunks list.
The error occurs in the command "udated_records = p.imap(data_scraping, chunks)"

```<code>    with Pool(4) as p:
        # Calcola la lunghezza di ogni suddivisione (La lista deve essere divisa per il numero esatto di sottoprocessi)
        chunk_size = len(result) // 6
        # Calcola il reso della suddivisione (Verrà poi attribuito all'ultima esecuzione)
        chunk_rest = len(result) % 6

        # Dividi la lista in 4 parti (= al numero di sottoprocessi)
        chunks = [result[i:i+chunk_size] for i in range(0, len(result) - (len(result) % 6), chunk_size)]
        # Se è presente del resto viene assegnato all'ultima sottolista
        if(chunk_rest>0):
            # Assegna la parte rimanente all'ultima suddivisione (assegna il resto all'ultima sottolista)
            chunks[-1].extend(result[-chunk_rest:])
        print('chunks', chunks)
        print('chunk1', chunks[0])
        print('chunk2', chunks[1])
        print('chunk3', chunks[2])
        print('chunk4', chunks[3])
        print('chunk5', chunks[4])
        print('chunk6', chunks[5])

        udated_records = p.imap(data_scraping, chunks)
        array = [chunk for chunk in  udated_records]
</code>```

I've tried verifying the integrity of the chunks list and chunk sublists and they seem to have no problems. I deleted some superfluous libraries in the program but it doesn't seem to have solved

Body:
I have a problem with this code: specifically it returns the error Exception has occurred: IndexError list index out of range even if the whole process is iterated by for loops and therefore it is impossible for the process to go out of the index .
The program in question starts a pool of threads which iterates the chunks list so that operations are performed on the records in that list.
I noticed that the error only comes up when the process moves to the last element of the chunks list.
The error occurs in the command "udated_records = p.imap(data_scraping, chunks)"

    with Pool(4) as p:
        # Calcola la lunghezza di ogni suddivisione (La lista deve essere divisa per il numero esatto di sottoprocessi)
        chunk_size = len(result) // 6
        # Calcola il reso della suddivisione (Verrà poi attribuito all'ultima esecuzione)
        chunk_rest = len(result) % 6

        # Dividi la lista in 4 parti (= al numero di sottoprocessi)
        chunks = [result[i:i+chunk_size] for i in range(0, len(result) - (len(result) % 6), chunk_size)]
        # Se è presente del resto viene assegnato all'ultima sottolista
        if(chunk_rest>0):
            # Assegna la parte rimanente all'ultima suddivisione (assegna il resto all'ultima sottolista)
            chunks[-1].extend(result[-chunk_rest:])
        print('chunks', chunks)
        print('chunk1', chunks[0])
        print('chunk2', chunks[1])
        print('chunk3', chunks[2])
        print('chunk4', chunks[3])
        print('chunk5', chunks[4])
        print('chunk6', chunks[5])

        udated_records = p.imap(data_scraping, chunks)
        array = [chunk for chunk in  udated_records]

I've tried verifying the integrity of the chunks list and chunk sublists and they seem to have no problems. I deleted some superfluous libraries in the program but it doesn't seem to have solved


问:
Foreign key in django signals
i need use node in created method signals, but raise this error

my signals :

```<code>@receiver(post_save, sender=AUTH_USER_MODEL)
def create_user_progress(sender, instance, created, **kwargs):
    specialties = instance.specialties
    section = SectionSpecialties.objects.filter(specialties=specialties)
    section_slice = section.values_list('section_id', flat=True)
    node = Nodes.objects.filter(sections__in=section_slice)
    if created:
        Progress.objects.create(user=instance, node=node)

</code>```

my error :
Cannot assign "<QuerySet [<Nodes: dsdsd - cccc>, <Nodes: chizi nemiyare - cccc>]>": "Progress.node" must be a "Nodes" instance.

my model :

```<code>class Progress(core_models.TimeStampedModel):
    node = models.ForeignKey(section_model.Nodes, related_name='mentor_user', on_delete=models.CASCADE, null=True)
    mentor = models.ForeignKey(mentor_user.MentorUser, related_name='mentor_user', on_delete=models.CASCADE, null=True)
    user = models.OneToOneField(User, related_name='mentor_user', on_delete=models.CASCADE)
</code>```

Title: Foreign key in django signals

Body:
i need use node in created method signals, but raise this error

my signals :

@receiver(post_save, sender=AUTH_USER_MODEL)
def create_user_progress(sender, instance, created, **kwargs):
    specialties = instance.specialties
    section = SectionSpecialties.objects.filter(specialties=specialties)
    section_slice = section.values_list('section_id', flat=True)
    node = Nodes.objects.filter(sections__in=section_slice)
    if created:
        Progress.objects.create(user=instance, node=node)

my error :
Cannot assign "<QuerySet [<Nodes: dsdsd - cccc>, <Nodes: chizi nemiyare - cccc>]>": "Progress.node" must be a "Nodes" instance.

my model :

class Progress(core_models.TimeStampedModel):
    node = models.ForeignKey(section_model.Nodes, related_name='mentor_user', on_delete=models.CASCADE, null=True)
    mentor = models.ForeignKey(mentor_user.MentorUser, related_name='mentor_user', on_delete=models.CASCADE, null=True)
    user = models.OneToOneField(User, related_name='mentor_user', on_delete=models.CASCADE)


问:
The dynamic call of a static function fails - "Class "SomeClassName" not found"
I would like to call a model dynamically via a variable. However, it fails ( "Class "SomeClassName" not found"). Here is my code:

use App\Models\SomeClassName;
use App\Models\SomeClassName1;

class SomeClassName {
    public function store(string $someClassName, array $requestData): array
    {
        $model = $someClassName::with('relation')->findOrFail($requestData['item_id']);
        // ...
    }
}

$someClassName->store('className', []);
```


问:
Coulmns align on Windows, but not on macOS
I have a very simple layout. On Windows, the columns align, but on macOS, they do not! How do I fix this? I am using the PySimpleGUIQt version.

Windows

macOS

```<code>def display_stats(character):
    column_1 = [
        [sg.Text('Birth/Family', background_color='gold', justification='c')],
        [sg.Text('Species'), sg.Text(character.species, background_color='lightblue'), sg.Text('Gender'),
         sg.Text(character.gender, background_color='lightblue')],
        [sg.Text('Birthdate'),
         sg.Text(f'{character.birth_month} {character.birth_day}',
                 background_color='lightblue'),
         sg.Text('Sunsign'), sg.Text(f'{character.sunsign}', background_color='lightblue')
         ]
    ]

    column_2 = [
        [sg.Text('Appearance', background_color='gold')],
        [sg.Text('Height'), sg.Text(character.height, background_color='lightblue'), sg.Text('Frame'),
         sg.Text(character.frame, background_color='lightblue'), sg.Text('Weight'),
         sg.Text(character.weight, background_color='lightblue')],
        [sg.Text('Size'), sg.Text(character.size, background_color='lightblue'), sg.Text('Comeliness'),
         sg.Text(character.comeliness, background_color='lightblue'), sg.Text('Handedness'),
         sg.Text(character.handedness, background_color='lightblue')],
        [sg.Text('Physical', background_color='gold', justification='c')],
        [sg.Text('Strength'), sg.Text(character.strength, background_color='lightblue'), sg.Text('Endurance'),
         sg.Text(character.endurance, background_color='lightblue'), sg.Text('Dexterity'),
         sg.Text(character.dexterity, background_color='lightblue')],
        [sg.Text('Agility'), sg.Text(character.agility, background_color='lightblue'), sg.Text('Speed'),
         sg.Text(character.speed, background_color='lightblue'), sg.Text('Eyesight'),
         sg.Text(character.eyesight, background_color='lightblue')],
        [sg.Text('Hearing'), sg.Text(character.hearing, background_color='lightblue'), sg.Text('Smell/Taste'),
         sg.Text(character.smell_taste, background_color='lightblue'), sg.Text('Touch'),
         sg.Text(character.touch, background_color='lightblue')],
        [sg.Text('Voice'), sg.Text(character.voice, background_color='lightblue')],
        [sg.Text('Personality', background_color='gold', justification='c')],
        [sg.Text('Intelligence'), sg.Text(character.intelligence, background_color='lightblue'), sg.Text('Aura'),
         sg.Text(character.aura, background_color='lightblue')],
        [sg.Text('Will'), sg.Text(character.will, background_color='lightblue'), sg.Text('Morality'),
         sg.Text(character.morality, background_color='lightblue')],
        [sg.Text('Piety'), sg.Text(character.piety, background_color='lightblue')]
    ]

    layout = [
        [sg.Column(column_1)],
        [sg.Column(column_2)],
        [sg.OK(auto_size_button=False), sg.Button('Save', auto_size_button=False),
         sg.Button('Re-roll', auto_size_button=False)]
    ]

    window = sg.Window('Generated Character', layout, finalize=True, size=(800, 600), font=('Baskerville', 25))
    event, values = window.read()
    if event == 'Save' or event == 'Re-roll':
        window.close()
        return event
    # End program if user closes window or
    # presses the OK button
    window.close()

</code>```

I expect the same code (using the same underlying framework) to work in the same (or at least a very similar) fashion! The alignment should not be wildly different!

Body:
I have a very simple layout. On Windows, the columns align, but on macOS, they do not! How do I fix this? I am using the PySimpleGUIQt version.

Windows

macOS

def display_stats(character):
    column_1 = [
        [sg.Text('Birth/Family', background_color='gold', justification='c')],
        [sg.Text('Species'), sg.Text(character.species, background_color='lightblue'), sg.Text('Gender'),
         sg.Text(character.gender, background_color='lightblue')],
        [sg.Text('Birthdate'),
         sg.Text(f'{character.birth_month} {character.birth_day}',
                 background_color='lightblue'),
         sg.Text('Sunsign'), sg.Text(f'{character.sunsign}', background_color='lightblue')
         ]
    ]

    column_2 = [
        [sg.Text('Appearance', background_color='gold')],
        [sg.Text('Height'), sg.Text(character.height, background_color='lightblue'), sg.Text('Frame'),
         sg.Text(character.frame, background_color='lightblue'), sg.Text('Weight'),
         sg.Text(character.weight, background_color='lightblue')],
        [sg.Text('Size'), sg.Text(character.size, background_color='lightblue'), sg.Text('Comeliness'),
         sg.Text(character.comeliness, background_color='lightblue'), sg.Text('Handedness'),
         sg.Text(character.handedness, background_color='lightblue')],
        [sg.Text('Physical', background_color='gold', justification='c')],
        [sg.Text('Strength'), sg.Text(character.strength, background_color='lightblue'), sg.Text('Endurance'),
         sg.Text(character.endurance, background_color='lightblue'), sg.Text('Dexterity'),
         sg.Text(character.dexterity, background_color='lightblue')],
        [sg.Text('Agility'), sg.Text(character.agility, background_color='lightblue'), sg.Text('Speed'),
         sg.Text(character.speed, background_color='lightblue'), sg.Text('Eyesight'),
         sg.Text(character.eyesight, background_color='lightblue')],
        [sg.Text('Hearing'), sg.Text(character.hearing, background_color='lightblue'), sg.Text('Smell/Taste'),
         sg.Text(character.smell_taste, background_color='lightblue'), sg.Text('Touch'),
         sg.Text(character.touch, background_color='lightblue')],
        [sg.Text('Voice'), sg.Text(character.voice, background_color='lightblue')],
        [sg.Text('Personality', background_color='gold', justification='c')],
        [sg.Text('Intelligence'), sg.Text(character.intelligence, background_color='lightblue'), sg.Text('Aura'),
         sg.Text(character.aura, background_color='lightblue')],
        [sg.Text('Will'), sg.Text(character.will, background_color='lightblue'), sg.Text('Morality'),
         sg.Text(character.morality, background_color='lightblue')],
        [sg.Text('Piety'), sg.Text(character.piety, background_color='lightblue')]
    ]

    layout = [
        [sg.Column(column_1)],
        [sg.Column(column_2)],
        [sg.OK(auto_size_button=False), sg.Button('Save', auto_size_button=False),
         sg.Button('Re-roll', auto_size_button=False)]
    ]

    window = sg.Window('Generated Character', layout, finalize=True, size=(800, 600), font=('Baskerville', 25))
    event, values = window.read()
    if event == 'Save' or event == 'Re-roll':
        window.close()
        return event
    # End program if user closes window or
    # presses the OK button
    window.close()

I expect the same code (using the same underlying framework) to work in the same (or at least a very similar) fashion! The alignment should not be wildly different!


问:
Using 'Class'-type object to create an object it's representing
Let's say I have an object created from class:

public Class Cat {
  public Cat(String name) {
    this.name = name;
  }
}
```
<pre class="lang-java prettyprint-override"><code>Cat cat = new Cat("Just cat");
</code>```

I create a Class-instance of my cat like this:

Class catClass = cat.getClass();
```
<p>My question is, can I use that Class-object to create cats by doing something like this:</p>
<pre class="lang-java prettyprint-override"><code>Cat newCat = catClass...something...("Another cat");
</code>```

My problem is that I have a method accepting array of strings. This method needs to decide which object it has to construct using these strings as arguments. I tried to use getConstructor methods, but I can't seem to figure out how this works.

Body:
Let's say I have an object created from class:

public Class Cat {
  public Cat(String name) {
    this.name = name;
  }
}

Cat cat = new Cat("Just cat");

I create a Class-instance of my cat like this:

Class catClass = cat.getClass();

My question is, can I use that Class-object to create cats by doing something like this:

Cat newCat = catClass...something...("Another cat");

My problem is that I have a method accepting array of strings. This method needs to decide which object it has to construct using these strings as arguments. I tried to use getConstructor methods, but I can't seem to figure out how this works.


问:
How to access other Build Actions for an xml project in Visual Studio 2022
I'm following a MSWord project demo walkthrough that controls content in the document through xml parts (I'm using the vb version):

https://learn.microsoft.com/en-us/visualstudio/vsto/walkthrough-binding-content-controls-to-custom-xml-parts?view=vs-2022&tabs=vb

In the "To create the data file" step, it instructs to change the Build action property to Embedded Resource to embed the xml file into the assembly.

When I go to do this, the dropdown in the Build Action property window only contains the "Content" option, and it doesn't work if I manually enter "Embedded Resource".

For what I can find, there should be other build actions like AdditionalFiles, ApplicationDefinition, Compile, DesignData, etc., but the only one available to me is Content.

Do I have to import these other build types? Is there a library that is relevant to this that I don't have?

I have restarted Visual studio multiple times, some since full computer shutdown. I tried manually entering Embedded Resource.

I was expecting a dropdown list of all build actions.


问:
Symfony : a form field does not want to be null dispite the constraints
In my entity Transaction, the field credit is nullable. field credit in entity Transaction
In my transactionType,I wrote for the chield credit, the option required at false.
the chield credit in transactionType
But when I submit the form, a message asks me to fill in the field.

I tried changing the attribute in the entity, and the constraint in the form but it didn't work.


问:
How to stop function that's listening to AsyncGenerator
I have two functions

```<code>import asyncio
import typing

async def listen(self) -> typing.AsyncGenerator:
    events_queue: asyncio.Queue = asyncio.Queue()
    try:
        while True:

            new_event_task = asyncio.create_task(events_queue.get())
            try:
                yield await new_event_task
            except asyncio.CancelledError:
                return

    finally:
        finally_block()
        # Finally block

async def run_polling(self):
    async for event in self.events_factory.listen():
        handling_event(event)
        # Some stuff

</code>```

How can i throw an exception or "return" or a "break" from generator to run_polling when its approaching to the finally block

I tried to send exceptions but it doesn't seem to work

Body:
I have two functions

import asyncio
import typing

async def listen(self) -> typing.AsyncGenerator:
    events_queue: asyncio.Queue = asyncio.Queue()
    try:
        while True:

            new_event_task = asyncio.create_task(events_queue.get())
            try:
                yield await new_event_task
            except asyncio.CancelledError:
                return

    finally:
        finally_block()
        # Finally block

async def run_polling(self):
    async for event in self.events_factory.listen():
        handling_event(event)
        # Some stuff

How can i throw an exception or "return" or a "break" from generator to run_polling when its approaching to the finally block

I tried to send exceptions but it doesn't seem to work


问:
cargo-maven3-plugin: unable to add datasource
I am trying to configure datasources on a Tomcat using Cargo to allow people doing local tests of the software.
When I start the application using cargo, I have the following error:

```<code>SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mosesEntityManagerFactory' defined in class path resource [app-logic.xml]: Cannot resolve reference to bean 'appDataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appDataSource' defined in class path resource [logic-datasource.xml]: Invocation of init method failed; nested exception is javax.naming.NameNotFoundException: Name [jdbc/app] is not bound in this Context. Unable to find [jdbc].
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334)
...
</code>```

The cargo maven plugin is configured in this way:

      <plugin>
        <groupId>org.codehaus.cargo</groupId>
        <artifactId>cargo-maven3-plugin</artifactId>
        <version>1.10.4</version>
        <configuration>
          <container>
            <containerId>tomcat7x</containerId>
            <zipUrlInstaller>
              <url>https://repo.maven.apache.org/maven2/org/apache/tomcat/tomcat/7.0.55/tomcat-7.0.55.zip</url>
            </zipUrlInstaller>
            <timeout>600000</timeout>
            <output>${project.build.directory}/tomcat7x/container.log</output>
            <append>false</append>
            <log>${project.build.directory}/tomcat7x/cargo.log</log>
            <dependencies>
              [...] some dependencies like mysql, etc...
            </dependencies>
          </container>
          <configuration>
            <type>standalone</type>
            <home>${project.build.directory}/tomcat7x/catalina-base</home>
            <properties>
              <cargo.jvmargs>-Xmx4096m</cargo.jvmargs>
              <cargo.datasource.datasource.mysql>
                cargo.datasource.driver=com.mysql.jdbc.Driver|
                cargo.datasource.url=jdbc:mysql://server:3306/app|
                cargo.datasource.jndi=jdbc/app|
                cargo.datasource.username=ignore|
                cargo.datasource.password=ignore
              </cargo.datasource.datasource.mysql>
            </properties>
            <configfiles>
              <configfile>
                <file>${project.basedir}/src/test/resources/tomcat7/tomcat-users.xml</file>
                <todir>conf</todir>
              </configfile>
              <configfile>
                <file>${project.basedir}/src/test/resources/tomcat7/context.xml</file>
                <todir>conf</todir>
              </configfile>
            </configfiles>
          </configuration>
        </configuration>
      </plugin>
```
<p>The <code>context.xml</code> I provide contains:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<Context path="/">
    <Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader"/>

    <ResourceLink global="jdbc/app" name="jdbc/app" type="javax.sql.DataSource" />

</Context>
</code>```

and the logic-datasource.xml mentioned in the exception contains:

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="appDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/app" />
  </bean>

</beans>
```

I didn't find a way to debug what's happening by myself.

Do you know what is wrong looking at the configuration or how can I check what cargo is doing?
Thanks

Body:
I am trying to configure datasources on a Tomcat using Cargo to allow people doing local tests of the software.
When I start the application using cargo, I have the following error:

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mosesEntityManagerFactory' defined in class path resource [app-logic.xml]: Cannot resolve reference to bean 'appDataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appDataSource' defined in class path resource [logic-datasource.xml]: Invocation of init method failed; nested exception is javax.naming.NameNotFoundException: Name [jdbc/app] is not bound in this Context. Unable to find [jdbc].
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334)
...

The cargo maven plugin is configured in this way:

      <plugin>
        <groupId>org.codehaus.cargo</groupId>
        <artifactId>cargo-maven3-plugin</artifactId>
        <version>1.10.4</version>
        <configuration>
          <container>
            <containerId>tomcat7x</containerId>
            <zipUrlInstaller>
              <url>https://repo.maven.apache.org/maven2/org/apache/tomcat/tomcat/7.0.55/tomcat-7.0.55.zip</url>
            </zipUrlInstaller>
            <timeout>600000</timeout>
            <output>${project.build.directory}/tomcat7x/container.log</output>
            <append>false</append>
            <log>${project.build.directory}/tomcat7x/cargo.log</log>
            <dependencies>
              [...] some dependencies like mysql, etc...
            </dependencies>
          </container>
          <configuration>
            <type>standalone</type>
            <home>${project.build.directory}/tomcat7x/catalina-base</home>
            <properties>
              <cargo.jvmargs>-Xmx4096m</cargo.jvmargs>
              <cargo.datasource.datasource.mysql>
                cargo.datasource.driver=com.mysql.jdbc.Driver|
                cargo.datasource.url=jdbc:mysql://server:3306/app|
                cargo.datasource.jndi=jdbc/app|
                cargo.datasource.username=ignore|
                cargo.datasource.password=ignore
              </cargo.datasource.datasource.mysql>
            </properties>
            <configfiles>
              <configfile>
                <file>${project.basedir}/src/test/resources/tomcat7/tomcat-users.xml</file>
                <todir>conf</todir>
              </configfile>
              <configfile>
                <file>${project.basedir}/src/test/resources/tomcat7/context.xml</file>
                <todir>conf</todir>
              </configfile>
            </configfiles>
          </configuration>
        </configuration>
      </plugin>

The context.xml I provide contains:

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/">
    <Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader"/>

    <ResourceLink global="jdbc/app" name="jdbc/app" type="javax.sql.DataSource" />

</Context>

and the logic-datasource.xml mentioned in the exception contains:

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="appDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/app" />
  </bean>

</beans>

I didn't find a way to debug what's happening by myself.

Do you know what is wrong looking at the configuration or how can I check what cargo is doing?
Thanks


问:
Elastic range query with range greater than a particular day of month
I want to do a query using a range where in timestamp date is greater than , say 10th of the month (month in which query is being run) and less than now ( Time when query is being run) . I keep getting following exception when I run my query (snippet below)

"caused_by" : {
"type" : "illegal_argument_exception",
"reason" : "failed to parse date field [10d/d] with format [dd]",
"caused_by" : {
"type" : "date_time_parse_exception",
"reason" : "date_time_parse_exception: Text '10d/d' could not be parsed, unparsed text found at index 2"
}

GET /_search

{
"query": {

```<code>        "bool": {
          "filter": [
             {
              "range": {
                "@timestamp": {
                  "format": "dd", // I can't use MM in the format and in gte value as I want it to month and year agnostic
                  "gte": "10d/d",
                  "lt": "now" // The query run time, which will always be after 10th of every month
                }
              }
            },
            {
              "wildcard": {
                "kubernetes.namespace": {
                  "value": "apps-*-service"
                }
              }
            },

            {
              "term": {
                "level": {
                  "value": "WARN"
                }
              }
            },
            {
              "match": {
                "message": {
                  "query": "Some log text"
                }
              }
            }
          ]
        }
</code>```

}
}

I tried above code snippet and was expecting it to give me results by for the specified date range range.
However it keeps giving parse error.
Elastic version I am using is - 7.16.3

Body:
I want to do a query using a range where in timestamp date is greater than , say 10th of the month (month in which query is being run) and less than now ( Time when query is being run) . I keep getting following exception when I run my query (snippet below)

"caused_by" : {
"type" : "illegal_argument_exception",
"reason" : "failed to parse date field [10d/d] with format [dd]",
"caused_by" : {
"type" : "date_time_parse_exception",
"reason" : "date_time_parse_exception: Text '10d/d' could not be parsed, unparsed text found at index 2"
}

GET /_search

{
"query": {

        "bool": {
          "filter": [
             {
              "range": {
                "@timestamp": {
                  "format": "dd", // I can't use MM in the format and in gte value as I want it to month and year agnostic
                  "gte": "10d/d",
                  "lt": "now" // The query run time, which will always be after 10th of every month
                }
              }
            },
            {
              "wildcard": {
                "kubernetes.namespace": {
                  "value": "apps-*-service"
                }
              }
            },

            {
              "term": {
                "level": {
                  "value": "WARN"
                }
              }
            },
            {
              "match": {
                "message": {
                  "query": "Some log text"
                }
              }
            }
          ]
        }

}
}

I tried above code snippet and was expecting it to give me results by for the specified date range range.
However it keeps giving parse error.
Elastic version I am using is - 7.16.3


问:
list activities on google drive
I would like to be able to upload my file activities with API from google drive activity or other ideas. Each of my files are stored in a tree structure that contains the name of my client. And in the following put it in an excel file in order to be able to sort it correctly for example if a file has been modified more than 2 times in one day, it is validated

Currently, I used the code provided by google but I can't find the directory of these modified files

I thank you in advance, I really block, other ideas or API are welcome.
Sincerly

```<code>/**
 * Lists 10 activity for a Drive user.
 * @see https://developers.google.com/drive/activity/v2/reference/rest/v2/activity/query
 */
function listDriveActivity() {
  const request = {
  "ancestor_name": "items/root",
  "filter": "time >= \"2022-06-01T00:00:00Z\" time < \"2022-06-30T00:00:00Z\" detail.action_detail_case:EDIT",
  "consolidation_strategy": { "legacy": {} },
  "page_size": 10,
};
  try {
    // Activity.query method is used Query past activity in Google Drive.
    const response = DriveActivity.Activity.query(request);
    const activities = response.activities;
    if (!activities || activities.length === 0) {
      console.log('No activity.');
      return;
    }
    console.log('Recent activity:');
    for (const activity of activities) {
      // get time information of activity.
      const time = getTimeInfo(activity);
      // get the action details/information
      const action = getActionInfo(activity.primaryActionDetail);
      // get the actor's details of activity
      const actors = activity.actors.map(getActorInfo);
      // get target information of activity.
      const targets = activity.targets.map(getTargetInfo);
      // print the time,actor,action and targets of drive activity.
      console.log('%s: %s, %s, %s', time, actors, action, targets);
    }
  } catch (err) {
    // TODO (developer) - Handle error from drive activity API
    console.log('Failed with an error %s', err.message);
  }
}

/**
 * @param {object} object
 * @return {string}  Returns the name of a set property in an object, or else "unknown".
 */
function getOneOf(object) {
  for (const key in object) {
    return key;
  }
  return 'unknown';
}

/**
 * @param {object} activity Activity object.
 * @return {string} Returns a time associated with an activity.
 */
function getTimeInfo(activity) {
  if ('timestamp' in activity) {
    return activity.timestamp;
  }
  if ('timeRange' in activity) {
    return activity.timeRange.endTime;
  }
  return 'unknown';
}

/**
 * @param {object} actionDetail The primary action details of the activity.
 * @return {string} Returns the type of action.
 */
function getActionInfo(actionDetail) {
  return getOneOf(actionDetail);
}

/**
 * @param {object} user The User object.
 * @return {string}  Returns user information, or the type of user if not a known user.
 */
function getUserInfo(user) {
  if ('knownUser' in user) {
    const knownUser = user.knownUser;
    const isMe = knownUser.isCurrentUser || false;
    return isMe ? 'people/me' : knownUser.personName;
  }
  return getOneOf(user);
}

/**
 * @param {object} actor The Actor object.
 * @return {string} Returns actor information, or the type of actor if not a user.
 */
function getActorInfo(actor) {
  if ('user' in actor) {
    return getUserInfo(actor.user);
  }
  return getOneOf(actor);
}

/**
 * @param {object} target The Target object.
 * @return {string} Returns the type of a target and an associated title.
 */
function getTargetInfo(target) {
  if ('driveItem' in target) {
    const title = target.driveItem.title || 'unknown';
    return 'driveItem:"' + title + '"';
  }
  if ('drive' in target) {
    const title = target.drive.title || 'unknown';
    return 'drive:"' + title + '"';
  }
  if ('fileComment' in target) {
    const parent = target.fileComment.parent || {};
    const title = parent.title || 'unknown';
    return 'fileComment:"' + title + '"';
  }
  return getOneOf(target) + ':unknown';
}
</code>```

Final goal: to get the amount of days I work for all my clients.
That a idea

After some search and code (some help with GTP so sorry for begin code)

```<code>function listDriveActivity(sheet,timezone) {

    let pageToken = null;
    do {
      try {
        // Activity.query method is used Query past activity in Google Drive.
        const response = DriveActivity.Activity.query({ "ancestor_name": "items/13oHhdSDQqnM4ppO48FPJq7HAmVjR27H5", //"items/root",
  "filter": "time >= \"2022-01-01T00:00:00Z\" time < \"2022-01-31T00:00:00Z\" detail.action_detail_case:EDIT",
  "consolidation_strategy": { "legacy": {} },"pageSize": 10,pageToken: pageToken});
        //Logger.log(response);
        const activities = response.activities;
        if (!activities || activities.length === 0) {
          console.log('No activity.');
          return;
        }
        //console.log('Recent activity:');
        for (const activity of activities) {
          // get time information of activity.

          const time = getTimeInfo(activity);
          // get the action details/information
          const action = getActionInfo(activity.primaryActionDetail);
          // get the actor's details of activity
          //const actors = activity.actors.map(getActorInfo);
          // get target information of activity.
          const targets = activity.targets.map(getTargetInfo);
          // print the time,actor,action and targets of drive activity.
        // const folderName = activity.targets.map(getFileArborescenceByName);
          const folderName = activity.targets.map(getFileArborescenceByID);
          var NomDossier = JSON.stringify(folderName).replace(/\[\"|\"\]/g,'');
          const ClientName = getClient(NomDossier);
          //console.log('%s: %s, %s, %s, %s', time, action, targets, folderName, ClientName);
          const timeAsDate = new Date(time);
          const lastModified = Utilities.formatDate(timeAsDate, "UTC", "dd-MM-yyyy HH:mm");
          var Nomfichier = JSON.stringify(targets).replace(/\[\"|\"\]/g,'');

          sheet.appendRow([lastModified, action,  Nomfichier,  NomDossier, ClientName]);
        }
        pageToken = response.nextPageToken;
      }
      catch (err) {
        // TODO (developer) - Handle error from drive activity API
        console.log('Failed with an error %s', err.message);
      }
    } while (pageToken);
  return sheet;
}

function getFileArborescenceByID(activity) {
    if ('driveItem' in activity) {
      try {
        const fileName = activity.driveItem.name;
        var modif = getLastPart (fileName);
        var file = DriveApp.getFileById(modif);

          var folders = [];
          var parent = file.getParents();
          while (parent.hasNext()) {

            parent = parent.next();

            folders.push(parent.getName());

            parent = parent.getParents();

          }

        if (folders.length) {
          // Display the full folder path
          var folderName = (folders.reverse().join("/"));
        }
        //var ClientName = getClient(folderName);
        }
      catch (err) {
        // TODO (developer) - Handle error from drive activity API
        console.log('Failed with an error %s', err.message);
      }
    }
  //return 'folderName:"' + folderName + '", Client :"' + ClientName + '"';
  return folderName;
</code>```

Title: list activities on google drive

Body:
I would like to be able to upload my file activities with API from google drive activity or other ideas. Each of my files are stored in a tree structure that contains the name of my client. And in the following put it in an excel file in order to be able to sort it correctly for example if a file has been modified more than 2 times in one day, it is validated

Currently, I used the code provided by google but I can't find the directory of these modified files

I thank you in advance, I really block, other ideas or API are welcome.
Sincerly

/**
 * Lists 10 activity for a Drive user.
 * @see https://developers.google.com/drive/activity/v2/reference/rest/v2/activity/query
 */
function listDriveActivity() {
  const request = {
  "ancestor_name": "items/root",
  "filter": "time >= \"2022-06-01T00:00:00Z\" time < \"2022-06-30T00:00:00Z\" detail.action_detail_case:EDIT",
  "consolidation_strategy": { "legacy": {} },
  "page_size": 10,
};
  try {
    // Activity.query method is used Query past activity in Google Drive.
    const response = DriveActivity.Activity.query(request);
    const activities = response.activities;
    if (!activities || activities.length === 0) {
      console.log('No activity.');
      return;
    }
    console.log('Recent activity:');
    for (const activity of activities) {
      // get time information of activity.
      const time = getTimeInfo(activity);
      // get the action details/information
      const action = getActionInfo(activity.primaryActionDetail);
      // get the actor's details of activity
      const actors = activity.actors.map(getActorInfo);
      // get target information of activity.
      const targets = activity.targets.map(getTargetInfo);
      // print the time,actor,action and targets of drive activity.
      console.log('%s: %s, %s, %s', time, actors, action, targets);
    }
  } catch (err) {
    // TODO (developer) - Handle error from drive activity API
    console.log('Failed with an error %s', err.message);
  }
}

/**
 * @param {object} object
 * @return {string}  Returns the name of a set property in an object, or else "unknown".
 */
function getOneOf(object) {
  for (const key in object) {
    return key;
  }
  return 'unknown';
}

/**
 * @param {object} activity Activity object.
 * @return {string} Returns a time associated with an activity.
 */
function getTimeInfo(activity) {
  if ('timestamp' in activity) {
    return activity.timestamp;
  }
  if ('timeRange' in activity) {
    return activity.timeRange.endTime;
  }
  return 'unknown';
}

/**
 * @param {object} actionDetail The primary action details of the activity.
 * @return {string} Returns the type of action.
 */
function getActionInfo(actionDetail) {
  return getOneOf(actionDetail);
}

/**
 * @param {object} user The User object.
 * @return {string}  Returns user information, or the type of user if not a known user.
 */
function getUserInfo(user) {
  if ('knownUser' in user) {
    const knownUser = user.knownUser;
    const isMe = knownUser.isCurrentUser || false;
    return isMe ? 'people/me' : knownUser.personName;
  }
  return getOneOf(user);
}

/**
 * @param {object} actor The Actor object.
 * @return {string} Returns actor information, or the type of actor if not a user.
 */
function getActorInfo(actor) {
  if ('user' in actor) {
    return getUserInfo(actor.user);
  }
  return getOneOf(actor);
}

/**
 * @param {object} target The Target object.
 * @return {string} Returns the type of a target and an associated title.
 */
function getTargetInfo(target) {
  if ('driveItem' in target) {
    const title = target.driveItem.title || 'unknown';
    return 'driveItem:"' + title + '"';
  }
  if ('drive' in target) {
    const title = target.drive.title || 'unknown';
    return 'drive:"' + title + '"';
  }
  if ('fileComment' in target) {
    const parent = target.fileComment.parent || {};
    const title = parent.title || 'unknown';
    return 'fileComment:"' + title + '"';
  }
  return getOneOf(target) + ':unknown';
}

Final goal: to get the amount of days I work for all my clients.
That a idea

After some search and code (some help with GTP so sorry for begin code)

function listDriveActivity(sheet,timezone) {

    let pageToken = null;
    do {
      try {
        // Activity.query method is used Query past activity in Google Drive.
        const response = DriveActivity.Activity.query({ "ancestor_name": "items/13oHhdSDQqnM4ppO48FPJq7HAmVjR27H5", //"items/root",
  "filter": "time >= \"2022-01-01T00:00:00Z\" time < \"2022-01-31T00:00:00Z\" detail.action_detail_case:EDIT",
  "consolidation_strategy": { "legacy": {} },"pageSize": 10,pageToken: pageToken});
        //Logger.log(response);
        const activities = response.activities;
        if (!activities || activities.length === 0) {
          console.log('No activity.');
          return;
        }
        //console.log('Recent activity:');
        for (const activity of activities) {
          // get time information of activity.

          const time = getTimeInfo(activity);
          // get the action details/information
          const action = getActionInfo(activity.primaryActionDetail);
          // get the actor's details of activity
          //const actors = activity.actors.map(getActorInfo);
          // get target information of activity.
          const targets = activity.targets.map(getTargetInfo);
          // print the time,actor,action and targets of drive activity.
        // const folderName = activity.targets.map(getFileArborescenceByName);
          const folderName = activity.targets.map(getFileArborescenceByID);
          var NomDossier = JSON.stringify(folderName).replace(/\[\"|\"\]/g,'');
          const ClientName = getClient(NomDossier);
          //console.log('%s: %s, %s, %s, %s', time, action, targets, folderName, ClientName);
          const timeAsDate = new Date(time);
          const lastModified = Utilities.formatDate(timeAsDate, "UTC", "dd-MM-yyyy HH:mm");
          var Nomfichier = JSON.stringify(targets).replace(/\[\"|\"\]/g,'');

          sheet.appendRow([lastModified, action,  Nomfichier,  NomDossier, ClientName]);
        }
        pageToken = response.nextPageToken;
      }
      catch (err) {
        // TODO (developer) - Handle error from drive activity API
        console.log('Failed with an error %s', err.message);
      }
    } while (pageToken);
  return sheet;
}

function getFileArborescenceByID(activity) {
    if ('driveItem' in activity) {
      try {
        const fileName = activity.driveItem.name;
        var modif = getLastPart (fileName);
        var file = DriveApp.getFileById(modif);

          var folders = [];
          var parent = file.getParents();
          while (parent.hasNext()) {

            parent = parent.next();

            folders.push(parent.getName());

            parent = parent.getParents();

          }

        if (folders.length) {
          // Display the full folder path
          var folderName = (folders.reverse().join("/"));
        }
        //var ClientName = getClient(folderName);
        }
      catch (err) {
        // TODO (developer) - Handle error from drive activity API
        console.log('Failed with an error %s', err.message);
      }
    }
  //return 'folderName:"' + folderName + '", Client :"' + ClientName + '"';
  return folderName;


问:
Get some elements from yaml files and sort in dataframe
I have couple of yaml files and I need to extract some informations from them. Example of file:

```<code>users:
  user_a:
    topics:
      ab_a: [CONSUME, PRODUCE]
      ab_b: [CONSUME, PRODUCE]
      ab_c: [CONSUME, PRODUCE]
    groups:
      "group_a*":
        - All
  user_b:
    topics:
      bb_a: [CONSUME]
      bb_b: [PRODUCE]
    groups:
      "group_a*":
        - All
  user_c:
    topics:
      cb_a:
        - Consume
      cb_c:
        - Produce
    groups:
      "group_c":
        - All
</code>```

I would like to have dataframe or any other type which will be converted to excel at the end anyway in a format like:

```<code>users | topics | type
user_a| ab_a   | consume, produce
      | ab_b   | consume, produce
      | ab_c   | consume, produce
user_b| bb_a   | consume
      | bb_b   | produce
user_c| cb_a   | produce
      | cb_b   | consume
</code>```

Not really sure how to achieve this in a most neat way, tried this but it's not getting wanted ouptut

```<code>def flatten_dict(nested_dict):
    res = {}
    if isinstance(nested_dict, dict):
        for k in nested_dict:
            flattened_dict = flatten_dict(nested_dict[k])
            for key, val in flattened_dict.items():
                key = list(key)
                key.insert(0, k)
                res[tuple(key)] = val
    else:
        res[()] = nested_dict
    return res

def nested_dict_to_df(values_dict):
    flat_dict = flatten_dict(values_dict)
    df = pd.DataFrame.from_dict(flat_dict, orient="index")
    df.index = pd.MultiIndex.from_tuples(df.index)
    df = df.unstack(level=-1)
    df.columns = df.columns.map("{0[1]}".format)
    return df

nested_dict_to_df(mydict)
</code>```

Body:
I have couple of yaml files and I need to extract some informations from them. Example of file:

users:
  user_a:
    topics:
      ab_a: [CONSUME, PRODUCE]
      ab_b: [CONSUME, PRODUCE]
      ab_c: [CONSUME, PRODUCE]
    groups:
      "group_a*":
        - All
  user_b:
    topics:
      bb_a: [CONSUME]
      bb_b: [PRODUCE]
    groups:
      "group_a*":
        - All
  user_c:
    topics:
      cb_a:
        - Consume
      cb_c:
        - Produce
    groups:
      "group_c":
        - All

I would like to have dataframe or any other type which will be converted to excel at the end anyway in a format like:

users | topics | type
user_a| ab_a   | consume, produce
      | ab_b   | consume, produce
      | ab_c   | consume, produce
user_b| bb_a   | consume
      | bb_b   | produce
user_c| cb_a   | produce
      | cb_b   | consume

Not really sure how to achieve this in a most neat way, tried this but it's not getting wanted ouptut

def flatten_dict(nested_dict):
    res = {}
    if isinstance(nested_dict, dict):
        for k in nested_dict:
            flattened_dict = flatten_dict(nested_dict[k])
            for key, val in flattened_dict.items():
                key = list(key)
                key.insert(0, k)
                res[tuple(key)] = val
    else:
        res[()] = nested_dict
    return res

def nested_dict_to_df(values_dict):
    flat_dict = flatten_dict(values_dict)
    df = pd.DataFrame.from_dict(flat_dict, orient="index")
    df.index = pd.MultiIndex.from_tuples(df.index)
    df = df.unstack(level=-1)
    df.columns = df.columns.map("{0[1]}".format)
    return df

nested_dict_to_df(mydict)


问:
CCDS Data Source Script will not log string
I have a script that runs when I click a "Test Connection" button in an Adaptive Insights Integration script.  I am trying to log the XML that is returned, just to verify the information prior to coding the next part.  The script I have is as follows:

```<code>function testConnection(context) {
    // dataSource variable to get Data Source Setting Parameters
    var dataSource = context.getDataSource();

    // Get the static credentials parameters.
    const userName = dataSource.getSetting("Adaptive Username").getValue(); // Not Nedeed after WD User Sync. Do Not delete
    const password = dataSource.getSetting("Adaptive Password").getValue(); // Not Nedeed after WD User Sync. Do Not delete
    const instanceCode = dataSource.getSetting("instanceCode").getValue();

    //This example connects to Postman Echo using POST
    var url = 'https://api.adaptiveinsights.com/api/v35';
    var method = 'POST';

    // XML request body, this is where the method type (ie. exportUsers) goes.
    var body = '<?xml version="1.0" encoding="UTF-8"?><call method="exportUsers" callerName="AdaptiveInsightsAPI">'
    body += '<credentials login="' + userName + '" password="' + password + '" /></call>';

    var headers = { 'Content-Type': 'application/xml' };

    var response = null;
    let finalResponse = null;

    try {
        response = ai.https.request(url, method, body, headers);
        finalResponse = response.getBody();
        ai.log.logVerbose("API Call Successful", finalResponse);
        return true;
    }
    catch (exception) {
        ai.log.logInfo('api call failed', '' + exception);
        return false;
    }
}
</code>```

The response will not show in the log, it only shows "...".  However, if I change "finalResponse" to "finalResponse[1]" or try to log any other character from the string ([2],[3],[4],etc.), it displays the character in the string.  I also tried to slice the characters to fit within the 1000 character limit, but that displays nothing at all when I try to log the response.

What can I do different to get the response body into the log?

Body:
I have a script that runs when I click a "Test Connection" button in an Adaptive Insights Integration script.  I am trying to log the XML that is returned, just to verify the information prior to coding the next part.  The script I have is as follows:

function testConnection(context) {
    // dataSource variable to get Data Source Setting Parameters
    var dataSource = context.getDataSource();

    // Get the static credentials parameters.
    const userName = dataSource.getSetting("Adaptive Username").getValue(); // Not Nedeed after WD User Sync. Do Not delete
    const password = dataSource.getSetting("Adaptive Password").getValue(); // Not Nedeed after WD User Sync. Do Not delete
    const instanceCode = dataSource.getSetting("instanceCode").getValue();

    //This example connects to Postman Echo using POST
    var url = 'https://api.adaptiveinsights.com/api/v35';
    var method = 'POST';

    // XML request body, this is where the method type (ie. exportUsers) goes.
    var body = '<?xml version="1.0" encoding="UTF-8"?><call method="exportUsers" callerName="AdaptiveInsightsAPI">'
    body += '<credentials login="' + userName + '" password="' + password + '" /></call>';

    var headers = { 'Content-Type': 'application/xml' };

    var response = null;
    let finalResponse = null;

    try {
        response = ai.https.request(url, method, body, headers);
        finalResponse = response.getBody();
        ai.log.logVerbose("API Call Successful", finalResponse);
        return true;
    }
    catch (exception) {
        ai.log.logInfo('api call failed', '' + exception);
        return false;
    }
}

The response will not show in the log, it only shows "...".  However, if I change "finalResponse" to "finalResponse[1]" or try to log any other character from the string ([2],[3],[4],etc.), it displays the character in the string.  I also tried to slice the characters to fit within the 1000 character limit, but that displays nothing at all when I try to log the response.

What can I do different to get the response body into the log?


问:
Cumulative Values on Missing Data Quicksight
I'm trying to create a cumulative quarterly count divided by week. I have the underlying table that looks like this:

Date
Id

01/01/2022
X

02/01/2022
Y

The result is this

Screenshot of the problem](https://i.stack.imgur.com/9tmFA.png)

There are some white spaces due to particular weeks where there are no data. I would like to fill these blank spaces with the value of the week before (as it should be on a cumulative count) and with zero if it's the first week of the quarter.
Is there a way to solve this problem without creating any support table or any "fake data" to avoid the cell to be blank?


问:
Python logging, get DEBUG message from only my code
You know when you set the root logger in Python to DEBUG, and annoyingly it prints debug messages from whatever libraries you're using (Pytorch, Numpy, Matplotlib, whatever)? And then you have to manually turn them off in-code, only for more debug logs from other libraries that you install later to appear?

What I want is a switch that turns all of my loggers (that I got from logging.getLogger(__name__)) to level DEBUG, but not anything else. I initially thought about having a "root" logger for all of my code, named my_root, say, and defining my own get_logger() that wraps around logging.getLogger() by prepending my_root to the names of all the loggers. But then, my "root" logger my_root is still the child of the real root logger, and I can't switch my_root to DEBUG without also switching the root logger to DEBUG (as far as I understand), which I don't want to do. Is there a (preferably elegant) way to get what I want?

I guess the equivalent question is, can I set a child logger's level lower than its parent logger?


问:
jira jql for user story pulled from next sprint
I am lookin for a Jira JQL which would show those user stories that are pulled from next sprint into current sprint.

Below screenshot is one of the history of a user story in which JQLSCRIP Sprint 2 is the current sprint and JQLSCRIP Sprint 3 is the next sprint. Need help to create a JQL query in jira to pull all such user stories.


问:
How to get the commit IDs of the submodule and their tags? (GITLAB)
I'm using the following command to get the tags in each of the submodules listed from newest to oldest:

```<code>git submodule foreach git tag --sort=-taggerdate -l
</code>```

I'm getting the output below. I grabbed 3 random submodules along with its tags:

What I'm trying to do now is to also get the commit IDs, of both the submodules and all the tags listed inside each submodule.

Is there a way to do this?

Body:
I'm using the following command to get the tags in each of the submodules listed from newest to oldest:

git submodule foreach git tag --sort=-taggerdate -l

I'm getting the output below. I grabbed 3 random submodules along with its tags:

What I'm trying to do now is to also get the commit IDs, of both the submodules and all the tags listed inside each submodule.

Is there a way to do this?


问:
Read BMP with fake alpha with twelvemonkeys
I have a BMP file with fake alpha (similar to rgb32fakealpha.bmp from the bmp suite). That is, it has 32 bits per pixel, but doesn't have bitfields set, but uses the extra bits in each pixel as alpha anyways. And I'm using the twelvemonkeys library with the imageio-bmp plugin to read the BMP.

If I just do ImageIO.read(inputFile), then it doesn't preserve the transparency. Is there some way I can configure imageio, to use the alpha channel for this image?


问:
conflicting requests and missing packages while installing KDE Plasma Workspaces
I am completely new to RHEL based OSes. Trying to switch from GNOME to KDE.
Followed the instructions at this link

Got some errors except for step 1. Adding some screenshots for reference.

Also this problem is occuring after I installed a product called EDB. (https://www.enterprisedb.com/)