问:
How can I make a buttons from a Layout in Android Studio
I have buttons what I made with "LinearLayout" but when I want to made them clickable and so that it goes to another activity. I understand, that I need to change from "LinearLayout" to "ImageButton" because I want to make a beautiful app [what I want it looks like][1], but when I launch it, it stops working. What can I do to repair that? Thank you in advance for your help and sorry for my bad english. :(</p>
```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackground"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layoutHeader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/header_background"
        android:padding="20dp"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/textHello"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="4dp"
            android:text="@string/hello"
            android:textColor="@color/colorWhite"
            android:textSize="25sp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:ignore="TextContrastCheck" />

        <TextView
            android:id="@+id/textUsername"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="4dp"
            android:text="@string/vassili"
            android:textColor="@color/colorWhite"
            android:textSize="25sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toEndOf="@id/textHello"
            tools:ignore="TextContrastCheck" />

        <ImageView
            android:id="@+id/imageMenu"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:contentDescription="@string/app_name"
            android:src="@drawable/ic_menu"
            app:layout_constraintBottom_toBottomOf="@id/textHello"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="@id/textHello"
            app:tint="@color/colorWhite"
            tools:ignore="ImageContrastCheck" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:overScrollMode="never"
        android:scrollbars="none"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/layoutHeader"
        app:layout_constraintVertical_bias="0.0"
        tools:layout_editor_absoluteX="-96dp">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:id="@+id/layoutGoal"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="22dp"
                android:background="@drawable/white_background_icons"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="15dp"
                app:layout_constraintDimensionRatio="H, 1:1"
                app:layout_constraintEnd_toStartOf="@id/layoutTraining"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                tools:ignore="UseCompoundDrawables">

                <ImageView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_margin="8dp"
                    android:contentDescription="@string/app_name"
                    android:padding="8dp"
                    android:src="@drawable/notepad" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@string/goals"
                    android:textColor="@color/colorAccent"
                    android:textSize="20sp"
                    android:textStyle="bold" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/layoutTraining"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="22dp"
                android:background="@drawable/white_background_icons"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="15dp"
                app:layout_constraintDimensionRatio="H, 1:1"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@id/layoutGoal"
                app:layout_constraintTop_toTopOf="parent"
                tools:ignore="UseCompoundDrawables">

                <ImageView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_margin="8dp"
                    android:contentDescription="@string/app_name"
                    android:padding="8dp"
                    android:src="@drawable/dumbbell" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@string/Trainings"
                    android:textColor="@color/colorAccent"
                    android:textSize="20sp"
                    android:textStyle="bold" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/layoutWater"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="22dp"
                android:background="@drawable/white_background_icons"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="15dp"
                app:layout_constraintDimensionRatio="H, 1:1"
                app:layout_constraintEnd_toStartOf="@id/layoutTraining"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/layoutGoal"
                tools:ignore="UseCompoundDrawables">

                <ImageView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_margin="8dp"
                    android:contentDescription="@string/app_name"
                    android:padding="8dp"
                    android:src="@drawable/bottle" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@string/Water"
                    android:textColor="@color/colorAccent"
                    android:textSize="20sp"
                    android:textStyle="bold" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/layoutStepCounter"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="22dp"
                android:background="@drawable/white_background_icons"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="15dp"
                app:layout_constraintDimensionRatio="H, 1:1"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@id/layoutGoal"
                app:layout_constraintTop_toBottomOf="@id/layoutTraining"
                tools:ignore="UseCompoundDrawables">

                <ImageView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_margin="8dp"
                    android:contentDescription="@string/app_name"
                    android:padding="8dp"
                    android:src="@drawable/walk" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@string/step_counter"
                    android:textColor="@color/colorAccent"
                    android:textSize="20sp"
                    android:textStyle="bold" />

            </LinearLayout>

        </androidx.constraintlayout.widget.ConstraintLayout>

    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

  [1]: https://i.stack.imgur.com/WdW6v.png
</code>```

答: May you need to change  constraintlayout  to LinearLayout and if you want click be on image  add id to imageview</p>

Body:
I have buttons what I made with "LinearLayout" but when I want to made them clickable and so that it goes to another activity. I understand, that I need to change from "LinearLayout" to "ImageButton" because I want to make a beautiful app [what I want it looks like][1], but when I launch it, it stops working. What can I do to repair that? Thank you in advance for your help and sorry for my bad english. :(

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackground"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layoutHeader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/header_background"
        android:padding="20dp"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/textHello"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="4dp"
            android:text="@string/hello"
            android:textColor="@color/colorWhite"
            android:textSize="25sp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:ignore="TextContrastCheck" />

        <TextView
            android:id="@+id/textUsername"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="4dp"
            android:text="@string/vassili"
            android:textColor="@color/colorWhite"
            android:textSize="25sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toEndOf="@id/textHello"
            tools:ignore="TextContrastCheck" />

        <ImageView
            android:id="@+id/imageMenu"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:contentDescription="@string/app_name"
            android:src="@drawable/ic_menu"
            app:layout_constraintBottom_toBottomOf="@id/textHello"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="@id/textHello"
            app:tint="@color/colorWhite"
            tools:ignore="ImageContrastCheck" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:overScrollMode="never"
        android:scrollbars="none"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/layoutHeader"
        app:layout_constraintVertical_bias="0.0"
        tools:layout_editor_absoluteX="-96dp">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:id="@+id/layoutGoal"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="22dp"
                android:background="@drawable/white_background_icons"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="15dp"
                app:layout_constraintDimensionRatio="H, 1:1"
                app:layout_constraintEnd_toStartOf="@id/layoutTraining"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                tools:ignore="UseCompoundDrawables">

                <ImageView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_margin="8dp"
                    android:contentDescription="@string/app_name"
                    android:padding="8dp"
                    android:src="@drawable/notepad" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@string/goals"
                    android:textColor="@color/colorAccent"
                    android:textSize="20sp"
                    android:textStyle="bold" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/layoutTraining"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="22dp"
                android:background="@drawable/white_background_icons"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="15dp"
                app:layout_constraintDimensionRatio="H, 1:1"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@id/layoutGoal"
                app:layout_constraintTop_toTopOf="parent"
                tools:ignore="UseCompoundDrawables">

                <ImageView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_margin="8dp"
                    android:contentDescription="@string/app_name"
                    android:padding="8dp"
                    android:src="@drawable/dumbbell" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@string/Trainings"
                    android:textColor="@color/colorAccent"
                    android:textSize="20sp"
                    android:textStyle="bold" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/layoutWater"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="22dp"
                android:background="@drawable/white_background_icons"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="15dp"
                app:layout_constraintDimensionRatio="H, 1:1"
                app:layout_constraintEnd_toStartOf="@id/layoutTraining"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/layoutGoal"
                tools:ignore="UseCompoundDrawables">

                <ImageView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_margin="8dp"
                    android:contentDescription="@string/app_name"
                    android:padding="8dp"
                    android:src="@drawable/bottle" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@string/Water"
                    android:textColor="@color/colorAccent"
                    android:textSize="20sp"
                    android:textStyle="bold" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/layoutStepCounter"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="22dp"
                android:background="@drawable/white_background_icons"
                android:gravity="center"
                android:orientation="vertical"
                android:padding="15dp"
                app:layout_constraintDimensionRatio="H, 1:1"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@id/layoutGoal"
                app:layout_constraintTop_toBottomOf="@id/layoutTraining"
                tools:ignore="UseCompoundDrawables">

                <ImageView
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_margin="8dp"
                    android:contentDescription="@string/app_name"
                    android:padding="8dp"
                    android:src="@drawable/walk" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@string/step_counter"
                    android:textColor="@color/colorAccent"
                    android:textSize="20sp"
                    android:textStyle="bold" />

            </LinearLayout>

        </androidx.constraintlayout.widget.ConstraintLayout>

    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

  [1]: https://i.stack.imgur.com/WdW6v.png


来源: stackexchange

问:
Argo Events: Use data filter in sensor to identify modified/added/removed path in mono-repo
I'm using Argo Events and Argo Workflow for my CI/CD chain, which works pretty neat. But I'm having some troubles setting up the data filter for the GitHub webhook payloads of my mono repo.

I'm trying to let the sensor only trigger the defined workflow if files were changed in a certain subpath. The payload contains three fields added, removed, modified. There the files are listed which were changed in this commit (webhook-events-and-payloads#push).

The paths I'm searching for is service/jobs/* and service/common*/*.

The filter I defined is:

```<code>          - path: "[commits.#.modified.#(%\"*service*\")#,commits.#.added.#(%\"*service*\")#,commits.#.removed.#(%\"*service*\")#]"
            type: string
            value:
              - "(\bservice/jobs\b)|(\bservice/common*)"
</code>```

I valididated my filter in a tiny Go script, as gjson is used by Argo Events to apply the data filter.

```<code>package main

import (
    "github.com/tidwall/gjson"
    "regexp"
)

const json = `{
    "commits": [
      {
        "added": [

        ],
        "removed": [

        ],
        "modified": [
          "service/job-manager/README.md"
        ]
      },
      {
        "added": [

        ],
        "removed": [
            "service/joby/something.md"
        ],
        "modified": [
          "service/job-manager/something.md"
        ]
      },
      {
        "added": [

        ],
        "removed": [
            "service/joby/something.md"
        ],
        "modified": [
          "service/joby/someother.md"
        ]
      }
    ],
    "head_commit": {
      "added": [
        "service/job-manager/something.md"
      ],
      "removed": [
        "service/joby/something.md"
      ],
      "modified": [
        "service/job-manager/README.md"
      ]
    }
  }`

func main() {
    value := gjson.Get(json, "[commits.#.modified.#(%\"*service*\")#,commits.#.added.#(%\"*service*\")#,commits.#.removed.#(%\"*service*\")#]")
    println(value.String())

    matched, _ := regexp.MatchString(`(\bservice/job-manager\b)|(\bservice/common*)`, value.String())
    println(matched) // string is contained?
}
</code>```

The script gives me the results I expect. But for the same webhook payload the workflow is not triggered, when adding the data filter to the sensor.

Someone any ideas?

UPDATED:

Thanks for the hint incl. body. in the paths.

I ended up setting the filters:

```<code>- path: "[body.commits.#.modified.#()#,body.commits.#.added.#()#,body.commits.#.removed.#()#]"
  type: string
  value:
    - ".*service/jobs.*"
    - ".*service/common.*"
</code>```

答:
Path shoud start with body.

Value should add escape special character with \\

So the data filter should be

```<code>- path: "[body.commits.#.modified.#(%\"*service*\")#,body.commits.#.added.#(%\"*service*\")#,body.commits.#.removed.#(%\"*service*\")#]"
  type: string
  value:
    - "(\\bservice/jobs\\b)|(\\bservice/common*)"

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using Argo Events and Argo Workflow for my CI/CD chain, which works pretty neat. But I'm having some troubles setting up the data filter for the GitHub webhook payloads of my mono repo.

I'm trying to let the sensor only trigger the defined workflow if files were changed in a certain subpath. The payload contains three fields added, removed, modified. There the files are listed which were changed in this commit (webhook-events-and-payloads#push).

The paths I'm searching for is service/jobs/* and service/common*/*.

The filter I defined is:

          - path: "[commits.#.modified.#(%\"*service*\")#,commits.#.added.#(%\"*service*\")#,commits.#.removed.#(%\"*service*\")#]"
            type: string
            value:
              - "(\bservice/jobs\b)|(\bservice/common*)"

I valididated my filter in a tiny Go script, as gjson is used by Argo Events to apply the data filter.

package main

import (
    "github.com/tidwall/gjson"
    "regexp"
)

const json = `{
    "commits": [
      {
        "added": [

        ],
        "removed": [

        ],
        "modified": [
          "service/job-manager/README.md"
        ]
      },
      {
        "added": [

        ],
        "removed": [
            "service/joby/something.md"
        ],
        "modified": [
          "service/job-manager/something.md"
        ]
      },
      {
        "added": [

        ],
        "removed": [
            "service/joby/something.md"
        ],
        "modified": [
          "service/joby/someother.md"
        ]
      }
    ],
    "head_commit": {
      "added": [
        "service/job-manager/something.md"
      ],
      "removed": [
        "service/joby/something.md"
      ],
      "modified": [
        "service/job-manager/README.md"
      ]
    }
  }`

func main() {
    value := gjson.Get(json, "[commits.#.modified.#(%\"*service*\")#,commits.#.added.#(%\"*service*\")#,commits.#.removed.#(%\"*service*\")#]")
    println(value.String())

    matched, _ := regexp.MatchString(`(\bservice/job-manager\b)|(\bservice/common*)`, value.String())
    println(matched) // string is contained?
}

The script gives me the results I expect. But for the same webhook payload the workflow is not triggered, when adding the data filter to the sensor.

Someone any ideas?

UPDATED:

Thanks for the hint incl. body. in the paths.

I ended up setting the filters:

- path: "[body.commits.#.modified.#()#,body.commits.#.added.#()#,body.commits.#.removed.#()#]"
  type: string
  value:
    - ".*service/jobs.*"
    - ".*service/common.*"

Body:
Path shoud start with body.

Value should add escape special character with \\

So the data filter should be

- path: "[body.commits.#.modified.#(%\"*service*\")#,body.commits.#.added.#(%\"*service*\")#,body.commits.#.removed.#(%\"*service*\")#]"
  type: string
  value:
    - "(\\bservice/jobs\\b)|(\\bservice/common*)"


问:
SPHINX: Indexer --rotate syntax and multiple main delta schemes
I am setting up Sphinx right now and have a few questions. I have 2 different indexes with main delta schemes setup. So basicaly my conf file looks something like this:

```<code>source jobsmain
{...}

source jobsdelta : jobsmain
{...}

source usersmain
{...}

source usersdelta : usersmain
{...}
</code>```

Question - I am setting up crontab to update my delta indexes every 5 minutes. My cronfile looks something like this:

*/5 * * * /usr/bin/indexer --rotate --config /etc/sphinx/sphinx.conf jobsdelta usersdelta

Is that a valid way to have only the delta indexes updated? Or do I need to make two separate statements for each delta index? If I need to make two separate statements, is the indexer gonna be busy already fulfilling the first request? Am I gonna have to set a delay on the second request?

Thanks in advance

答: That is correct syntax. Just make sure that they're updating properly, so that you can then merge them together later.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am setting up Sphinx right now and have a few questions. I have 2 different indexes with main delta schemes setup. So basicaly my conf file looks something like this:

source jobsmain
{...}

source jobsdelta : jobsmain
{...}

source usersmain
{...}

source usersdelta : usersmain
{...}

Question - I am setting up crontab to update my delta indexes every 5 minutes. My cronfile looks something like this:

*/5 * * * /usr/bin/indexer --rotate --config /etc/sphinx/sphinx.conf jobsdelta usersdelta

Is that a valid way to have only the delta indexes updated? Or do I need to make two separate statements for each delta index? If I need to make two separate statements, is the indexer gonna be busy already fulfilling the first request? Am I gonna have to set a delay on the second request?

Thanks in advance


问:
Running PySpark job on Kubernetes spark cluster
I am trying to run a Spark job on a separate master Spark server hosted on kubernetes but port forwarding reports the following error:

E0206 19:52:24.846137   14968 portforward.go:400] an error occurred forwarding 7077 -> 7077: error forwarding port 7077 to pod 1cf922cbe9fc820ea861077c030a323f6dffd4b33bb0c354431b4df64e0db413, uid : exit status 1: 2022/02/07 00:52:26 socat[25402] E connect(16, AF=2 127.0.0.1:7077, 16): Connection refused
```
<p>My setup is:</p>
<ul>
<li>I am using VS Code with a dev container to manage a setup where I can run Spark applications. I can run local spark jobs when I build my context like so : <code>sc = pyspark.SparkContext(appName="Pi")</code></li>
<li>My host computer is running Docker Desktop where I have kubernetes running and used Helm to run the Spark release from Bitnami https://artifacthub.io/packages/helm/bitnami/spark</li>
<li>The VS Code dev container <strong>can</strong> access the host correctly since I can do <code>curl host.docker.internal:80</code> and I get the Spark web UI status page. The port 80 is forwarded from the host using <code>kubectl port-forward --namespace default --address 0.0.0.0 svc/my-release-spark-master-svc 80:80</code></li>
<li>I am also forwarding the port <code>7077</code> using a similar command <code>kubectl port-forward --address 0.0.0.0 svc/my-release-spark-master-svc 7077:7077</code>.</li>
</ul>
<p>When I create a Spark context like this <code>sc = pyspark.SparkContext(appName="Pi", master="spark://host.docker.internal:7077")</code> I am expecting Spark to submit jobs to that master. I don't know much about Spark but I have seen a few examples creating a context like this.</p>
<p>When I run the code, I see connections attempts failing at port 7077 of kubernetes port forwarding, so the requests are going through but they are being refused somehow.</p>
<pre class="lang-none prettyprint-override"><code>Handling connection for 7077
E0206 19:52:24.846137   14968 portforward.go:400] an error occurred forwarding 7077 -> 7077: error forwarding port 7077 to pod 1cf922cbe9fc820ea861077c030a323f6dffd4b33bb0c354431b4df64e0db413, uid : exit status 1: 2022/02/07 00:52:26 socat[25402] E connect(16, AF=2 127.0.0.1:7077, 16): Connection refused
</code>```

Now, I have no idea why the connections are being refused. I know the Spark server is accepting requests because I can see the Web UI from within the docker dev container. I know that the Spark service is exposing port 7077 because I can do:

$ kubectl get services
NAME                          TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)           AGE
kubernetes                    ClusterIP   10.96.0.1        <none>        443/TCP           28h
my-release-spark-headless     ClusterIP   None             <none>        <none>            7h40m
my-release-spark-master-svc   ClusterIP   10.108.109.228   <none>        7077/TCP,80/TCP   7h40m
```
<p>Can anyone tell why the connections are refused and how I can successfully configure the Spark master to accept jobs from external callers ?</p>
<p>Example code I am using is:</p>
<pre class="lang-py prettyprint-override"><code>import findspark
findspark.init()

import pyspark
import random

#sc = pyspark.SparkContext(appName="Pi", master="spark://host.docker.internal:7077")
sc = pyspark.SparkContext(appName="Pi")
num_samples = 100000000

def inside(p):
  x, y = random.random(), random.random()
  return x*x + y*y < 1

count = sc.parallelize(range(0, num_samples)).filter(inside).count()

pi = 4 * count / num_samples
print(pi)

sc.stop()
</code>```

答:
After tinkering with it a bit more, I noticed this output when launching the helm chart for Apache Spark ** IMPORTANT: When submit an application from outside the cluster service type should be set to the NodePort or LoadBalancer. **.

This led me to research a bit more into Kubernetes networking. To submit a job, it is not sufficient to forward port 7077. Instead, the cluster itself needs to have an IP assigned. This requires the helm chart to be launched with the following commands to set Spark config values helm install my-release --set service.type=LoadBalancer --set service.loadBalancerIP=192.168.2.50 bitnami/spark. My host IP address is above and will be reachable by the Docker container.

With the LoadBalancer IP assigned, Spark will run using the example code provided.

Recap: Don't use port forwarding to submit jobs, a Cluster IP needs to be assigned.

Body:
I am trying to run a Spark job on a separate master Spark server hosted on kubernetes but port forwarding reports the following error:

E0206 19:52:24.846137   14968 portforward.go:400] an error occurred forwarding 7077 -> 7077: error forwarding port 7077 to pod 1cf922cbe9fc820ea861077c030a323f6dffd4b33bb0c354431b4df64e0db413, uid : exit status 1: 2022/02/07 00:52:26 socat[25402] E connect(16, AF=2 127.0.0.1:7077, 16): Connection refused

My setup is:

I am using VS Code with a dev container to manage a setup where I can run Spark applications. I can run local spark jobs when I build my context like so : sc = pyspark.SparkContext(appName="Pi")

My host computer is running Docker Desktop where I have kubernetes running and used Helm to run the Spark release from Bitnami https://artifacthub.io/packages/helm/bitnami/spark

The VS Code dev container can access the host correctly since I can do curl host.docker.internal:80 and I get the Spark web UI status page. The port 80 is forwarded from the host using kubectl port-forward --namespace default --address 0.0.0.0 svc/my-release-spark-master-svc 80:80

I am also forwarding the port 7077 using a similar command kubectl port-forward --address 0.0.0.0 svc/my-release-spark-master-svc 7077:7077.

When I create a Spark context like this sc = pyspark.SparkContext(appName="Pi", master="spark://host.docker.internal:7077") I am expecting Spark to submit jobs to that master. I don't know much about Spark but I have seen a few examples creating a context like this.

When I run the code, I see connections attempts failing at port 7077 of kubernetes port forwarding, so the requests are going through but they are being refused somehow.

Handling connection for 7077
E0206 19:52:24.846137   14968 portforward.go:400] an error occurred forwarding 7077 -> 7077: error forwarding port 7077 to pod 1cf922cbe9fc820ea861077c030a323f6dffd4b33bb0c354431b4df64e0db413, uid : exit status 1: 2022/02/07 00:52:26 socat[25402] E connect(16, AF=2 127.0.0.1:7077, 16): Connection refused

Now, I have no idea why the connections are being refused. I know the Spark server is accepting requests because I can see the Web UI from within the docker dev container. I know that the Spark service is exposing port 7077 because I can do:

$ kubectl get services
NAME                          TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)           AGE
kubernetes                    ClusterIP   10.96.0.1        <none>        443/TCP           28h
my-release-spark-headless     ClusterIP   None             <none>        <none>            7h40m
my-release-spark-master-svc   ClusterIP   10.108.109.228   <none>        7077/TCP,80/TCP   7h40m

Can anyone tell why the connections are refused and how I can successfully configure the Spark master to accept jobs from external callers ?

Example code I am using is:

import findspark
findspark.init()

import pyspark
import random

#sc = pyspark.SparkContext(appName="Pi", master="spark://host.docker.internal:7077")
sc = pyspark.SparkContext(appName="Pi")
num_samples = 100000000

def inside(p):
  x, y = random.random(), random.random()
  return x*x + y*y < 1

count = sc.parallelize(range(0, num_samples)).filter(inside).count()

pi = 4 * count / num_samples
print(pi)

sc.stop()


问:
Regular expression not returning everything on pattern in python
I'm using https://regexr.com/ for testing the regex pattern with the following,

but when I try to use the same pattern in python I got

how can I rewrite the python pattern so I can retrieve the "state of " as in the regexr site?

答:
Assuming you want to match patterns such as "state of ny" or "state that is named new york", you should put the entire string you want to capture into parentheses and use a non-capturing group for the alternative.

```<code>re.findall(r'(state.*.(?:ny|new york))', " consuption state of ny  ")
</code>```

Additionally, .*. could be written as .+ to be a little more concise.

Body:
Assuming you want to match patterns such as "state of ny" or "state that is named new york", you should put the entire string you want to capture into parentheses and use a non-capturing group for the alternative.

re.findall(r'(state.*.(?:ny|new york))', " consuption state of ny  ")

Additionally, .*. could be written as .+ to be a little more concise.


问:
Inconsistent performance of a Python Flask app using Threading on Google Cloud Run
I'm trying to understand seemingly inconsistent performance of a Python Flask app on Google Cloud Run. The app takes an image file as input and does some pre-processing using cv2 and then OCR using Tesseract. I use Python threading to parallelize the image and OCR processing but even so the total processing can take 10 to 20 sec.

```<code>@app.route('/process_image/<path:image_path>')
def process_image(image_path):
    processing_results = process_input_image(image_path)

    return processing_results

def process_input_image(image_path)
    # process_input_image uses Python Threads to parallelize image processing
    for work in list_of_image_processing_work:
        th = Thread(target=do_image_work, args=(work, results))
        th.start()
    # wait for all threads to complete
    return results
</code>```

I wanted to return a more immediate response indicating the processing would take a bit more time. So, I tried the following change to start a thread on the image processing call. Net, I'm starting a thread on a call to a routine that itself starts a series of threads to do image processing.

```<code>@app.route('/process_image/<path:image_path>')
def process_image(image_path):
    th = Thread(target=process_input_image, args=(image_path, results))
    th.start()

    return 'This\'ll just be a moment or so.'
</code>```

But, as soon as I added this second layer of threading, processing on Google Cloud Run seemed to stall. Looking at the logs I can see routine process_input_image start, but progress seems to inch along, almost like it's a low priority, and ultimately never completes. I'm wondering if this is a thread priority thing.

答:
When the HTTP Request returns the message, the CPU is idled. This means threads running after the HTTP request may be starved of CPU and may be terminated.

If you want background threads to run, select always-on CPU.

How to allocate always-on CPU

Body:
I'm trying to understand seemingly inconsistent performance of a Python Flask app on Google Cloud Run. The app takes an image file as input and does some pre-processing using cv2 and then OCR using Tesseract. I use Python threading to parallelize the image and OCR processing but even so the total processing can take 10 to 20 sec.

@app.route('/process_image/<path:image_path>')
def process_image(image_path):
    processing_results = process_input_image(image_path)

    return processing_results

def process_input_image(image_path)
    # process_input_image uses Python Threads to parallelize image processing
    for work in list_of_image_processing_work:
        th = Thread(target=do_image_work, args=(work, results))
        th.start()
    # wait for all threads to complete
    return results

I wanted to return a more immediate response indicating the processing would take a bit more time. So, I tried the following change to start a thread on the image processing call. Net, I'm starting a thread on a call to a routine that itself starts a series of threads to do image processing.

@app.route('/process_image/<path:image_path>')
def process_image(image_path):
    th = Thread(target=process_input_image, args=(image_path, results))
    th.start()

    return 'This\'ll just be a moment or so.'

But, as soon as I added this second layer of threading, processing on Google Cloud Run seemed to stall. Looking at the logs I can see routine process_input_image start, but progress seems to inch along, almost like it's a low priority, and ultimately never completes. I'm wondering if this is a thread priority thing.


问:
Regex for ANY string except "www"? (subdomain)
I was wondering if someone out there could help me with a regex in C#. I think it's fairly simple but I've been wracking my brain over it and not quite sure why I'm having such a hard time.  :)

I've found a few examples around but I can't seem to manipulate them to do what I need.

I just need to match ANY alphanumeric+dashes subdomain string that is not "www", and just up to the "."

Also, ideally, if someone were to type "www.subdomain.domain.com" I would like the www to be ignored if possible. If not, it's not a huge issue.

In other words, I would like to match:

(test).domain.com

(test2).domain.com

(wwwasdf).domain.com

(asdfwww).domain.com

(w).domain.com

(wwwwww).domain.com

(asfd-12345-www-bananas).domain.com

www.(subdomain).domain.com

And I don't want to match:

(www).domain.com

It seems to me like it should be easy, but I'm having troubles with the "not match" part.

For what it's worth, this is for use in the IIS 7 URL Rewrite Module, to rewrite for all non-www subdomains.

Thanks!

答:
This works:

```<code>^(?!www\.domain\.com)(?:[a-z\-\.]+\.domain\.com)$
</code>```

Or, with the necessary backslashes for Java (or C#?) strings:

```<code>"^(?!www\\.domain\\.com)(?:[a-z\\-\\.]+\\.domain\\.com)$"
</code>```

There may be a more concise way (i.e. only typing domain.com once), but this works ..

Body:
This works:

^(?!www\.domain\.com)(?:[a-z\-\.]+\.domain\.com)$

Or, with the necessary backslashes for Java (or C#?) strings:

"^(?!www\\.domain\\.com)(?:[a-z\\-\\.]+\\.domain\\.com)$"

There may be a more concise way (i.e. only typing domain.com once), but this works ..


问:
JPQL query that give me the highest value
I'm trying to do a JPQL query that give me the highest PK of the PKs in my table (https://drive.google.com/file/d/1_kaklkKdCbhT0-byqCtz6HgfluKKp8J-/view?usp=sharing). Here is my query :

```<code>@Override
public int lireMaxPk(Class cl, String nomPkElement) throws MyDBException {
    int nb = 1;
    try {
        String jpql = "SELECT max(e) FROM " + cl.getSimpleName() + " e";
        Query query = em.createQuery(jpql);
        nb = (int) query.getSingleResult();
    } catch (Exception ex) {
        throw new MyDBException(SystemLib.getFullMethodName(), ex.getMessage());
    }
    return nb;
}
</code>```

The error says that the syntax of my query is wrong. Can someone please help me ? Thank you for your help :)

答: Max needs to specify field names instead of table aliases.</p>

Body:
I'm trying to do a JPQL query that give me the highest PK of the PKs in my table (https://drive.google.com/file/d/1_kaklkKdCbhT0-byqCtz6HgfluKKp8J-/view?usp=sharing). Here is my query :

@Override
public int lireMaxPk(Class cl, String nomPkElement) throws MyDBException {
    int nb = 1;
    try {
        String jpql = "SELECT max(e) FROM " + cl.getSimpleName() + " e";
        Query query = em.createQuery(jpql);
        nb = (int) query.getSingleResult();
    } catch (Exception ex) {
        throw new MyDBException(SystemLib.getFullMethodName(), ex.getMessage());
    }
    return nb;
}

The error says that the syntax of my query is wrong. Can someone please help me ? Thank you for your help :)


问:
C++ code wont run if a vector contains value
I am using VS-Code and Vim, Windows OS, MSYS2 MingW GCC/G++ (V.11.2.0) compiler.

If my code contains a vector there is no output when I run the code. I get no error/warning when compiling or running the code.

```<code>#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main () {

vector<string> test = {"Why", "Wont", "This", "Run", "??\n"};
cout << test[0] << test[1]<< test[2] << test[3] << test[4];

cout <<"This is a test";
return 0;

}
</code>```

If I comment out:

```<code>//vector<string> test = {"Why", "Wont", "This", "Run", "??\n"};
//cout << test[0] << test[1] << test[2] << test[3] << test[4];
</code>```

I get the output:  "This is a test"

I have tried reinstalling the compiler with no luck.

答:
I spent about 20 hours fighting this one and I lost -- at least on windows. My very smart friend said that there was "something wrong with my runtime" and recommended a fresh install of windows to try fixing it for that environment (I haven't tested that yet because I am lazy)

What did work was installing WSL (Windows Subsystem for Linux) and grabbing Ubuntu. C++ works as expected now, just launch VS Code through the bash terminal you'll get

Note: I had this same issue with a very similar setup. Laptop with VS Code, Windows 10, MSYS2 MingW GCC/G++ (V.11.2.0). If your error is very similar to mine, your code should run when the vector exists but does not have any contents. I could run C++ programs unrelated to vectors, or use vector's size() and empty() functions on empty vectors that were created. Allocating contents to a vector either on initialization or with push_back() was what prevented me from getting output. If you're able to compile other things and you have this issue without seeing extra info from -Wall, the compiler is probably fine but not the runtime. I feel that this is moreso correct because I made test programs, compiled the .exes, and they could be run by another computer, just not my own.

My other attempted fixes included uninstalling and reinstalling MSYS2 and its compilers, VS Code, Microsoft Visual C++ Redistributables, several restarts, and more. Windows itself is the last ditch effort, I'm just waiting on making a backup.

Body:
I am using VS-Code and Vim, Windows OS, MSYS2 MingW GCC/G++ (V.11.2.0) compiler.

If my code contains a vector there is no output when I run the code. I get no error/warning when compiling or running the code.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main () {

vector<string> test = {"Why", "Wont", "This", "Run", "??\n"};
cout << test[0] << test[1]<< test[2] << test[3] << test[4];

cout <<"This is a test";
return 0;

}

If I comment out:

//vector<string> test = {"Why", "Wont", "This", "Run", "??\n"};
//cout << test[0] << test[1] << test[2] << test[3] << test[4];

I get the output:  "This is a test"

I have tried reinstalling the compiler with no luck.


问:
MS Report Service: how to set up my own class as a dataset?
I'm trying to build some report. The problem is I cannot set up several sources for my table whereas I need to accumulate different data into 1 table. I've created class and put it in the same domain as my EF classes are. When I try to add new dataset the wizard sees and behaves as if I can add it it but the list "Available datasets" is not updated. What did I wrong? How could this problem be solved?

Thanks a lot

答:
I've found the solution but it looks very stupid (from the architectural point of view) - you just add several different tables as sources and then in the table refer to theirs fields as if they are field of one big table. For example:

```<code>Fields!DriverLicense.Value
Fields!BrokerName.Value
</code>```

Whereas both of them belong to different tables.

Body:
I've found the solution but it looks very stupid (from the architectural point of view) - you just add several different tables as sources and then in the table refer to theirs fields as if they are field of one big table. For example:

Fields!DriverLicense.Value
Fields!BrokerName.Value

Whereas both of them belong to different tables.


问:
Problem `.x` is empty in pammtools packages
I am trying to replicate the example code in Bender and Schleip for Piece-wise exponential Additive Mixed modelling tools. Specifically a survival exercise with time varying effects.
https://arxiv.org/pdf/1806.01042.pdf

```<code>   library(dplyr); library(tidyr); library(purrr); library(ggplot2)
library(survival); library(mgcv); library(pammtools)

