问:
instances where a variable gets its updated value
I have a question. I am currently trying to understand how a variable is updated/changed. I am working with a binary search tree and I get how the pointer are used aswell as the dereferencing in the parameter to access a classes variable.
...

```<code>class BST {
public:
  int value;
  BST *left;
  BST *right;

  BST(int val);
  BST &insert(int val);
};

int findClosestValueInBst(BST *tree, int target);
int findClosestValueInBstHelper(BST *tree, int target, int closest);

int findClosestValueInBst(BST *tree, int target){
  return findClosestValueInBstHelper(tree, target, tree->value);
}

int findClosestValueInBstHelper(BST *tree, int target, int closest) {
  // Write your code here.
  if(abs(target - closest) > abs(target - tree->value)){
    closest = tree->value;
  }
  if(target < tree ->value && tree->left != nullptr){
    return findClosestValueInBstHelper(tree->left, target, closest);
  }
  else if(target > tree->value && tree -> right != nullptr){
    return findClosestValueInBstHelper(tree->right, target, closest);
  }
  else {
    return closest;
  }

}
</code>```

...
I see that the variable 'closest' has a direct value change in the findClosestValueInBstHelper(). I know that I have to physically put a value for closest in the paraeter so that the function will run. So what im asking is to describe the instances where the values change. please.

Body:
I have a question. I am currently trying to understand how a variable is updated/changed. I am working with a binary search tree and I get how the pointer are used aswell as the dereferencing in the parameter to access a classes variable.
...

class BST {
public:
  int value;
  BST *left;
  BST *right;

  BST(int val);
  BST &insert(int val);
};

int findClosestValueInBst(BST *tree, int target);
int findClosestValueInBstHelper(BST *tree, int target, int closest);

int findClosestValueInBst(BST *tree, int target){
  return findClosestValueInBstHelper(tree, target, tree->value);
}

int findClosestValueInBstHelper(BST *tree, int target, int closest) {
  // Write your code here.
  if(abs(target - closest) > abs(target - tree->value)){
    closest = tree->value;
  }
  if(target < tree ->value && tree->left != nullptr){
    return findClosestValueInBstHelper(tree->left, target, closest);
  }
  else if(target > tree->value && tree -> right != nullptr){
    return findClosestValueInBstHelper(tree->right, target, closest);
  }
  else {
    return closest;
  }

}

...
I see that the variable 'closest' has a direct value change in the findClosestValueInBstHelper(). I know that I have to physically put a value for closest in the paraeter so that the function will run. So what im asking is to describe the instances where the values change. please.


来源: stackexchange

问:
In Spring 2.5, how to config like tag <mvc:resources> in Spring MVC 3.0?
I need maintain old system with JDK/Java 1.6 , Apache Tomcat 6.0.x, Spring 2.5.6 . I am reading tutorial https://mkyong.com/spring-mvc/spring-mvc-jquery-autocomplete-example/

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.mkyong" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    <mvc:resources mapping="/resources/**" location="/resources/" />
    <mvc:annotation-driven />
</beans>
```
<p>I focus at (this line of code for Spring 3.0, full source code https://1drv.ms/u/s!AhMAe-fS33VbhYw_5QZm9dwpwUTQnQ?e=sYcvYG )</p>
<pre class="lang-xml prettyprint-override"><code><mvc:resources mapping="/resources/**" location="/resources/" />
</code>```

and looking configuration for same purpose for Spring 2.5.6 .

I see at here http://www.springframework.org/schema/mvc/ , but not see what for Spring 2.5 .
In Spring 2.5, how to config like tag <mvc:resources> in Spring MVC 3.0?

ContentLicense: CC BY-SA 4.0

Body:
I need maintain old system with JDK/Java 1.6 , Apache Tomcat 6.0.x, Spring 2.5.6 . I am reading tutorial https://mkyong.com/spring-mvc/spring-mvc-jquery-autocomplete-example/

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.mkyong" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    <mvc:resources mapping="/resources/**" location="/resources/" />
    <mvc:annotation-driven />
</beans>

I focus at (this line of code for Spring 3.0, full source code https://1drv.ms/u/s!AhMAe-fS33VbhYw_5QZm9dwpwUTQnQ?e=sYcvYG )

<mvc:resources mapping="/resources/**" location="/resources/" />

and looking configuration for same purpose for Spring 2.5.6 .

I see at here http://www.springframework.org/schema/mvc/ , but not see what for Spring 2.5 .
In Spring 2.5, how to config like tag <mvc:resources> in Spring MVC 3.0?


问:
I am getting an error while running the servlet app (implementing the servlet interface)
I was simply trying a basic servlet app by implementing a servlet class. But I am getting errors. I did some research and found that src folder location may not be correct.
Can anyone help me out in this?

`web browser logs
console logs
package explorer details

FirstServlet.java file
web.xml file`


问:
Updgrading to Android Dolphin 2021.3.1 Patch 1 from Arctic Fox
Currently I am using Arctic Fox 2020.3.1 Patch 4 IDE on Windows 10. I want to upgrade to newer version Dolphin 2021.3.1 Patch 1 version.

Checking for updates (Help>Check for updates) I get a dialog box, I get a dialog box with "Download" button. This button takes me to download the full version of the Dolphin. As no "Upgrade" option available, this can finally make a new installation parallel to earlier installation.

My concerns are

Is this correct? We need to download full version and install.

If so what will happen to changes to settings/behaviour in my Arctic Fox version? I do not remeber all the changes done.

Please let me know how to proceed as I am sure many would have faced this problem and solved.


问:
DevExpress XtraReport generate excel sheets based on DetailReport band
I've been working on a project to export xml data into .xlsx files. But I ran into some difficulties in implementing the above in .NET Core using DevExpress XtraReport Class.

Is it possible to customize generated Excel sheet such that the number of excel sheet is based on the DetailReport band page break?

I got 5 DetailReport band so is it possible when I Export to Excel, the file contains 5 sheets, and the header part is on another sheet?

I've attached a screenshot below, please refer it and provide an appropriate solution


问:
Extremely Slow for Selenium Webdriver to get URL
Trying to learn Selenium today but it takes around 9 seconds to just to get the URL, any suggestions? Running on a new 2022 Mac.

```<code>from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
start_time = time.time()

url = 'https://www.google.com'
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install())) #this takes about 5 seconds

#tried those things, didn't help
# options = webdriver.ChromeOptions()
# options.add_argument('--disable-gpu')
# options.add_argument("--disable-extensions")
# prefs = {"profile.managed_default_content_settings.images": 2}
# options.add_experimental_option("prefs", prefs)
# options.add_argument('-no-sandbox')
# # options.add_argument('headless')
# options.add_argument('-disable-dev-shm-usage')
# driver = webdriver.Chrome(options=options)

driver.get(url) #takes another 5 seconds
print("hi")
print("--- %s seconds ---" % (time.time() - start_time))

</code>```

Tried "headless" option as well. Auto Proxy is also off in the setting.

I'd expect to have the code finish within 1 second.

Body:
Trying to learn Selenium today but it takes around 9 seconds to just to get the URL, any suggestions? Running on a new 2022 Mac.

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
start_time = time.time()

url = 'https://www.google.com'
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install())) #this takes about 5 seconds

#tried those things, didn't help
# options = webdriver.ChromeOptions()
# options.add_argument('--disable-gpu')
# options.add_argument("--disable-extensions")
# prefs = {"profile.managed_default_content_settings.images": 2}
# options.add_experimental_option("prefs", prefs)
# options.add_argument('-no-sandbox')
# # options.add_argument('headless')
# options.add_argument('-disable-dev-shm-usage')
# driver = webdriver.Chrome(options=options)

driver.get(url) #takes another 5 seconds
print("hi")
print("--- %s seconds ---" % (time.time() - start_time))

Tried "headless" option as well. Auto Proxy is also off in the setting.

I'd expect to have the code finish within 1 second.


问:
Integrating ARGO to Keycloak to enable SSO
I want to integrate ARGO with keycloak to enable SSO and we made necessary changes in quick-start-postgres.yaml.

Here is the yaml file we are using to start argo locally. https://raw.githubusercontent.com/argoproj/argo-workflows/master/manifests/quick-start-postgres.yaml

And below are the sections we are modifying to support for SSO integration

Deployment section:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: argo-server
spec:
  selector:
    matchLabels:
      app: argo-server
  template:
    metadata:
      labels:
        app: argo-server
    spec:
      containers:
      - args:
        - server
        - --auth-mode=sso
</code>```

workflow-controller-configmap section :

```<code>apiVersion: v1
data:
  sso: |
    # This is the root URL of the OIDC provider (required).
    issuer: http://notebook3254:8080/auth/realms/master
    # This is name of the secret and the key in it that contain OIDC client
    # ID issued to the application by the provider (required).
    clientId:
      name: client-id-secret4
      key: client-id-key
    # This is name of the secret and the key in it that contain OIDC client
    # secret issued to the application by the provider (required).
    clientSecret:
      name: client-secret-secret4
      key: client-secret-key
    # This is the redirect URL supplied to the provider (required). It must
    # be in the form <argo-server-root-url>/oauth2/callback. It must be
    # browser-accessible.
    redirectUrl: http://localhost:2746/oauth2/callback
  artifactRepository: |
    s3:
      bucket: my-bucket
</code>```

In KeyCloak UI new client **"avatar" **is created and made it as confidential and for the same secrets are generated "rBbvw4sNXk3Ssh1jV1NdIkDRN22xGBFP".

the redirect uri for the created client is :

keycloak_redirect_uri_snapshot

Also at kubernates level, we are creating secrets for the both client-id, client secrets generated in keycloak.

kubectl create secret -n argo generic client-id-secret4 --from-literal=client-id-key=avatar
kubectl create secret -n argo generic client-secret-secret4 --from-literal=client-secret-key=rBbvw4sNXk3Ssh1jV1NdIkDRN22xGBFP

We are starting the argo by issuing below 2 commands

kubectl apply -n argo -f modified-file/quick-start-postgres.yaml
kubectl -n argo port-forward svc/argo-server 2746:2746

After executing above commands and trying to login as Single-sign on , it is getting redirected to keycloak ui but it is showing issue as below.

redirect_page_snapshot

and below are the logs getting printed in kubernates  .

logs_snapshot

can someone help me on this?

Body:
I want to integrate ARGO with keycloak to enable SSO and we made necessary changes in quick-start-postgres.yaml.

Here is the yaml file we are using to start argo locally. https://raw.githubusercontent.com/argoproj/argo-workflows/master/manifests/quick-start-postgres.yaml

And below are the sections we are modifying to support for SSO integration

Deployment section:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: argo-server
spec:
  selector:
    matchLabels:
      app: argo-server
  template:
    metadata:
      labels:
        app: argo-server
    spec:
      containers:
      - args:
        - server
        - --auth-mode=sso

workflow-controller-configmap section :

apiVersion: v1
data:
  sso: |
    # This is the root URL of the OIDC provider (required).
    issuer: http://notebook3254:8080/auth/realms/master
    # This is name of the secret and the key in it that contain OIDC client
    # ID issued to the application by the provider (required).
    clientId:
      name: client-id-secret4
      key: client-id-key
    # This is name of the secret and the key in it that contain OIDC client
    # secret issued to the application by the provider (required).
    clientSecret:
      name: client-secret-secret4
      key: client-secret-key
    # This is the redirect URL supplied to the provider (required). It must
    # be in the form <argo-server-root-url>/oauth2/callback. It must be
    # browser-accessible.
    redirectUrl: http://localhost:2746/oauth2/callback
  artifactRepository: |
    s3:
      bucket: my-bucket

In KeyCloak UI new client **"avatar" **is created and made it as confidential and for the same secrets are generated "rBbvw4sNXk3Ssh1jV1NdIkDRN22xGBFP".

the redirect uri for the created client is :

keycloak_redirect_uri_snapshot

Also at kubernates level, we are creating secrets for the both client-id, client secrets generated in keycloak.

kubectl create secret -n argo generic client-id-secret4 --from-literal=client-id-key=avatar
kubectl create secret -n argo generic client-secret-secret4 --from-literal=client-secret-key=rBbvw4sNXk3Ssh1jV1NdIkDRN22xGBFP

We are starting the argo by issuing below 2 commands

kubectl apply -n argo -f modified-file/quick-start-postgres.yaml
kubectl -n argo port-forward svc/argo-server 2746:2746

After executing above commands and trying to login as Single-sign on , it is getting redirected to keycloak ui but it is showing issue as below.

redirect_page_snapshot

and below are the logs getting printed in kubernates  .

logs_snapshot

can someone help me on this?


问:
CameraX + OpenCV Image Analysis
I want to draw a rectangle with opencv from the image acquired by camerax and display it in imageview.

The top of the attached image is Image View and the bottom is Preview View.

ImageView Noise

ImageView Black

An image with noise or a completely black image is output.

I suspect there is a problem with the process of converting ImageProxy to Mat or Bitmap.

```<code>class MyImageAnalyzer(previewview:PreviewView,imageview:ImageView) : ImageAnalysis.Analyzer {
var previewView:PreviewView = previewview
var imageView:ImageView = imageview

override fun analyze(image: ImageProxy) {
    /* Create cv::mat(RGB888) from image(NV21) */
    val matOrg = getMatFromImage(image)

    /* Fix image rotation (it looks image in PreviewView is automatically fixed by CameraX???) */
    val mat = fixMatRotation(matOrg)

    /* Do some image processing */
    val matOutput = Mat(mat.rows(), mat.cols(), mat.type())

    /* Draw something for test */
    Imgproc.rectangle(
        matOutput,
        Rect(10, 10, 100, 100),
        Scalar(255.0, 0.0, 0.0)
    )

    /* Convert cv::mat to bitmap for drawing */
    val bitmap =
        Bitmap.createBitmap(matOutput.cols(), matOutput.rows(), Bitmap.Config.ARGB_8888)
    Utils.matToBitmap(matOutput, bitmap)

    /* Display the result onto ImageView */
    Handler(Looper.getMainLooper()).post {
        imageView.setImageBitmap(bitmap)
    }

    /* Close the image otherwise, this function is not called next time */
    image.close()
}

