问:
How can I force nrwl nx to respect tag updates?
When I update project tags in nx.json, TSLint seems unaware that the tags have changed, and lints and builds the project even though the dependencies are violated.

Example

Currently my nx.json file looks like

```<code>{
  "npmScope": "patient-engagement",
  "implicitDependencies": {
    "package.json": "*",
    "tsconfig.json": "*",
    "nx.json": "*"
  },
  "projects": {
    "hep": {
      "tags": ["scope:hep", "compatibility:ie10"],
      "implicitDependencies": []
    },
    "mb-ui": {
      "tags": ["scope:shared", "compatibility:ie10"],
      "implicitDependencies": []
    },
    "utils": {
      "tags": ["scope:shared", "compatibility:ie10"],
      "implicitDependencies": []
    }
  }
}
</code>```

And my root tslint.json includes:

```<code>"nx-enforce-module-boundaries": [
      true,
      {
        "enforceBuildableLibDependency": true,
        "allow": [],
        "depConstraints": [
          {
            "sourceTag": "scope:hep",
            "onlyDependOnLibsWithTags": [
              "scope:hep",
              "scope:shared"
            ]
          },
          {
            "sourceTag": "compatibility:ie10",
            "onlyDependOnLibsWithTags": [
              "compatibility:ie10"
            ]
          },
          {
            "sourceTag": "scope:shared",
            "onlyDependOnLibsWithTags": [
              "scope:shared"
            ]
          }
        ]
      }
    ],
</code>```

This passes linting as expected when I run ng lint hep.

However, if I edit the tags in nx.json, the linter does not show any errors. For example, if I modify nx.json to look like this (removing tags from the libraries), it still lints and builds without any errors.

```<code>{
  "npmScope": "patient-engagement",
  "implicitDependencies": {
    "package.json": "*",
    "tsconfig.json": "*",
    "nx.json": "*"
  },
  "projects": {
    "hep": {
      "tags": ["scope:hep", "compatibility:ie10"],
      "implicitDependencies": []
    },
    "mb-ui": {
      "tags": [],
      "implicitDependencies": []
    },
    "utils": {
      "tags": [],
      "implicitDependencies": []
    }
  }
}
</code>```

If it's useful, when I update the rules in tslint.json, the linter DOES throw errors, but I would like it to also acknowledge changes to nx.json.

Is there a way I can get the linter to show errors when tags in nx.json are updated?

答:
Nx caches a bunch of information concerning dependencies in generated file: /dist/nxdeps.json

You can simply delete this file to immediately see changes to nx.json.

Body:
When I update project tags in nx.json, TSLint seems unaware that the tags have changed, and lints and builds the project even though the dependencies are violated.

Example

Currently my nx.json file looks like

{
  "npmScope": "patient-engagement",
  "implicitDependencies": {
    "package.json": "*",
    "tsconfig.json": "*",
    "nx.json": "*"
  },
  "projects": {
    "hep": {
      "tags": ["scope:hep", "compatibility:ie10"],
      "implicitDependencies": []
    },
    "mb-ui": {
      "tags": ["scope:shared", "compatibility:ie10"],
      "implicitDependencies": []
    },
    "utils": {
      "tags": ["scope:shared", "compatibility:ie10"],
      "implicitDependencies": []
    }
  }
}

And my root tslint.json includes:

"nx-enforce-module-boundaries": [
      true,
      {
        "enforceBuildableLibDependency": true,
        "allow": [],
        "depConstraints": [
          {
            "sourceTag": "scope:hep",
            "onlyDependOnLibsWithTags": [
              "scope:hep",
              "scope:shared"
            ]
          },
          {
            "sourceTag": "compatibility:ie10",
            "onlyDependOnLibsWithTags": [
              "compatibility:ie10"
            ]
          },
          {
            "sourceTag": "scope:shared",
            "onlyDependOnLibsWithTags": [
              "scope:shared"
            ]
          }
        ]
      }
    ],

This passes linting as expected when I run ng lint hep.

However, if I edit the tags in nx.json, the linter does not show any errors. For example, if I modify nx.json to look like this (removing tags from the libraries), it still lints and builds without any errors.

{
  "npmScope": "patient-engagement",
  "implicitDependencies": {
    "package.json": "*",
    "tsconfig.json": "*",
    "nx.json": "*"
  },
  "projects": {
    "hep": {
      "tags": ["scope:hep", "compatibility:ie10"],
      "implicitDependencies": []
    },
    "mb-ui": {
      "tags": [],
      "implicitDependencies": []
    },
    "utils": {
      "tags": [],
      "implicitDependencies": []
    }
  }
}

If it's useful, when I update the rules in tslint.json, the linter DOES throw errors, but I would like it to also acknowledge changes to nx.json.

Is there a way I can get the linter to show errors when tags in nx.json are updated?


来源: stackexchange

问:
Issue connecting to Database during Google Cloud Build process
Similar to this issue. (I will describe the link in more detail below)

Problem:
When running my Google Cloud Build I get an error stating:

```<code>django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/cloudsql/sample-kubernetes-268320:us-west1:cloud-build-staging/.s.PGSQL.3306"
</code>```

I am following the solution posted here by collaborator. They provide a sample cloudbuild.yaml that I followed closely without any luck.

Working cloudbuild.yaml

```<code>steps:
  - id: proxy-install
    name: alpine:3.10
    entrypoint: sh
    args:
      - -c
      - 'wget -O /workspace/cloud_sql_proxy https://storage.googleapis.com/cloudsql-proxy/v1.16/cloud_sql_proxy.linux.386 &&  chmod +x /workspace/cloud_sql_proxy'
    waitFor: ['-']
  - id: execute-with-proxy
    name: python:3.7
    timeout: 100s
    entrypoint: sh
    args:
      - -c
      - '(/workspace/cloud_sql_proxy -dir=/workspace -instances=[INSTANCE_CONNECTION_NAME] & sleep 2) && (pip install -r requirements.txt && python test_sql.py)'
    waitFor: ['proxy-install']
</code>```

My cloudbuild.yaml

```<code>steps:
  - id: proxy-install
    name: alpine:3.10
    entrypoint: sh
    args:
      - -c
      - 'wget -O /workspace/cloud_sql_proxy https://storage.googleapis.com/cloudsql-proxy/v1.16/cloud_sql_proxy.linux.386 &&  chmod +x /workspace/cloud_sql_proxy'
    waitFor: ['-']
  - id: Test
    name: 'python:3.7.6-buster'
    env:
      - "CLOUDBUILD_TEST=True"
    timeout: 100s
    entrypoint: /bin/sh
    args:
      - -c
      - '(/workspace/cloud_sql_proxy -dir=/workspace -instances=sample-kubernetes-268320:us-west1:cloud-build-staging & sleep 2) && (pip install -r requirements.txt && cd fastestfollowup && python3 manage.py test)'
    waitFor: ['proxy-install']
</code>```

Steps I've taken to debug this:

I have added the Cloud Build Service as the Cloud SQL Admin

I have ensured my instance name is correct through using gcloud sqlinstances describe cloud-build-staging and copying the "connectionname"

Edit:
I changed my cloudbuild.yaml file from

```<code>    args:
      - -c
      - '(/workspace/cloud_sql_proxy -dir=/workspace -instances=sample-kubernetes-268320:us-west1:cloud-build-staging & sleep 2) && (pip install -r requirements.txt && cd fastestfollowup && python3 manage.py test)'
</code>```

to:

```<code>    args:
      - -c
      - '(/workspace/cloud_sql_proxy -dir=/cloudsql -instances=sample-kubernetes-268320:us-west1:cloud-build-staging & sleep 2) && (pip install -r requirements.txt && cd fastestfollowup && python3 manage.py test)'
</code>```

With no effect.

答:
Looks like you started the proxy with -dir=/workspace but then tried to connect at /cloudsql. You'll need either update the proxy or update the path your app uses to connect.

The line:

```<code>args:
      - -c
      - '(/workspace/cloud_sql_proxy -dir=/workspace -instances=sample-kubernetes-268320:us-west1:cloud-build-staging & sleep 2) && (pip install -r requirements.txt && cd fastestfollowup && python3 manage.py test)'
</code>```

Should Read:

```<code>args:
      - -c
      - '(/workspace/cloud_sql_proxy -dir=/cloudsql -instances=sample-kubernetes-268320:us-west1:cloud-build-staging & sleep 2) && (pip install -r requirements.txt && cd fastestfollowup && python3 manage.py test)'
</code>```

Other mistakes include:

Listening at the wrong port. In your logs you will see the port that your database listens on. The default for postgres is 5432, yours is 3306.

Verify your Cloud Build service has the correct permissions. Add [projectnumber]@cloudbuild.gserviceaccount.com as a "Cloud SQL Admin" through the IAM dashboard.

ContentLicense: CC BY-SA 4.0

Body:
Similar to this issue. (I will describe the link in more detail below)

Problem:
When running my Google Cloud Build I get an error stating:

django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/cloudsql/sample-kubernetes-268320:us-west1:cloud-build-staging/.s.PGSQL.3306"

I am following the solution posted here by collaborator. They provide a sample cloudbuild.yaml that I followed closely without any luck.

Working cloudbuild.yaml

steps:
  - id: proxy-install
    name: alpine:3.10
    entrypoint: sh
    args:
      - -c
      - 'wget -O /workspace/cloud_sql_proxy https://storage.googleapis.com/cloudsql-proxy/v1.16/cloud_sql_proxy.linux.386 &&  chmod +x /workspace/cloud_sql_proxy'
    waitFor: ['-']
  - id: execute-with-proxy
    name: python:3.7
    timeout: 100s
    entrypoint: sh
    args:
      - -c
      - '(/workspace/cloud_sql_proxy -dir=/workspace -instances=[INSTANCE_CONNECTION_NAME] & sleep 2) && (pip install -r requirements.txt && python test_sql.py)'
    waitFor: ['proxy-install']

My cloudbuild.yaml

steps:
  - id: proxy-install
    name: alpine:3.10
    entrypoint: sh
    args:
      - -c
      - 'wget -O /workspace/cloud_sql_proxy https://storage.googleapis.com/cloudsql-proxy/v1.16/cloud_sql_proxy.linux.386 &&  chmod +x /workspace/cloud_sql_proxy'
    waitFor: ['-']
  - id: Test
    name: 'python:3.7.6-buster'
    env:
      - "CLOUDBUILD_TEST=True"
    timeout: 100s
    entrypoint: /bin/sh
    args:
      - -c
      - '(/workspace/cloud_sql_proxy -dir=/workspace -instances=sample-kubernetes-268320:us-west1:cloud-build-staging & sleep 2) && (pip install -r requirements.txt && cd fastestfollowup && python3 manage.py test)'
    waitFor: ['proxy-install']

Steps I've taken to debug this:

I have added the Cloud Build Service as the Cloud SQL Admin

I have ensured my instance name is correct through using gcloud sqlinstances describe cloud-build-staging and copying the "connectionname"

Edit:
I changed my cloudbuild.yaml file from

    args:
      - -c
      - '(/workspace/cloud_sql_proxy -dir=/workspace -instances=sample-kubernetes-268320:us-west1:cloud-build-staging & sleep 2) && (pip install -r requirements.txt && cd fastestfollowup && python3 manage.py test)'

to:

    args:
      - -c
      - '(/workspace/cloud_sql_proxy -dir=/cloudsql -instances=sample-kubernetes-268320:us-west1:cloud-build-staging & sleep 2) && (pip install -r requirements.txt && cd fastestfollowup && python3 manage.py test)'