data("pbc", package="survival")
# event time information
pbc <- pbc %>%
  filter(id <= 312) %>%
  mutate(status = ifelse(status==0,0,1) )%>%
  select(id:status, trt:sex, bili, protime)
pbc %>% slice(1:6)

pbc_ped <- as_ped(
  data = list(pbc, pbcseq),
  formula = Surv(pbc$time, pbc$status)~sex|concurrent(bili, protime, tz_var = "day"),
  id = "id")
</code>```

I always get the error

Error: .x is empty, and no .init supplied

I installed and checked Rtools, I tried with different (older) version of Purrr, which sometimes is related with this error. I tried to run the code also on https://rdrr.io/snippets/.

Any idea? thank you very much...

答:
You have not used the code in that vignette. And you added pbc$ to the arguments in Surv(), a common mistake but generally not a productive strategy

```<code># Need to narrow the material from pbcseq
pbcseq <- pbcseq %>% select(id, day, bili, protime)
# I would have given it a different name

#------ Error when using "|" rather than "+"
pbc_ped <- as_ped(
    data = list(pbc, pbcseq),
    formula = Surv(time, status)~sex|concurrent(bili, protime, tz_var = "day"),
    id = "id")
#Error: `.x` is empty, and no `.init` supplied
#________________

pbc_ped <- as_ped(
    data = list(pbc, pbcseq),
    formula = Surv(time, status)~sex + concurrent(bili, protime, tz_var = "day"),
    id = "id")    # No error