private fun getMatFromImage(image: ImageProxy): Mat {
    /* https://stackoverflow.com/questions/30510928/convert-android-camera2-api-yuv-420-888-to-rgb */
    val yBuffer: ByteBuffer = image.planes[0].buffer
    val uBuffer: ByteBuffer = image.planes[1].buffer
    val vBuffer: ByteBuffer = image.planes[2].buffer
    val ySize: Int = yBuffer.remaining()
    val uSize: Int = uBuffer.remaining()
    val vSize: Int = vBuffer.remaining()
    val nv21 = ByteArray(ySize + uSize + vSize)
    yBuffer.get(nv21, 0, ySize)
    vBuffer.get(nv21, ySize, vSize)
    uBuffer.get(nv21, ySize + vSize, uSize)
    val yuv = Mat(image.height + image.height / 2, image.width, CvType.CV_8UC1)
    yuv.put(0, 0, nv21)
    val mat = Mat()
    Imgproc.cvtColor(yuv, mat, Imgproc.COLOR_YUV2RGB_NV21, 3)
    return mat
}

private fun fixMatRotation(matOrg: Mat): Mat {
    val mat: Mat
    when (previewView.display.rotation) {
        Surface.ROTATION_0 -> {
            mat = Mat(matOrg.cols(), matOrg.rows(), matOrg.type())
            Core.transpose(matOrg, mat)
            Core.flip(mat, mat, 1)
        }
        Surface.ROTATION_90 -> mat = matOrg
        Surface.ROTATION_270 -> {
            mat = matOrg
            Core.flip(mat, mat, -1)
        }
        else -> {
            mat = Mat(matOrg.cols(), matOrg.rows(), matOrg.type())
            Core.transpose(matOrg, mat)
            Core.flip(mat, mat, 1)
        }
    }
    return mat
}
</code>```

}

I hope the processed image is displayed smoothly on the ImageView

Title: CameraX + OpenCV Image Analysis

Body:
I want to draw a rectangle with opencv from the image acquired by camerax and display it in imageview.

The top of the attached image is Image View and the bottom is Preview View.

ImageView Noise

ImageView Black

An image with noise or a completely black image is output.

I suspect there is a problem with the process of converting ImageProxy to Mat or Bitmap.

class MyImageAnalyzer(previewview:PreviewView,imageview:ImageView) : ImageAnalysis.Analyzer {
var previewView:PreviewView = previewview
var imageView:ImageView = imageview

override fun analyze(image: ImageProxy) {
    /* Create cv::mat(RGB888) from image(NV21) */
    val matOrg = getMatFromImage(image)

    /* Fix image rotation (it looks image in PreviewView is automatically fixed by CameraX???) */
    val mat = fixMatRotation(matOrg)

    /* Do some image processing */
    val matOutput = Mat(mat.rows(), mat.cols(), mat.type())

    /* Draw something for test */
    Imgproc.rectangle(
        matOutput,
        Rect(10, 10, 100, 100),
        Scalar(255.0, 0.0, 0.0)
    )

    /* Convert cv::mat to bitmap for drawing */
    val bitmap =
        Bitmap.createBitmap(matOutput.cols(), matOutput.rows(), Bitmap.Config.ARGB_8888)
    Utils.matToBitmap(matOutput, bitmap)

    /* Display the result onto ImageView */
    Handler(Looper.getMainLooper()).post {
        imageView.setImageBitmap(bitmap)
    }

    /* Close the image otherwise, this function is not called next time */
    image.close()
}

private fun getMatFromImage(image: ImageProxy): Mat {
    /* https://stackoverflow.com/questions/30510928/convert-android-camera2-api-yuv-420-888-to-rgb */
    val yBuffer: ByteBuffer = image.planes[0].buffer
    val uBuffer: ByteBuffer = image.planes[1].buffer
    val vBuffer: ByteBuffer = image.planes[2].buffer
    val ySize: Int = yBuffer.remaining()
    val uSize: Int = uBuffer.remaining()
    val vSize: Int = vBuffer.remaining()
    val nv21 = ByteArray(ySize + uSize + vSize)
    yBuffer.get(nv21, 0, ySize)
    vBuffer.get(nv21, ySize, vSize)
    uBuffer.get(nv21, ySize + vSize, uSize)
    val yuv = Mat(image.height + image.height / 2, image.width, CvType.CV_8UC1)
    yuv.put(0, 0, nv21)
    val mat = Mat()
    Imgproc.cvtColor(yuv, mat, Imgproc.COLOR_YUV2RGB_NV21, 3)
    return mat
}

private fun fixMatRotation(matOrg: Mat): Mat {
    val mat: Mat
    when (previewView.display.rotation) {
        Surface.ROTATION_0 -> {
            mat = Mat(matOrg.cols(), matOrg.rows(), matOrg.type())
            Core.transpose(matOrg, mat)
            Core.flip(mat, mat, 1)
        }
        Surface.ROTATION_90 -> mat = matOrg
        Surface.ROTATION_270 -> {
            mat = matOrg
            Core.flip(mat, mat, -1)
        }
        else -> {
            mat = Mat(matOrg.cols(), matOrg.rows(), matOrg.type())
            Core.transpose(matOrg, mat)
            Core.flip(mat, mat, 1)
        }
    }
    return mat
}

}

I hope the processed image is displayed smoothly on the ImageView


问:
Errors during changing collations of all columns of all tables in MYSQL
I am trying to change collation for all columns of all tables in MySQL. I saw in other posts that it can be as following

```<code>SELECT CONCAT('ALTER TABLE `', TABLE_NAME, '` MODIFY COLUMN `', COLUMN_NAME,'` ',
              DATA_TYPE, IF(CHARACTER_MAXIMUM_LENGTH IS NULL
       OR DATA_TYPE LIKE 'longtext', '', CONCAT('(', CHARACTER_MAXIMUM_LENGTH,
                                         ')')
       ), ' COLLATE utf8mb4_0900_ai_ci;') AS 'USE whitesource_collate_test;'
    FROM   INFORMATION_SCHEMA.COLUMNS
    WHERE  TABLE_SCHEMA = 'my_schema'
           AND (SELECT INFORMATION_SCHEMA.TABLES.TABLE_TYPE
                FROM   INFORMATION_SCHEMA.TABLES
                WHERE  INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA =
                       INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA
                       AND INFORMATION_SCHEMA.TABLES.TABLE_NAME =
                           INFORMATION_SCHEMA.COLUMNS.TABLE_NAME
                LIMIT  1) LIKE 'BASE TABLE'
           AND DATA_TYPE IN ( 'char', 'varchar' )