With no effect.

Body:
Looks like you started the proxy with -dir=/workspace but then tried to connect at /cloudsql. You'll need either update the proxy or update the path your app uses to connect.

The line:

args:
      - -c
      - '(/workspace/cloud_sql_proxy -dir=/workspace -instances=sample-kubernetes-268320:us-west1:cloud-build-staging & sleep 2) && (pip install -r requirements.txt && cd fastestfollowup && python3 manage.py test)'

Should Read:

args:
      - -c
      - '(/workspace/cloud_sql_proxy -dir=/cloudsql -instances=sample-kubernetes-268320:us-west1:cloud-build-staging & sleep 2) && (pip install -r requirements.txt && cd fastestfollowup && python3 manage.py test)'

Other mistakes include:

Listening at the wrong port. In your logs you will see the port that your database listens on. The default for postgres is 5432, yours is 3306.

Verify your Cloud Build service has the correct permissions. Add [projectnumber]@cloudbuild.gserviceaccount.com as a "Cloud SQL Admin" through the IAM dashboard.


问:
How to assign an entered value on a TextField to a String property?
I made a project in C# and I'm now trying to translate it to JavaFX, using IntelliJ IDEA and Gluon Scene Builder

I have some doubts:

How to assign an entered value on a TextField to a String property? I've done many Google searches and still can't figure this out.

My code in C#:

//Declaring and Initializing pFirstName Property
public string pFirstName { get; set; } = "";

...

//Assigning value entered in txtBox_PatientFirstNam to pFirstName
Pat.pFirstName = txtBox_PatientFirstNam.Text;
```

How would this look like in JavaFX?

How to rename controls in Gluon Scene Builder? Wasn't able to find this option yet, for example in WinForms I can rename a TextBox to txtBox_PatientFirstNam, but I don't know how to rename TextFields in Scene Builder

I'm stuck after spending a day learning how to design GUIs in Scene Builder, so thanks in advance to anyone willing to help me.

答:
In java to get the string value of a filed is: </p>

```<code>string text = aTextField.getText()
</code>```

<p>To assign </p>

```<code>aTextField.setText("string");
</code>```

Body:
I made a project in C# and I'm now trying to translate it to JavaFX, using IntelliJ IDEA and Gluon Scene Builder

I have some doubts:

How to assign an entered value on a TextField to a String property? I've done many Google searches and still can't figure this out.

My code in C#:

//Declaring and Initializing pFirstName Property
public string pFirstName { get; set; } = "";

...

//Assigning value entered in txtBox_PatientFirstNam to pFirstName
Pat.pFirstName = txtBox_PatientFirstNam.Text;

How would this look like in JavaFX?

How to rename controls in Gluon Scene Builder? Wasn't able to find this option yet, for example in WinForms I can rename a TextBox to txtBox_PatientFirstNam, but I don't know how to rename TextFields in Scene Builder

I'm stuck after spending a day learning how to design GUIs in Scene Builder, so thanks in advance to anyone willing to help me.

Body:
In java to get the string value of a filed is:

string text = aTextField.getText()

To assign

aTextField.setText("string");


问:
WebRTC: Undefined reference to "__real_malloc" in Android project linking with WebRTC library
My project is an NDK-based Android shared library that links in Chromium's WebRTC shared library. When linking my project's native code component, I see some "undefined reference" errors, but they are for symbols that should be generated by the linker itself:

```<code>    __real_malloc, et. al.
    __executable_start
</code>```

The undefined references stem from WebRTC object files:

```<code>base/allocator/allocator_shim_default_dispatch_to_linker_wrapped_symbols.cc:39: undefined reference to `__real_malloc'
base/trace_event/trace_log.cc:1615: undefined reference to `__executable_start'
</code>```

My question: Why are these symbols undefined? How can I fix it? These are the only errors reported. There are no other errors or warnings.

I look forward to any insights from the community. I've been stuck on this for a long time! I'm new to Android development and probably doing something basic wrong.

Thanks!

Additional background information, in case it's helpful.

WebRTC build environment:

Ubuntu 18.04

Toolchain: NDK r13/clang/llvm (installed via Depot Tools)

Cross-compile for Android

My own project build environment:

Windows 10

Toolchain: NDK r19/clang/llvm

Cross-compile for Android

I build my project using a Gradle+CMake configuration generated by Android Studio. First I have to build Chromium's WebRTC library using their Ninja-based build system (called Depot Tools). Once that succeeds, I create a static library for the WebRTC component using a bash script:

    # Get the names of all the object files.
    find ./obj -name *.o >libwebrtc.list
    # Generate the static library.
    cat libwebrtc.list | xargs ar -crs libwebrtc.a
    # Add an index to the static library.
    ranlib libwebrtc.a
```

Now I have a static library with WebRTC symbols I can link into my project (my project is itself a shared library). As an aside, I wonder if there's an "official" way to build this static WebRTC library. I couldn't find any mention of it.

Next, I compile and link my project using the NDK's externalNativeBuild to call my CMakeLists.txt script. It compiles everything with no warnings, but the linker fails to find a the symbols mentioned above.

答: I solved my own problem. For future reference: The Chromium WebRTC build does in fact create its own libwebrtc.a static library. I didn't need to make it myself. Everything links successfully when I reference the "official" version of libwebrtc.a.</p>

Body:
My project is an NDK-based Android shared library that links in Chromium's WebRTC shared library. When linking my project's native code component, I see some "undefined reference" errors, but they are for symbols that should be generated by the linker itself:

    __real_malloc, et. al.
    __executable_start

The undefined references stem from WebRTC object files:

base/allocator/allocator_shim_default_dispatch_to_linker_wrapped_symbols.cc:39: undefined reference to `__real_malloc'
base/trace_event/trace_log.cc:1615: undefined reference to `__executable_start'

My question: Why are these symbols undefined? How can I fix it? These are the only errors reported. There are no other errors or warnings.

I look forward to any insights from the community. I've been stuck on this for a long time! I'm new to Android development and probably doing something basic wrong.

Thanks!

Additional background information, in case it's helpful.

WebRTC build environment:

Ubuntu 18.04

Toolchain: NDK r13/clang/llvm (installed via Depot Tools)

Cross-compile for Android

My own project build environment:

Windows 10

Toolchain: NDK r19/clang/llvm

Cross-compile for Android

I build my project using a Gradle+CMake configuration generated by Android Studio. First I have to build Chromium's WebRTC library using their Ninja-based build system (called Depot Tools). Once that succeeds, I create a static library for the WebRTC component using a bash script:

    # Get the names of all the object files.
    find ./obj -name *.o >libwebrtc.list
    # Generate the static library.
    cat libwebrtc.list | xargs ar -crs libwebrtc.a
    # Add an index to the static library.
    ranlib libwebrtc.a

Now I have a static library with WebRTC symbols I can link into my project (my project is itself a shared library). As an aside, I wonder if there's an "official" way to build this static WebRTC library. I couldn't find any mention of it.

Next, I compile and link my project using the NDK's externalNativeBuild to call my CMakeLists.txt script. It compiles everything with no warnings, but the linker fails to find a the symbols mentioned above.


问:
How to convert SqlExpression<T> into SqlExpression<TU> with ServiceStack OrmLite?
I need to work with SqlExpression<T> in a private method but the result should be SqlExpression<TU> (due to my project context).
T and TU aims same structure (TU is a subset of T with some computed expressions)
I didn't find a way to convert SqlExpression<T> into SqlExpression<TU>.

In following code T = Product class and TU = Powder class.

```<code>// Sample code
private static SqlExpression<Powder> CreateDefaultExpression(IDbConnection db, IPowderListFilter request)
{
    var ev = db.From<Product>()
    // Joins are set here...
            .Select(p => new
            {
                CustomRalId = Sql.As(p.CustomRalId, nameof(Powder.CustomRalId)),
                Mass = Sql.As(Sql.Sum(p.Width * p.Height / 1000000) * 2 * Settings.LacqueringGramsPerSquareMeter / 1000, nameof(Powder.Mass))
            });

    // I need to do something like...
    ev.ConvertTo<SqlExpression<Powder>>();
    // or ...
    return new SqlExpression<Powder>(ev);
}
</code>```

答:
You basically can’t, the typed SqlExpression is a query builder that you can’t just change the Type of and have it automatically erase and reapply all the mutations to the query builder using a different Type.

If reuse is the goal you’d need to use standard C# to DRY as much code as possible which won’t be much since all lambda expressions is typed to a different Type.

Body:
I need to work with SqlExpression<T> in a private method but the result should be SqlExpression<TU> (due to my project context).
T and TU aims same structure (TU is a subset of T with some computed expressions)
I didn't find a way to convert SqlExpression<T> into SqlExpression<TU>.

In following code T = Product class and TU = Powder class.

// Sample code
private static SqlExpression<Powder> CreateDefaultExpression(IDbConnection db, IPowderListFilter request)
{
    var ev = db.From<Product>()
    // Joins are set here...
            .Select(p => new
            {
                CustomRalId = Sql.As(p.CustomRalId, nameof(Powder.CustomRalId)),
                Mass = Sql.As(Sql.Sum(p.Width * p.Height / 1000000) * 2 * Settings.LacqueringGramsPerSquareMeter / 1000, nameof(Powder.Mass))
            });

    // I need to do something like...
    ev.ConvertTo<SqlExpression<Powder>>();
    // or ...
    return new SqlExpression<Powder>(ev);
}


问:
SQL query to find multi level hierarchical data
Imagine I have some data in a relational table like below.

```<code>name           friend_name

Ryan           James
Chin           James
Jack           Charley
Tomy           Ryan
Bill           Chin
</code>```

Now, given friend_name 'James' I want the result as

```<code>name

Ryan
Chin
Tomy
Bill
</code>```

What should my SQL query look like? I'm using SQL Server.

答:
You can use a recursive CTE to find all the friends of friends of James:

```<code>WITH CTE AS (
  SELECT *
  FROM friends
  WHERE friend_name = 'James'
  UNION ALL
  SELECT f.*
  FROM friends f
  JOIN CTE ON f.friend_name = CTE.name
)
SELECT name
FROM CTE
</code>```

Output:

```<code>name
Ryan
Chin
Bill
Tomy
</code>```

Demo on SQLFiddle

Body:
Imagine I have some data in a relational table like below.

name           friend_name

Ryan           James
Chin           James
Jack           Charley
Tomy           Ryan
Bill           Chin

Now, given friend_name 'James' I want the result as

name

Ryan
Chin
Tomy
Bill

What should my SQL query look like? I'm using SQL Server.

Body:
You can use a recursive CTE to find all the friends of friends of James:

WITH CTE AS (
  SELECT *
  FROM friends
  WHERE friend_name = 'James'
  UNION ALL
  SELECT f.*
  FROM friends f
  JOIN CTE ON f.friend_name = CTE.name
)
SELECT name
FROM CTE

Output:

name
Ryan
Chin
Bill
Tomy

Demo on SQLFiddle


问:
Filtering a graph with a specific camp
I'm trying to put a filter in my graph.

Table's data

```<code>plt.plot(figsize=(20, 10))
tb_final['Price'].loc['2018-01-01':].plot(label='Price')
tb_final['MA10'].loc['2018-01-01':].plot(label='MA10')
tb_final['MA50'].loc['2018-01-01':].plot(label='MA50')
plt.legend()
</code>```

How can I filter my graph with only one of the Symbols, for example, plot the data of symbol 'JSLG3.SA'?
Thanks.