</code>```

I think there may be an error in the vignette. I don't see any examples using the construct ...

```<code>Surv(time,status)~ variates | special(.)
</code>```

They all use a "+" sign for adding the time-dependent covariates. If you go to https://adibender.github.io/pammtools//articles/data-transformation.html you see them using a "+" rather than a "|".  I think there is some sloppiness in that package's documentation. But your additions only made the problem worse.

Body:
I am trying to replicate the example code in Bender and Schleip for Piece-wise exponential Additive Mixed modelling tools. Specifically a survival exercise with time varying effects.
https://arxiv.org/pdf/1806.01042.pdf

   library(dplyr); library(tidyr); library(purrr); library(ggplot2)
library(survival); library(mgcv); library(pammtools)

data("pbc", package="survival")
# event time information
pbc <- pbc %>%
  filter(id <= 312) %>%
  mutate(status = ifelse(status==0,0,1) )%>%
  select(id:status, trt:sex, bili, protime)
pbc %>% slice(1:6)

pbc_ped <- as_ped(
  data = list(pbc, pbcseq),
  formula = Surv(pbc$time, pbc$status)~sex|concurrent(bili, protime, tz_var = "day"),
  id = "id")

I always get the error

Error: .x is empty, and no .init supplied

I installed and checked Rtools, I tried with different (older) version of Purrr, which sometimes is related with this error. I tried to run the code also on https://rdrr.io/snippets/.

Any idea? thank you very much...

Body:
You have not used the code in that vignette. And you added pbc$ to the arguments in Surv(), a common mistake but generally not a productive strategy

# Need to narrow the material from pbcseq
pbcseq <- pbcseq %>% select(id, day, bili, protime)
# I would have given it a different name

#------ Error when using "|" rather than "+"
pbc_ped <- as_ped(
    data = list(pbc, pbcseq),
    formula = Surv(time, status)~sex|concurrent(bili, protime, tz_var = "day"),
    id = "id")
#Error: `.x` is empty, and no `.init` supplied
#________________

pbc_ped <- as_ped(
    data = list(pbc, pbcseq),
    formula = Surv(time, status)~sex + concurrent(bili, protime, tz_var = "day"),
    id = "id")    # No error

I think there may be an error in the vignette. I don't see any examples using the construct ...

Surv(time,status)~ variates | special(.)

They all use a "+" sign for adding the time-dependent covariates. If you go to https://adibender.github.io/pammtools//articles/data-transformation.html you see them using a "+" rather than a "|".  I think there is some sloppiness in that package's documentation. But your additions only made the problem worse.


问:
Array multiplication with different dimensions to make probability tables in R
I have an array and want to make a probability table for each matrix of dimensions 1 and 2. For example, consider this:

```<code>A <- array(1:12,c(2,2,3))
print(A)
, , 1

     [,1] [,2]