</code>```

After creating and running the script on part of tables I am getting errors like

```<code>Referencing column 'COL1_ID_' and referenced column 'ID_' in foreign key constraint 'MY_FK_GROUP' are incompatible
</code>```

As I understand this can cause because of order of tables processed. The question is - what is the best way to handle such errors except of manually process tables with errors ? Thanks in advance

Body:
I am trying to change collation for all columns of all tables in MySQL. I saw in other posts that it can be as following

SELECT CONCAT('ALTER TABLE `', TABLE_NAME, '` MODIFY COLUMN `', COLUMN_NAME,'` ',
              DATA_TYPE, IF(CHARACTER_MAXIMUM_LENGTH IS NULL
       OR DATA_TYPE LIKE 'longtext', '', CONCAT('(', CHARACTER_MAXIMUM_LENGTH,
                                         ')')
       ), ' COLLATE utf8mb4_0900_ai_ci;') AS 'USE whitesource_collate_test;'
    FROM   INFORMATION_SCHEMA.COLUMNS
    WHERE  TABLE_SCHEMA = 'my_schema'
           AND (SELECT INFORMATION_SCHEMA.TABLES.TABLE_TYPE
                FROM   INFORMATION_SCHEMA.TABLES
                WHERE  INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA =
                       INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA
                       AND INFORMATION_SCHEMA.TABLES.TABLE_NAME =
                           INFORMATION_SCHEMA.COLUMNS.TABLE_NAME
                LIMIT  1) LIKE 'BASE TABLE'
           AND DATA_TYPE IN ( 'char', 'varchar' )

After creating and running the script on part of tables I am getting errors like

Referencing column 'COL1_ID_' and referenced column 'ID_' in foreign key constraint 'MY_FK_GROUP' are incompatible

As I understand this can cause because of order of tables processed. The question is - what is the best way to handle such errors except of manually process tables with errors ? Thanks in advance


问:
Finding subarray with sum closest to K
We want to find the subset of elements in an array whose sum is closest to a target value. It could be higher or lower, the absolute difference matter. The output should be a list of indices. If there exists multiple subsets with the same sum, we want to pick the lexicographically smallest one.

For example nums = [400, 800, 400, 500, 350, 350], target = 2000
Subsets [1, 3, 4, 5] and [0, 2, 3, 4, 5] both sum up to 2000, so we pick [0, 2, 3, 4, 5] since it is lexicographically smaller.

The following code I wrote passes initial tests but exceeds the time limit.

```<code>def solution(nums, target):

    def helper(i, path, currSum):
        if i == len(nums):
            currDiff = abs(currSum - target)
            if  currDiff < ans[0]:
                ans[0] = currDiff
                ans[1] = path
            elif currDiff == ans[0]:
                if "".join([str(u) for u in path]) < "".join([str(u) for u in ans[1]]):
                    ans[1] = path
            return
        helper(i+1, path, currSum)
        helper(i+1, path+[i], currSum+nums[i])

    minDiff = float("Inf")
    minPath = [float("Inf") for _ in range(len(nums))]
    ans = [minDiff, minPath]
    helper(0, [], 0)
    return ans[1]

print(solution([400, 800, 400, 500, 350, 350], 2000))

</code>```

Any idea how to write the optimal solution?

Title: Finding subarray with sum closest to K

Body:
We want to find the subset of elements in an array whose sum is closest to a target value. It could be higher or lower, the absolute difference matter. The output should be a list of indices. If there exists multiple subsets with the same sum, we want to pick the lexicographically smallest one.

For example nums = [400, 800, 400, 500, 350, 350], target = 2000
Subsets [1, 3, 4, 5] and [0, 2, 3, 4, 5] both sum up to 2000, so we pick [0, 2, 3, 4, 5] since it is lexicographically smaller.

The following code I wrote passes initial tests but exceeds the time limit.

def solution(nums, target):

    def helper(i, path, currSum):
        if i == len(nums):
            currDiff = abs(currSum - target)
            if  currDiff < ans[0]:
                ans[0] = currDiff
                ans[1] = path
            elif currDiff == ans[0]:
                if "".join([str(u) for u in path]) < "".join([str(u) for u in ans[1]]):
                    ans[1] = path
            return
        helper(i+1, path, currSum)
        helper(i+1, path+[i], currSum+nums[i])

    minDiff = float("Inf")
    minPath = [float("Inf") for _ in range(len(nums))]
    ans = [minDiff, minPath]
    helper(0, [], 0)
    return ans[1]

print(solution([400, 800, 400, 500, 350, 350], 2000))

Any idea how to write the optimal solution?


问:
SAP_HANA ) How to execute a SQL Query with UTF-8 characters?
When executing a query that contains Korean(UTF-8), the column name is returned normally, but the data is returned abnormally.

Executed SQL statements and results are as follows:

SQL : SELECT '한글' FROM DUMMY

RESULT :

The queries you run are encoded in UTF-8. The reason is that the LOCALE executing the query is ko_KR.UTF8, and the Korean alphabet appears normal in the session.

However, SAP HANA DB determines the SQL statement that was created as ASCII.

If the CHAR_AS_UTF8 option is set to true, the above phenomenon appears, and if the CHAR_AS_UTF8 option is set to false, the data appears normally.

Can you explain this phenomenon?

How can I get the result I want?

The text is broken after SQLPrepare provided by ODBC.

How to change Encoding type of SAP HANA DB Server?
Now, enc          : ASCII

but, we need
enc          : UTF-8


问:
What's the best way to filter out content user has already seen from a large corpus?
I am building a video app where users can watch a curated list of videos. I do not want to show them the same videos again if they have seen them already.

With SQL database, it would be could be accomplished with a WHERE NOT IN and JOIN operations. However, I can't seem to find a good solution for NoSQL or non-relational database.

A few things I could think of:

Use a in-memory database and calculate difference in the two set A and B where A is the set of videos watched by the user and B is set of all videos. However, this would be expensive to operate.

Perform a time-bound filtering at the serving time and serve the best possible feed. The obvious trade-off here is the quality of the feed since now there is a non-zero chance that user would see watched videos again.

How do platforms such as YouTube, TikTok, Instagram achieve this? Do they rely on machine learning for this?


问:
Redux Dev tools doesn't show the initial state
I am working on front-end authentication. I can register just fine, however, I realized that the dev tools show

```<code>null(pin):undefined
</code>```

I could see the state just fine before, when I first created the initialState. I haven't changed anything specific to that, I just added the register function, reducers, etc. Here's the related code:

authSlice:

```<code>import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import authService from "./authService";
//Get user from localStorage
const user = JSON.parse(localStorage.getItem("user"));

const initialState = {
  user: user ? user : null,
  isError: false,
  isSuccess: false,
  isLoading: false,
  message: "",
};

// Register user