答:
First, consider taking loc first and then selecting the columns:

```<code>fig, ax = plt.subplots(1, 1)
tb_final.loc['2018-01-01':][['Price', 'MA10', 'MA50']].plot(ax=ax)
</code>```

ax.legend is unnecessary because pd.DataFrame.plot created appropriate labels for you. For filtering use a binary filter:

```<code>fig, ax = plt.subplots(1, 1)
tb_final[tb_final['Symbol'] == 'JSLG3.SA'].loc['2018-01-01':][['Price', 'MA10', 'MA50']].plot(ax=ax)
</code>```

If you want to generate more plots for each of the classes you can groubpy Symbol and apply a function that takes a dataframe, plots and saves the plot on disk.

Title: Filtering a graph with a specific camp

Body:
I'm trying to put a filter in my graph.

Table's data

plt.plot(figsize=(20, 10))
tb_final['Price'].loc['2018-01-01':].plot(label='Price')
tb_final['MA10'].loc['2018-01-01':].plot(label='MA10')
tb_final['MA50'].loc['2018-01-01':].plot(label='MA50')
plt.legend()

How can I filter my graph with only one of the Symbols, for example, plot the data of symbol 'JSLG3.SA'?
Thanks.

Body:
First, consider taking loc first and then selecting the columns:

fig, ax = plt.subplots(1, 1)
tb_final.loc['2018-01-01':][['Price', 'MA10', 'MA50']].plot(ax=ax)

ax.legend is unnecessary because pd.DataFrame.plot created appropriate labels for you. For filtering use a binary filter:

fig, ax = plt.subplots(1, 1)
tb_final[tb_final['Symbol'] == 'JSLG3.SA'].loc['2018-01-01':][['Price', 'MA10', 'MA50']].plot(ax=ax)

If you want to generate more plots for each of the classes you can groubpy Symbol and apply a function that takes a dataframe, plots and saves the plot on disk.


问:
Haskell: Get caller function name
In Haskell, is there a way to get the caller function name?  Of course I could hard-code it, but that turns into a maintenance burden: If someone were to rename the function, nothing is forcing them to rename the hard-coded name.

A contrived example:

```<code>f1 :: String
f1 = "f1" -- can this be automated?
</code>```

答:
A kernel of an idea: make f1 be a parameterized thing. This will make it possible to put the code name and the string representing the code name together, to reduce the chances that somebody renames one without the other. So:

```<code>f1Raw :: String -> String
f1Raw name = name

f1 :: String
f1 = f1Raw "f1"
</code>```

With a bit of Template Haskell hackery, it is likely that you could make an interface withName :: String -> Q [Decl] or so that let you write something like this as a shorthand for this pattern:

```<code>-- f1Raw exactly as before
f1Raw :: String -> String
f1Raw name = name

-- this next line...
$(withName "f1")
-- ...would expand to these two:
-- f1 :: String
-- f1 = f1Raw "f1"
</code>```

The behavior of withName would be, roughly:

Take the given String, append "Raw", and create a Name for the corresponding thing in the current module.

Use introspection to get the type of the raw thing, check that it starts out String -> ..., then strip the String -> bit and create a Decl that declares f1 :: ....

Implement f1 = f1Raw "f1" as a second Decl.

Title: Haskell: Get caller function name

Body:
In Haskell, is there a way to get the caller function name?  Of course I could hard-code it, but that turns into a maintenance burden: If someone were to rename the function, nothing is forcing them to rename the hard-coded name.

A contrived example:

f1 :: String
f1 = "f1" -- can this be automated?

Body:
A kernel of an idea: make f1 be a parameterized thing. This will make it possible to put the code name and the string representing the code name together, to reduce the chances that somebody renames one without the other. So:

f1Raw :: String -> String
f1Raw name = name

f1 :: String
f1 = f1Raw "f1"

With a bit of Template Haskell hackery, it is likely that you could make an interface withName :: String -> Q [Decl] or so that let you write something like this as a shorthand for this pattern:

-- f1Raw exactly as before
f1Raw :: String -> String
f1Raw name = name

-- this next line...
$(withName "f1")
-- ...would expand to these two:
-- f1 :: String
-- f1 = f1Raw "f1"

The behavior of withName would be, roughly:

Take the given String, append "Raw", and create a Name for the corresponding thing in the current module.

Use introspection to get the type of the raw thing, check that it starts out String -> ..., then strip the String -> bit and create a Decl that declares f1 :: ....

Implement f1 = f1Raw "f1" as a second Decl.


问:
CS0119 in compiling C#, Error at Task parameters
I've been working on a Discord Bot, and I get a really bad error.

I'm a beginner. I'm sorry if it's a dumb error, I probably didn't even knew C# basics more than a month ago.

private async Task Filter(SocketMessage arg)
{

}

public async Task StartInterpretation()
{
    await Filter(SocketMessage arg);
}
```

This is a small example that makes the error i'm getting. the await Filter(SocketMessage arg) causes this error:

error CS0119: 'SocketMessage' is a type, which is not valid in the given context

(the error is something with parameters as i can see.)

答:
The CS0119 compilation error is specifically because you are putting in a type parameter when you call a method.  That's not allowed, it's only when declaring a method do you specify the type that it should expect.

However you have another issue where you are not instantiating arg.  Below is your code updated so that it would compile.

// this is correct, SocketMessage is the type parameter that Filter expects
private async Task Filter(SocketMessage arg)
{

}

public async Task StartInterpretation()
{
    var arg = new SocketMessage();
    // do not specify the type parameter, just pass the variable
    await Filter(arg);
}
```

Body:
I've been working on a Discord Bot, and I get a really bad error.

I'm a beginner. I'm sorry if it's a dumb error, I probably didn't even knew C# basics more than a month ago.

private async Task Filter(SocketMessage arg)
{

}

public async Task StartInterpretation()
{
    await Filter(SocketMessage arg);
}

This is a small example that makes the error i'm getting. the await Filter(SocketMessage arg) causes this error:

error CS0119: 'SocketMessage' is a type, which is not valid in the given context

(the error is something with parameters as i can see.)


问:
Adding a default header only for POST request
I'm trying a Typed HttpClient as below. I'm looking to find a way to add DefaultRequestHeaders only to my POST request (and not to other requests such GET or PUT). Is there way to achieve this?

Here is my code snippet.

```<code>var builder = services
     .AddHttpClient("MyService", client =>
      {
         client.BaseAddress = configuration.BaseAddress;

         // Need to default header only for "POST" request
         client.DefaultRequestHeaders.Add("MyHeader", "MyHeaderValue");
      })
      .AddTypedClient<IMyServiceClient, MyServiceRestClient>();
</code>```

I'm trying to find a way where line client.DefaultRequestHeaders.Add("MyHeader", "MyHeaderValue") is only effective for POST request.

答:
I was actually being stupid here. I realized that I could achieve what I wanted through the DelegatingHandler.

```<code>var builder = services
    .AddHttpClient("MyService", client =>
    {
        client.BaseAddress = configuration.BaseAddress;
    })
    .AddHttpMessageHandler<MySpecialHeaderDelegatingHandler>()
    .AddTypedClient<IMyServiceClient, MyServiceRestClient>();

public class MySpecialHeaderDelegatingHandler: DelegatingHandler
{
    private const string MySpecialHeader = "my-special-header";

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        EnsureMySpecialHeaderExists(request);
        return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
    }

    private static void EnsureMySpecialHeaderExists(HttpRequestMessage request)
    {
        if (request.Method != HttpMethod.Post) return;

        if (!request.Headers.Contains(MySpecialHeader))
        {
            request.Headers.Add(MySpecialHeader, "MyHeaderValue");
        }
    }
</code>```

Body:
I'm trying a Typed HttpClient as below. I'm looking to find a way to add DefaultRequestHeaders only to my POST request (and not to other requests such GET or PUT). Is there way to achieve this?

Here is my code snippet.

var builder = services
     .AddHttpClient("MyService", client =>
      {
         client.BaseAddress = configuration.BaseAddress;

         // Need to default header only for "POST" request
         client.DefaultRequestHeaders.Add("MyHeader", "MyHeaderValue");
      })
      .AddTypedClient<IMyServiceClient, MyServiceRestClient>();

I'm trying to find a way where line client.DefaultRequestHeaders.Add("MyHeader", "MyHeaderValue") is only effective for POST request.

Body:
I was actually being stupid here. I realized that I could achieve what I wanted through the DelegatingHandler.

var builder = services
    .AddHttpClient("MyService", client =>
    {
        client.BaseAddress = configuration.BaseAddress;
    })
    .AddHttpMessageHandler<MySpecialHeaderDelegatingHandler>()
    .AddTypedClient<IMyServiceClient, MyServiceRestClient>();

public class MySpecialHeaderDelegatingHandler: DelegatingHandler
{
    private const string MySpecialHeader = "my-special-header";

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        EnsureMySpecialHeaderExists(request);
        return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
    }

    private static void EnsureMySpecialHeaderExists(HttpRequestMessage request)
    {
        if (request.Method != HttpMethod.Post) return;

        if (!request.Headers.Contains(MySpecialHeader))
        {
            request.Headers.Add(MySpecialHeader, "MyHeaderValue");
        }
    }


问:
SQL - Dividing aggregated fields, very new to SQL
I have list of line items from invoices with a field that indicates if a line was delivered or picked up. I need to find a percentage of delivered items from the total number of lines.

SALES_NBR | Total | Deliveryrate

1 = Delivered 0 = picked up from FULFILLMENT.

```<code>SELECT SALES_NBR,
COUNT (ITEMS) as Total,
SUM (case when FULFILLMENT = '1' then 1 else 0 end) as delivered,
(SELECT delivered/total) as Deliveryrate
FROM Invoice_table
WHERE STORE IN '0123'
And SALE_DATE >='2020-02-01'
And SALE_DATE <='2020-02-07'
Group By SALES_NBR, Deliveryrate;
</code>```

My query executes but never finishes for some reason. Is there any easier way to do this? Fulfillment field does not contain any NULL values.

Any help would be appreciated.

答:
I need to find a percentage of delivered items from the total number of lines.

The simplest method is to use avg():

```<code>select SALES_NBR,
       avg(fulfillment) as delivered_ratio
from Invoice_table
where STORE = '0123' and
      SALE_DATE >='2020-02-01' and
      SALE_DATE <='2020-02-07'
group by SALES_NBR;
</code>```

I'm not sure if the group by sales_nbr is needed.

Body:
I have list of line items from invoices with a field that indicates if a line was delivered or picked up. I need to find a percentage of delivered items from the total number of lines.

SALES_NBR | Total | Deliveryrate

1 = Delivered 0 = picked up from FULFILLMENT.

SELECT SALES_NBR,
COUNT (ITEMS) as Total,
SUM (case when FULFILLMENT = '1' then 1 else 0 end) as delivered,
(SELECT delivered/total) as Deliveryrate
FROM Invoice_table
WHERE STORE IN '0123'
And SALE_DATE >='2020-02-01'
And SALE_DATE <='2020-02-07'
Group By SALES_NBR, Deliveryrate;

My query executes but never finishes for some reason. Is there any easier way to do this? Fulfillment field does not contain any NULL values.

Any help would be appreciated.

Body:
I need to find a percentage of delivered items from the total number of lines.

The simplest method is to use avg():

select SALES_NBR,
       avg(fulfillment) as delivered_ratio