[1,]    1    3
[2,]    2    4

, , 2

     [,1] [,2]
[1,]    5    7
[2,]    6    8

, , 3

     [,1] [,2]
[1,]    9   11
[2,]   10   12
</code>```

I want each of the 2x2 matrices become probability tables with sum 1 for each, i.e. each 2x2 matrix is divided by its sum of element. For this, I ran the below code by first taking sum and then creating an array with the same dimension.

```<code>Asum <- apply(A,3,sum)

B <- array(rep(Asum,each=length(A[,,1])),dim(A))

A/B
, , 1

     [,1] [,2]
[1,]  0.1  0.3
[2,]  0.2  0.4

, , 2

          [,1]      [,2]
[1,] 0.1923077 0.2692308
[2,] 0.2307692 0.3076923

, , 3

          [,1]      [,2]
[1,] 0.2142857 0.2619048
[2,] 0.2380952 0.2857143
</code>```

Is there a better way to do this?

Body:
I have an array and want to make a probability table for each matrix of dimensions 1 and 2. For example, consider this:

A <- array(1:12,c(2,2,3))
print(A)
, , 1

     [,1] [,2]
[1,]    1    3
[2,]    2    4

, , 2

     [,1] [,2]
[1,]    5    7
[2,]    6    8

, , 3

     [,1] [,2]
[1,]    9   11
[2,]   10   12

I want each of the 2x2 matrices become probability tables with sum 1 for each, i.e. each 2x2 matrix is divided by its sum of element. For this, I ran the below code by first taking sum and then creating an array with the same dimension.

Asum <- apply(A,3,sum)

B <- array(rep(Asum,each=length(A[,,1])),dim(A))

A/B
, , 1

     [,1] [,2]
[1,]  0.1  0.3
[2,]  0.2  0.4

, , 2

          [,1]      [,2]
[1,] 0.1923077 0.2692308
[2,] 0.2307692 0.3076923

, , 3

          [,1]      [,2]
[1,] 0.2142857 0.2619048
[2,] 0.2380952 0.2857143

Is there a better way to do this?

Body:
You can use proportions():

proportions(A, margin = 3)

, , 1

     [,1] [,2]
[1,]  0.1  0.3
[2,]  0.2  0.4

, , 2

          [,1]      [,2]
[1,] 0.1923077 0.2692308
[2,] 0.2307692 0.3076923

, , 3

          [,1]      [,2]
[1,] 0.2142857 0.2619048
[2,] 0.2380952 0.2857143


问:
What are the differences between Abstract Factory and Factory design patterns?
I know there are many posts out there about the differences between these two patterns, but there are a few things that I cannot find.

From what I have been reading, I see that the factory method pattern allows you to define how to create a single concrete product but hiding the implementation from the client as they will see a generic product. My first question is about the abstract factory. Is its role to allow you to create families of concrete objects in (that can depend on what specific factory you use) rather than just a single concrete object? Does the abstract factory only return one very large object or many objects depending on what methods you call?

My final two questions are about a single quote that I cannot fully understand that I have seen in numerous places:

One difference between the two is that
  with the Abstract Factory pattern, a
  class delegates the responsibility of
  object instantiation to another object
  via composition whereas the Factory
  Method pattern uses inheritance and
  relies on a subclass to handle the
  desired object instantiation.

My understanding is that the factory method pattern has a Creator interface that will make the ConcreteCreator be in charge of knowing which ConcreteProduct to instantiate. Is this what it means by using inheritance to handle object instantiation?

Now with regards to that quote, how exactly does the Abstract Factory pattern delegate the responsibility of object instantiation to another object via composition? What does this mean? It looks like the Abstract Factory pattern also uses inheritance to do the construction process as well in my eyes, but then again I am still learning about these patterns.

Any help especially with the last question, would be greatly appreciated.

答: My conclusion: there is no difference. Why? Because I cannot see any justification to equip objects other than factories with factory methods - otherwise you get a violation of the separation of responsibility principle. In addition, I cannot see any difference between a factory with a single factory method and a factory with multiple factory methods: both create "families of related objects" unless anyone can prove that a single-family-member family is not a family. Or a collection that contains a single item is not a collection.


问:
DD_INSERT in the update strategy transformation
Informatica automatically inserts all the rows to the target...so why do we have to use update strategy transformation (DD_INSERT) to insert the records???</p>

答:
Update strategy transformation is used when you want handy logic to check insert/update/delete records by comparing source key columns with target key columns. for each type of update strategy transformation, you can choose how you want to process your data. below link examples by Informatica will help you to understand this:

https://docs.informatica.com/data-integration/powercenter/10-5/transformation-language-reference/constants/dd_insert/examples.html

You can achieve the same by using a lookup and setting IUD Flag in expression transformation and then based on each flag you can route different types of records (ins, upd, del) into different target to update target in different ways.

Informatica is giving you read to use logic in the form of Update strategy transformation and dd_insert is one type of that.


问:
Git diff for n'th modified file?
Suppose we change several files, and want to view the diff for one at a time, I know we can use something like this

git status

Changes not staged for commit:
 directory)
    modified:   app/assets/stylesheets/application.scss
    modified:   app/javascript/packs/application.js
    modified:   app/views/layouts/application.html.erb
    modified:   config/webpack/environment.js
```
<p>and run</p>
<pre class="lang-sh prettyprint-override"><code>git diff app/assets/stylesheets/application.scss
</code>```

then

git diff app/javascript/packs/application.js
```
<p>and so on..</p>
<pre class="lang-sh prettyprint-override"><code>git diff app/views/layouts/application.html.erb
</code>```

To view each of the files' diffs one by one (one by one is desired here, but all the typing of file paths isn't, even with tab to auto complete).

Question

Is there a way to achieve the same (i.e. view git diff for a single file at a time) but without having to type (manually, nor with tab autocomplete) the full path to the changed file? (e.g. can we reference somehow, pseudo-code: git diff --mod_file 1, git diff --mod_file 2 etc) ?

答:
If you're working in a bash-like shell, you can define a shell function such as

function gitdiffn() {
    git diff ${@:2} $(git diff --name-only | sed -n "$1 p")
}
```
<p>which can then be used to browse the list of modified files (with 1-based indexing)
as</p>
<pre class="lang-sh prettyprint-override"><code>$ gitdiffn 1
$ gitdiffn 2
# ...
</code>```

By including ${@:2} before the $(command substitution) that fetches the nth file name, we allow for the propagation additional arbitrary flags to the git diff invocation, so commands like

$ gitdiffn 1 --minimal
```