export const register = createAsyncThunk(
  "auth/register",
  async (user, thunkAPI) => {
    try {
        return await authService.register(user)
    } catch (error) {
        const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString()
        return thunkAPI.rejectWithValue(message)
    }
  }
);

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    reset: (state) => {
      state.isLoading = false;
      state.isSuccess = false;
      state.isError = false;
      state.message = "";
    },
  },
  extraReducers: (builder) => {
     builder
       .addCase(register.pending, (state) => {
         state.isLoading = true;
       })
       .addCase(register.fulfilled, (state, action) => {
         state.isLoading = false;
         state.isSuccess = true;
         state.user = action.payload;
       })
       .addCase(register.rejected, (state, action) => {
         state.isLoading = false;
         state.isError = true;
         state.message = action.payload;
         state.user = null;
       });
  },
});
export const { reset } = authSlice.actions;
export default authSlice.reducer;
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from "react-redux";
import App from './App';
import { store } from './app/store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);
</code>```

Register function in Register page:

```<code>export default function SignUp() {
  const [formData, setFormData] = useState({
    username: "",
    email: "",
    password: "",
    password2: "",
  });
  const { username, email, password, password2 } = formData;

  const navigate = useNavigate();
  const dispatch = useDispatch();

  const { user, isLoading, isError, isSuccess, message } = useSelector(
    (state) => state.auth
  );

  useEffect(() => {
    if (isError) {
      toast.error(message);
    }

    if (isSuccess || user) {
      navigate("/");
    }

    dispatch(reset());
  }, [user, isError, isSuccess, message, navigate, dispatch]);

  const onChange = (e) => {
    setFormData((prevState) => ({
      ...prevState,
      [e.target.name]: e.target.value,
    }));
  };

  const onSubmit = (e) => {
    e.preventDefault();
    if (password !== password2) {
      toast.error("Passwords do not match");
    } else {
      const userData = {
        username,
        email,
        password,
      };
      dispatch(register(userData));
    }
  };
</code>```

Edited:

works fine before registering(cleared cache from browser to 'logout')

As soon as I go to the register page, the info is gone on the dev tools, as well as after the registration. However, I did see the actions before, now they are gone as well.

Body:
I am working on front-end authentication. I can register just fine, however, I realized that the dev tools show

null(pin):undefined

I could see the state just fine before, when I first created the initialState. I haven't changed anything specific to that, I just added the register function, reducers, etc. Here's the related code:

authSlice:

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import authService from "./authService";
//Get user from localStorage
const user = JSON.parse(localStorage.getItem("user"));

const initialState = {
  user: user ? user : null,
  isError: false,
  isSuccess: false,
  isLoading: false,
  message: "",
};

// Register user

export const register = createAsyncThunk(
  "auth/register",
  async (user, thunkAPI) => {
    try {
        return await authService.register(user)
    } catch (error) {
        const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString()
        return thunkAPI.rejectWithValue(message)
    }
  }
);

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    reset: (state) => {
      state.isLoading = false;
      state.isSuccess = false;
      state.isError = false;
      state.message = "";
    },
  },
  extraReducers: (builder) => {
     builder
       .addCase(register.pending, (state) => {
         state.isLoading = true;
       })
       .addCase(register.fulfilled, (state, action) => {
         state.isLoading = false;
         state.isSuccess = true;
         state.user = action.payload;
       })
       .addCase(register.rejected, (state, action) => {
         state.isLoading = false;
         state.isError = true;
         state.message = action.payload;
         state.user = null;
       });
  },
});
export const { reset } = authSlice.actions;
export default authSlice.reducer;

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from "react-redux";
import App from './App';
import { store } from './app/store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

Register function in Register page:

export default function SignUp() {
  const [formData, setFormData] = useState({
    username: "",
    email: "",
    password: "",
    password2: "",
  });
  const { username, email, password, password2 } = formData;

  const navigate = useNavigate();
  const dispatch = useDispatch();

  const { user, isLoading, isError, isSuccess, message } = useSelector(
    (state) => state.auth
  );

  useEffect(() => {
    if (isError) {
      toast.error(message);
    }

    if (isSuccess || user) {
      navigate("/");
    }

    dispatch(reset());
  }, [user, isError, isSuccess, message, navigate, dispatch]);

  const onChange = (e) => {
    setFormData((prevState) => ({
      ...prevState,
      [e.target.name]: e.target.value,
    }));
  };

  const onSubmit = (e) => {
    e.preventDefault();
    if (password !== password2) {
      toast.error("Passwords do not match");
    } else {
      const userData = {
        username,
        email,
        password,
      };
      dispatch(register(userData));
    }
  };

Edited:

works fine before registering(cleared cache from browser to 'logout')

As soon as I go to the register page, the info is gone on the dev tools, as well as after the registration. However, I did see the actions before, now they are gone as well.


问:
Points not rendered when origin outside of camera view
I am attempting to use a Points object at scene origin for a particle system.
It is easy to implement (world coordinates can be used) and works well, except that the points are only rendered when the origin is in the camera's view.

Is there a way to enable/force rendering?

Or will I have to attach it to the (moving) emitter and recalculate world position of each particle accordingly?


问:
How to flatten the dataset properly
I have a dataset like this

The problem here is i want to have General_officers_0_Name , General_officers_0_Title, General_officers_0_YearBorn and same for the others ones with different values like MAtainance_name_type_work_ty like this for the nested data type how to do this please help to solve this?
If this question is asked previously and contains the answer please remind to link with that.

The output of print (df.head().to_dict(orient='list'))  is

Title: How to flatten the dataset properly


问:
why dropdown value is erased when we scroll down the data block items
when I select the first row of populated field values in drop down it is showing year  as intended.

But when I select second row the value in drop down is not visible.
Can anyone tell me why it is happening.


问:
Outlook Add-In with SSO publishing on AppSource for multiple organizations with their AAD app
Outlook Add-In with SSO, publishing on AppSource | used by multiple organizations.

how the <ID> and <Resource> tags are updated/configured for different organizations using the Add-In. (sample given below)

When we install with Manifest.xml file, can update them manually for their Azure active directory App ID (client ID).
(e.g. Microsoft 365 admin center {centralized deployment})

Are we need to publish individual Add-In "Manifest.xml" on AppSource for each organization?

```<code><WebApplicationInfo>
    <Id>5661fed9-f33d-4e95-b6cf-624a34a2f51d</Id>
    <Resource>api://addin.contoso.com/5661fed9-f33d-4e95-b6cf-624a34a2f51d</Resource>
    <Scopes>
        <Scope>openid</Scope>
        <Scope>profile</Scope>
    </Scopes>
</WebApplicationInfo>
</code>```

Body:
Outlook Add-In with SSO, publishing on AppSource | used by multiple organizations.

how the <ID> and <Resource> tags are updated/configured for different organizations using the Add-In. (sample given below)

When we install with Manifest.xml file, can update them manually for their Azure active directory App ID (client ID).
(e.g. Microsoft 365 admin center {centralized deployment})

Are we need to publish individual Add-In "Manifest.xml" on AppSource for each organization?

<WebApplicationInfo>
    <Id>5661fed9-f33d-4e95-b6cf-624a34a2f51d</Id>
    <Resource>api://addin.contoso.com/5661fed9-f33d-4e95-b6cf-624a34a2f51d</Resource>
    <Scopes>
        <Scope>openid</Scope>
        <Scope>profile</Scope>
    </Scopes>
</WebApplicationInfo>


问:
Parse Issue (Xcode): Module 'shared_preferences_ios' not found
I am building a Flutter App for both IOS and Android, using FlutLab.io to do so.
When I try to build out the IOS application (FlutLab.io builds it out for me) I get the following error:

Parse Issue (Xcode): Module 'shared_preferences_ios' not found

I have seen a few fixes for this problem but they all involve using Xcode, which I don't have access to at all (Windows user).

Is there a code-orientated way of getting around this problem or at least a way to hard-code any fixes that may involve Xcode?

Note:
shared_preferences has been added to the pubspec.yaml file and has been placed correctly in the file

I have tried searching the problem but every answer I get involves Xcode, which I don't have access to


问:
Html email decrease space between two tables
Having problems on decreasing the space with my two tables in Outlook windows if i send an email thru my gmail and outlook mcbook the space between two tables are fine but if the email is send to outlook windows it's having a large space between my tables please if anyone who is expert on doing some issue like this Thank you for your helpThis is on windows outlook table
This is on my mac

I want to fix this problem because its driving me crazy T.T


问:
How to load the latest version of delta parquet using spark?
I have access to a repository where a team writes parquet file (without partitioning them), using delta (i.e there is a delta log in this repo). I have no access to the table itself though. To create a dataframe from those parquet, I am using the below code:

spark.read.format('delta').load(repo)
```

Executing this loads the entire dataframe, regardless of the delta log. How should I proceed to load the latest version of my data?

Body:
I have access to a repository where a team writes parquet file (without partitioning them), using delta (i.e there is a delta log in this repo). I have no access to the table itself though. To create a dataframe from those parquet, I am using the below code:

spark.read.format('delta').load(repo)

Executing this loads the entire dataframe, regardless of the delta log. How should I proceed to load the latest version of my data?


问:
procedure is not working in start TRANSACTION(mysql)
I created and CALLed the procedure below, but it didn't work properly, so I posted it. which part is the problem??

I think the part where v_log_table goes in is not wrong. Because it worked well with that syntax in other procedures as well.

As a result of searching with test debug, it seems that the START TRANSACTION part does not work well...

```<code>    DECLARE v_done              INT DEFAULT 0;
    DECLARE v_date_client_req   VARCHAR(8);
    DECLARE v_log_table         VARCHAR(6);
    DECLARE v_cnt               INT;
    DECLARE v_table_name        VARCHAR(18);

    DECLARE v_cursor CURSOR FOR

    SELECT DATE_FORMAT(A.date_client_req, '%Y%m%d') as date_client_req
           , count(*) AS cnt
      FROM   ( SELECT DATE_FORMAT(date_client_req, '%Y%m%d') AS date_client_req
               FROM   ata_mmt_tran
               WHERE  ata_id = p_ata_id
               AND    msg_status = '3'
               LIMIT  1000
            ) A
      GROUP BY DATE_FORMAT(A.date_client_req, '%Y%m%d')
      LIMIT 5;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_done = 1;
    DECLARE CONTINUE HANDLER FOR SQLWARNING ROLLBACK;
    DECLARE CONTINUE HANDLER FOR SQLEXCEPTION ROLLBACK;

    /*set transaction isolation level READ UNCOMMITTED;*/
    SET v_done=0;

    OPEN v_cursor;
    cursor_loop:LOOP
    FETCH v_cursor INTO v_date_client_req, v_cnt;
    IF v_done = 1 THEN
        LEAVE cursor_loop;
    END IF;

    IF v_date_client_req IS NULL THEN
        LEAVE cursor_loop;
    END IF;

    SET v_log_table = SUBSTRING(v_date_client_req,1,6);
    CALL bzt_ato_log_create(v_log_table);

    SET @sql_insert = CONCAT("INSERT IGNORE INTO ata_mmt_log_", v_log_table , "
            SELECT mt_pr
                , mt_refkey
                , priority
                , date_client_req
                , subject
                , content
                , callback
                , msg_status
                , recipient_num
                , date_mt_sent
                , date_rslt
                , date_mt_report
                , report_code
                , rs_id
                , country_code
                , msg_type
                , crypto_yn
                , ata_id
                , reg_date
                , sysdate()
                , sender_key
                , template_code
                , response_method
                , message_group_code
                , attachment_type
                , attachment_name
                , attachment_url
                , img_url
                , img_link
                , etc_text_1
                , etc_text_2
                , etc_text_3
                , etc_num_1
                , etc_num_2
                , etc_num_3
                , etc_date_1
            FROM  ata_mmt_tran
            WHERE ata_id = ?
            AND   msg_status = '3'
            AND   DATE_FORMAT(date_client_req, '%Y%m%d') = ?
            LIMIT 2000");

        SET @p_ata_id = p_ata_id;
        SET @v_date_client_req = v_date_client_req;

        START TRANSACTION;

        PREPARE stmt_insert FROM @sql_insert;
        EXECUTE stmt_insert USING @p_ata_id, @v_date_client_req;
        DEALLOCATE PREPARE stmt_insert;

        SET @sql_insert = CONCAT("DELETE FROM ata_mmt_tran USING ata_mmt_tran A
        INNER JOIN ata_mmt_log_", v_log_table ," B
        ON A.mt_pr = B.mt_pr");

        PREPARE stmt_insert FROM @sql_insert;

        EXECUTE stmt_insert;
        DEALLOCATE PREPARE stmt_insert;

        COMMIT;

        END LOOP cursor_loop;

    CLOSE v_cursor;

    SET v_done=0;
</code>```

Body:
I created and CALLed the procedure below, but it didn't work properly, so I posted it. which part is the problem??

I think the part where v_log_table goes in is not wrong. Because it worked well with that syntax in other procedures as well.

As a result of searching with test debug, it seems that the START TRANSACTION part does not work well...

    DECLARE v_done              INT DEFAULT 0;
    DECLARE v_date_client_req   VARCHAR(8);
    DECLARE v_log_table         VARCHAR(6);
    DECLARE v_cnt               INT;
    DECLARE v_table_name        VARCHAR(18);

    DECLARE v_cursor CURSOR FOR

    SELECT DATE_FORMAT(A.date_client_req, '%Y%m%d') as date_client_req
           , count(*) AS cnt
      FROM   ( SELECT DATE_FORMAT(date_client_req, '%Y%m%d') AS date_client_req
               FROM   ata_mmt_tran
               WHERE  ata_id = p_ata_id
               AND    msg_status = '3'
               LIMIT  1000
            ) A
      GROUP BY DATE_FORMAT(A.date_client_req, '%Y%m%d')
      LIMIT 5;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_done = 1;
    DECLARE CONTINUE HANDLER FOR SQLWARNING ROLLBACK;
    DECLARE CONTINUE HANDLER FOR SQLEXCEPTION ROLLBACK;

    /*set transaction isolation level READ UNCOMMITTED;*/
    SET v_done=0;

    OPEN v_cursor;
    cursor_loop:LOOP
    FETCH v_cursor INTO v_date_client_req, v_cnt;
    IF v_done = 1 THEN
        LEAVE cursor_loop;
    END IF;

    IF v_date_client_req IS NULL THEN
        LEAVE cursor_loop;
    END IF;

    SET v_log_table = SUBSTRING(v_date_client_req,1,6);
    CALL bzt_ato_log_create(v_log_table);

    SET @sql_insert = CONCAT("INSERT IGNORE INTO ata_mmt_log_", v_log_table , "
            SELECT mt_pr
                , mt_refkey
                , priority
                , date_client_req
                , subject
                , content
                , callback
                , msg_status
                , recipient_num
                , date_mt_sent
                , date_rslt
                , date_mt_report
                , report_code
                , rs_id
                , country_code
                , msg_type
                , crypto_yn
                , ata_id
                , reg_date
                , sysdate()
                , sender_key
                , template_code
                , response_method
                , message_group_code
                , attachment_type
                , attachment_name
                , attachment_url
                , img_url
                , img_link
                , etc_text_1
                , etc_text_2
                , etc_text_3
                , etc_num_1
                , etc_num_2
                , etc_num_3
                , etc_date_1
            FROM  ata_mmt_tran
            WHERE ata_id = ?
            AND   msg_status = '3'
            AND   DATE_FORMAT(date_client_req, '%Y%m%d') = ?
            LIMIT 2000");

        SET @p_ata_id = p_ata_id;
        SET @v_date_client_req = v_date_client_req;

        START TRANSACTION;

        PREPARE stmt_insert FROM @sql_insert;
        EXECUTE stmt_insert USING @p_ata_id, @v_date_client_req;
        DEALLOCATE PREPARE stmt_insert;

        SET @sql_insert = CONCAT("DELETE FROM ata_mmt_tran USING ata_mmt_tran A
        INNER JOIN ata_mmt_log_", v_log_table ," B
        ON A.mt_pr = B.mt_pr");

        PREPARE stmt_insert FROM @sql_insert;

        EXECUTE stmt_insert;
        DEALLOCATE PREPARE stmt_insert;

        COMMIT;

        END LOOP cursor_loop;

    CLOSE v_cursor;

    SET v_done=0;


问:
Access Ant Design table column value
I am trying to condionally render Bage based on status column value. Even though I can render the table with the status values, I cannot access the status column for each item  for conditional rendering of status Badge. How do I access the values listed on the column ?
The "status" value is inside data [ ]</p>
```<code>const tableColumns = columns.map((item) => ({
    ...item,
    ellipsis,
  }));

 const columns = [
{
      title: 'Статус',
      dataIndex: 'status',
      render: () =>   {dataIndex.status === "in progress" ?  <Badge status="processing" text="in progress" /> : <Badge status="success" text="delivered" />}
    },
]

 <Table
        {...tableProps}
        pagination={{
          position: [top, bottom],
        }}
        columns={tableColumns}
        dataSource={hasData ? data : []}
        scroll={scroll}
      />
</code>```

Title: Access Ant Design table column value

Body:
I am trying to condionally render Bage based on status column value. Even though I can render the table with the status values, I cannot access the status column for each item  for conditional rendering of status Badge. How do I access the values listed on the column ?
The "status" value is inside data [ ]

const tableColumns = columns.map((item) => ({
    ...item,
    ellipsis,
  }));

 const columns = [
{
      title: 'Статус',
      dataIndex: 'status',
      render: () =>   {dataIndex.status === "in progress" ?  <Badge status="processing" text="in progress" /> : <Badge status="success" text="delivered" />}
    },
]


问:
how to make the camera offset relative to the object in the roblox studio via a script?
i cannot make offset of camera in roblox
there is no errors in output but its anyways dont works

```<code>task.wait(3)
print('hvnrherjwl')

local runService = game:GetService('RunService')
local cam = game.Workspace.CurrentCamera
local camAttachment = script.Parent

local offset = camAttachment.Position + Vector3.new(25,40,25)
local lookAt = camAttachment.Position

cam.CameraType = 'Scriptable'

runService.Heartbeat:Connect(function(deltaTime)
    cam.CFrame = CFrame.new(offset,lookAt)
end)
</code>```

p.s. i used runService to modify it in the future

Body:
i cannot make offset of camera in roblox
there is no errors in output but its anyways dont works

task.wait(3)
print('hvnrherjwl')

local runService = game:GetService('RunService')
local cam = game.Workspace.CurrentCamera
local camAttachment = script.Parent

local offset = camAttachment.Position + Vector3.new(25,40,25)
local lookAt = camAttachment.Position

cam.CameraType = 'Scriptable'

runService.Heartbeat:Connect(function(deltaTime)
    cam.CFrame = CFrame.new(offset,lookAt)
end)

p.s. i used runService to modify it in the future


问:
Prevent program from forking
I want to run a binary in Python, but I want to disallow the binary from making new processes. It seems like the standard way to do this is to call setrlimit through the resource module, and constrain resource.RLIMIT_NPROC. However, my attempts have all failed.

Here's a simple example:

foo.py:

import subprocess
import resource
import os

def set_nproc() -> None:
    resource.setrlimit(
        resource.RLIMIT_NPROC,
        (1, 1),
    )

if __name__ == '__main__':
    subprocess.Popen(['./a.out'], preexec_fn=set_nproc)
```
<p>foo.c:</p>
```#include <unistd.h>
#include <stdlib.h>

int main() {
    printf("Running C Program!\n");
    int pid = fork();
    sleep(10);
    return 0;
}
```

Also, a.out is the binary produced by compiling foo.c. Running foo.py, I'd expect the following to take place:

subprocess.Popen will spawn a new process. Before running ./a.out, it will run the set_nproc function, which will set the RLIMIT_NPROC soft and hard limit to 1.

The new process will run the binary a.out. The binary will print Running C Program! and terminate because the next line tries to spawn a new process, which is not allowed.

It seems like my understanding is not correct because the C program actually terminates to completion (i.e., I do not receive any sort of error). How can I fix this?

Note: I realize that setrlimit imposes a limit on the user and not the process. Even then, I'd expect an error to take place somewhere here.

Title: Prevent program from forking

Body:
I want to run a binary in Python, but I want to disallow the binary from making new processes. It seems like the standard way to do this is to call setrlimit through the resource module, and constrain resource.RLIMIT_NPROC. However, my attempts have all failed.

Here's a simple example:

foo.py:

import subprocess
import resource
import os

def set_nproc() -> None:
    resource.setrlimit(
        resource.RLIMIT_NPROC,
        (1, 1),
    )

if __name__ == '__main__':
    subprocess.Popen(['./a.out'], preexec_fn=set_nproc)

foo.c:

#include <unistd.h>
#include <stdlib.h>

int main() {
    printf("Running C Program!\n");
    int pid = fork();
    sleep(10);
    return 0;
}

Also, a.out is the binary produced by compiling foo.c. Running foo.py, I'd expect the following to take place:

subprocess.Popen will spawn a new process. Before running ./a.out, it will run the set_nproc function, which will set the RLIMIT_NPROC soft and hard limit to 1.

The new process will run the binary a.out. The binary will print Running C Program! and terminate because the next line tries to spawn a new process, which is not allowed.

It seems like my understanding is not correct because the C program actually terminates to completion (i.e., I do not receive any sort of error). How can I fix this?

Note: I realize that setrlimit imposes a limit on the user and not the process. Even then, I'd expect an error to take place somewhere here.


问:
maintain additional field in service ticket in SAP C4C
anyone knows how to maintain an additional field in Service ticket in SAP C4C? We have a field Repair Category, and want to add additional choices on its dropdown. S14 and S15 wants to be maintained as seen on the 1st photo.[enter image description here](https://i.stack.imgur.com/IWoBh.jpg)

Already tried checking Implementation Projects > Code List Mapping but unable to find a table for the Repair Category.


问:
Is it possible to get test count of each class separately from testng xml file?
Currently we use testng ITestContext to get the test count running via testng xml file. My file contains multiple classes and

```<code>context.getPassedTests().size()
</code>```

returns the total count of passed tests from all the classes mentioned in the xml file
my file looks like this :

```<code><!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >

<suite name="Main service" verbose="1" >
    <test name="Smoke and Sanity" >
        <classes>
            <class name="tests.Service1" />
            <class name="tests.Service2" />
            <class name="tests.Service3" />
        </classes>
    </test>
    <listeners>
        <listener class-name="com.service.data.Base.TestResult"></listener>
    </listeners>
</suite>
</code>```

TestResult implements ITestListener and calculates the total number of tests being run by summing up context.getPassedTests().size() + context.getFailedTests().size() + context.getSkippedTests().size(), and this returns the total number of tests from classes service1, service2, service3

What i want is to get the total number of test cases from individual test class mentioned in xml and not the combined.

unable to find an approach

Body:
Currently we use testng ITestContext to get the test count running via testng xml file. My file contains multiple classes and

context.getPassedTests().size()

returns the total count of passed tests from all the classes mentioned in the xml file
my file looks like this :

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >

<suite name="Main service" verbose="1" >
    <test name="Smoke and Sanity" >
        <classes>
            <class name="tests.Service1" />
            <class name="tests.Service2" />
            <class name="tests.Service3" />
        </classes>
    </test>
    <listeners>
        <listener class-name="com.service.data.Base.TestResult"></listener>
    </listeners>
</suite>

TestResult implements ITestListener and calculates the total number of tests being run by summing up context.getPassedTests().size() + context.getFailedTests().size() + context.getSkippedTests().size(), and this returns the total number of tests from classes service1, service2, service3

What i want is to get the total number of test cases from individual test class mentioned in xml and not the combined.

unable to find an approach


问:
i get value error in model.fit(x_train,y_train) why? and what is the solution please?
```<code>model_1 = SGDClassifier(random_state = 0)
model_2 = DecisionTreeClassifier(random_state = 0)
model_3 = KNeighborsClassifier(n_neighbors = 2)

for model in (model_1, model_2, model_3):
    #x_train,y_train,x_test,y_test = train_test_split(x, y, test_size = 0.3, random_state = 0)
    model.fit(x_train, y_train)
    print(mode.__class__.__name, model.score(x_test, y_test)
</code>```


问:
add IConfiguration in the program of .net 6
i need a similar action in class program in asp.net core 6

```<code>public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        Setting.Configuration = configuration;
    }

    public IConfiguration Configuration { get; }
}

public class Setting
{
    public static string ServiceUrl
    {
        get
        {
            var config = Configuration["ServiceUrl"];
            return config != null ? config : string.Empty;
        }
    }
}
</code>```

or maybe something like that helps me to call data from the API using .net 6

Body:
i need a similar action in class program in asp.net core 6

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        Setting.Configuration = configuration;
    }

    public IConfiguration Configuration { get; }
}

public class Setting
{
    public static string ServiceUrl
    {
        get
        {
            var config = Configuration["ServiceUrl"];
            return config != null ? config : string.Empty;
        }
    }
}

or maybe something like that helps me to call data from the API using .net 6


问:
Create chart when the first file of the day and when the last one was saved
I have tried to create a program to analyze a NEtzwerk folder.

I would like to know between Monday and Friday when, for a selected period, the first file of the day is filed and when the last file of the day is filed.

This way I can see if there are any discrepancies on the same day of the week and between days for the selected time period.

For the last file of the day I want to display the curve in blue and for the first file in red, but for now I have only tried to realize the first curve.

Maybe someone has an idea how I get it to run?

```<code>import os
import datetime
import matplotlib.pyplot as plt

def get_first_times(folder_path):
    week = {
        "Monday": None,
        "Tuesday": None,
        "Wednesday": None,
        "Thursday": None,
        "Friday": None,
        "Saturday": None,
        "Sunday": None
    }
    for file in os.listdir(folder_path):
        file_time = datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(folder_path, file)))
        day_of_week = file_time.strftime("%A")
        if week[day_of_week] is None or file_time < week[day_of_week]:
            week[day_of_week] = file_time
    # Wochentage ohne gültige Uhrzeit auf 23:59 setzen
    for day, time in week.items():
        if time is None:
            week[day] = datetime.datetime.strptime("23:59", "%H:%M")
    return week