from Invoice_table
where STORE = '0123' and
      SALE_DATE >='2020-02-01' and
      SALE_DATE <='2020-02-07'
group by SALES_NBR;

I'm not sure if the group by sales_nbr is needed.


问:
Mips, continuous user input
How would I go about asking a user for continuous input? Basically I want to capture only numbers greater than 0, anything less than 0 I want to print an error message followed by the enter number message.</p>

答:
How would you go about solving this in high-level language pseudocode? One way is -

```<code>while true
  print("Enter a number: ")
    n = read_a_number()
    if n < 0
      print("Error. Negative number")
    else
      # process the non-negative number (>= 0)
    # detect when to break while loop
</code>```

Once the above is clear, it is fairly easy to translate this to MIPS.

```<code>.data
prompt: .asciiz "Enter a number: "
error:  .asciiz "Error. Negative number\n"

.text
while:
la   $a0, prompt                    # print prompt to enter a number
li   $v0, 4                         # $v0 = 4 to print string with address in $a0
syscall

li   $v0, 5                         # to read an int. Read in $v0
syscall

bltz $v0, negative                  # is the input negative?
j    non_negative                   # else, handle non_negative

negative:
la   $a0, error                     # print error
li   $v0, 4
syscall
j    next                           # and goto 'next'

non_negative:
# process the non-negative number (>= 0)
j    next                           # and goto 'next'

next:
# detect when to break while loop (or do that at the start of the loop)
j    while                          # continue loop

after_while:                        # after the loop
li   $v0, 10                        # $v0=10 to exit
syscall
</code>```

Title: Mips, continuous user input

Body:
How would you go about solving this in high-level language pseudocode? One way is -

while true
  print("Enter a number: ")
    n = read_a_number()
    if n < 0
      print("Error. Negative number")
    else
      # process the non-negative number (>= 0)
    # detect when to break while loop

Once the above is clear, it is fairly easy to translate this to MIPS.

.data
prompt: .asciiz "Enter a number: "
error:  .asciiz "Error. Negative number\n"

.text
while:
la   $a0, prompt                    # print prompt to enter a number
li   $v0, 4                         # $v0 = 4 to print string with address in $a0
syscall

li   $v0, 5                         # to read an int. Read in $v0
syscall

bltz $v0, negative                  # is the input negative?
j    non_negative                   # else, handle non_negative

negative:
la   $a0, error                     # print error
li   $v0, 4
syscall
j    next                           # and goto 'next'

non_negative:
# process the non-negative number (>= 0)
j    next                           # and goto 'next'

next:
# detect when to break while loop (or do that at the start of the loop)
j    while                          # continue loop

after_while:                        # after the loop
li   $v0, 10                        # $v0=10 to exit
syscall


问:
React rendering output as HTML rather than a component
I am writing a small system that displays a component and next to it, it displays the source. This is great for developers. However, in some instances I need raw HTML. The only way to get away from this limitation is to duplicate code

Rendering as normal:

<CustomComponent></CustomComponent>

Rendering the encapsulated code "beautified"

content

What I would like to do is in my application to provide the <CustomComponent> and be able to Render it as normal and also the encapsulated code. I have look at a few solutions but they only provide the solution to render the <CustomComponent></CustomComponent> tags but not the contents inside the render method.

答:
How about rendering the component, and then using an effect hook to copy the html as a string into the DOM as text?

```<code>/**
 * Component that renders it's children, and then then puts the html source
 * equivalent of that component in a code tag.
 */
function ShowHtml({ children }) {
  // Use refs to store the nodes our after render hook will need.
  const component = useRef(null);
  const code = useRef(null);

  // After render, read the html from the DOM of the component, and insert it
  // as text into the target <code> element.
 useEffect(() => {
    if (code.current && component.current) {
      code.current.innerText = component.current.innerHTML;
    }
  });

  // Render the component, and the code tag.
  return (
    <div>
      <div ref={component}>{children}</div>
      <code ref={code} />
    </div>
  );
}
</code>```

Usage:

```<code><ShowHtml>
  <Test />
</ShowHtml>
</code>```

Working example

Caveat: not all props get put in the HTML. Event handlers, for instance, are bound to DOM elements in a different way, with pure javascript. A component is more than just it's HTML, so no matter what, you won't get a complete picture. But you should get any attributes that actually are fully HTML-able with this approach.

Refs are null on first render, because the component has to exist before you can get a reference on the first render. So you have to handle that.

But your new sandbox has another problem. If you need the source at render time in order to pass to a react component, then you cannot use an after-render effect to do that, since rendering is done.

So I am changing my answer to:

```<code>import { renderToStaticMarkup } from 'react-dom/server'
</code>```

Using that function, you should be able to get a string from any rendered react node:

```<code>  <div ref={component}>{children}</div>
  <Highlight
    {...defaultProps}
    code={renderToStaticMarkup(children)}
    language={"html"}
  >
</code>```

Body:
How about rendering the component, and then using an effect hook to copy the html as a string into the DOM as text?

/**
 * Component that renders it's children, and then then puts the html source
 * equivalent of that component in a code tag.
 */
function ShowHtml({ children }) {
  // Use refs to store the nodes our after render hook will need.
  const component = useRef(null);
  const code = useRef(null);

  // After render, read the html from the DOM of the component, and insert it
  // as text into the target <code> element.
 useEffect(() => {
    if (code.current && component.current) {
      code.current.innerText = component.current.innerHTML;
    }
  });

  // Render the component, and the code tag.
  return (
    <div>
      <div ref={component}>{children}</div>
      <code ref={code} />
    </div>
  );
}

Usage:

<ShowHtml>
  <Test />
</ShowHtml>

Working example

Caveat: not all props get put in the HTML. Event handlers, for instance, are bound to DOM elements in a different way, with pure javascript. A component is more than just it's HTML, so no matter what, you won't get a complete picture. But you should get any attributes that actually are fully HTML-able with this approach.

Refs are null on first render, because the component has to exist before you can get a reference on the first render. So you have to handle that.

But your new sandbox has another problem. If you need the source at render time in order to pass to a react component, then you cannot use an after-render effect to do that, since rendering is done.

So I am changing my answer to:

import { renderToStaticMarkup } from 'react-dom/server'

Using that function, you should be able to get a string from any rendered react node:

  <div ref={component}>{children}</div>
  <Highlight
    {...defaultProps}
    code={renderToStaticMarkup(children)}
    language={"html"}
  >


问:
GREP Regex not working properly, but my regex is correct
Hopefully this is a simple mistake I am making, I am fairly new to regex in general. Basically I am trying to extract the name of a website from a text file.

myfile.txt example:

Hello please enjoy your stay at%sbananas.com%sfor the rest of the day. Bye now!

I am trying to extract only the word bananas from this. My regex is as follows:

```<code>/(?<=m%s)(.*?)(?=\.com)/
</code>```

Using regexr online it works just fine but in GREP code I just can't figure out how to get this to work properly. It doesn't return any results. I have tried several variants of the following:

```<code>grep "/(?<=m%s)(.*?)(?=\.com)/" myfile.txt
grep -E "/(?<=m%s)(.*?)(?=\.com)/" myfile.txt
grep '/(?<=m%s)(.*?)(?=\.com)/' myfile.txt
grep "(?<=m%s)(.*?)(?=\.com)" myfile.txt
grep '(?<=m%s)(.*?)(?=\.com)' myfile.txt
</code>```

Nothing seems to work. I would love if someone could point me in the right direction.

答:
The problem with regular expressions in grep and other Unix tools is that they usually support one, two or three different kinds of regular expressions. These are:

Basic regular expressions (BRE)

Extended regular expressions (ERE or EREG)

Perl compatible regular expressions (PCRE or PREG)