will work as expected.

Title: Git diff for n'th modified file?

Body:
Suppose we change several files, and want to view the diff for one at a time, I know we can use something like this

git status

Changes not staged for commit:
 directory)
    modified:   app/assets/stylesheets/application.scss
    modified:   app/javascript/packs/application.js
    modified:   app/views/layouts/application.html.erb
    modified:   config/webpack/environment.js

and run

git diff app/assets/stylesheets/application.scss

then

git diff app/javascript/packs/application.js

and so on..

git diff app/views/layouts/application.html.erb

To view each of the files' diffs one by one (one by one is desired here, but all the typing of file paths isn't, even with tab to auto complete).

Question

Is there a way to achieve the same (i.e. view git diff for a single file at a time) but without having to type (manually, nor with tab autocomplete) the full path to the changed file? (e.g. can we reference somehow, pseudo-code: git diff --mod_file 1, git diff --mod_file 2 etc) ?

Body:
If you're working in a bash-like shell, you can define a shell function such as

function gitdiffn() {
    git diff ${@:2} $(git diff --name-only | sed -n "$1 p")
}

which can then be used to browse the list of modified files (with 1-based indexing)
as

$ gitdiffn 1
$ gitdiffn 2
# ...

By including ${@:2} before the $(command substitution) that fetches the nth file name, we allow for the propagation additional arbitrary flags to the git diff invocation, so commands like

$ gitdiffn 1 --minimal

will work as expected.


问:
How to round robin by UUID in SQL database?
I have a list of agents that I want to assign tasks to using round robin.

agents table:

id

uuid1

uuid2

uuid3

uuid4

How to get rows of the table above in a round robin fashion?

Desired outcome:

uuid1 -> uuid2 -> uuid3 -> uuid4 -> uuid1 (repeat)

I tried ordering uuids then selecting the next one based on the previous uuid

SELECT id FROM agents ORDER BY id; // When there is no previous

SELECT id FROM agents WHERE id > 'uuid1' ORDER BY id; // After the first query
```

But I don't know how to repeat when I reach the last uuid (when uuid4 is retrieved and uuid1 must be selected again)

答:
```<code>select nxt
from (
  select
    -- for every id, find the next item, if not exists, use the earliest (min)
    id, coalesce(lead(id) over (order by id),(select min(id) from Tbl)) as nxt
  from Tbl
  ) as Agents
where id = 'uuid4'
</code>```

Body:
I have a list of agents that I want to assign tasks to using round robin.

agents table:

id

uuid1

uuid2

uuid3

uuid4

How to get rows of the table above in a round robin fashion?

Desired outcome:

uuid1 -> uuid2 -> uuid3 -> uuid4 -> uuid1 (repeat)

I tried ordering uuids then selecting the next one based on the previous uuid

SELECT id FROM agents ORDER BY id; // When there is no previous

SELECT id FROM agents WHERE id > 'uuid1' ORDER BY id; // After the first query

But I don't know how to repeat when I reach the last uuid (when uuid4 is retrieved and uuid1 must be selected again)


问:
Doctrine 2 Inheritance Mapping with Association
NOTE : if what I want is not possible, a "not possible" answer will be accepted

In the Doctrine 2 documentation about inheritance mapping, it says there are 2 ways :

Single table inheritance (STI)

Class table inheritance (CTI)

For both, there is the warning :

If you use a STI/CTI entity as a many-to-one or one-to-one entity you should never use one of the classes at the upper levels of the inheritance hierachy as “targetEntity”, only those that have no subclasses. Otherwise Doctrine CANNOT create proxy instances of this entity and will ALWAYS load the entity eagerly.

So, how can I proceed to use inheritance with an association to the base (abstract) class ? (and keep the performance of course)

Example

A user has many Pet (abstract class extended by Dog or Cat).

What I want to do :

```<code>class User {
    /**
     * @var array(Pet) (array of Dog or Cat)
     */
    private $pets;
}
</code>```

Because of the warning in Doctrine documentation, I should do that :

```<code>class User {
    /**
     * @var array(Dog)
     */
    private $dogs;
    /**
     * @var array(Cat)
     */
    private $cats;
}
</code>```

This is annoying, because I loose the benefits of inheritance !

Note : I didn't add the Doctrine annotations for the mapping to DB, but you can understand what I mean

答:
I'm tired, but this seems like much ado about nothing.

You missed the important bit of that warning:

If you use a STI/CTI entity as a many-to-one or one-to-one entity

That's not the case in your example!  If you had not omitted the doctrine annotations, you might have noticed.

The association User::pets is OneToMany, not [One|Many]ToOne.  One user has many pets.

The inverse association is OneToOne, but it's targeting User, which has no inheritance.

Robin's answer should have been a good hint -- you can log the sql queries and see what doctrine actually does to  your database!

The bad-for-performance scenario is something like:

```<code>abstract class Pet { ... }

class Cat extends Pet { ... }

class Dog extends Pet { ... }

class Collar {
   /**
    * @Column(length="16")
    */