folder_path = "//DEKER/Bench/Data/D10"

first_times = get_first_times(folder_path)

days = list(first_times.keys())
times = [time.strftime("%H:%M") for time in first_times.values()]

plt.plot(days, times)
plt.xlabel("Day of the week")
plt.ylabel("Time")
plt.show()
</code>```

Body:
I have tried to create a program to analyze a NEtzwerk folder.

I would like to know between Monday and Friday when, for a selected period, the first file of the day is filed and when the last file of the day is filed.

This way I can see if there are any discrepancies on the same day of the week and between days for the selected time period.

For the last file of the day I want to display the curve in blue and for the first file in red, but for now I have only tried to realize the first curve.

Maybe someone has an idea how I get it to run?

import os
import datetime
import matplotlib.pyplot as plt

def get_first_times(folder_path):
    week = {
        "Monday": None,
        "Tuesday": None,
        "Wednesday": None,
        "Thursday": None,
        "Friday": None,
        "Saturday": None,
        "Sunday": None
    }
    for file in os.listdir(folder_path):
        file_time = datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(folder_path, file)))
        day_of_week = file_time.strftime("%A")
        if week[day_of_week] is None or file_time < week[day_of_week]:
            week[day_of_week] = file_time
    # Wochentage ohne gültige Uhrzeit auf 23:59 setzen
    for day, time in week.items():
        if time is None:
            week[day] = datetime.datetime.strptime("23:59", "%H:%M")
    return week

folder_path = "//DEKER/Bench/Data/D10"

first_times = get_first_times(folder_path)

days = list(first_times.keys())
times = [time.strftime("%H:%M") for time in first_times.values()]

plt.plot(days, times)
plt.xlabel("Day of the week")
plt.ylabel("Time")
plt.show()


问:
Gradle Build with gradle cache on docker container
To use the live reload functionality i have to use entry point as  gradle quarkusDev to build and run my app/service on a docker container.
But as I am working with a monorepo there are a lot of dependencies that gets downloaded as part of build and a lot tasks that was already completed on my local gradle.

Is there any way that i can mount my .gradle local folder to .gradle on docker container so that it can use the pre processed tasks or loaded dependencies.


问:
html2Canvas dropdown screenshot glitch
I took a screenshot of a simple dropdown using html2canvas and the screenshot is not proper.

```<code><div id="container">
  <select><option value="allen">allen</option><option value="lola">lola</option></select>