Your pattern is in PCRE syntax, therefore you need to identify your pattern as one (using -P). Note that I also removed the m between = and % (I don't know what that was supposed to do).

```<code>grep -Po "(?<=%s)(.*?)(?=\.com)" myfile.txt
</code>```

With -o, you say you only want to print the matching part. My grep man page declares PCRE in grep as experimental so there probably might be cases where you'd get a segmentation fault or where the evaluation takes unusually much time.

Body:
Hopefully this is a simple mistake I am making, I am fairly new to regex in general. Basically I am trying to extract the name of a website from a text file.

myfile.txt example:

Hello please enjoy your stay at%sbananas.com%sfor the rest of the day. Bye now!

I am trying to extract only the word bananas from this. My regex is as follows:

/(?<=m%s)(.*?)(?=\.com)/

Using regexr online it works just fine but in GREP code I just can't figure out how to get this to work properly. It doesn't return any results. I have tried several variants of the following:

grep "/(?<=m%s)(.*?)(?=\.com)/" myfile.txt
grep -E "/(?<=m%s)(.*?)(?=\.com)/" myfile.txt
grep '/(?<=m%s)(.*?)(?=\.com)/' myfile.txt
grep "(?<=m%s)(.*?)(?=\.com)" myfile.txt
grep '(?<=m%s)(.*?)(?=\.com)' myfile.txt

Nothing seems to work. I would love if someone could point me in the right direction.

Body:
The problem with regular expressions in grep and other Unix tools is that they usually support one, two or three different kinds of regular expressions. These are:

Basic regular expressions (BRE)

Extended regular expressions (ERE or EREG)

Perl compatible regular expressions (PCRE or PREG)

Your pattern is in PCRE syntax, therefore you need to identify your pattern as one (using -P). Note that I also removed the m between = and % (I don't know what that was supposed to do).

grep -Po "(?<=%s)(.*?)(?=\.com)" myfile.txt

With -o, you say you only want to print the matching part. My grep man page declares PCRE in grep as experimental so there probably might be cases where you'd get a segmentation fault or where the evaluation takes unusually much time.


问:
Using java jcabi SSH client (or other) to execute several commands in shell
I understand how to create a ssh shell

```<code>Shell ssh = new SshByPassword("192.168.1.5", 22, "admin", "password");
</code>```

i also understand how to run a command

```<code>String output = new Shell.Plain(ssh).exec("some command");
</code>```

and i can easly analyze the output string

but how do i send in the same "shell" one command after the other

and bonus question sometimes the commands require a user confirmation ("press Y to continue")

is it possible with the library?

答:
Generally, most Java SSH APIs leave it to the developer to sort out the complexities of executing multiple commands within a shell. It is a complicated problem because SSH does not provide any indication of where commands start and end within the shell; the protocol only provides a stream of data, which is the raw output of the shell.

I would humbly like to introduce my project Maverick Synergy. An open-source API (LGPL) that does provide an interface for interactive shells. I documented the options for interactive commands in an article.

Here is a very basic example, the ExpectShell class allows you to execute multiple commands, each time returning a ShellProcess that encapsulates the command output. You can use the ShellProcess InputStream to read the output, it will return EOF when the command is done.

You can also use a ShellProcessController to interact with the command as this example shows.

```<code>SshClient ssh = new SshClient("localhost", 22, "lee", "xxxxxx".toCharArray());

ssh.runTask(new ShellTask(ssh) {
    protected void onOpenSession(SessionChannelNG session)
         throws IOException, SshException, ShellTimeoutException {

         ExpectShell shell = new ExpectShell(this);

         // Execute the first command
         ShellProcess process = shell.executeCommand("ls -l");
         process.drain();
         String output = process.getCommandOutput();

         // After processing output execute another
         ShellProcessController controller =
               new ShellProcessController(
                  shell.executeCommand("rm -i file.txt"));

         if(controller.expect("remove")) {
             controller.typeAndReturn("y");
         }

         controller.getProcess().drain();
   }
});

ssh.disconnect();
</code>```

Body:
I understand how to create a ssh shell

Shell ssh = new SshByPassword("192.168.1.5", 22, "admin", "password");

i also understand how to run a command

String output = new Shell.Plain(ssh).exec("some command");

and i can easly analyze the output string

but how do i send in the same "shell" one command after the other

and bonus question sometimes the commands require a user confirmation ("press Y to continue")

is it possible with the library?

Body:
Generally, most Java SSH APIs leave it to the developer to sort out the complexities of executing multiple commands within a shell. It is a complicated problem because SSH does not provide any indication of where commands start and end within the shell; the protocol only provides a stream of data, which is the raw output of the shell.

I would humbly like to introduce my project Maverick Synergy. An open-source API (LGPL) that does provide an interface for interactive shells. I documented the options for interactive commands in an article.

Here is a very basic example, the ExpectShell class allows you to execute multiple commands, each time returning a ShellProcess that encapsulates the command output. You can use the ShellProcess InputStream to read the output, it will return EOF when the command is done.

You can also use a ShellProcessController to interact with the command as this example shows.

SshClient ssh = new SshClient("localhost", 22, "lee", "xxxxxx".toCharArray());

ssh.runTask(new ShellTask(ssh) {
    protected void onOpenSession(SessionChannelNG session)
         throws IOException, SshException, ShellTimeoutException {

         ExpectShell shell = new ExpectShell(this);

         // Execute the first command
         ShellProcess process = shell.executeCommand("ls -l");
         process.drain();
         String output = process.getCommandOutput();

         // After processing output execute another
         ShellProcessController controller =
               new ShellProcessController(
                  shell.executeCommand("rm -i file.txt"));

         if(controller.expect("remove")) {
             controller.typeAndReturn("y");
         }

         controller.getProcess().drain();
   }
});

ssh.disconnect();


问:
Density function ggplot2 deciding the scale_y_continuous scale factor
so I've been attempting to put my KDE function of my histogram and Ive managed to do so, however when i try to scale the sec.axis = sec_axis(~./#number) i cant seem to match it t my histogram is there a way i can make it automatically choose which number it should display to get the best match.

the code im using is

```<code>a <- ggplot(birds, aes(birds$`Log10(Total Average)`))+
  geom_histogram(col = 'black', fill = 'white', binwidth = 0.2)+
  labs(x = 'Log10 total body mass (kg)', y = 'Frequency', title = 'Average total body mass (kg) of bird species (male adn female) in KNP')
a + geom_density(aes(y=..count..), col=2, size=1)+
  scale_y_continuous(sec.axis = sec_axis(~./40, name = "Density"))
</code>```

答:
Like in your previous post, you did not provide a reproducible example of your dataset... so it is hard to provide a solution that will work for your data.

One way is to compute the max count per bins and the maximal value of the density function, then you can make a ratio and apply it to the geom_density

set.seed(123)
df <- data.frame(Total_average = rnorm(100,0,2))
binwidth = 0.2

Seq <- seq(floor(min(df$Total_average)), ceiling(max(df$Total_average)), by = binwidth)

# Determine max count per bins
Max_HIST <- max(hist(df$Total_average, breaks = Seq)$counts)

# Determine the max of the density
Max_Dens <- max(density(df$Total_average)$y)

Ratio <- Max_HIST / Max_Dens

library(ggplot2)
ggplot(df, aes(Total_average))+
  geom_histogram(col = 'black', fill = 'white',binwidth = binwidth)+
  geom_density(aes(y = ..density..*Ratio))+
  scale_y_continuous(sec.axis = sec_axis(~./Ratio, name = "Density"))
```

Does it answer your question ?

If not, please provide a reproducible example of your dataset by following this tutorial: How to make a great R reproducible example

NB: For some reasons, it seems that geom_histogram and hist function are not counting per bins in the exact same way.... for now, I don't have a good explanation of it.

Body:
so I've been attempting to put my KDE function of my histogram and Ive managed to do so, however when i try to scale the sec.axis = sec_axis(~./#number) i cant seem to match it t my histogram is there a way i can make it automatically choose which number it should display to get the best match.

the code im using is

a <- ggplot(birds, aes(birds$`Log10(Total Average)`))+
  geom_histogram(col = 'black', fill = 'white', binwidth = 0.2)+
  labs(x = 'Log10 total body mass (kg)', y = 'Frequency', title = 'Average total body mass (kg) of bird species (male adn female) in KNP')
a + geom_density(aes(y=..count..), col=2, size=1)+
  scale_y_continuous(sec.axis = sec_axis(~./40, name = "Density"))

Body:
Like in your previous post, you did not provide a reproducible example of your dataset... so it is hard to provide a solution that will work for your data.

One way is to compute the max count per bins and the maximal value of the density function, then you can make a ratio and apply it to the geom_density

set.seed(123)
df <- data.frame(Total_average = rnorm(100,0,2))
binwidth = 0.2

Seq <- seq(floor(min(df$Total_average)), ceiling(max(df$Total_average)), by = binwidth)

# Determine max count per bins
Max_HIST <- max(hist(df$Total_average, breaks = Seq)$counts)

# Determine the max of the density
Max_Dens <- max(density(df$Total_average)$y)

Ratio <- Max_HIST / Max_Dens

library(ggplot2)
ggplot(df, aes(Total_average))+
  geom_histogram(col = 'black', fill = 'white',binwidth = binwidth)+
  geom_density(aes(y = ..density..*Ratio))+
  scale_y_continuous(sec.axis = sec_axis(~./Ratio, name = "Density"))

Does it answer your question ?

If not, please provide a reproducible example of your dataset by following this tutorial: How to make a great R reproducible example

NB: For some reasons, it seems that geom_histogram and hist function are not counting per bins in the exact same way.... for now, I don't have a good explanation of it.


问:
How to make a dropdown for time input field in Orbeon forms CE
I created a form. It is having time inputs and date inputs. Date input is working fine. I can choose the date from dropdown. But time can't be selected through dropdown. There is no dropdown working at time input. Only tome icon is showing. I want to have a dropdown for time inputs as date inputs.

How can I do this?

答:
The short answer is that at time of this writing, Orbeon Forms doesn't come out-of-the-box with a control that allows users to select a time through dropdowns on a desktop browser. So for now users will have to type the time in a text field.

On mobile browsers, you'll get the equivalent of dropdowns on that platform (iOS or Android), as shown in the screenshots on this very old blog post on the topic.

On desktop browsers, this is covered by request for enhancement #4252.


问:
Image Base64 string to Uint8ClampedArray
I have imagedata in base64 format returned from Expo ImagePicker component, and I want to convert it to An Uint8ClampedArray of RGBA pixel values in the form [r0, g0, b0, a0, r1, g1, b1, a1, ...], cause it's the only input accepted by jsQR library

I tried this, but did not work:

```<code>const dataURItoBlob = byteString  => {

  // write the bytes of the string to a typed array
  var ia = new Uint8ClampedArray(byteString.length);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  return ia;
};
</code>```

any help will be highly appreciated

答:
I'm guessing your base64-encoded URI is actually a PNG, so you could do the following:</p>

```<code>const {PNG} = require('pngjs');
const jsqr = require('jsqr');

const dataUri = 'data:image/png;base64,ABCDEFYOURIMAGEHEREABCDEF';
const png = PNG.sync.read(Buffer.from(dataUri.slice('data:image/png;base64,'.length), 'base64'));
const code = jsqr(Uint8ClampedArray.from(png.data), png.width, png.height);

// code.data now contains the URL string encoded by the QR code
</code>```

Body:
I have imagedata in base64 format returned from Expo ImagePicker component, and I want to convert it to An Uint8ClampedArray of RGBA pixel values in the form [r0, g0, b0, a0, r1, g1, b1, a1, ...], cause it's the only input accepted by jsQR library

I tried this, but did not work:

const dataURItoBlob = byteString  => {

  // write the bytes of the string to a typed array
  var ia = new Uint8ClampedArray(byteString.length);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  return ia;
};

any help will be highly appreciated

Body:
I'm guessing your base64-encoded URI is actually a PNG, so you could do the following:

const {PNG} = require('pngjs');
const jsqr = require('jsqr');

const dataUri = 'data:image/png;base64,ABCDEFYOURIMAGEHEREABCDEF';
const png = PNG.sync.read(Buffer.from(dataUri.slice('data:image/png;base64,'.length), 'base64'));
const code = jsqr(Uint8ClampedArray.from(png.data), png.width, png.height);

// code.data now contains the URL string encoded by the QR code


问:
Select top 3 parents (groups) in plotly graph using R
What I want is to plot only 3 of my parents, the ones that spend the highest cost with below coding.

```<code>parent <- as.character(c("Sam","Elena","Sam","Jhon","Raul","Sam","Jhon","Sara","Paul","Chris"))
cost <- as.numeric(as.character(c(15000,10000,12000,15000,10000,12000,15000,14000,19000,2000)))
topic <- as.character(c("Banana","Banana","Berries","Apple","Watermelon","Banana","Berries","Avocado","Watermelon","Pinneaple"))

sample <- as.data.frame(cbind(parent,cost,topic))
sample$cost <- as.numeric(as.character(sample$cost))
sample$parent <- as.character(sample$parent)
sample$topic <- as.character(sample$topic)

# Color setting
ramp2 <- colorRamp(c("deepskyblue4", "white"))
ramp.list2 <- rgb( ramp2(seq(0, 1, length = 15)), max = 255)

plot_ly(sample, x = ~parent, y = ~cost, type = 'bar', color = ~topic) %>%
  layout(yaxis = list(title = 'Cost'), xaxis = list(title = 'Parent'), barmode = 'stack', colorway = ramp.list2) %>%
  config(displayModeBar = FALSE)

</code>```

I tried to use transforms inside plotly function, like this:

```<code>transforms = list(
list(
type = 'aggregate',
groups = sample$parent,
aggregations = list(
list(
target = 'x',
func = 'max',
enabled = T))
))
</code>```

But it still gives me the same output and I want to select only 3. Also, tried to use it like this:

```<code>transforms = list(
list(
type = 'filter',
target = 'y',
operation = '>',
value = cost[-3:-1]))
</code>```

But it takes only cost without takin the full cost parent spent on and only gives me 2 parents instead of 3. And finally, it's not using ramp.list2 to select colors.

答:
According to what I understood, you can use the following code to get the top 3 parents separately, as follows:

```<code>top_3 <- sample %>%
         group_by(parent) %>%
         summarise(cost = sum(cost)) %>%
         arrange(-cost) %>%
         head(3)
</code>```

This will give you the following:

```<code># A tibble: 3 x 2
#   parent  cost
#   <chr>  <dbl>
# 1 Sam    39000
# 2 Jhon   30000
# 3 Paul   19000
</code>```

Then, in your plot_ly, you can just refer to these top_3 parents, as follows:

```<code>plot_ly(sample[sample$parent %in% top_3$parent,], x = ~parent, y = ~cost, type = 'bar', color = ~topic) %>%
   layout(yaxis = list(title = 'Cost'), xaxis = list(title = 'Parent'), barmode = 'stack', colorway = ramp.list2) %>%
   config(displayModeBar = FALSE)
</code>```

which will produce the following plot:

Hope it helps.

Body:
What I want is to plot only 3 of my parents, the ones that spend the highest cost with below coding.

parent <- as.character(c("Sam","Elena","Sam","Jhon","Raul","Sam","Jhon","Sara","Paul","Chris"))
cost <- as.numeric(as.character(c(15000,10000,12000,15000,10000,12000,15000,14000,19000,2000)))
topic <- as.character(c("Banana","Banana","Berries","Apple","Watermelon","Banana","Berries","Avocado","Watermelon","Pinneaple"))

sample <- as.data.frame(cbind(parent,cost,topic))
sample$cost <- as.numeric(as.character(sample$cost))
sample$parent <- as.character(sample$parent)
sample$topic <- as.character(sample$topic)

# Color setting
ramp2 <- colorRamp(c("deepskyblue4", "white"))
ramp.list2 <- rgb( ramp2(seq(0, 1, length = 15)), max = 255)

plot_ly(sample, x = ~parent, y = ~cost, type = 'bar', color = ~topic) %>%
  layout(yaxis = list(title = 'Cost'), xaxis = list(title = 'Parent'), barmode = 'stack', colorway = ramp.list2) %>%
  config(displayModeBar = FALSE)

I tried to use transforms inside plotly function, like this:

transforms = list(
list(
type = 'aggregate',
groups = sample$parent,
aggregations = list(
list(
target = 'x',
func = 'max',
enabled = T))
))

But it still gives me the same output and I want to select only 3. Also, tried to use it like this:

transforms = list(
list(
type = 'filter',
target = 'y',
operation = '>',
value = cost[-3:-1]))

But it takes only cost without takin the full cost parent spent on and only gives me 2 parents instead of 3. And finally, it's not using ramp.list2 to select colors.

Body:
According to what I understood, you can use the following code to get the top 3 parents separately, as follows:

top_3 <- sample %>%
         group_by(parent) %>%
         summarise(cost = sum(cost)) %>%
         arrange(-cost) %>%
         head(3)

This will give you the following:

# A tibble: 3 x 2
#   parent  cost
#   <chr>  <dbl>
# 1 Sam    39000
# 2 Jhon   30000
# 3 Paul   19000

Then, in your plot_ly, you can just refer to these top_3 parents, as follows:

plot_ly(sample[sample$parent %in% top_3$parent,], x = ~parent, y = ~cost, type = 'bar', color = ~topic) %>%
   layout(yaxis = list(title = 'Cost'), xaxis = list(title = 'Parent'), barmode = 'stack', colorway = ramp.list2) %>%
   config(displayModeBar = FALSE)

which will produce the following plot:

Hope it helps.


问:
How do I know if the broadcast event is working?
I am not running this on an emulator, but an actual Android Device (Google Pixel 3).

If I issue this command: am broadcast -a android.intent.action.BOOT_COMPLETED

I get the output :

```<code>> Broadcasting: Intent { act=android.intent.action.BOOT_COMPLETED
> flg=0x400000 } Broadcast completed: result=0
</code>```

I was expecting the device to reboot. Does this mean that the broadcast isn't working?

答:
I was expecting the device to reboot.

That broadcast does not reboot the device. It is a broadcast, sent by the system, after the device has booted.

Body:
I am not running this on an emulator, but an actual Android Device (Google Pixel 3).

If I issue this command: am broadcast -a android.intent.action.BOOT_COMPLETED

I get the output :

> Broadcasting: Intent { act=android.intent.action.BOOT_COMPLETED
> flg=0x400000 } Broadcast completed: result=0

I was expecting the device to reboot. Does this mean that the broadcast isn't working?


问:
Extend Entity Framework Save on a single Entity Type
I have a rather large save routine that updates hundreds of items using the Entity Framework and then saves the whole lot in one go.

using (var dc = new EntityLayer.Entities())
{
    dc.Entity1.Prop1 = 1;
    dc.Entity1.Prop2 = 2;
    dc.Entity2.Prop1 = 1;
    dc.Entity2.Prop2 = 2; // Audit item
    dc.Entity2.Prop3 = 3; // Audit item
    dc.Entity3.Prop1 = 1;
    ...
    dc.SaveChanges();
}
```

<p>What I would love to be able to do is somehow either extend the Save for an individual Entity or pick up on this change and kick off another method.</p>

<p>The main purpose of this is to hook into our Audit system, which only audits some key items, (so for example only Entity2.Prop2 and Entity2.Prop3 in the simplified version above) but would also possibly kick off some other routines, creating tasks etc, but the crux is - can it be done?</p>

<p>Basically I'm aiming to remove the extra audit line we have to put in for specific types as below:</p>

<pre class="lang-cs prettyprint-override"><code>using (var dc = new EntityLayer.Entities())
{
    dc.Entity1.Prop1 = 1;
    dc.Entity1.Prop2 = 2;
    dc.Entity2.Prop1 = 1;
    dc.Entity2.Prop2 = 2;
    dc.Audit.CreateObject() { Type = "Entity2", Change = "Prop2", From = oldVal, To = 2}
    dc.Entity2.Prop3 = 3;
    dc.Audit.CreateObject() { Type = "Entity2", Change = "Prop3", From = oldVal, To = 3}
    ...
    dc.SaveChanges();
}
</code>```

答:
The only way is override SaveChanges, find changed entities and call your routines for them.

```<code>public override int SaveChanges()
{
    var entities = ChangeTracker.Entries<Entity1>()
                                .Where(e => e.State == EntityState.Modified)
                                .Select(e => e.Entity);

    foreach(var entity in entities)
    {
        // call your rutine.
    }

    return base.SaveChanges();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a rather large save routine that updates hundreds of items using the Entity Framework and then saves the whole lot in one go.

using (var dc = new EntityLayer.Entities())
{
    dc.Entity1.Prop1 = 1;
    dc.Entity1.Prop2 = 2;
    dc.Entity2.Prop1 = 1;
    dc.Entity2.Prop2 = 2; // Audit item
    dc.Entity2.Prop3 = 3; // Audit item
    dc.Entity3.Prop1 = 1;
    ...
    dc.SaveChanges();
}

What I would love to be able to do is somehow either extend the Save for an individual Entity or pick up on this change and kick off another method.

The main purpose of this is to hook into our Audit system, which only audits some key items, (so for example only Entity2.Prop2 and Entity2.Prop3 in the simplified version above) but would also possibly kick off some other routines, creating tasks etc, but the crux is - can it be done?

Basically I'm aiming to remove the extra audit line we have to put in for specific types as below:

using (var dc = new EntityLayer.Entities())
{
    dc.Entity1.Prop1 = 1;
    dc.Entity1.Prop2 = 2;
    dc.Entity2.Prop1 = 1;
    dc.Entity2.Prop2 = 2;
    dc.Audit.CreateObject() { Type = "Entity2", Change = "Prop2", From = oldVal, To = 2}
    dc.Entity2.Prop3 = 3;
    dc.Audit.CreateObject() { Type = "Entity2", Change = "Prop3", From = oldVal, To = 3}
    ...
    dc.SaveChanges();
}

Body:
The only way is override SaveChanges, find changed entities and call your routines for them.

public override int SaveChanges()
{
    var entities = ChangeTracker.Entries<Entity1>()
                                .Where(e => e.State == EntityState.Modified)
                                .Select(e => e.Entity);

    foreach(var entity in entities)
    {
        // call your rutine.
    }

    return base.SaveChanges();
}


问:
SQL Filter based on Case
I have a table as such:

```<code>email | event

e1     a
e1     c
e2     a
e3     b
e4     a
e4     b
e5     c
e6     d

</code>```

I'm trying to create a query that gets only those who have event a exclusively

Desired output:

```<code>email  |  attended

e2       0
</code>```

Here's my SQL:

```<code>SELECT
    tm.email,
    MAX(
    CASE
    WHEN tm.event = 'b' or tm.event = 'c' THEN 1
    ELSE 0
    END)
    as attended,
FROM
    table.events as tm
WHERE
    tm.event IN ('a', 'b', 'c', 'd')
    AND attended = 0
GROUP BY
    tm.email, attended

</code>```

I can't seem to figure out the correct way to go about this.

答:
If you want emails that have only 'a', then I would use aggregation, but like this:

```<code>select email
from events
group by email
having min(event) = max(event) and min(event) = 'a';
</code>```

Title: SQL Filter based on Case

Body:
I have a table as such:

email | event

e1     a
e1     c
e2     a
e3     b
e4     a
e4     b
e5     c
e6     d

I'm trying to create a query that gets only those who have event a exclusively

Desired output:

email  |  attended

e2       0

Here's my SQL:

SELECT
    tm.email,
    MAX(
    CASE
    WHEN tm.event = 'b' or tm.event = 'c' THEN 1
    ELSE 0
    END)
    as attended,
FROM
    table.events as tm
WHERE
    tm.event IN ('a', 'b', 'c', 'd')
    AND attended = 0
GROUP BY
    tm.email, attended

I can't seem to figure out the correct way to go about this.

Body:
If you want emails that have only 'a', then I would use aggregation, but like this:

select email
from events
group by email
having min(event) = max(event) and min(event) = 'a';


问:
Form Recognizer
I generated the Model Id using From Recognizer Labeling too (The docker image).
I am trying to use this same model id in From Recognizer API.

https://{endpoint}/formrecognizer/v1.0-preview/custom/models/{id}

but it say 404 .

https://centralus.dev.cognitive.microsoft.com/docs/services/form-recognizer-api/operations/GetCustomModel

The below URL says we can use the generated model Id:
https://learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/quickstarts/label-tool

Model ID - The ID of the model that was created and trained. Each training call creates a new model with its own ID. Copy this string to a secure location; you'll need it if you want to do prediction calls through the REST API.

答: When generating models using the Form Recognizer sample labeling tool you are generating Form Recognizer v2.0 (preview) models. To get those models status or analyze forms with those models please use the Form Recognizer v2.0-preivew API https://aka.ms/form-recognizer/api . </p>

Title: Form Recognizer


问:
Django- invalid token in plural form: EXPRESSION
I added 'Kurdish' language to my django website. this language is not supported by django, so I added to languages as follow:
in settings.py

```<code>gettext = lambda s: s
NEW_LANG_INFO = {
    'ku': {
       'bidi': True,
       'code': 'ku',
       'name': 'Kurdish',
       'name_local': u'کوردی',
    },
}

import django.conf.locale
LANG_INFO = dict(**django.conf.locale.LANG_INFO, **NEW_LANG_INFO)
django.conf.locale.LANG_INFO = LANG_INFO

LANGUAGES = (
    ('en', 'English'),
    ('ku', gettext('Kurdish')),
    ('ar', 'Arabic')
)
</code>```

now when i go to mysite.com/en/admin/ it works properly. when I go to mysite.com/ar/admin/ it works properly.
but when I go to mysite.com/ku/admin/ it raises an error with this message:
ValueError at /ku/admin/
 invalid token in plural form: EXPRESSION

the django version is 1.11.6.

what's the problem and how can i solve it?

Update
I find that in django.po in locale/ku/LC_MESSAGES, the last line of comments is "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n"

答:
Here is also an answer to the same error, but a different case (their language is supported):

French translation raises "ValueError('invalid token in plural form: %s' % value)"

Maybe somebody finds that helpful. I was also searching for help and found your problem, but my solution was on the link above.
(Solution was to delete the projects virtual environment and install it again)

Body:
I added 'Kurdish' language to my django website. this language is not supported by django, so I added to languages as follow:
in settings.py

gettext = lambda s: s
NEW_LANG_INFO = {
    'ku': {
       'bidi': True,
       'code': 'ku',
       'name': 'Kurdish',
       'name_local': u'کوردی',
    },
}

import django.conf.locale
LANG_INFO = dict(**django.conf.locale.LANG_INFO, **NEW_LANG_INFO)
django.conf.locale.LANG_INFO = LANG_INFO

LANGUAGES = (
    ('en', 'English'),
    ('ku', gettext('Kurdish')),
    ('ar', 'Arabic')
)

now when i go to mysite.com/en/admin/ it works properly. when I go to mysite.com/ar/admin/ it works properly.
but when I go to mysite.com/ku/admin/ it raises an error with this message:
ValueError at /ku/admin/
 invalid token in plural form: EXPRESSION

the django version is 1.11.6.

what's the problem and how can i solve it?

Update
I find that in django.po in locale/ku/LC_MESSAGES, the last line of comments is "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n"


问:
Time complexity : how do we find O(n^3)?
I know f(n) = 3*n^3 + 4*n + 2 has O(n^3) complexity, but I want to know how to calculate it using the definition of big O :

```<code>If f(n) has complexity O(g(n)), that means there exists a constant c > 0, n0 >=1 where f(n) < c*g(n)
</code>```

But how do you determine what is the c and what is the g(n) ?

答:
You can use any dirty hack you want to divine a c and n0 that work, then prove them (induction usually works well but sometimes is not necessary).

Here, simply note that for n >= 1, n^3 >= n >= 1, so

```<code>f(n) = 3*n^3 + 4*n + 2
    <= 3*n^3 + 4*n^3 + 2*n^3
     = 9n^3
</code>```

This has told us the choice n0 = 1 and c = 9 works. Here we knew the bound and wanted to find constants to verify; if we hadn't known the bound we could have guessed one based on the formula or written out some terms.

Body:
I know f(n) = 3*n^3 + 4*n + 2 has O(n^3) complexity, but I want to know how to calculate it using the definition of big O :

If f(n) has complexity O(g(n)), that means there exists a constant c > 0, n0 >=1 where f(n) < c*g(n)

But how do you determine what is the c and what is the g(n) ?

Body:
You can use any dirty hack you want to divine a c and n0 that work, then prove them (induction usually works well but sometimes is not necessary).

Here, simply note that for n >= 1, n^3 >= n >= 1, so

f(n) = 3*n^3 + 4*n + 2
    <= 3*n^3 + 4*n^3 + 2*n^3
     = 9n^3

This has told us the choice n0 = 1 and c = 9 works. Here we knew the bound and wanted to find constants to verify; if we hadn't known the bound we could have guessed one based on the formula or written out some terms.


问:
Regular expression matching strings with at least 1 uppercase, 1 lowercase, 1 number and 1 special character from a list
Here's the regex expression

```<code>^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[\-$*.{}?"!@#%&\/\\,><':;|_~`^\]\[\)\(]).{8,}
</code>```

This currently makes sure that a string contains at least 1 uppercase, 1 lowercase, 1 number and one special character from a list.

What I want is to make sure I don't allow white spaces but I could not find a way to do it.

Body:
Here's the regex expression

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[\-$*.{}?"!@#%&\/\\,><':;|_~`^\]\[\)\(]).{8,}