   protected $color;
   /**
    * ManyToOne(targetEntity="Pet")
    */
   protected $owner;
}
</code>```

Now, if you wanted to iterate over all the blue collars, Doctrine runs into some trouble.  It doesn't know what class $owner is going to be, so it can't use a Proxy.  Instead, it's forced to eagerly load $owner to find out whether it's a Cat or a Dog.

This isn't a problem for OneToMany or ManyToMany relationships, because in that case, lazy loading works fine.  Instead of a proxy, you get a PersistentCollection.  And a PersistentCollection is always just a PersistentCollection.  It doesn't care about it's own contents until you actually ask for them.  So lazy loading works fine.

Body:
NOTE : if what I want is not possible, a "not possible" answer will be accepted

In the Doctrine 2 documentation about inheritance mapping, it says there are 2 ways :

Single table inheritance (STI)

Class table inheritance (CTI)

For both, there is the warning :

If you use a STI/CTI entity as a many-to-one or one-to-one entity you should never use one of the classes at the upper levels of the inheritance hierachy as “targetEntity”, only those that have no subclasses. Otherwise Doctrine CANNOT create proxy instances of this entity and will ALWAYS load the entity eagerly.

So, how can I proceed to use inheritance with an association to the base (abstract) class ? (and keep the performance of course)

Example

A user has many Pet (abstract class extended by Dog or Cat).

What I want to do :

class User {
    /**
     * @var array(Pet) (array of Dog or Cat)
     */
    private $pets;
}

Because of the warning in Doctrine documentation, I should do that :

class User {
    /**
     * @var array(Dog)
     */
    private $dogs;
    /**
     * @var array(Cat)
     */
    private $cats;
}

This is annoying, because I loose the benefits of inheritance !

Note : I didn't add the Doctrine annotations for the mapping to DB, but you can understand what I mean

Body:
I'm tired, but this seems like much ado about nothing.

You missed the important bit of that warning:

If you use a STI/CTI entity as a many-to-one or one-to-one entity

That's not the case in your example!  If you had not omitted the doctrine annotations, you might have noticed.

The association User::pets is OneToMany, not [One|Many]ToOne.  One user has many pets.

The inverse association is OneToOne, but it's targeting User, which has no inheritance.

Robin's answer should have been a good hint -- you can log the sql queries and see what doctrine actually does to  your database!

The bad-for-performance scenario is something like:

abstract class Pet { ... }

class Cat extends Pet { ... }

class Dog extends Pet { ... }

class Collar {
   /**
    * @Column(length="16")
    */

   protected $color;
   /**
    * ManyToOne(targetEntity="Pet")
    */
   protected $owner;
}

Now, if you wanted to iterate over all the blue collars, Doctrine runs into some trouble.  It doesn't know what class $owner is going to be, so it can't use a Proxy.  Instead, it's forced to eagerly load $owner to find out whether it's a Cat or a Dog.

This isn't a problem for OneToMany or ManyToMany relationships, because in that case, lazy loading works fine.  Instead of a proxy, you get a PersistentCollection.  And a PersistentCollection is always just a PersistentCollection.  It doesn't care about it's own contents until you actually ask for them.  So lazy loading works fine.


问:
How to define a validator.Fieldlevel equivalent of a given string variable in Go?
I'm validating my config file using Go's validator package

One of the fields(createTime) from the config file I'm reading as a string, and want to make sure that it is a valid time duration:

```<code>type Config struct{
    ...
    CreateTime   string `yaml:"createTime" validate:"duration,required"`
    ...
}
</code>```

So, I have written a custom validation function as follows:

```<code>import (
    "time"
    "github.com/go-playground/validator/v10"
)

// isValidDuration is a custom validation function, and it will check if the given string is a valid time duration
func isValidDuration(fl validator.FieldLevel) bool {
    if _, err := time.ParseDuration(fl.Field().String()); err != nil {
        return false
    }
    return true
}
</code>```

Which I'm using for validation as follows:

```<code>func (configObject *Config) Validate() error {

    // Validate configurations
    validate := validator.New()
    if err := validate.RegisterValidation("duration", isValidDuration); err != nil {
        return err
    }
    return validate.Struct(configObject)
}
</code>```

The custom validator is working fine and I want to write a unit test for isValidDuration function. Following is the unit test boilerplate generated by IDE:

```<code>import (
    "testing"
    "github.com/go-playground/validator/v10"
)

func Test_isValidDuration(t *testing.T) {
    type args struct {
        fl validator.FieldLevel
    }
    var tests = []struct {
        name string
        args args
        want bool
    }{
        // TODO: Add test cases.
        {name: "positive", args: ???????, want: true},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := isValidDuration(tt.args.fl); got != tt.want {
                t.Errorf("isValidDuration() = %v, want %v", got, tt.want)
            }
        })
    }
}
</code>```

I'm new to Go and not sure what to pass in the args field of the testcase above. How do I create a struct containing one validator.FieldLevel field?

Ideally, I would like to pass something like "10m" as args and since it is a valid time duration, would expect the output of isValidDuration as true since "10m" is a valid duration.
I'm trying this: {name: "positive", args: struct{ fl validator.FieldLevel }{fl: "10m"}, want: true} but getting this ereor: '"10m"' (type string) cannot be represented by the type validator.FieldLevel

How do I create a validator.FieldLevel variable with value equivalent to "10m"? Could someone please help me out?

答:
problem1

A language semantic problem, fl is not the type String.

{
  name: "positive",
  args: args{
    fl: validator.FieldLevel{
       // ....
    },
  },
  want: true,
},
```
<h3>problem2</h3>
<p>How to use <code>validator.FieldLevel</code>.</p>
<p>In code base, we can see FieldLevel is a interface, and you need create struct <code>validate</code>, which is not exported and not supposed to be used by user.</p>
<pre class="lang-golang prettyprint-override"><code>type FieldLevel interface

// ...