</div>
</code>```
```<code>html2canvas(document.querySelector("#container")).then(canvas => {
   document.getElementById("container").appendChild(canvas);
});
</code>```

codepen link attached

Title: html2Canvas dropdown screenshot glitch

Body:
I took a screenshot of a simple dropdown using html2canvas and the screenshot is not proper.

  <select><option value="allen">allen</option><option value="lola">lola</option></select>

html2canvas(document.querySelector("#container")).then(canvas => {
   document.getElementById("container").appendChild(canvas);
});

codepen link attached


问:
I used html2Canvas to convert web pages into pdf，because there was a lot of content in web pages
I used html2Canvas to convert web pages into pdf, because there was a lot of content in web pages (pictures and charts), the exported pictures reached 13.4MB, set scale to 1, which could be exported normally, but it was too fuzzy to use, set scale to 2, some contents could not be exported. html2Canvas is there a file size setting? What should I do?

html2canvas 1.4.1

I tried to set scale to 1, and the export can be normal. Set scale to 2, the export is incomplete


问:
Why can I not iterate over an array of strings?
I don't get an error message however it does not print "Dieser Artikel ist vorhanden" when I input the same "Artiklenummer" although it should. What did I do wrong?</p>
```<code> int main()
    {
    printf("                                LAGERVERWALTUNGSSYSTEM \n");
    printf("                             DRUECK DIE 1 FUER Einlagerung \n" );
    printf("                             DRUECK DIE 2 FUER Auslagerung \n" );

    char artnr[50],menge[50],me[50],neu[50],date[50];
    int zahl, calcam, id, sub,amount;
    int lenm = 0;
    int len = 0;
    int greatlen = 0;
    int result = 0;
    char str[5][5][5];
    int mengen[10];
    int a = 1;
    int s = 0;
    while(a > 0){
     printf("Geben sie eine Zahl ein:");
     scanf("%d", &zahl);
     if(zahl == 1){
       printf("Geben sie ein:\nArtikelnr.:");
       scanf("%s",&artnr);
       strcpy(str[s][0],artnr);
       len= len+1;
       printf("Menge:");
       scanf("%d",&mengen[lenm]);
       lenm = lenm+1;
       printf("Mengeneinheit:");
       scanf("%s",&me);
       strcpy(str[s][1],me);
       len= len+1;
       printf("Datum:");
       scanf("%s",&date);
       strcpy(str[s][2],date);
       len= len+1;
     };
     s =s+1;
     greatlen = greatlen +1;
     if(zahl == 2){
       printf("Welche Ware wollen sie auslagern?:\nArtikelnr.:");
       scanf("%s",&neu);
       printf("Welche Menge wollen sie auslagern?:");
       scanf("%d",&sub);
       for(int i= 0; i<len;i++){
           if(str[j][0] == neu){
                printf("Dieser Artikel ist vorhanden");
           }
          };
        };

    };

    return 0;
   }
</code>```

Body:
I don't get an error message however it does not print "Dieser Artikel ist vorhanden" when I input the same "Artiklenummer" although it should. What did I do wrong?

 int main()
    {
    printf("                                LAGERVERWALTUNGSSYSTEM \n");
    printf("                             DRUECK DIE 1 FUER Einlagerung \n" );
    printf("                             DRUECK DIE 2 FUER Auslagerung \n" );

    char artnr[50],menge[50],me[50],neu[50],date[50];
    int zahl, calcam, id, sub,amount;
    int lenm = 0;
    int len = 0;
    int greatlen = 0;
    int result = 0;
    char str[5][5][5];
    int mengen[10];
    int a = 1;
    int s = 0;
    while(a > 0){
     printf("Geben sie eine Zahl ein:");
     scanf("%d", &zahl);
     if(zahl == 1){
       printf("Geben sie ein:\nArtikelnr.:");
       scanf("%s",&artnr);
       strcpy(str[s][0],artnr);
       len= len+1;
       printf("Menge:");
       scanf("%d",&mengen[lenm]);
       lenm = lenm+1;
       printf("Mengeneinheit:");
       scanf("%s",&me);
       strcpy(str[s][1],me);
       len= len+1;
       printf("Datum:");
       scanf("%s",&date);
       strcpy(str[s][2],date);
       len= len+1;
     };
     s =s+1;
     greatlen = greatlen +1;
     if(zahl == 2){
       printf("Welche Ware wollen sie auslagern?:\nArtikelnr.:");
       scanf("%s",&neu);
       printf("Welche Menge wollen sie auslagern?:");
       scanf("%d",&sub);
       for(int i= 0; i<len;i++){
           if(str[j][0] == neu){
                printf("Dieser Artikel ist vorhanden");
           }
          };
        };

    };

    return 0;
   }


问:
How to store the data in a variable instead of saving it to local storage after downloading the file using axios?
Currently this code is downloading the file from the url and then it is saving to the local storage. Now what I want to do is I want to store the data in a string variable instead of saving it as a file.
Here's my code:

```<code>function download(url, token){

    return new Promise(function (resolve,reject) {
        axios({
      method: "get",
      url: url,
      headers: {
            Authorization: 'Bearer ' + token,
          },
      responseType: "stream"
  }).then(async function (response) {
        const stream = response.data.pipe(fs.createWriteStream("File.txt"));
        stream.on("finish", function() {
          console.log("File has been downloaded!")
          resolve(1)
        } );
        stream.on("error", () => console.log("An error occured while downloading..."));

  }) .catch(error => {
      console.log('error downloading file');
      console.log(error)
  });
      });
}
</code>```

To something like this

```<code>//not a working code
function download(url, token){

    return new Promise(function (resolve,reject) {
        axios({
      method: "get",
      url: url,
      headers: {
            Authorization: 'Bearer ' + token,
          },
      responseType: "stream"
  }).then(async function (response) {
        let stringvariable = FileDownloadedAsAStringFromTheStream;
        resolve(stringvariable)

  }) .catch(error => {
      console.log('error downloading file');
      console.log(error)
  });
      });
}
</code>```

Body:
Currently this code is downloading the file from the url and then it is saving to the local storage. Now what I want to do is I want to store the data in a string variable instead of saving it as a file.
Here's my code:

function download(url, token){

    return new Promise(function (resolve,reject) {
        axios({
      method: "get",
      url: url,
      headers: {
            Authorization: 'Bearer ' + token,
          },
      responseType: "stream"
  }).then(async function (response) {
        const stream = response.data.pipe(fs.createWriteStream("File.txt"));
        stream.on("finish", function() {
          console.log("File has been downloaded!")
          resolve(1)
        } );
        stream.on("error", () => console.log("An error occured while downloading..."));

  }) .catch(error => {
      console.log('error downloading file');
      console.log(error)
  });
      });
}

To something like this

//not a working code
function download(url, token){

    return new Promise(function (resolve,reject) {
        axios({
      method: "get",
      url: url,
      headers: {
            Authorization: 'Bearer ' + token,
          },
      responseType: "stream"
  }).then(async function (response) {
        let stringvariable = FileDownloadedAsAStringFromTheStream;
        resolve(stringvariable)

  }) .catch(error => {
      console.log('error downloading file');
      console.log(error)
  });
      });
}


问:
how to import mininet.topo at python?
trying to import mininet package and getting an error

'from mininet.topo import Topo'

that's the error that i get when trying to do :

```<code>C:\Users\liran\AppData\Local\Programs\Python\Python38\python.exe
C:/liran/Program/SMTR3/Code_try/TopologyFiles/Printer.py
Traceback (most recent call last):
File "C:/liran/Program/SMTR3/Code_try/TopologyFiles/Printer.py", line 85, in <module>
from mininet.topo import Topo
File "C:\Users\liran\AppData\Local\Programs\Python\Python38\lib\site-packages\mininet\topo.py", line 14, in <module>
from mininet.util import irange, natural, naturalSeq
File "C:\Users\liran\AppData\Local\Programs\Python\Python38\lib\site-packages\mininet\util.py", line 7, in <module>
from resource import getrlimit, setrlimit, RLIMIT_NPROC, RLIMIT_NOFILE
ModuleNotFoundError: No module named 'resource'
</code>```

Title: how to import mininet.topo at python?

Body:
trying to import mininet package and getting an error

'from mininet.topo import Topo'

that's the error that i get when trying to do :

C:\Users\liran\AppData\Local\Programs\Python\Python38\python.exe
C:/liran/Program/SMTR3/Code_try/TopologyFiles/Printer.py
Traceback (most recent call last):
File "C:/liran/Program/SMTR3/Code_try/TopologyFiles/Printer.py", line 85, in <module>
from mininet.topo import Topo
File "C:\Users\liran\AppData\Local\Programs\Python\Python38\lib\site-packages\mininet\topo.py", line 14, in <module>
from mininet.util import irange, natural, naturalSeq
File "C:\Users\liran\AppData\Local\Programs\Python\Python38\lib\site-packages\mininet\util.py", line 7, in <module>
from resource import getrlimit, setrlimit, RLIMIT_NPROC, RLIMIT_NOFILE
ModuleNotFoundError: No module named 'resource'


问:
Linux GPIO persistent output
In the deprecated sysfs interface, writing a value to an output pin would persist. I'm not sure how to do this with the new interface.

This is how I'm writing a value for 2 seconds:

// get linehandle
ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &request);
if (ret < 0) {
  return -1;
}
// write
ret = ioctl(request.fd, GPIOHANDLE_SET_LINE_VALUES_IOCTL, &data);
if (ret < 0) {
  close(request.fd);
  return -1;
}

usleep(2000000);
close(request.fd);
```