This currently makes sure that a string contains at least 1 uppercase, 1 lowercase, 1 number and one special character from a list.

What I want is to make sure I don't allow white spaces but I could not find a way to do it.

Body:
You can change . to \S:

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[\-$*.{}?"!@#%&\/\\,><':;|_~`^\]\[\)\(])\S{8,}$


问:
How to create a menu bar on OSX with PySide2?
I'm looking at the Data Visualization Tool Tutorial on the QT website where they have an example of creating a menu bar inside a QMainWindow:

```<code>self.menu = self.menuBar()
self.file_menu = self.menu.addMenu("File")
</code>```

This doesn't work for me on OSX 10.13.6. I've also tried using QMenuBar to create my own menu bar rather than using the default one that comes with a QMainWindow:

```<code>menu_bar = QMenuBar()
menu_bar.addMenu('File')
self.setMenuBar(menu_bar)
</code>```

This also has no effect. I never see the "File" option in the menu bar of my app. I just get a generic menu bar with a single "python" option.

答:
I believe it is working, but "File" will only appear once you add actions to the file menu.</p>

```<code>menu = self.menuBar()
file = menu.addMenu('File')
file.addAction(QAction('Open...', self))
</code>```

Body:
I'm looking at the Data Visualization Tool Tutorial on the QT website where they have an example of creating a menu bar inside a QMainWindow:

self.menu = self.menuBar()
self.file_menu = self.menu.addMenu("File")

This doesn't work for me on OSX 10.13.6. I've also tried using QMenuBar to create my own menu bar rather than using the default one that comes with a QMainWindow:

menu_bar = QMenuBar()
menu_bar.addMenu('File')
self.setMenuBar(menu_bar)

This also has no effect. I never see the "File" option in the menu bar of my app. I just get a generic menu bar with a single "python" option.

Body:
I believe it is working, but "File" will only appear once you add actions to the file menu.

menu = self.menuBar()
file = menu.addMenu('File')
file.addAction(QAction('Open...', self))


问:
select query using an invalid package reference in oracle
I have a package that contains a function which simply returns a description from a table given the product id.

now i have a procedure that has a select statement which makes the use of this function.
this morning i noticed that, the package body has become invalid,
and all the calls to this procedure results in running that select statement,
 which never completes because of invalid package reference.

I need to make changes to my package, but i cannot do so until all the processes have completed ( or rolled back).

What can i do..?

答:
You can query active processes using the following query to obtain the sid & serial#.

```<code>SELECT ses.sid, ses.serial#, ses.username, ses.schemaname, sql.sql_text
FROM   v$session ses,
       v$sql     sql
WHERE  sql.sql_id(+) = ses.sql_id
AND    ses.type      = 'USER'
AND    ses.status    = 'ACTIVE'
AND    UPPER(sql.sql_text) LIKE '%MY_PKG.MY_FUNC%';
</code>```

Then you can have a DBA terminate the sessions executing your function.

```<code>ALTER SYSTEM KILL SESSION '<sid, serial#>';
</code>```

Body:
You can query active processes using the following query to obtain the sid & serial#.

SELECT ses.sid, ses.serial#, ses.username, ses.schemaname, sql.sql_text
FROM   v$session ses,
       v$sql     sql
WHERE  sql.sql_id(+) = ses.sql_id
AND    ses.type      = 'USER'
AND    ses.status    = 'ACTIVE'
AND    UPPER(sql.sql_text) LIKE '%MY_PKG.MY_FUNC%';

Then you can have a DBA terminate the sessions executing your function.

ALTER SYSTEM KILL SESSION '<sid, serial#>';


问:
Add 2 input values and display result in another input box
I am new to AngularJS. Want to get values from 2 input text boxes, add them and then display them in a 3rd text box.

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.sum = ( $scope.a + $scope.b );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">
  <form>
    <input ng-model="a" type="number">
    <input ng-model="b" type="number">
    <input ng-model="sum" type="number">
  </form>
</div>

</body>
</html></code>```

答:
Use the ng-change directive:

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.a = $scope.b = $scope.sum = 0;
    $scope.updateSum = function() {
        $scope.sum =  $scope.a + $scope.b;
    };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">
  <form>
    A=<input ng-model="a" ng-change="updateSum()" type="number"><br>
    B=<input ng-model="b" ng-change="updateSum()" type="number"><br><br>
    Sum=<input ng-model="sum">
  </form>
</div>

</body>
</html></code>```

Body:
I am new to AngularJS. Want to get values from 2 input text boxes, add them and then display them in a 3rd text box.

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.sum = ( $scope.a + $scope.b );
});