var _ FieldLevel = new(validate)
</code>```

answer

So, you'd best to write your UT like UT of validator package. Don't use the code from your IDE!

```<code>// have a look at this UT
// github.com/go-playground/validator/v10@v10.10.0/validator_test.go
func TestKeysCustomValidation(t *testing.T) {
</code>```

Body:
I'm validating my config file using Go's validator package

One of the fields(createTime) from the config file I'm reading as a string, and want to make sure that it is a valid time duration:

type Config struct{
    ...
    CreateTime   string `yaml:"createTime" validate:"duration,required"`
    ...
}

So, I have written a custom validation function as follows:

import (
    "time"
    "github.com/go-playground/validator/v10"
)

// isValidDuration is a custom validation function, and it will check if the given string is a valid time duration
func isValidDuration(fl validator.FieldLevel) bool {
    if _, err := time.ParseDuration(fl.Field().String()); err != nil {
        return false
    }
    return true
}

Which I'm using for validation as follows:

func (configObject *Config) Validate() error {

    // Validate configurations
    validate := validator.New()
    if err := validate.RegisterValidation("duration", isValidDuration); err != nil {
        return err
    }
    return validate.Struct(configObject)
}

The custom validator is working fine and I want to write a unit test for isValidDuration function. Following is the unit test boilerplate generated by IDE:

import (
    "testing"
    "github.com/go-playground/validator/v10"
)

func Test_isValidDuration(t *testing.T) {
    type args struct {
        fl validator.FieldLevel
    }
    var tests = []struct {
        name string
        args args
        want bool
    }{
        // TODO: Add test cases.
        {name: "positive", args: ???????, want: true},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := isValidDuration(tt.args.fl); got != tt.want {
                t.Errorf("isValidDuration() = %v, want %v", got, tt.want)
            }
        })
    }
}

I'm new to Go and not sure what to pass in the args field of the testcase above. How do I create a struct containing one validator.FieldLevel field?

Ideally, I would like to pass something like "10m" as args and since it is a valid time duration, would expect the output of isValidDuration as true since "10m" is a valid duration.
I'm trying this: {name: "positive", args: struct{ fl validator.FieldLevel }{fl: "10m"}, want: true} but getting this ereor: '"10m"' (type string) cannot be represented by the type validator.FieldLevel

How do I create a validator.FieldLevel variable with value equivalent to "10m"? Could someone please help me out?

Body:
problem1

A language semantic problem, fl is not the type String.

{
  name: "positive",
  args: args{
    fl: validator.FieldLevel{
       // ....
    },
  },
  want: true,
},

problem2

How to use validator.FieldLevel.

In code base, we can see FieldLevel is a interface, and you need create struct validate, which is not exported and not supposed to be used by user.

type FieldLevel interface

// ...

var _ FieldLevel = new(validate)

answer

So, you'd best to write your UT like UT of validator package. Don't use the code from your IDE!

// have a look at this UT
// github.com/go-playground/validator/v10@v10.10.0/validator_test.go
func TestKeysCustomValidation(t *testing.T) {


问:
Limit DateTime strftime precision to milliseconds
I'm working on a project which involves integrating with a 3rd party API. As part of the contract, I need to include a UTC date string in the below ISO format, within the XML body of the HTTP request:

yyyy-MM-ddTHH:mm:ss.sssZ

I've been trying a few options in re.pl to generate a date string in the above format. So far, I've been able to come up with this:

```<code>use DateTime;

my $now_utc = DateTime->now(time_zone => 'UTC');

my $now_iso_format = $now_utc->strftime('%Y-%m-%dT%H:%M:%S.%sZ');
</code>```

When I execute these lines in re.pl, I get the date string in the format:

2022-02-07T03:55:22.1644206122Z

How do I limit the precision to milliseconds? As you can see, right now it's nanoseconds.

答:
Details are listed on strftime patterns page and %N is for fractional seconds digits

```<code>.. -> strftime('%Y-%m-%dT%H:%M:%S.%3NZ');
</code>```

Body:
I'm working on a project which involves integrating with a 3rd party API. As part of the contract, I need to include a UTC date string in the below ISO format, within the XML body of the HTTP request:

yyyy-MM-ddTHH:mm:ss.sssZ

I've been trying a few options in re.pl to generate a date string in the above format. So far, I've been able to come up with this:

use DateTime;

my $now_utc = DateTime->now(time_zone => 'UTC');

my $now_iso_format = $now_utc->strftime('%Y-%m-%dT%H:%M:%S.%sZ');

When I execute these lines in re.pl, I get the date string in the format:

2022-02-07T03:55:22.1644206122Z

How do I limit the precision to milliseconds? As you can see, right now it's nanoseconds.

Body:
Details are listed on strftime patterns page and %N is for fractional seconds digits

.. -> strftime('%Y-%m-%dT%H:%M:%S.%3NZ');


问:
c# - cast generic class to its base non-generic class
I have following classes:

```<code>public abstract class CustomerBase
{
    public long CustomerNumber { get; set; }
    public string Name { get; set; }
}

public abstract class CustomerWithChildern<T> : CustomerBase
    where T: CustomerBase
{
    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

public class SalesOffice : CustomerWithChildern<NationalNegotiation>
{
}
</code>```

The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like:

```<code>    public void WalkHierarchy(CustomerBase start)
    {
        Print(start.CustomerNumber);
        if (start is CustomerWithChildern<>)
        {
            foreach(ch in start.Childern)
            {
                WalkHierarchy(ch);
            }
        }
    }
</code>```

Is there any chance I could get something like this working?

The solution based on suggested has-childern interface I implemented:

```<code>public interface ICustomerWithChildern
{
    IEnumerable ChildernEnum { get; }
}

public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern
    where T: CustomerBase
{
    public IEnumerable ChildernEnum { get { return Childern; } }

    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

    public void WalkHierarchy(CustomerBase start)
    {
        var x = start.CustomerNumber;
        var c = start as ICustomerWithChildern;
        if (c != null)
        {
            foreach(var ch in c.ChildernEnum)
            {
                WalkHierarchy((CustomerBase)ch);
            }
        }
    }
</code>```

答:
"Is" and "As" only work on fully qualified generic types.

See this MSDN discussion for details including workarounds.

The most common workaround I've seen is to add an interface to the mix that your CustomerWithChildren could implement, and check for that interface.

OwnerDisplayName: Buthrakaur

ContentLicense: CC BY-SA 2.5

Body:
I have following classes:

public abstract class CustomerBase
{
    public long CustomerNumber { get; set; }
    public string Name { get; set; }
}

public abstract class CustomerWithChildern<T> : CustomerBase
    where T: CustomerBase
{
    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

public class SalesOffice : CustomerWithChildern<NationalNegotiation>
{
}

The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like:

    public void WalkHierarchy(CustomerBase start)
    {
        Print(start.CustomerNumber);
        if (start is CustomerWithChildern<>)
        {
            foreach(ch in start.Childern)
            {
                WalkHierarchy(ch);
            }
        }
    }

Is there any chance I could get something like this working?

The solution based on suggested has-childern interface I implemented:

public interface ICustomerWithChildern
{
    IEnumerable ChildernEnum { get; }
}

public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern
    where T: CustomerBase
{
    public IEnumerable ChildernEnum { get { return Childern; } }

    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

    public void WalkHierarchy(CustomerBase start)
    {
        var x = start.CustomerNumber;
        var c = start as ICustomerWithChildern;
        if (c != null)
        {
            foreach(var ch in c.ChildernEnum)
            {
                WalkHierarchy((CustomerBase)ch);
            }
        }
    }

LastEditorDisplayName: Buthrakaur

OwnerDisplayName: Reed Copsey


问:
IPublicClientApplication GetAccountsAsync returns nothing in Windows Forms App
I am trying to make the sample application available at https://cmatskas.com/modern-authentication-with-azure-ad-for-winforms-native-apps-2/ work.

I registered application in Azure and got Client ID and Tenant ID. Both IDs are GUID-like numbers. These codes were substituted to the program.

I also added a multiline textbox txtLog to the Form1 to show progress messages.

The following procedure does not return accounts:

```<code>private async Task<AuthenticationResult> Login()
{

AuthenticationResult authResult = null;
var accounts = await Program.PublicClientApp.GetAccountsAsync();
txtLog.Text += "accounts count " + accounts.ToArray().Count().ToString() + "\r\n";

if (accounts != null)
{ label2.Text += $"GetAccountsAsync passed!"; }
else
{ label2.Text += "PublicClientApp.GetAccountsAsync returned an empty list"; }

var firstAccount = accounts.FirstOrDefault();

if (firstAccount != null)
{ label2.Text += firstAccount.Username; }
else
{ label2.Text += "firstAccount is null"; }

try
{
authResult = await Program.PublicClientApp.AcquireTokenSilent(scopes, firstAccount)
    .ExecuteAsync();
    label2.Text = "Auth result passed!";
}
catch (MsalUiRequiredException ex)
        {
            // A MsalUiRequiredException happened on AcquireTokenSilent.
            // This indicates you need to call AcquireTokenInteractive to acquire a token
            System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
            label2.Text += $"Auth result error: {ex.Message}";

            try
            {
                authResult = await Program.PublicClientApp.AcquireTokenInteractive(scopes)
                    .WithAccount(accounts.FirstOrDefault())
                    .WithPrompt(Prompt.SelectAccount)
                    .ExecuteAsync();
                txtLog.Text += "authResult AccessToken: " + authResult.AccessToken + "\r\n";
                label2.Text += "AcquireTokenInteractive passed";
            }
            catch (MsalException msalex)
            {
                label1.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
            }
        }
        catch (Exception ex)
        {
            label1.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
        }
        return authResult;
    }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Identity.Client;

namespace Modern2
{
    static class Program
    {

    public static string ClientId = "1189b025-e4c7-4265-b3fb-a03e15582165";
    public static string Tenant = "223591c8-866c-485c-b6db-35e7d2527da7";

    //public static string ClientId = Environment.GetEnvironmentVariable("ClientId", EnvironmentVariableTarget.User);
    //public static string Tenant = Environment.GetEnvironmentVariable("Tenant", EnvironmentVariableTarget.User);
    private static IPublicClientApplication clientApp;

    public static Form1 goFrmMain;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        goFrmMain = new Form1();
        goFrmMain.txtLog.Text = "";
        InitializeAuth();
        Application.Run(goFrmMain);
    }
    public static IPublicClientApplication PublicClientApp { get { return clientApp; } }

    private static void InitializeAuth()
    {

        clientApp = PublicClientApplicationBuilder.Create(ClientId)
                .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
                .WithAuthority(AzureCloudInstance.AzurePublic, Tenant)
                .Build();
        goFrmMain.txtLog.Text += "clientApp.Authority: " + clientApp.Authority + "\r\n";
        TokenCacheHelper.EnableSerialization(clientApp.UserTokenCache);
        goFrmMain.txtLog.Text += "TokenCacheHelper.CacheFilePath: " + TokenCacheHelper.CacheFilePath + "\r\n";
    }
}
</code>```

}

答:
The company directory in Azure was Unmanaged.

Once the steps of "Take over an unmanaged directory as administrator in Azure Active Directory" at https://learn.microsoft.com/en-us/azure/active-directory/enterprise-users/domains-admin-takeover were implemented, the function started returning the accounts.

Body:
I am trying to make the sample application available at https://cmatskas.com/modern-authentication-with-azure-ad-for-winforms-native-apps-2/ work.

I registered application in Azure and got Client ID and Tenant ID. Both IDs are GUID-like numbers. These codes were substituted to the program.

I also added a multiline textbox txtLog to the Form1 to show progress messages.

The following procedure does not return accounts:

private async Task<AuthenticationResult> Login()
{

AuthenticationResult authResult = null;
var accounts = await Program.PublicClientApp.GetAccountsAsync();
txtLog.Text += "accounts count " + accounts.ToArray().Count().ToString() + "\r\n";

if (accounts != null)
{ label2.Text += $"GetAccountsAsync passed!"; }
else
{ label2.Text += "PublicClientApp.GetAccountsAsync returned an empty list"; }

var firstAccount = accounts.FirstOrDefault();

if (firstAccount != null)
{ label2.Text += firstAccount.Username; }
else
{ label2.Text += "firstAccount is null"; }

try
{
authResult = await Program.PublicClientApp.AcquireTokenSilent(scopes, firstAccount)
    .ExecuteAsync();
    label2.Text = "Auth result passed!";
}
catch (MsalUiRequiredException ex)
        {
            // A MsalUiRequiredException happened on AcquireTokenSilent.
            // This indicates you need to call AcquireTokenInteractive to acquire a token
            System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
            label2.Text += $"Auth result error: {ex.Message}";

            try
            {
                authResult = await Program.PublicClientApp.AcquireTokenInteractive(scopes)
                    .WithAccount(accounts.FirstOrDefault())
                    .WithPrompt(Prompt.SelectAccount)
                    .ExecuteAsync();
                txtLog.Text += "authResult AccessToken: " + authResult.AccessToken + "\r\n";
                label2.Text += "AcquireTokenInteractive passed";
            }
            catch (MsalException msalex)
            {
                label1.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
            }
        }
        catch (Exception ex)
        {
            label1.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
        }
        return authResult;
    }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Identity.Client;

namespace Modern2
{
    static class Program
    {

    public static string ClientId = "1189b025-e4c7-4265-b3fb-a03e15582165";
    public static string Tenant = "223591c8-866c-485c-b6db-35e7d2527da7";

    //public static string ClientId = Environment.GetEnvironmentVariable("ClientId", EnvironmentVariableTarget.User);
    //public static string Tenant = Environment.GetEnvironmentVariable("Tenant", EnvironmentVariableTarget.User);
    private static IPublicClientApplication clientApp;

    public static Form1 goFrmMain;

    ///
    /// The main entry point for the application.
    ///
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        goFrmMain = new Form1();
        goFrmMain.txtLog.Text = "";
        InitializeAuth();
        Application.Run(goFrmMain);
    }
    public static IPublicClientApplication PublicClientApp { get { return clientApp; } }

    private static void InitializeAuth()
    {

        clientApp = PublicClientApplicationBuilder.Create(ClientId)
                .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
                .WithAuthority(AzureCloudInstance.AzurePublic, Tenant)
                .Build();
        goFrmMain.txtLog.Text += "clientApp.Authority: " + clientApp.Authority + "\r\n";
        TokenCacheHelper.EnableSerialization(clientApp.UserTokenCache);
        goFrmMain.txtLog.Text += "TokenCacheHelper.CacheFilePath: " + TokenCacheHelper.CacheFilePath + "\r\n";
    }
}

}


问:
EasyAdmin 3 Edit Photo
I have a commercial entity for portfolio management I use vichImage, but I don't understand why I cannot modify or delete an image.
I can't change the photo without modifying another form field.

```<code><?php

namespace App\Controller\Admin;

use App\Entity\Commercial;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Config\Filters;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use Vich\UploaderBundle\Form\Type\VichImageType;

class CommercialCrudController extends AbstractCrudController
{
    public static function getEntityFqcn(): string
    {
        return Commercial::class;
    }

    public function configureCrud(Crud $crud): Crud
    {
        return $crud
            ->setPageTitle(Crud::PAGE_INDEX, 'Commercial Gallery')
            ->setPageTitle(Crud::PAGE_NEW, 'Add Photos')
            ->setPageTitle(Crud::PAGE_EDIT, 'Edit Photo')
            ->setDefaultSort(['created_at' => 'DESC']);

    }

    public function configureFields(string $pageName): iterable
    {
        // Photos configuration
        $imageFile = TextareaField::new('imageFile', 'Photo')->setFormType(VichImageType::class);
        $image = ImageField::new('commercialPhoto', 'Photo')->setBasePath('images/commercial');

        $fields = [

            IdField::new('id')->onlyOnDetail(),
            TextField::new('name', 'Services name'),
            AssociationField::new('users', 'Published by')->hideOnForm(),
            DateTimeField::new('created_at', 'Date')->hideOnForm(),

        ];

        // CRUD ACTIONS
        if ($pageName == Crud::PAGE_INDEX || $pageName == Crud::PAGE_DETAIL) {
            $fields[] = $image; // afficher l'image dans la page Index et Detail
        } else {
            $fields[] = $imageFile; // afficher l'image dans la page Edit
        }
        return $fields;
    }

    public function configureActions(Actions $actions): Actions
    {
        return $actions // Add boutton show
            ->add(Crud::PAGE_INDEX, Action::DETAIL);

    }

    //create a filter
    public function configureFilters(Filters $filters): Filters
    {
        return $filters
            ->add('name')
            ->add('users')
            ->add('created_at');
    }
}
</code>```

before it was enough to add this line, but now the file has changed

now is this:

```<code>namespace EasyCorp\Bundle\EasyAdminBundle\Event;

/**
 * @author Javier Eguiluz <javier.eguiluz@gmail.com>
 */
final class BeforeEntityDeletedEvent extends AbstractLifecycleEvent
{
    use StoppableEventTrait;

}
</code>```

And when i try to delet,

what can i do please?, I am a beginner, thank you in advance for your help.

答: it was just a spelling problem, I typed updated instead of update. and to delete just add ? before the string in the setCommercial photo property

Title: EasyAdmin 3 Edit Photo

Body:
I have a commercial entity for portfolio management I use vichImage, but I don't understand why I cannot modify or delete an image.
I can't change the photo without modifying another form field.

<?php

namespace App\Controller\Admin;

use App\Entity\Commercial;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Config\Filters;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use Vich\UploaderBundle\Form\Type\VichImageType;

class CommercialCrudController extends AbstractCrudController
{
    public static function getEntityFqcn(): string
    {
        return Commercial::class;
    }

    public function configureCrud(Crud $crud): Crud
    {
        return $crud
            ->setPageTitle(Crud::PAGE_INDEX, 'Commercial Gallery')
            ->setPageTitle(Crud::PAGE_NEW, 'Add Photos')
            ->setPageTitle(Crud::PAGE_EDIT, 'Edit Photo')
            ->setDefaultSort(['created_at' => 'DESC']);

    }

    public function configureFields(string $pageName): iterable
    {
        // Photos configuration
        $imageFile = TextareaField::new('imageFile', 'Photo')->setFormType(VichImageType::class);
        $image = ImageField::new('commercialPhoto', 'Photo')->setBasePath('images/commercial');

        $fields = [

            IdField::new('id')->onlyOnDetail(),
            TextField::new('name', 'Services name'),
            AssociationField::new('users', 'Published by')->hideOnForm(),
            DateTimeField::new('created_at', 'Date')->hideOnForm(),

        ];

        // CRUD ACTIONS
        if ($pageName == Crud::PAGE_INDEX || $pageName == Crud::PAGE_DETAIL) {
            $fields[] = $image; // afficher l'image dans la page Index et Detail
        } else {
            $fields[] = $imageFile; // afficher l'image dans la page Edit
        }
        return $fields;
    }

    public function configureActions(Actions $actions): Actions
    {
        return $actions // Add boutton show
            ->add(Crud::PAGE_INDEX, Action::DETAIL);

    }

    //create a filter
    public function configureFilters(Filters $filters): Filters
    {
        return $filters
            ->add('name')
            ->add('users')
            ->add('created_at');
    }
}

before it was enough to add this line, but now the file has changed

now is this:

namespace EasyCorp\Bundle\EasyAdminBundle\Event;

/**
 * @author Javier Eguiluz <javier.eguiluz@gmail.com>
 */
final class BeforeEntityDeletedEvent extends AbstractLifecycleEvent
{
    use StoppableEventTrait;

}

And when i try to delet,

what can i do please?, I am a beginner, thank you in advance for your help.


问:
Hierarchical Table and Query in SQL Server
I have a scenario as follows:

```<code>ManufacturerID        Name
1                     XXX
2                     YYY

DeptID     Name  ManufacturerID
1          abc   1
2          bcd   1
3          efg   2

ProductID   name      deptid
1           dfdfg     1
2           dfdg      2
3           sdfsd     2

PartsID      name      productid
1            sdfs      1
2            sfdfs     2
3            sdd       1
</code>```

I want the above table structure to be made as hierarchical using levels. How do I design the table?

答:
I cannot understand what hierarchy you need to make, but if you're using sql server 2008 please take a look at hierachyId datatype.
And please provide more desdcription about you process. Now it looks straightforward:

Manufacturer has many departments, department has many products, product has many parts.

Body:
I have a scenario as follows:

ManufacturerID        Name
1                     XXX
2                     YYY

DeptID     Name  ManufacturerID
1          abc   1
2          bcd   1
3          efg   2

ProductID   name      deptid
1           dfdfg     1
2           dfdg      2
3           sdfsd     2

PartsID      name      productid
1            sdfs      1
2            sfdfs     2
3            sdd       1

I want the above table structure to be made as hierarchical using levels. How do I design the table?


问:
Why does upload_from_file Google Cloud Storage Function Throws timeout error?
I created a function that works for me, It uploads a file to Google Cloud Storage.

The problem is when my friend tries to upload the same file to the same bucket using the same code from his local machine, he gets timeout error. His internet is very good and he should be able to upload the file with no problems within his connections.

Any idea why is this happening?

def upload_to_cloud(file_path):
    """
        saves a file in the google storage. As Google requires audio files greater than 60 seconds to be saved on cloud before processing
        It always saves in 'audio-files-bucket' (folder)
        Input:
            Path of file to be saved
        Output:
            URI of the saved file
    """
    print("Uploading to cloud...")
    client = storage.Client().from_service_account_json(KEY_PATH)
    bucket = client.get_bucket('audio-files-bucket')
    file_name = str(file_path).split('\\')[-1]
    print(file_name)
    blob = bucket.blob(file_name)
    f = open(file_path, 'rb')
    blob.upload_from_file(f)
    f.close()
    print("uploaded at: ", "gs://audio-files-bucket/{}".format(file_name))
    return "gs://audio-files-bucket/{}".format(file_name)
```

It throughs the timeout exception in upload_from_file(f) line.

We tried to use upload_from_filename function, but the same error still occurs.

答:
Now, you can add a custom timeout with blob as this PR is merged, default is 60 seconds. So, if your internet connection is slow, you can add a custom timeout for the upload operation.</p>
```<code>def upload_blob(bucket_name, source_file_name, destination_blob_name):

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    blob.upload_from_filename(source_file_name, timeout=300)

    print(
        "File {} uploaded to {}.".format(
            source_file_name, destination_blob_name
        )
    )
</code>```

Body:
I created a function that works for me, It uploads a file to Google Cloud Storage.

The problem is when my friend tries to upload the same file to the same bucket using the same code from his local machine, he gets timeout error. His internet is very good and he should be able to upload the file with no problems within his connections.

Any idea why is this happening?

def upload_to_cloud(file_path):
    """
        saves a file in the google storage. As Google requires audio files greater than 60 seconds to be saved on cloud before processing
        It always saves in 'audio-files-bucket' (folder)
        Input:
            Path of file to be saved
        Output:
            URI of the saved file
    """
    print("Uploading to cloud...")
    client = storage.Client().from_service_account_json(KEY_PATH)
    bucket = client.get_bucket('audio-files-bucket')
    file_name = str(file_path).split('\\')[-1]
    print(file_name)
    blob = bucket.blob(file_name)
    f = open(file_path, 'rb')
    blob.upload_from_file(f)
    f.close()
    print("uploaded at: ", "gs://audio-files-bucket/{}".format(file_name))
    return "gs://audio-files-bucket/{}".format(file_name)

It throughs the timeout exception in upload_from_file(f) line.

We tried to use upload_from_filename function, but the same error still occurs.

Body:
Now, you can add a custom timeout with blob as this PR is merged, default is 60 seconds. So, if your internet connection is slow, you can add a custom timeout for the upload operation.

def upload_blob(bucket_name, source_file_name, destination_blob_name):

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    blob.upload_from_filename(source_file_name, timeout=300)

    print(
        "File {} uploaded to {}.".format(
            source_file_name, destination_blob_name
        )
    )