In order for this to persist, I could launch a thread... but would I leave this request fd open? And when I want to lower the pin, do I just close this request fd?

I was expecting there to be an easier way to keep gpio pins high in the new interface since it was so simple with sysfs. However, I am testing with gpio-mockup so there is a chance something isn't working quite right.

Title: Linux GPIO persistent output

Body:
In the deprecated sysfs interface, writing a value to an output pin would persist. I'm not sure how to do this with the new interface.

This is how I'm writing a value for 2 seconds:

// get linehandle
ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &request);
if (ret < 0) {
  return -1;
}
// write
ret = ioctl(request.fd, GPIOHANDLE_SET_LINE_VALUES_IOCTL, &data);
if (ret < 0) {
  close(request.fd);
  return -1;
}

usleep(2000000);
close(request.fd);

In order for this to persist, I could launch a thread... but would I leave this request fd open? And when I want to lower the pin, do I just close this request fd?

I was expecting there to be an easier way to keep gpio pins high in the new interface since it was so simple with sysfs. However, I am testing with gpio-mockup so there is a chance something isn't working quite right.


问:
Connect to MongoDB
I am not able to connect to mongo dB, what am I doing wrong?

I am getting in terminal this message. I am following different ways and still I am getting same message.

```<code> UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).

</code>```

I am trying to keep it very simple , here is my code

```<code>const express = require('express')
const app = express()
const mongoose = require('mongoose')
const UserModel = require('./models/Users')
const dotenv = require('dotenv')
dotenv.config()

const connectDB = async () => {
  try {
      const connect = await mongoose.connect(process.env.MONGO_URI)
      console.log(`mongo connected ${connect.connection.host}`)
  } catch (error) {
     console.log(error)
     process.exit(1)
  }
}

connectDB()

app.use(express.json())

app.get('/', (req, res) => {
  res.send('welcome a')
})

app.post("/user", async (req, res) => {
  const user = req.body
  const newUser = new UserModel(user)
  await newUser.save()
  res.json(user)
})

const port = 5000

app.listen(port, () => {
  console.log(`server on ${port}`)
})

</code>```

Postman show me data from app.get() method , but if I want to use app.post() there is error

Title: Connect to MongoDB

Body:
I am not able to connect to mongo dB, what am I doing wrong?

I am getting in terminal this message. I am following different ways and still I am getting same message.

 UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).

I am trying to keep it very simple , here is my code

const express = require('express')
const app = express()
const mongoose = require('mongoose')
const UserModel = require('./models/Users')
const dotenv = require('dotenv')
dotenv.config()

const connectDB = async () => {
  try {
      const connect = await mongoose.connect(process.env.MONGO_URI)
      console.log(`mongo connected ${connect.connection.host}`)
  } catch (error) {
     console.log(error)
     process.exit(1)
  }
}

connectDB()

app.use(express.json())

app.get('/', (req, res) => {
  res.send('welcome a')
})

app.post("/user", async (req, res) => {
  const user = req.body
  const newUser = new UserModel(user)
  await newUser.save()
  res.json(user)
})

const port = 5000

app.listen(port, () => {
  console.log(`server on ${port}`)
})

Postman show me data from app.get() method , but if I want to use app.post() there is error


问:
AppDynamics adeum plugin insecure protocol error
I'm experiencing a problem while using adeum plugin with insecure nexus repositories. While executing gradle tasks, the following error rises.

```<code>1: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':app:dataBindingMergeDependencyArtifactsAlphaRelease'.
> Could not resolve all dependencies for configuration ':app:alphaReleaseRuntimeClasspath'.
   > Using insecure protocols with repositories, without explicit opt-in, is unsupported. Switch Maven repository 'maven_adeum(http://***.***.***.***:8081/repository/maven-public/)' to redirect to a secure protocol (like HTTPS) or allow insecure protocols. See https://docs.gradle.org/7.4.1/dsl/org.gradle.api.artifacts.repositories.UrlArtifactRepository.html#org.gradle.api.artifacts.repositories.UrlArtifactRepository:allowInsecureProtocol for more details.

</code>```

Project level build.gradle:

```<code>buildscript {
    repositories {
        maven { url "http://***.***.***.***:8081/repository/maven-public/"; setAllowInsecureProtocol(true) }
        maven { url "http://***.***.***.***:8081/repository/google-maven2-proxy/"; setAllowInsecureProtocol(true) }
        maven { url "http://***.***.***.***:8081/repository/developer-huawei/"; setAllowInsecureProtocol(true) }
    }
}

...

    dependencies {
        classpath 'com.android.tools.build:gradle:7.3.1'
        classpath 'com.appdynamics:appdynamics-gradle-plugin:22.8.0'
        ...
    }

...

allprojects {
    repositories {
        maven { url "http://***.***.***.***:8081/repository/maven-public/"; setAllowInsecureProtocol(true) }
        maven { url "http://***.***.***.***:8081/repository/google-maven2-proxy/"; setAllowInsecureProtocol(true) }
        maven { url "http://***.***.***.***:8081/repository/developer-huawei/"; setAllowInsecureProtocol(true) }
    }
}
</code>```

App level build.gralde:

```<code>plugins {
    id 'com.android.application'
    id 'adeum'
    ...
}

...

dependencies {
    implementation 'com.appdynamics:appdynamics-runtime:22.8.0'
    ...
}

</code>```

Body:
I'm experiencing a problem while using adeum plugin with insecure nexus repositories. While executing gradle tasks, the following error rises.

1: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':app:dataBindingMergeDependencyArtifactsAlphaRelease'.
> Could not resolve all dependencies for configuration ':app:alphaReleaseRuntimeClasspath'.
   > Using insecure protocols with repositories, without explicit opt-in, is unsupported. Switch Maven repository 'maven_adeum(http://***.***.***.***:8081/repository/maven-public/)' to redirect to a secure protocol (like HTTPS) or allow insecure protocols. See https://docs.gradle.org/7.4.1/dsl/org.gradle.api.artifacts.repositories.UrlArtifactRepository.html#org.gradle.api.artifacts.repositories.UrlArtifactRepository:allowInsecureProtocol for more details.

Project level build.gradle:

buildscript {
    repositories {
        maven { url "http://***.***.***.***:8081/repository/maven-public/"; setAllowInsecureProtocol(true) }
        maven { url "http://***.***.***.***:8081/repository/google-maven2-proxy/"; setAllowInsecureProtocol(true) }
        maven { url "http://***.***.***.***:8081/repository/developer-huawei/"; setAllowInsecureProtocol(true) }
    }
}

...

    dependencies {
        classpath 'com.android.tools.build:gradle:7.3.1'
        classpath 'com.appdynamics:appdynamics-gradle-plugin:22.8.0'
        ...
    }

...

allprojects {
    repositories {
        maven { url "http://***.***.***.***:8081/repository/maven-public/"; setAllowInsecureProtocol(true) }
        maven { url "http://***.***.***.***:8081/repository/google-maven2-proxy/"; setAllowInsecureProtocol(true) }
        maven { url "http://***.***.***.***:8081/repository/developer-huawei/"; setAllowInsecureProtocol(true) }
    }
}

App level build.gralde:

plugins {
    id 'com.android.application'
    id 'adeum'
    ...
}

...

dependencies {
    implementation 'com.appdynamics:appdynamics-runtime:22.8.0'
    ...
}


问:
Unable to login to tomcat manager
```<code><role rolename="manager-gui"/>
<role rolename="manager-script"/>
<user username="madhukar" password="madhukar" roles="manager-gui, manager-script"/>
</code>```

I have set the tomcat credentials with username and password, but I am unable to login to tomcat gui to manage the server running on localhost:8080

If anyone has encountered similar issue before or know to resolve it, please help me on it.

I have set the credentials for login to tomcat server, but its not letting me login to http://localhost:8080/manager/status

Help is appreciated.

I was expecting login to tomcat manager but it did not worked out.

Title: Unable to login to tomcat manager

Body:
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<user username="madhukar" password="madhukar" roles="manager-gui, manager-script"/>

I have set the tomcat credentials with username and password, but I am unable to login to tomcat gui to manage the server running on localhost:8080

If anyone has encountered similar issue before or know to resolve it, please help me on it.

I have set the credentials for login to tomcat server, but its not letting me login to http://localhost:8080/manager/status

Help is appreciated.

I was expecting login to tomcat manager but it did not worked out.


问:
Problem with adding values to insert on trigger MySQL (Error 1193 unknown system variable)
I have a table with sensor data and a table that gets data from an app.
Every time the app saves data to it's table, it saves two datetime values to "start time" and "end time" columns. Based on that time gap, I have to get some values from the sensor data table (start temp, maximum temp, max humidity...).

I am currently using a before insert trigger and using new.colName = (select from sensor ...).
First column inserts fine but after that I get "Error Code: 1193 Unknown system variable 'NEW.max_temp'".

Im sure this is because i have something wrong in my trigger syntax, but I am not able to determine what is causing this.

The values im filling are originally Null when the app inserts it's data and the columns exist im trying to SET NEW.XXXX exist.

My Trigger:

```<code>DELIMITER $$

CREATE DEFINER = CURRENT_USER TRIGGER `Cegasa`.`FAB_BEFORE_INSERT`
BEFORE INSERT ON `fabrication`
FOR EACH ROW
SET NEW.start_temp = (SELECT temp FROM sensors WHERE (NEW.fab_start_date) <= date ORDER BY date LIMIT 1);
SET NEW.max_temp = (SELECT temp  FROM sensors WHERE (NEW.fab_end_date) >= date ORDER BY date DESC LIMIT 1);

DELIMITER;
</code>```

First SET statement works fine but second one gives the error. I can provide further table structure if necessary but I think it has more to do with my syntax.

Body:
I have a table with sensor data and a table that gets data from an app.
Every time the app saves data to it's table, it saves two datetime values to "start time" and "end time" columns. Based on that time gap, I have to get some values from the sensor data table (start temp, maximum temp, max humidity...).

I am currently using a before insert trigger and using new.colName = (select from sensor ...).
First column inserts fine but after that I get "Error Code: 1193 Unknown system variable 'NEW.max_temp'".

Im sure this is because i have something wrong in my trigger syntax, but I am not able to determine what is causing this.

The values im filling are originally Null when the app inserts it's data and the columns exist im trying to SET NEW.XXXX exist.

My Trigger:

DELIMITER $$

CREATE DEFINER = CURRENT_USER TRIGGER `Cegasa`.`FAB_BEFORE_INSERT`
BEFORE INSERT ON `fabrication`
FOR EACH ROW
SET NEW.start_temp = (SELECT temp FROM sensors WHERE (NEW.fab_start_date) <= date ORDER BY date LIMIT 1);
SET NEW.max_temp = (SELECT temp  FROM sensors WHERE (NEW.fab_end_date) >= date ORDER BY date DESC LIMIT 1);