<!DOCTYPE html>

  <form>
    <input ng-model="a" type="number">
    <input ng-model="b" type="number">
    <input ng-model="sum" type="number">
  </form>

Body:
Use the ng-change directive:

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.a = $scope.b = $scope.sum = 0;
    $scope.updateSum = function() {
        $scope.sum =  $scope.a + $scope.b;
    };
});

<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">
  <form>
    A=<input ng-model="a" ng-change="updateSum()" type="number"><br>
    B=<input ng-model="b" ng-change="updateSum()" type="number"><br><br>
    Sum=<input ng-model="sum">
  </form>
</div>

</body>
</html>


问:
WINDOW function alternative in HAVING Clause
I'm trying to get the oldest processing date on each product like this:

```<code>select prod_id, prod_name, prod_date, min(prod_date) over (partition by prod_id) as min_prod_date
from dim_product
where prod_name in ('xxx', 'yyy', 'zzz')
having prod_date = min_prod_date
</code>```

This gives me the error:

ORA-00904: "min_prod_date": invalid identifier

So I tried to use the min() function in the having clause which gave me the error:

ORA-30483: window  functions are not allowed here

As an alternative I modified my query like this:

```<code>with temp as(
select prod_id, prod_name, prod_date, min(prod_date) over (partition by prod_id) as min_prod_date
    from dim_product
    where prod_name in ('xxx', 'yyy', 'zzz')
    having prod_date = min_prod_date))
select * from temp where prod_date = min_prod_date
</code>```

Is this the right way to do things or Is there any other efficient method?

答:
This sounds like aggregation:</p>

```<code>select prod_name, min(prod_date)
from dim_product
where prod_name in ('xxx', 'yyy', 'zzz')
group by prod_name;
</code>```

Body:
I'm trying to get the oldest processing date on each product like this:

select prod_id, prod_name, prod_date, min(prod_date) over (partition by prod_id) as min_prod_date
from dim_product
where prod_name in ('xxx', 'yyy', 'zzz')
having prod_date = min_prod_date

This gives me the error:

ORA-00904: "min_prod_date": invalid identifier

So I tried to use the min() function in the having clause which gave me the error:

ORA-30483: window  functions are not allowed here

As an alternative I modified my query like this:

with temp as(
select prod_id, prod_name, prod_date, min(prod_date) over (partition by prod_id) as min_prod_date
    from dim_product
    where prod_name in ('xxx', 'yyy', 'zzz')
    having prod_date = min_prod_date))
select * from temp where prod_date = min_prod_date

Is this the right way to do things or Is there any other efficient method?

Body:
This sounds like aggregation:

select prod_name, min(prod_date)
from dim_product
where prod_name in ('xxx', 'yyy', 'zzz')
group by prod_name;


问:
Authentification on DHL-SOAP API with zeep
I just started working with one of the DHL-SOAP APIs and use zeep to run requests against the API.
The API expects and Element Authentification like this:

```<code>...
<soapenv:Header>
    <cis:Authentification>
        <cis:user>USER</cis:user>
        <cis:signature>PASSWORD</cis:signature>
    </cis:Authentification>
</soapenv:Header>
...
</code>```

I tried to pass the authentification as part of the _soapheaders as described in the zeep documentation, neigher the dict notation nor the xsd.Element notation seem to work.

```<code>from zeep import Client
from zeep import xsd

client = Client('<URL_TO_WSDL>')
auth_header = {'user': 'user', 'signature': 'signature'}
# dict approach
client.service.DHL_SERVICE(_soapheaders={'Authentification': auth_header})

# xsd approach
header = xsd.Element('Authentification',
    xsd.ComplexType([
        xsd.Element('user', xsd.String()),
        xsd.Element('signature', xsd.String())
    ])
)
header_values = header(user='user', signature='signature')
client.service.DHL_SERVICE(_soapheaders=[header_values])
</code>```

I don't find helpful information in the DHL docs not in the zeep documentation.

Thank you in advance!

Regards