DELIMITER;

First SET statement works fine but second one gives the error. I can provide further table structure if necessary but I think it has more to do with my syntax.


问:
Generating pdf from google sheet by app script
I am generating a pdf from a google sheet by first updating the F3 cell with a timestamp. The problem is that the PDF file is generated first, and then cell F3 is updated.

I am trying to do by code in google app script.

```<code>function updateAndExportSheet(e) {
  // ID of the sheet to update
  var sheetId = "sheet_id";

  // ID of the cell to update
  var cellId = "F3";

  // ID of the folder to save the PDF file in
  var folderId = "folder_ID";

  // Get the response date from the form
  var formResponse = e.response.getTimestamp().toString();

  // Get a reference to the sheet and update the cell with the form response
  var sheet = SpreadsheetApp.openById(sheetId).getSheetByName("Sheet1");
  sheet.getRange(cellId).setValue(formResponse);

  // Construct the URL to export the sheet to a PDF with horizontal orientation and 0.5 cm margins
  var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", sheet.getParent().getId());
  var url_ext = 'exportFormat=pdf&format=pdf' +
                '&size=A4' +
                '&portrait=false' +
                '&fitw=true&source=labnol' +
                '&sheetnames=false&printtitle=false' +
                '&pagenumbers=false&gridlines=false' +
                '&fzr=false' +
                '&top_margin=0.0&bottom_margin=0.0&left_margin=0.0&right_margin=0.0' +
                '&gid=';

  // Get the response for the sheet that can later be converted to a blob
  var token = ScriptApp.getOAuthToken();
  var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
    headers: {
      'Authorization': 'Bearer ' +  token
    }
  });

  // Save the PDF file to the specified folder
  var folder = DriveApp.getFolderById(folderId);
  folder.createFile(response.getBlob().setName("sheet.pdf"));
}

</code>```

Body:
I am generating a pdf from a google sheet by first updating the F3 cell with a timestamp. The problem is that the PDF file is generated first, and then cell F3 is updated.

I am trying to do by code in google app script.

function updateAndExportSheet(e) {
  // ID of the sheet to update
  var sheetId = "sheet_id";

  // ID of the cell to update
  var cellId = "F3";

  // ID of the folder to save the PDF file in
  var folderId = "folder_ID";

  // Get the response date from the form
  var formResponse = e.response.getTimestamp().toString();

  // Get a reference to the sheet and update the cell with the form response
  var sheet = SpreadsheetApp.openById(sheetId).getSheetByName("Sheet1");
  sheet.getRange(cellId).setValue(formResponse);

  // Construct the URL to export the sheet to a PDF with horizontal orientation and 0.5 cm margins
  var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", sheet.getParent().getId());
  var url_ext = 'exportFormat=pdf&format=pdf' +
                '&size=A4' +
                '&portrait=false' +
                '&fitw=true&source=labnol' +
                '&sheetnames=false&printtitle=false' +
                '&pagenumbers=false&gridlines=false' +
                '&fzr=false' +
                '&top_margin=0.0&bottom_margin=0.0&left_margin=0.0&right_margin=0.0' +
                '&gid=';

  // Get the response for the sheet that can later be converted to a blob
  var token = ScriptApp.getOAuthToken();
  var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
    headers: {
      'Authorization': 'Bearer ' +  token
    }
  });

  // Save the PDF file to the specified folder
  var folder = DriveApp.getFolderById(folderId);
  folder.createFile(response.getBlob().setName("sheet.pdf"));
}


问:
Test automation Error during script execution on page https://xxx.xxxx.fr/ SecurityError: The operation is insecure. Build info: version: 'unknown
how to make "network.websocket.allowInsecureFromHTTPS" true?
I have firefox installed on the openstack cloud VM and when i run the test i have this

Error during script execution on page https://...fr/ SecurityError: The operation is insecure. Build info: version: 'unknown', revision: 'unknown', time: 'unknown' System info: host: 'tanaguru', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '5.15.0-52-generic', java.version: '11.0.17' Driver info: org.openqa.selenium.firefox.FirefoxDriver Capabilities {acceptInsecureCerts: true, browserName: firefox, browserVersion: 102.4.0, javascriptEnabled: true, moz:accessibilityChecks: false, moz:buildID: 20221010114559, moz:geckodriverVersion: 0.32.0, moz:headless: true, moz:processID: 516150, moz:profile: /tmp/rust_mozprofileiUzVeb, moz:shutdownTimeout: 60000, moz:useNonSpecCompliantPointerOrigin: false, moz:webdriverClick: true, moz:windowless: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, platformVersion: 5.15.0-52-generic, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify} Session ID: b97f16bc-d5ee-4cb2-8fc7-1f54efcf585c

I install the certificat but I still have the same problem


问:
I made a script that detects if there is white space surrounding an image and automatically removes it, sometimes, it still leaves some of it
The code is a simple image cropper that allows the user to select an image file, crop the image to remove any surrounding white space, and then download the resulting cropped image.

My problem is that sometimes the code leaves a little bit of white space around some images and i don't have any idea on why it does that.

Here is my code:

```<code>      // Add an event listener to the file input field to process the selected file
      document
        .getElementById("fileInput")
        .addEventListener("change", function () {
          // Get the file object
          var file = this.files[0];

          // Create a FileReader object
          var reader = new FileReader();

          // Add an event listener to the FileReader object to process the file when it's loaded
          reader.addEventListener("load", function () {
            // Create an image object and set its src to the data URL of the file
            var img = new Image();
            img.src = this.result;

            // Wait for the image to load
            img.onload = function () {
              // Get the width and height of the image
              var width = img.naturalWidth;
              var height = img.naturalHeight;

              // Create a canvas element and draw the image onto it
              var canvas = document.createElement("canvas");
              canvas.width = width;
              canvas.height = height;
              var ctx = canvas.getContext("2d");
              ctx.drawImage(img, 0, 0);

              // Get the image data of the canvas
              var imageData = ctx.getImageData(0, 0, width, height);
              var data = imageData.data;

              // Iterate through the image data and determine the edges of the non-white pixels
              var top = height;
              var bottom = 0;
              var left = width;
              var right = 0;
              for (var y = 0; y < height; y++) {
                for (var x = 0; x < width; x++) {
                  var index = (y * width + x) * 4;
                  if (
                    data[index] !== 255 ||
                    data[index + 1] !== 255 ||
                    data[index + 2] !== 255
                  ) {
                    // This pixel is not white, so update the edges if necessary
                    top = Math.min(top, y);
                    bottom = Math.max(bottom, y);
                    left = Math.min(left, x);
                    right = Math.max(right, x);
                  }
                }
              }

              // Calculate the dimensions of the cropped image
              var croppedWidth = right - left;
              var croppedHeight = bottom - top;

              // Create a second canvas element and draw the cropped image onto it
              var croppedCanvas = document.createElement("canvas");
              croppedCanvas.width = croppedWidth;
              croppedCanvas.height = croppedHeight;
              var croppedCtx = croppedCanvas.getContext("2d");
              croppedCtx.drawImage(
                img,
                left,
                top,
                croppedWidth,
                croppedHeight,
                0,
                0,
                croppedWidth,
                croppedHeight
              );

              // Get the data URL of the cropped image and set it as the href of the download link
              var downloadLink = document.getElementById("downloadLink");
              downloadLink.href = croppedCanvas.toDataURL();

              // Set the download attribute of the link to the file name of the original image
              downloadLink.download = file.name;

              // Set the src of the cropped image element to the data URL of the cropped image
              var croppedImage = document.getElementById("croppedImage");
              croppedImage.src = croppedCanvas.toDataURL();
            };
          });

          // Read the file as a data URL
          reader.readAsDataURL(file);
        });

</code>```

I tried adding a little bit of white tolerance but it seems not to fix the problem.

Body:
The code is a simple image cropper that allows the user to select an image file, crop the image to remove any surrounding white space, and then download the resulting cropped image.

My problem is that sometimes the code leaves a little bit of white space around some images and i don't have any idea on why it does that.

Here is my code:

      // Add an event listener to the file input field to process the selected file
      document
        .getElementById("fileInput")
        .addEventListener("change", function () {
          // Get the file object
          var file = this.files[0];

          // Create a FileReader object
          var reader = new FileReader();

          // Add an event listener to the FileReader object to process the file when it's loaded
          reader.addEventListener("load", function () {
            // Create an image object and set its src to the data URL of the file
            var img = new Image();
            img.src = this.result;

            // Wait for the image to load
            img.onload = function () {
              // Get the width and height of the image
              var width = img.naturalWidth;
              var height = img.naturalHeight;

              // Create a canvas element and draw the image onto it
              var canvas = document.createElement("canvas");
              canvas.width = width;
              canvas.height = height;
              var ctx = canvas.getContext("2d");
              ctx.drawImage(img, 0, 0);

              // Get the image data of the canvas
              var imageData = ctx.getImageData(0, 0, width, height);
              var data = imageData.data;

              // Iterate through the image data and determine the edges of the non-white pixels
              var top = height;
              var bottom = 0;
              var left = width;
              var right = 0;
              for (var y = 0; y < height; y++) {
                for (var x = 0; x < width; x++) {
                  var index = (y * width + x) * 4;
                  if (
                    data[index] !== 255 ||
                    data[index + 1] !== 255 ||
                    data[index + 2] !== 255
                  ) {
                    // This pixel is not white, so update the edges if necessary
                    top = Math.min(top, y);
                    bottom = Math.max(bottom, y);
                    left = Math.min(left, x);
                    right = Math.max(right, x);
                  }
                }
              }

              // Calculate the dimensions of the cropped image
              var croppedWidth = right - left;
              var croppedHeight = bottom - top;

              // Create a second canvas element and draw the cropped image onto it
              var croppedCanvas = document.createElement("canvas");
              croppedCanvas.width = croppedWidth;
              croppedCanvas.height = croppedHeight;
              var croppedCtx = croppedCanvas.getContext("2d");
              croppedCtx.drawImage(
                img,
                left,
                top,
                croppedWidth,
                croppedHeight,
                0,
                0,
                croppedWidth,
                croppedHeight
              );

              // Get the data URL of the cropped image and set it as the href of the download link
              var downloadLink = document.getElementById("downloadLink");
              downloadLink.href = croppedCanvas.toDataURL();

              // Set the download attribute of the link to the file name of the original image
              downloadLink.download = file.name;

              // Set the src of the cropped image element to the data URL of the cropped image
              var croppedImage = document.getElementById("croppedImage");
              croppedImage.src = croppedCanvas.toDataURL();
            };
          });

          // Read the file as a data URL
          reader.readAsDataURL(file);
        });

I tried adding a little bit of white tolerance but it seems not to fix the problem.