答:
Just in case someone ever encounters the same problems. It turned out that the client needs to authenticate at a gateway using HTTPBasicAuth. Additionally, the client had to be created using a Transport with a session in it, carrying the gateway authentication headers.
What made the xsd API header approach work was the addition {http://test.python-zeep.org}.
This setup made communication with the API working smoothly.

```<code>from requests import Session
from requests.auth import HTTPBasicAuth
from zeep import Client
from zeep.transports import Transport

session = Session()

# Authenticate  with gateway
session.auth = HTTPBasicAuth(user, password)
client = Client(WSDL_PATH, transport=Transport(session=session))

# Build Authentification header for API-Endpoint using zeep xsd
header = xsd.Element(
    '{http://test.python-zeep.org}Authentification',
    xsd.ComplexType([
        xsd.Element(
            '{http://test.python-zeep.org}user',
            xsd.String()),
        xsd.Element(
            '{http://test.python-zeep.org}signature',
            xsd.String()),
    ])
)
header_value = header(user=USER, signature=PASSWORD)
client.service.DHL_SERVICE(_soapheaders=[header_value])

</code>```

Body:
I just started working with one of the DHL-SOAP APIs and use zeep to run requests against the API.
The API expects and Element Authentification like this:

...
<soapenv:Header>
    <cis:Authentification>
        <cis:user>USER</cis:user>
        <cis:signature>PASSWORD</cis:signature>
    </cis:Authentification>
</soapenv:Header>
...

I tried to pass the authentification as part of the _soapheaders as described in the zeep documentation, neigher the dict notation nor the xsd.Element notation seem to work.

from zeep import Client
from zeep import xsd

client = Client('<URL_TO_WSDL>')
auth_header = {'user': 'user', 'signature': 'signature'}
# dict approach
client.service.DHL_SERVICE(_soapheaders={'Authentification': auth_header})

# xsd approach
header = xsd.Element('Authentification',
    xsd.ComplexType([
        xsd.Element('user', xsd.String()),
        xsd.Element('signature', xsd.String())
    ])
)
header_values = header(user='user', signature='signature')
client.service.DHL_SERVICE(_soapheaders=[header_values])

I don't find helpful information in the DHL docs not in the zeep documentation.

Thank you in advance!

Regards

Body:
Just in case someone ever encounters the same problems. It turned out that the client needs to authenticate at a gateway using HTTPBasicAuth. Additionally, the client had to be created using a Transport with a session in it, carrying the gateway authentication headers.
What made the xsd API header approach work was the addition {http://test.python-zeep.org}.
This setup made communication with the API working smoothly.

from requests import Session
from requests.auth import HTTPBasicAuth
from zeep import Client
from zeep.transports import Transport

session = Session()

# Authenticate  with gateway
session.auth = HTTPBasicAuth(user, password)
client = Client(WSDL_PATH, transport=Transport(session=session))

# Build Authentification header for API-Endpoint using zeep xsd
header = xsd.Element(
    '{http://test.python-zeep.org}Authentification',
    xsd.ComplexType([
        xsd.Element(
            '{http://test.python-zeep.org}user',
            xsd.String()),
        xsd.Element(
            '{http://test.python-zeep.org}signature',
            xsd.String()),
    ])
)
header_value = header(user=USER, signature=PASSWORD)
client.service.DHL_SERVICE(_soapheaders=[header_value])


问:
problem in submitting form to cgi file
I coded a CMS for a client everything is ok except client said:

Use his previous shopping cart and embed that into the new design. The previous shopping cart file is shopper.cgi and I want to submit my form to that shopper.cgi

When I do this the file open dialog opens asking me to save the file or open the file.

Can someone suggest how can I make my form submit to shopper.cgi? I am running wamp server than ks

答:
Sounds like you don't have apache configured to execute .cgi files, hence it's serving the file rather then processing it.

http://httpd.apache.org/docs/2.0/howto/cgi.html

Title: problem in submitting form to cgi file


问:
MySql Replication - slave lagging behind master
I have a master/slave replication on my MySql DB.

my slave DB was down for a few hours and is back up again (master was up all the time), when issuing show slave status I can see that the slave is X seconds behind the master.

the problem is that the slave dont seem to catch up with the master, the X seconds behind master dont seem to drop...

any ideas on how I can help the slave catch up?

答:
I have an issue similar to this. and both of my MySQL server hosted on AWS EC2 (master and replication). by increasing EBS disk size (which automatically increased IOPS) for MySQL slave server, its turned out the solution for me. R/W Throughput and bandwidth is increased R/W latency were decreased.

now my MySQL database replication is catching up to the master. and Seconds_Behind_Master was decreased (it was got increased from day to day).

so if you have MySQL hosted on EC2. I suggest you tried to increase EBS disk size or its IOPS on the slave.


问:
If I create a project to react native how to make it support on several Android platforms for example (Android 6 and later)
I'm new in the world of APP(mobile applications). I want to create a APP using react native. But it is necessary that it works out in several versions of android (6 onwards).

Now I am working on no expo way and on windows 10 too. So,  I installed react native that now it works with android 9 (PIE) API LVL 28 AVD. If I finish my project with this API, would the apk work on different old versions of Android? or only in phones which have API 9. Give me advices pleases.

if i development my project with react native 0.61.5 version (the last i think 18/02/2020), would i run old APIs of android (6 onwards i want)?. Or, do i need to put my react native version on an old version to development an APP on android 6 to run on several versions?. Or the only thing that i need to do is write a sentence in my code that cover some plataforms.

PD: I'm new in this web page too.

答: You want to set your minSDK in the Android project. To do so, open up your build.gradle in the Android portion of your project and then change minSDK to whatever version you need. IIRC React Native supports all the way back to API 19 and Android 6 is API 21. If it's already low enough, no need to change it. That being said, I'd still recommend testing on multiple phones.</p>


问:
XML Input limit results with XSLT file
First let me start I am just taking a stab at XML and have no formal training so this may be a very basic question but it is oblivious for me.

I have an XML file that looks similar to this.

```<code>   <?xml version='1.0' encoding='UTF-8' ?>
    <document>
          <properties>
            <basic>
              <property id="number">
                <value>305</value>
              </property>
              <property id="first">
                <value>given</value>
              </property>
              <property id="last">
                <value>family</value>
              </property>
           </basic>
          </properties>
        </document>
</code>```

I then need to show with XML an output similar to this.

```<code><document>
      <properties>
        <basic>
          <property id="number">
            <value>305</value>
          </property>
          <property id="last">
            <value>family</value>
          </property>
       </basic>
      </properties>
    </document>
</code>```

Where I am just including certain property id values to the final destination.

I have been able to do this with CSV but not with XML being the output and not sure where I should start.

Example XSL that gives me a , deliminator value.

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="preg" match="property" use="@id"/>
    <xsl:output method="text"></xsl:output>
    <xsl:strip-space elements="*" />
    <xsl:template match="/">

    <!-- Item 1 Value -->
    <xsl:for-each select="key('preg','number')">
    <xsl:value-of select="value"/>
    <xsl:text disable-output-escaping="yes">,</xsl:text>
    </xsl:for-each>

    <!-- Item 2 Value -->
    <xsl:for-each select="key('preg','last')">
    <xsl:value-of select="value"/>
    <xsl:text disable-output-escaping="yes">,</xsl:text>
    </xsl:for-each>

    <xsl:text>
</xsl:text>
    <xsl:text>
</xsl:text>

</xsl:template>
</xsl:stylesheet>
</code>```

Thank you for any suggestions you may have as I this is not my full time job doing these type of things. :)

答:
You can generate the desired outcome with the following XSLT-1.0 stylesheet, a Blacklist approach. This solution just omits certain (the blacklisted) elements and copies the rest.

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" />
    <xsl:strip-space elements="*" />

    <!-- Identity template -->
    <xsl:template match="node()|@*">
        <xsl:copy>
             <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="property[@id='first']" />

</xsl:stylesheet>
</code>```

It is a combination of the Identity template and an empty template assuring that the matched elements are not copied.

The other approach is a Whitelist approach. It masks all property elements and then only copies the one's defined in the copy template:

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" />
    <xsl:strip-space elements="*" />

    <!-- Identity template -->
    <xsl:template match="node()|@*">
        <xsl:copy>
             <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

    <!-- Omit all 'property' elements... -->
    <xsl:template match="property" />

    <!-- ...except for those with an @id of 'number' or 'last' -->
    <xsl:template match="property[@id='number' or @id='last']">
        <xsl:copy>
             <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
</code>```

Result in both cases is:

```<code><?xml version="1.0"?>
<document>
  <properties>
    <basic>
      <property id="number">
        <value>305</value>
      </property>
      <property id="last">
        <value>family</value>
      </property>
    </basic>
  </properties>
</document>
</code>```

Title: XML Input limit results with XSLT file

Body:
First let me start I am just taking a stab at XML and have no formal training so this may be a very basic question but it is oblivious for me.

I have an XML file that looks similar to this.

   <?xml version='1.0' encoding='UTF-8' ?>
    <document>
          <properties>
            <basic>
              <property id="number">
                <value>305</value>
              </property>
              <property id="first">
                <value>given</value>
              </property>
              <property id="last">
                <value>family</value>
              </property>
           </basic>
          </properties>
        </document>

I then need to show with XML an output similar to this.

<document>
      <properties>
        <basic>
          <property id="number">
            <value>305</value>
          </property>
          <property id="last">
            <value>family</value>
          </property>
       </basic>
      </properties>
    </document>

Where I am just including certain property id values to the final destination.

I have been able to do this with CSV but not with XML being the output and not sure where I should start.

Example XSL that gives me a , deliminator value.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="preg" match="property" use="@id"/>
    <xsl:output method="text"></xsl:output>
    <xsl:strip-space elements="*" />
    <xsl:template match="/">

    <xsl:for-each select="key('preg','number')">
    <xsl:value-of select="value"/>
    <xsl:text disable-output-escaping="yes">,</xsl:text>
    </xsl:for-each>

    <xsl:for-each select="key('preg','last')">
    <xsl:value-of select="value"/>
    <xsl:text disable-output-escaping="yes">,</xsl:text>
    </xsl:for-each>

    <xsl:text>
</xsl:text>
    <xsl:text>
</xsl:text>

</xsl:template>
</xsl:stylesheet>

Thank you for any suggestions you may have as I this is not my full time job doing these type of things. :)

Body:
You can generate the desired outcome with the following XSLT-1.0 stylesheet, a Blacklist approach. This solution just omits certain (the blacklisted) elements and copies the rest.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" />
    <xsl:strip-space elements="*" />

    <!-- Identity template -->
    <xsl:template match="node()|@*">
        <xsl:copy>
             <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="property[@id='first']" />

</xsl:stylesheet>

It is a combination of the Identity template and an empty template assuring that the matched elements are not copied.

The other approach is a Whitelist approach. It masks all property elements and then only copies the one's defined in the copy template:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" />
    <xsl:strip-space elements="*" />

    <!-- Identity template -->
    <xsl:template match="node()|@*">
        <xsl:copy>
             <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

    <!-- Omit all 'property' elements... -->
    <xsl:template match="property" />

    <!-- ...except for those with an @id of 'number' or 'last' -->
    <xsl:template match="property[@id='number' or @id='last']">
        <xsl:copy>
             <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Result in both cases is:

<?xml version="1.0"?>
<document>
  <properties>
    <basic>
      <property id="number">
        <value>305</value>
      </property>
      <property id="last">
        <value>family</value>
      </property>
    </basic>
  </properties>
</document>