问:
How do I view data object contents within an npz file?
I am using Spyder IDE and Python 2.7.

I have a npz file called data.npz which was given to me. I want to load this file into Spyder and view whatever is inside.

To start I've done this:

```<code>import numpy as np
data = np.load('data.npz')
</code>```

In my Variable Explorer in Spyder, I have a variable with the name "data" and the type "object". When I double-click on this variable, Spyder gives an error saying "object arrays are currently not supported".

When I just type

```<code>data
</code>```

I get something like this:

```<code>array({'a': array([ 1,2,3, ...,
         4,5,6]), 'b': 10, 'c': array([-1,-2,-3]), 'd': 25, 'e': 1}, dtype=object)
</code>```

How do I access 'a', 'b', 'c', 'd', etc?

答: print(data.files) will give you a list of arrays contained within the npz file. you can then use the data['a'] to view contents of a, and data['b'] to view b, so on and so forth</p>

Body:
I am using Spyder IDE and Python 2.7.

I have a npz file called data.npz which was given to me. I want to load this file into Spyder and view whatever is inside.

To start I've done this:

import numpy as np
data = np.load('data.npz')

In my Variable Explorer in Spyder, I have a variable with the name "data" and the type "object". When I double-click on this variable, Spyder gives an error saying "object arrays are currently not supported".

When I just type

data

I get something like this:

array({'a': array([ 1,2,3, ...,
         4,5,6]), 'b': 10, 'c': array([-1,-2,-3]), 'd': 25, 'e': 1}, dtype=object)

How do I access 'a', 'b', 'c', 'd', etc?


来源: stackexchange

问:
plsql to_date function giving ORA-03001: unimplemented feature
I have two string parameters which are holding  dates in this format "dd.MM.yyyy HH:mm:ss".I am trying to getting datas between  two dates so i am using to_date function in oracle sql.But i am getting this error ORA-03001: unimplemented feature. This is how i am getting the datas:

```<code>...
ops.last_update_date between :to_date(startDate,'dd.MM.yyyy HH:mm:ss') and :to_date(endDate,'dd.MM.yyyy HH:mm:ss')

...
</code>```

答:
The : syntax should be used on the bind variables and not on the function wrapping then:

ops.last_update_date BETWEEN to_date(:startDate,'DD.MM.YYYY HH24:MI:SS')
                     AND     to_date(:endDate,  'DD.MM.YYYY HH24:MI:SS')
```
<p><em>Note: In the format model, you need <code>HH24</code> for a 24-hour clock and <code>MI</code> for minutes and, for the numeric format models, it is case insensitive.</em></p>
<p>If you pass the values as <code>DATE</code> or <code>TIMESTAMP</code> data types (rather than strings) then it should just be:</p>
<pre class="lang-sql prettyprint-override"><code>ops.last_update_date BETWEEN :startDate AND :endDate
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two string parameters which are holding  dates in this format "dd.MM.yyyy HH:mm:ss".I am trying to getting datas between  two dates so i am using to_date function in oracle sql.But i am getting this error ORA-03001: unimplemented feature. This is how i am getting the datas:

...
ops.last_update_date between :to_date(startDate,'dd.MM.yyyy HH:mm:ss') and :to_date(endDate,'dd.MM.yyyy HH:mm:ss')

...

Body:
The : syntax should be used on the bind variables and not on the function wrapping then:

ops.last_update_date BETWEEN to_date(:startDate,'DD.MM.YYYY HH24:MI:SS')
                     AND     to_date(:endDate,  'DD.MM.YYYY HH24:MI:SS')

Note: In the format model, you need HH24 for a 24-hour clock and MI for minutes and, for the numeric format models, it is case insensitive.

If you pass the values as DATE or TIMESTAMP data types (rather than strings) then it should just be:

ops.last_update_date BETWEEN :startDate AND :endDate


问:
Haskell Cartesian Product, Monad with filter
This has to be dead simple and I'm unhappy I can't figure it out at this point in my Haskell experience. I want a cartesian product of a list with itself, but I want to filter out identical items. I don't want a post filter.

This gets me the CP - seemingly set up to simply add a filter...

```<code>p as bs = do
            a <- as
            b <- bs
            return (a,b)

p [1,2,3] [1,2,3]
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
</code>```

I have read that return () is basically a noop in do notation - but this doesn't compile. (Are the tuples being mixed up)

```<code>pf as bs = do
            a <- as
            b <- bs
            if a == b then return () else return (a,b)

* Couldn't match type `()' with `(a, a)'
      Expected type: [(a, a)]
        Actual type: [()]

</code>```

I have tried a few other things, like the if' function from the Haskell wiki. I also tried when without success. When the filter is when

```<code>when (a /= b) return (a,b)

* Couldn't match type `m0 (a, a)' with `()'
      Expected type: (a, a) -> ()
        Actual type: (a, a) -> m0 (a, a)

</code>```

I suppose these error messages are leading me by the nose to the issue but I am not adept at translating most of them yet.

There is very possibly a higher level function that might handle this in a more straight forward way (filterM ?), and I'll be happy to hear about its usage, but I still want to know how to solve this issue in the pf function above.

Thanks

答:
You can fix your

```<code>pf as bs = do
             a <- as
             b <- bs
             if a == b then return () else return  (a,b)
</code>```

by changing it to

```<code>pf2 :: (Monad m, Eq t) => m t -> m t -> m [(t, t)]
pf2 as bs = do
             a <- as
             b <- bs
             if a == b then return [] else return [(a,b)]
</code>```

In case the m is []-type, this gets us

```<code>pf3 :: (Eq t) => [t] -> [t] -> [ [(t, t)] ]
pf3 as bs = do
             a <- as
             b <- bs
             if a == b then return [] else return [(a,b)]
</code>```

so it does pass the type-checker now, but we've created an extra layer of [] around our desired type:

```<code>> pf3 [1,2,3] [1,2,3] :: [ [(Int,Int)] ]
[[],[(1,2)],[(1,3)], [(2,1)],[],[(2,3)], [(3,1)],[(3,2)],[]]
</code>```

So this is almost what we wanted, except for some extra []s thrown around for good measure. If only we could make them disappear,

```<code>> concat it
[    (1,2),  (1,3),   (2,1),     (2,3),   (3,1),  (3,2)    ]
</code>```

we'd get what we really wanted as the end result.

As you can see above we did get the final desired value, by passing the output of pf3 through concat. But concat is []-type-monad's join:

```<code>> :t concat :: [] ([] a) -> [] a
concat ::       [] ([] a) -> [] a   :: [[a]] -> [a]

> :t join ::   [] ([] a) -> [] a
join ::         [] ([] a) -> [] a   :: [[a]] -> [a]

> :t join
join :: Monad m => m (m a) -> m a
</code>```

which is defined as

```<code>join xs = do                    = do
           { x <- xs               { x <- xs
           ; x                     ; y <- x
           }                       ; return y
                                   }
</code>```

and thus what we wrote above fuses together as

```<code>pf4 as bs = join $ do
                     a <- as
                     b <- bs
                     if a == b then return [] else return [(a,b)]
    = do {
           x <- do { a <- as
                   ; b <- bs
                   ; if a == b then return [] else return [(a,b)] }
         ; x
         }
    = do {           a <- as
                   ; b <- bs
         ; x <-      if a == b then return [] else return [(a,b)]
         ; x
         }
    = do { a <- as
         ; b <- bs
         ; let { x = if a == b then  []  else  [(a,b)]  }
         ; x
         }
    = do { a <- as
         ; b <- bs
         ;      if a == b then  []  else  [(a,b)]
         }
    = do { a <- as
         ; b <- bs
         ;      if a == b then  []  else  [()]
         ; return (a,b)
         }
</code>```

whichever of the last two you prefer. The first of the two is what you'd normally write out by hand, and the last corresponds to using reject (a==b) as the third do line, with the definition

```<code>reject :: MonadPlus m => Bool -> m ()
reject True  = mzero         -- mzero :: MonadPlus m => m a
reject False = return ()     -- () to be ignored
</code>```

where for the []-type monad, mzero = [] :: [] a (and of course, return x = [x] :: [] a).

It so happens that reject b = guard (not b), with the built-in guard.

A side remark:

return () is a no-op in the sense that

```<code>do {             a <- as ; b <- bs ; return (a,b) } ==
do { return () ; a <- as ; b <- bs ; return (a,b) } ==
do { a <- as ; return () ; b <- bs ; return (a,b) } ==
do { a <- as ; b <- bs ; return () ; return (a,b) }
</code>```

You can put it on any line of the do block except the last one and it won't change a thing. This is true for any monad.

Body:
This has to be dead simple and I'm unhappy I can't figure it out at this point in my Haskell experience. I want a cartesian product of a list with itself, but I want to filter out identical items. I don't want a post filter.

This gets me the CP - seemingly set up to simply add a filter...

p as bs = do
            a <- as
            b <- bs
            return (a,b)

p [1,2,3] [1,2,3]
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]

I have read that return () is basically a noop in do notation - but this doesn't compile. (Are the tuples being mixed up)

pf as bs = do
            a <- as
            b <- bs
            if a == b then return () else return (a,b)

* Couldn't match type `()' with `(a, a)'
      Expected type: [(a, a)]
        Actual type: [()]

I have tried a few other things, like the if' function from the Haskell wiki. I also tried when without success. When the filter is when

when (a /= b) return (a,b)

* Couldn't match type `m0 (a, a)' with `()'
      Expected type: (a, a) -> ()
        Actual type: (a, a) -> m0 (a, a)

I suppose these error messages are leading me by the nose to the issue but I am not adept at translating most of them yet.

There is very possibly a higher level function that might handle this in a more straight forward way (filterM ?), and I'll be happy to hear about its usage, but I still want to know how to solve this issue in the pf function above.

Thanks

Body:
You can fix your

pf as bs = do
             a <- as
             b <- bs
             if a == b then return () else return  (a,b)

by changing it to

pf2 :: (Monad m, Eq t) => m t -> m t -> m [(t, t)]
pf2 as bs = do
             a <- as
             b <- bs
             if a == b then return [] else return [(a,b)]

In case the m is []-type, this gets us

pf3 :: (Eq t) => [t] -> [t] -> [ [(t, t)] ]
pf3 as bs = do
             a <- as
             b <- bs
             if a == b then return [] else return [(a,b)]

so it does pass the type-checker now, but we've created an extra layer of [] around our desired type:

> pf3 [1,2,3] [1,2,3] :: [ [(Int,Int)] ]
[[],[(1,2)],[(1,3)], [(2,1)],[],[(2,3)], [(3,1)],[(3,2)],[]]

So this is almost what we wanted, except for some extra []s thrown around for good measure. If only we could make them disappear,

> concat it
[    (1,2),  (1,3),   (2,1),     (2,3),   (3,1),  (3,2)    ]

we'd get what we really wanted as the end result.

As you can see above we did get the final desired value, by passing the output of pf3 through concat. But concat is []-type-monad's join:

> :t concat :: [] ([] a) -> [] a
concat ::       [] ([] a) -> [] a   :: [[a]] -> [a]

> :t join ::   [] ([] a) -> [] a
join ::         [] ([] a) -> [] a   :: [[a]] -> [a]

> :t join
join :: Monad m => m (m a) -> m a

which is defined as

join xs = do                    = do
           { x <- xs               { x <- xs
           ; x                     ; y <- x
           }                       ; return y
                                   }

and thus what we wrote above fuses together as

pf4 as bs = join $ do
                     a <- as
                     b <- bs
                     if a == b then return [] else return [(a,b)]
    = do {
           x <- do { a <- as
                   ; b <- bs
                   ; if a == b then return [] else return [(a,b)] }
         ; x
         }
    = do {           a <- as
                   ; b <- bs
         ; x <-      if a == b then return [] else return [(a,b)]
         ; x
         }
    = do { a <- as
         ; b <- bs
         ; let { x = if a == b then  []  else  [(a,b)]  }
         ; x
         }
    = do { a <- as
         ; b <- bs
         ;      if a == b then  []  else  [(a,b)]
         }
    = do { a <- as
         ; b <- bs
         ;      if a == b then  []  else  [()]
         ; return (a,b)
         }

whichever of the last two you prefer. The first of the two is what you'd normally write out by hand, and the last corresponds to using reject (a==b) as the third do line, with the definition

reject :: MonadPlus m => Bool -> m ()
reject True  = mzero         -- mzero :: MonadPlus m => m a
reject False = return ()     -- () to be ignored

where for the []-type monad, mzero = [] :: [] a (and of course, return x = [x] :: [] a).

It so happens that reject b = guard (not b), with the built-in guard.

A side remark:

return () is a no-op in the sense that

do {             a <- as ; b <- bs ; return (a,b) } ==
do { return () ; a <- as ; b <- bs ; return (a,b) } ==
do { a <- as ; return () ; b <- bs ; return (a,b) } ==
do { a <- as ; b <- bs ; return () ; return (a,b) }

You can put it on any line of the do block except the last one and it won't change a thing. This is true for any monad.


问:
In a Flutter widget test, how can I verify a field validation error message?
I'm writing a widget test for a Flutter form, and want to verify that after form submission, validation fails, and errorText for one of the fields is displayed and is as expected.

The code for the field looks like:

```<code>Form(key: _formKey, ...
  TextFormField(validator: validateEmail, ...)
</code>```

For the test assertion, I've tried things like

```<code>expect(find.text('Please fill in your email.'), findsOneWidget);
</code>```

With no success. Hoping someone can point me in the right direction.

答:
If you want to verify the validation error message from a TextFormField, it is not straightforward but possible.

We can use the key of our TextFormField:

TextFormField(
  key: const Key('field_key'),
  // Rest of attributes...
),
```
<p>Then we scope our <code>find.text()</code> to find only within the descendants of the <code>TextFormField</code> like this:</p>
<pre class="lang-dart prettyprint-override"><code>final textFormField = find.byKey(const Key('field_key'));
final textFinder = find.text('Email is required');
final validationMessage = find.descendant(of: textFormField, matching: textFinder)
    .first.evaluate().single.widget as Text;
expect(validationMessage.data, 'Email is required');
</code>```

Alternatively, we can be a little bit less strict by just checking that the text exists as a child of the TextFormField:

final textFormField = find.byKey(const Key('field_key'));
final textFinder = find.text('Email is required');
final validationMessageFinder = find.descendant(of: textFormField, matching: textFinder);
expect(validationMessageFinder, findsOneWidget);
```

Body:
I'm writing a widget test for a Flutter form, and want to verify that after form submission, validation fails, and errorText for one of the fields is displayed and is as expected.

The code for the field looks like:

Form(key: _formKey, ...
  TextFormField(validator: validateEmail, ...)

For the test assertion, I've tried things like

expect(find.text('Please fill in your email.'), findsOneWidget);

With no success. Hoping someone can point me in the right direction.

Body:
If you want to verify the validation error message from a TextFormField, it is not straightforward but possible.

We can use the key of our TextFormField:

TextFormField(
  key: const Key('field_key'),
  // Rest of attributes...
),

Then we scope our find.text() to find only within the descendants of the TextFormField like this:

final textFormField = find.byKey(const Key('field_key'));
final textFinder = find.text('Email is required');
final validationMessage = find.descendant(of: textFormField, matching: textFinder)
    .first.evaluate().single.widget as Text;
expect(validationMessage.data, 'Email is required');

Alternatively, we can be a little bit less strict by just checking that the text exists as a child of the TextFormField:

final textFormField = find.byKey(const Key('field_key'));
final textFinder = find.text('Email is required');
final validationMessageFinder = find.descendant(of: textFormField, matching: textFinder);
expect(validationMessageFinder, findsOneWidget);


问:
icu-dev library removes /bin/sh or messes up the image entry point
I am trying to build an optimized PHP image. The strategy that I chose, was to install and compile everything in a build stage and then copy the extensions to a new stage and enable them. This allows me to shed 200MB.

All is good until the intl extension. This extension needs the icu-dev library, but once I install that, /bin/sh disappears, or somehow the entry point gets all messed up. This is very low level stuff and I don't really know how to even search for the issue.

```<code># Prepare compiled extensions
FROM php:8.1-cli-alpine as build

RUN apk --no-cache add autoconf build-base icu-dev

RUN docker-php-ext-install intl

FROM php:8.1-cli-alpine

COPY --from=build /usr/local/lib/php/extensions/no-debug-non-zts-20210902/intl.so /usr/local/lib/php/extensions/no-debug-non-zts-20210902/intl.so

RUN apk --no-cache add icu-dev

RUN docker-php-ext-enable intl

</code>```

This is the output of the image build

```<code>[+] Building 1.6s (10/10) FINISHED
 => [internal] load build definition from Dockerfile                                                                                0.0s
 => => transferring dockerfile: 429B                                                                                0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 2B                                                                                0.0s
 => [internal] load metadata for docker.io/library/php:8.1-cli-alpine                                                                                1.3s
 => [auth] library/php:pull token for registry-1.docker.io                                                                                0.0s
 => [build 1/3] FROM docker.io/library/php:8.1-cli-alpine@sha256:858d56e3ee12e138a9119380fb361a5b01f1ff9369d372ef73042b6cd4753f25                                                                                0.0s
 => CACHED [build 2/3] RUN apk --no-cache add autoconf build-base icu-dev                                                                                0.0s
 => CACHED [build 3/3] RUN docker-php-ext-install intl                                                                                0.0s
 => CACHED [stage-1 2/4] COPY --from=build /usr/local/lib/php/extensions/no-debug-non-zts-20210902/intl.so /usr/local/lib/php/extensions/no-debug-non-zts-20210902/intl.so                                                                                0.0s
 => CACHED [stage-1 3/4] RUN apk --no-cache add icu-dev                                                                                0.0s
 => ERROR [stage-1 4/4] RUN docker-php-ext-enable intl                                                                                0.3s
------
 > [stage-1 4/4] RUN docker-php-ext-enable intl:
#10 0.251 container_linux.go:380: starting container process caused: exec: "/bin/sh": stat /bin/sh: no such file or directory
------
executor failed running [/bin/sh -c docker-php-ext-enable intl]: exit code: 1
make: *** [Makefile:4: build] Error 1

</code>```

Here's a reproduction repo, in case anyone is interested

https://github.com/benelori/icu-dev-reproduction

EDIT:

Unfortunately I did not provide all the details:

The command I ran for building the image was DOCKER_BUILDKIT=1 docker build . -t test/icu:latest

Docker version 20.10.12, build e91ed57

It seems like this is not reproducible for everyone, so I do not know what else to provide.

In the end though, if I don't enable build kit, then the build command runs successfully, therefore I marked the answer below as accepted.

答:
I'm not exactly sure what you are trying to achieve here with your multistage build but this clearly messes up your extension. You don't really need a multistage here as alpine apk provides tools to deal with build dependencies.

I did not fully dig in the process so that might be further optimized, but here is a Dockerfile which:

Installs required build packages as a virtual package

Installs icu-dev and the php intl extension. Note that the extension is installed enabled so there is no need to do that in a separate step

Removes the build dependencies virtual package once this is done

All of this takes place in a single layer so you end up with only what is strictly needed (i.e. the intl extension and required icu-dev package, unless I forgot some additional possible cleanup...)

```<code>FROM php:8.1-cli-alpine

RUN apk add --no-cache autoconf build-base --virtual build_deps && \
    apk add --no-cache icu-dev && \
    docker-php-ext-install intl && \
    apk del build_deps
</code>```

You can build from that Dockerfile file as

```<code>docker build -t test:test .
</code>```

and see the extension is available as expected:

$ docker run -it --rm test:test sh -c "php -i | grep -A 7 intl"
Additional .ini files parsed => /usr/local/etc/php/conf.d/docker-php-ext-intl.ini,
/usr/local/etc/php/conf.d/docker-php-ext-sodium.ini

PHP API => 20210902
PHP Extension => 20210902
Zend Extension => 420210902
Zend Extension Build => API420210902,NTS
PHP Extension Build => API20210902,NTS
--
intl

Internationalization support => enabled
ICU version => 69.1
ICU Data version => 69.1
ICU Unicode version => 13.0

Directive => Local Value => Master Value
intl.default_locale => no value => no value
intl.error_level => 0 => 0
intl.use_exceptions => Off => Off

json

json support => enabled

libxml
```

The resulting image is 135MB (compared to 366MB without removing the build dependencies). This makes it roughly 40MB more than the base image which is 94.2MB at time of this writing.

Body:
I am trying to build an optimized PHP image. The strategy that I chose, was to install and compile everything in a build stage and then copy the extensions to a new stage and enable them. This allows me to shed 200MB.

All is good until the intl extension. This extension needs the icu-dev library, but once I install that, /bin/sh disappears, or somehow the entry point gets all messed up. This is very low level stuff and I don't really know how to even search for the issue.

# Prepare compiled extensions
FROM php:8.1-cli-alpine as build

RUN apk --no-cache add autoconf build-base icu-dev

RUN docker-php-ext-install intl

FROM php:8.1-cli-alpine

COPY --from=build /usr/local/lib/php/extensions/no-debug-non-zts-20210902/intl.so /usr/local/lib/php/extensions/no-debug-non-zts-20210902/intl.so

RUN apk --no-cache add icu-dev

RUN docker-php-ext-enable intl

This is the output of the image build

[+] Building 1.6s (10/10) FINISHED
 => [internal] load build definition from Dockerfile                                                                                0.0s
 => => transferring dockerfile: 429B                                                                                0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 2B                                                                                0.0s
 => [internal] load metadata for docker.io/library/php:8.1-cli-alpine                                                                                1.3s
 => [auth] library/php:pull token for registry-1.docker.io                                                                                0.0s
 => [build 1/3] FROM docker.io/library/php:8.1-cli-alpine@sha256:858d56e3ee12e138a9119380fb361a5b01f1ff9369d372ef73042b6cd4753f25                                                                                0.0s
 => CACHED [build 2/3] RUN apk --no-cache add autoconf build-base icu-dev                                                                                0.0s
 => CACHED [build 3/3] RUN docker-php-ext-install intl                                                                                0.0s
 => CACHED [stage-1 2/4] COPY --from=build /usr/local/lib/php/extensions/no-debug-non-zts-20210902/intl.so /usr/local/lib/php/extensions/no-debug-non-zts-20210902/intl.so                                                                                0.0s
 => CACHED [stage-1 3/4] RUN apk --no-cache add icu-dev                                                                                0.0s
 => ERROR [stage-1 4/4] RUN docker-php-ext-enable intl                                                                                0.3s
------
 > [stage-1 4/4] RUN docker-php-ext-enable intl:
#10 0.251 container_linux.go:380: starting container process caused: exec: "/bin/sh": stat /bin/sh: no such file or directory
------
executor failed running [/bin/sh -c docker-php-ext-enable intl]: exit code: 1
make: *** [Makefile:4: build] Error 1

Here's a reproduction repo, in case anyone is interested

https://github.com/benelori/icu-dev-reproduction

EDIT:

Unfortunately I did not provide all the details:

The command I ran for building the image was DOCKER_BUILDKIT=1 docker build . -t test/icu:latest

Docker version 20.10.12, build e91ed57

It seems like this is not reproducible for everyone, so I do not know what else to provide.

In the end though, if I don't enable build kit, then the build command runs successfully, therefore I marked the answer below as accepted.

Body:
I'm not exactly sure what you are trying to achieve here with your multistage build but this clearly messes up your extension. You don't really need a multistage here as alpine apk provides tools to deal with build dependencies.

I did not fully dig in the process so that might be further optimized, but here is a Dockerfile which:

Installs required build packages as a virtual package

Installs icu-dev and the php intl extension. Note that the extension is installed enabled so there is no need to do that in a separate step

Removes the build dependencies virtual package once this is done

All of this takes place in a single layer so you end up with only what is strictly needed (i.e. the intl extension and required icu-dev package, unless I forgot some additional possible cleanup...)

FROM php:8.1-cli-alpine

RUN apk add --no-cache autoconf build-base --virtual build_deps && \
    apk add --no-cache icu-dev && \
    docker-php-ext-install intl && \
    apk del build_deps

You can build from that Dockerfile file as

docker build -t test:test .

and see the extension is available as expected:

$ docker run -it --rm test:test sh -c "php -i | grep -A 7 intl"
Additional .ini files parsed => /usr/local/etc/php/conf.d/docker-php-ext-intl.ini,
/usr/local/etc/php/conf.d/docker-php-ext-sodium.ini

PHP API => 20210902
PHP Extension => 20210902
Zend Extension => 420210902
Zend Extension Build => API420210902,NTS
PHP Extension Build => API20210902,NTS
--
intl

Internationalization support => enabled
ICU version => 69.1
ICU Data version => 69.1
ICU Unicode version => 13.0

Directive => Local Value => Master Value
intl.default_locale => no value => no value
intl.error_level => 0 => 0
intl.use_exceptions => Off => Off

json

json support => enabled

libxml

The resulting image is 135MB (compared to 366MB without removing the build dependencies). This makes it roughly 40MB more than the base image which is 94.2MB at time of this writing.


问:
Dockerfile specifying path of API
I'm using docker for the first time. I have a web application in angular and a backend application in python/flask. After some struggle, I finally managed to get everything to work, but docker can't find my API program in my backend:

My server file is at /my_backend/src/server.py

My docker file is at /my_backend/Dockerfile.dockerfile

Content of Dockerfile.dockerfile:

```<code>FROM python:3.7-slim
COPY /src .
WORKDIR /src/app
ENV PYTHONUNBUFFERED 1
COPY requirements.txt /tmp/requirements.txt
RUN python3 -m pip install -r /tmp/requirements.txt
CMD ["python","server.py"]
</code>```

The error message in the command prompt is

```<code>Attaching to backend, frontend
backend   | python: can't open file 'server.py': [Errno 2] No such file or directory
backend exited with code 2
</code>```

Feel free to ask for more information.

I used this tutorial: https://medium.com/analytics-vidhya/dockerizing-angular-application-and-python-backend-bottle-flask-framework-21dcbf8715e5

答:
turn your workdir and copy instructions around to make it work.

FROM python:3.7-slim
WORKDIR /src/app # workdir first
COPY /src .
ENV PYTHONUNBUFFERED 1
COPY requirements.txt /tmp/requirements.txt
RUN python3 -m pip install -r /tmp/requirements.txt
CMD ["python","server.py"]
```

Title: Dockerfile specifying path of API

Body:
I'm using docker for the first time. I have a web application in angular and a backend application in python/flask. After some struggle, I finally managed to get everything to work, but docker can't find my API program in my backend:

My server file is at /my_backend/src/server.py

My docker file is at /my_backend/Dockerfile.dockerfile

Content of Dockerfile.dockerfile:

FROM python:3.7-slim
COPY /src .
WORKDIR /src/app
ENV PYTHONUNBUFFERED 1
COPY requirements.txt /tmp/requirements.txt
RUN python3 -m pip install -r /tmp/requirements.txt
CMD ["python","server.py"]

The error message in the command prompt is

Attaching to backend, frontend
backend   | python: can't open file 'server.py': [Errno 2] No such file or directory
backend exited with code 2

Feel free to ask for more information.

I used this tutorial: https://medium.com/analytics-vidhya/dockerizing-angular-application-and-python-backend-bottle-flask-framework-21dcbf8715e5


问:
How do I change app icon in Recents Screen?
I managed to change the icon except on the recents screen/recent apps part

答: If you tried Everything try Rebooting your phone and Rebuilding the project , It was the solution for me.


问:
Get remote client IP address in Deno
How to I get the IP address of the client in Deno?

I have created a test server using the standard http library but I can't figure out a way to extract client's IP.
I need that as a security feature for preventing multiple submissions.

In NodeJS/Express there is an ip property of the request object that does the same.
req.ip gives the thing I want in Express but what is it's equivalent in Deno?

My code is:

import { serve } from "https://deno.land/std@0.125.0/http/server.ts";

serve(
    (req) => {
        console.log(/* the client IP */);
        return new Response("hello");
    },
    { port: 8080 }
);

```

Is there any other work-around to prevent multiple access from the same device?

Thanks

答:
To do this in a type-safe way is a little complicated because of the way that serve is typed. First, I'll show you an example of how to do it, then I'll explain the types afterward.

Example

example.ts:

import {
  serve,
  type ConnInfo,
  type Handler,
  type ServeInit,
} from 'https://deno.land/std@0.125.0/http/server.ts';

function assertIsNetAddr (addr: Deno.Addr): asserts addr is Deno.NetAddr {
  if (!['tcp', 'udp'].includes(addr.transport)) {
    throw new Error('Not a network address');
  }
}

function getRemoteAddress (connInfo: ConnInfo): Deno.NetAddr {
  assertIsNetAddr(connInfo.remoteAddr);
  return connInfo.remoteAddr;
}

const handler: Handler = (request, connInfo) => {
  const {hostname, port} = getRemoteAddress(connInfo);
  const message = `You connected from the following address: ${hostname}`;
  return new Response(message);
};

const init: ServeInit = {port: 8080};

serve(handler, init);
console.log(`Listening on port ${init.port}...\nUse ctrl+c to stop`);

```
<hr />
<h2>Types</h2>
<p>Looking at the documentation for the <code>serve</code> function, you can see that it accepts two parameters: a callback of type <code>Handler</code>, and some options of type <code>ServeInit</code>:</p>
<pre class="lang-ts prettyprint-override"><code>async function serve(handler: Handler, options?: ServeInit): Promise<void>;
</code>```

The Handler callback accepts two parameters: a Request, and an object of type ConnInfo:

type Handler = (request: Request, connInfo: ConnInfo) => Response | Promise<Response>;
```
<p><code>ConnInfo</code> looks like this:</p>
<pre class="lang-ts prettyprint-override"><code>interface ConnInfo {
  readonly localAddr: Deno.Addr;
  readonly remoteAddr: Deno.Addr;
}
</code>```

The part that should have the remote IP address (technically, it's the remote hostname, but it's very likely to be an IP address unless you have configured custom DNS settings in your server environment) is the object at connInfo.remoteAddr, which (you can see above) is of type Deno.Addr, which looks like this:

// in the Deno namespace

type Addr = NetAddr | UnixAddr;
```
<p><strong>This is where it becomes complicated.</strong> <code>Deno.Addr</code> is a discriminated union of <code>Deno.NetAddr</code> and <code>Deno.UnixAddr</code> (which means that it could be either one), and the property <code>transport</code> is used to discriminate between the two.</p>
<pre class="lang-ts prettyprint-override"><code>// in the Deno namespace

interface NetAddr {
  hostname: string;
  port: number;
  transport: "tcp" | "udp";
}

interface UnixAddr {
  path: string;
  transport: "unix" | "unixpacket";
}
</code>```

A net address has hostname property (the value of which would be the IP address) and a port property, while a unix address has a path property.

The listener which is created internally to support the server is actually only listening on TCP, so I think it's safe to assume that the remote address will be a net address. However, because the type signature of the Handler callback parameter in the serve function doesn't make this explicit (although it should!), TypeScript doesn't know that.

So, it's left up to you as the programmer to make sure that the address is actually a net address before you can access properties that would be on a net address (instead of a unix address) in a type-safe way. That's where the type assertion function assertIsNetAddr comes into play. (A type assertion performs a runtime test which results in a "guarantee" of a condition to the compiler: by throwing an exception if the condition can't be guaranteed.) Because you as the programmer already know more than the TypeScript compiler (that the address is on TCP and will be a net address), you can assert that the address is indeed a net address. Then the compiler will allow you use the address as a net address.

If you want to do something besides throwing an Error in the case that the address is not a net address: instead of an assertion function, you can use a type predicate as a condition in your code.

Here is a link to the TypeScript Playground where I've created a playground with the types used in my example, so you can explore/experiment.

Finally, (this is not type-safe) if you just want to use the value without the checks (because you've done your research and are confident that you will never handle a non-TCP connection, you can simply use a type assertion:

const handler: Handler = (request, connInfo) => {
  const {hostname, port} = connInfo.remoteAddr as Deno.NetAddr;
  const message = `You connected from the following address: ${hostname}`;
  return new Response(message);
};
```

Title: Get remote client IP address in Deno

Body:
How to I get the IP address of the client in Deno?

I have created a test server using the standard http library but I can't figure out a way to extract client's IP.
I need that as a security feature for preventing multiple submissions.

In NodeJS/Express there is an ip property of the request object that does the same.
req.ip gives the thing I want in Express but what is it's equivalent in Deno?

My code is:

import { serve } from "https://deno.land/std@0.125.0/http/server.ts";

serve(
    (req) => {
        console.log(/* the client IP */);
        return new Response("hello");
    },
    { port: 8080 }
);

Is there any other work-around to prevent multiple access from the same device?

Thanks

Body:
To do this in a type-safe way is a little complicated because of the way that serve is typed. First, I'll show you an example of how to do it, then I'll explain the types afterward.

Example

example.ts:

import {
  serve,
  type ConnInfo,
  type Handler,
  type ServeInit,
} from 'https://deno.land/std@0.125.0/http/server.ts';

function assertIsNetAddr (addr: Deno.Addr): asserts addr is Deno.NetAddr {
  if (!['tcp', 'udp'].includes(addr.transport)) {
    throw new Error('Not a network address');
  }
}

function getRemoteAddress (connInfo: ConnInfo): Deno.NetAddr {
  assertIsNetAddr(connInfo.remoteAddr);
  return connInfo.remoteAddr;
}

const handler: Handler = (request, connInfo) => {
  const {hostname, port} = getRemoteAddress(connInfo);
  const message = `You connected from the following address: ${hostname}`;
  return new Response(message);
};

const init: ServeInit = {port: 8080};

serve(handler, init);
console.log(`Listening on port ${init.port}...\nUse ctrl+c to stop`);

Types

Looking at the documentation for the serve function, you can see that it accepts two parameters: a callback of type Handler, and some options of type ServeInit:

async function serve(handler: Handler, options?: ServeInit): Promise<void>;

The Handler callback accepts two parameters: a Request, and an object of type ConnInfo:

type Handler = (request: Request, connInfo: ConnInfo) => Response | Promise<Response>;

ConnInfo looks like this:

interface ConnInfo {
  readonly localAddr: Deno.Addr;
  readonly remoteAddr: Deno.Addr;
}

The part that should have the remote IP address (technically, it's the remote hostname, but it's very likely to be an IP address unless you have configured custom DNS settings in your server environment) is the object at connInfo.remoteAddr, which (you can see above) is of type Deno.Addr, which looks like this:

// in the Deno namespace

type Addr = NetAddr | UnixAddr;

This is where it becomes complicated. Deno.Addr is a discriminated union of Deno.NetAddr and Deno.UnixAddr (which means that it could be either one), and the property transport is used to discriminate between the two.

// in the Deno namespace

interface NetAddr {
  hostname: string;
  port: number;
  transport: "tcp" | "udp";
}

interface UnixAddr {
  path: string;
  transport: "unix" | "unixpacket";
}

A net address has hostname property (the value of which would be the IP address) and a port property, while a unix address has a path property.

The listener which is created internally to support the server is actually only listening on TCP, so I think it's safe to assume that the remote address will be a net address. However, because the type signature of the Handler callback parameter in the serve function doesn't make this explicit (although it should!), TypeScript doesn't know that.

So, it's left up to you as the programmer to make sure that the address is actually a net address before you can access properties that would be on a net address (instead of a unix address) in a type-safe way. That's where the type assertion function assertIsNetAddr comes into play. (A type assertion performs a runtime test which results in a "guarantee" of a condition to the compiler: by throwing an exception if the condition can't be guaranteed.) Because you as the programmer already know more than the TypeScript compiler (that the address is on TCP and will be a net address), you can assert that the address is indeed a net address. Then the compiler will allow you use the address as a net address.

If you want to do something besides throwing an Error in the case that the address is not a net address: instead of an assertion function, you can use a type predicate as a condition in your code.

<a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/PTAEBUE8AcFMGdQDMBOB7AtqAIrAdmqAG4CMAdCQBxkBMAUHgIYYLSMDGsO+hA3naFCwAHtDQoALqAkwuAQQAmClKAC8oAHKwJi5aAA+oAKp4AlsN0oA3HQFDR4qabwTYKJBy4AZU-Fd4AeWgJUzQ8RH5BQQALND8mFgB+AC5QPxRnAHMbKNAxSVS8AFcMACM3HNAAX1tBEXynFzcPTk1tS1BIqNj45lhU9KzKwQbCkvLrO0EJFEZw0dAAIgl2aEWDJaKFNcqau3rHUGdXd09jMwslFS6RxglogZmhqelZ+cdUxaKL9cMvi7Y7AA1tpFrs6HsQBBZIhUJhQNEJBJoPBkiAFDwyAAbOYKYB+BQAAQADBQaABWMjE4CI5H4txENxkCTwOjHZpnADCYTwAEk8Eg+HYULBGAowljIKAsWh2IwsZZUrgCGRLJURWKJVKRRg0K5FdwVWqIbYZHBQAAJXFYtxqUAAChFAEciggJKkAEqwF1ugA0oHYPP5gtS3LwfIFaAAlGoAHygL3wMThLiGAAK6AwvlgAB5E8n4LBYzY2U1Tq0AMoM2D80xSET+BSINOMSSmeU55VoMg+Pz4IIhMLweNdMIAURQ6BQKQdbinqW+QIIAHc8DHVPH80PU6AM5hs3nWNvi3Z4KZMkwsTO5KVHBXz5ebHsMewcSLkN92IO8Glq-botabipFaeAKDaKD+mgwShOEM5VigjK1hIUapHuWaFjmRBoKYCgnrYIAEYRYAiMw0A2syrJ0FCpgYA0nRUWAgiFghsC+gxURmlwYYRoKbFQtMsiWoBEHsQJ5rwYhZgSHxYBVMgmagAA5LSKJosAGIqjioH4hIRKkiQFJUjSSLQPSLEoBRiklkgn7fqAjDwMxEi8vAWg6FcDpisoSqYpYKH2Y5bgsvZHm+Ia3ZuR0XSmEgDoAIQANqKSs0CKf6ilbKlAC6ZDOK+WwIPaXkWTMcxJo4UYxjc0jROgy6gHgsD1ROU72opGh6vZDXaMu4hAiFygIPAilRuCew2XgX4waAmTaF6ur6lcQ0OoG4bBmgoZBpG-ldmQkUeV0q08d2Op6rAaqgFC0RuKxNVcJxRyouFqpXLUAVOS5+3KPaR3rWQp2Lcoo2XWA9z3YJDlOdNYVwO44gsAob3UbFYPvUF03Lg5DWdSw0n2T+LXiKAvVFFiCgIowjKgOU+A1XVeBsYIULwIQMXE1wGCMCCRxSPcYUeCgyTCtoRQoD+v2Rv9sALedVxWCDCI3f6qMPb4Pkql9KAmnQq1+BToHgcBwl2o63qun4-oS4K64jnYutSLwPQSAkt0NHJ6izRI81nZYQ0-Vt1uVPboAsI5jCzXaAAGACaaBFAGPKwF+sDk3CWCo4KWIysuWQDSKjmpAAJI7cTO30VSR+qIti919Vbim9qh-A4ewKNEIlsHzh1qkEk1lJdq8AslDEsPVQlsxjL-sJ-pd8hNi62g5Eypk9qR72-i52EeSHMXs9kG7ZCHwAOngRiFgGMxYgA1Ow0iEH4UGR23QA" rel="noreferrer">Here is a link to the TypeScript Playground where I've created a playground with the types used in my example, so you can explore/experiment.

Finally, (this is not type-safe) if you just want to use the value without the checks (because you've done your research and are confident that you will never handle a non-TCP connection, you can simply use a type assertion:

const handler: Handler = (request, connInfo) => {
  const {hostname, port} = connInfo.remoteAddr as Deno.NetAddr;
  const message = `You connected from the following address: ${hostname}`;
  return new Response(message);
};


问:
Gstreamer video latency first image
i have take the example 4 of gstreamer link and adapt for recieve a video stream rtsp from a camera. I have add these changes:

```<code>  g_object_set(data->pipeline,"latency",0,NULL);
  g_object_set(data->pipeline,"autovideosink", NULL);
  g_object_set (data->pipeline, "ring-buffer-max-size", (guint64) 1024 * 50, NULL);
</code>```

at the function gst_native_set_uri in the file tutorial-4.c for reduce the video latency.
My problem is that for view the video stream the first time i have to wait 2-3sec when i press the start button. There is a way to reduce this time?

Thanks

答:
You may try adding this callback function before app_function:

```<code>static void source_setup (GstElement *pipeline, GstElement *source, void* unused_data) {
    gchar* source_path = gst_object_get_path_string(GST_OBJECT_CAST(source));
    if (!strcmp(source_path, "/GstPlayBin:playbin0/GstURIDecodeBin:uridecodebin0/GstRTSPSrc:source")) {
        g_object_set(GST_OBJECT_CAST(source), "latency", 0, NULL);
    }
    g_free(source_path);
}
</code>```

And in app_function, just after pipeline creation add:

```<code>g_signal_connect (data->pipeline, "source-setup", G_CALLBACK (source_setup), NULL);
</code>```

When a source will be created, this callback would set its latency to 0 if the path matches playbin0/uridecodebin0/rtspsrc0 that should be ok for your case. This might be refined for more complex cases, though. Not tested with java.

Title: Gstreamer video latency first image

Body:
i have take the example 4 of gstreamer link and adapt for recieve a video stream rtsp from a camera. I have add these changes:

  g_object_set(data->pipeline,"latency",0,NULL);
  g_object_set(data->pipeline,"autovideosink", NULL);
  g_object_set (data->pipeline, "ring-buffer-max-size", (guint64) 1024 * 50, NULL);

at the function gst_native_set_uri in the file tutorial-4.c for reduce the video latency.
My problem is that for view the video stream the first time i have to wait 2-3sec when i press the start button. There is a way to reduce this time?

Thanks

Body:
You may try adding this callback function before app_function:

static void source_setup (GstElement *pipeline, GstElement *source, void* unused_data) {
    gchar* source_path = gst_object_get_path_string(GST_OBJECT_CAST(source));
    if (!strcmp(source_path, "/GstPlayBin:playbin0/GstURIDecodeBin:uridecodebin0/GstRTSPSrc:source")) {
        g_object_set(GST_OBJECT_CAST(source), "latency", 0, NULL);
    }
    g_free(source_path);
}

And in app_function, just after pipeline creation add:

g_signal_connect (data->pipeline, "source-setup", G_CALLBACK (source_setup), NULL);

When a source will be created, this callback would set its latency to 0 if the path matches playbin0/uridecodebin0/rtspsrc0 that should be ok for your case. This might be refined for more complex cases, though. Not tested with java.


问:
Compare two polars DataFrames for equality
How do I compare two polars DataFrames for value equality? It appears that == is only true if the two tables are the same object:

import polars as pl
pl.DataFrame({"x": [1,2,3]}) == pl.DataFrame({"x": [1,2,3]})  # False
```

答:
It's the frame_equal method of DataFrame:

import polars as pl
pl.DataFrame({"x": [1,2,3]}).frame_equal(pl.DataFrame({"x": [1,2,3]}))  # True
```


问:
rotate 3d point cloud to offset angle of floor plane given vNormal and floor point
I'm working with kinect and ofxopeni. I have a point cloud in real world coordinates but I need rotate those points to offset the tilt of the camera. The floor plane should give me all the information I need but I can't work out how to calculate the axis and angle of rotation.

my initial idea was...

```<code>ofVec3f target_normal(0,1,0);
ofVec3f vNormal; //set this from Xn3DPlane floorPlane (not shown here)
ofVec3f ptPoint; //as above

float rot_angle = target_normal.angle(vNormal);

for(int i = 0; i < numPoints; i++){

   cloudPoints[i].rotate(rot_angle, vNormal, ptPoint); //align my points to normal is (0 1 0)

}
</code>```

This it seems was too simplistic by far. I've been fishing through various articles and can see that it most probably involves a quarterion or rotation matrix but I can't work out where to start. I'd be really grateful for any pointers to relevant articles or what is the best technique to get an axis and angle of rotation ? I'm imagining it can be done quite easily using ofQuarterion or an openni function but I can't work out how to implement.

best

Simon

答:
I've never used ofxopeni, but this is the best mathematical explanation I can give.

You can rotate any set of data from one axis set to another using a TBN matrix,(tangent, bitangent, normal), where T B and N are your new set of axis. So, you already have the data for the normal, but you need to find a tangent. I'm not sure if your Xn3DPlane provides a tangent, but if it does, use that.

The bitangent is given by the cross-product of the normal and the tangent:

```<code> B = T x N
</code>```

A TBN looks like this:

```<code>TBN = { Tx ,Ty ,Tz,
        Bx, By, Bz,
        Nx, Ny, Nz }
</code>```

This will rotate your data on a new set of axis, but your plane also has an origin point, so we through in a translation:

```<code>A = {1 , 0 , 0, 0,    { Tx , Ty , Tz , 0,
     0,  1,  0, 0,      Bx , By , Bz , 0,
     0,  0,  1, 0,  x   Nx , Ny , Nz , 0,
     -Px,-Py,-Pz,1}      0 ,  0 ,  0 , 1}

// The multiply the vertex, v, to change it's coordinate system.
v = v * A
</code>```

If you can get things to this stage, you can transform all your points to the new coordinate system. One thing to note, the normal is now aligned with the z axis, if you want it to be aligned with the y, swap N and B in the TBN matrix.

EDIT: Final matrix calculation was slightly wrong. Fixed.

TBN calculation.

ContentLicense: CC BY-SA 3.0

Body:
I'm working with kinect and ofxopeni. I have a point cloud in real world coordinates but I need rotate those points to offset the tilt of the camera. The floor plane should give me all the information I need but I can't work out how to calculate the axis and angle of rotation.

my initial idea was...

ofVec3f target_normal(0,1,0);
ofVec3f vNormal; //set this from Xn3DPlane floorPlane (not shown here)
ofVec3f ptPoint; //as above

float rot_angle = target_normal.angle(vNormal);

for(int i = 0; i < numPoints; i++){

   cloudPoints[i].rotate(rot_angle, vNormal, ptPoint); //align my points to normal is (0 1 0)

}

This it seems was too simplistic by far. I've been fishing through various articles and can see that it most probably involves a quarterion or rotation matrix but I can't work out where to start. I'd be really grateful for any pointers to relevant articles or what is the best technique to get an axis and angle of rotation ? I'm imagining it can be done quite easily using ofQuarterion or an openni function but I can't work out how to implement.

best

Simon

Body:
I've never used ofxopeni, but this is the best mathematical explanation I can give.

You can rotate any set of data from one axis set to another using a TBN matrix,(tangent, bitangent, normal), where T B and N are your new set of axis. So, you already have the data for the normal, but you need to find a tangent. I'm not sure if your Xn3DPlane provides a tangent, but if it does, use that.

The bitangent is given by the cross-product of the normal and the tangent:

 B = T x N

A TBN looks like this:

TBN = { Tx ,Ty ,Tz,
        Bx, By, Bz,
        Nx, Ny, Nz }

This will rotate your data on a new set of axis, but your plane also has an origin point, so we through in a translation:

A = {1 , 0 , 0, 0,    { Tx , Ty , Tz , 0,
     0,  1,  0, 0,      Bx , By , Bz , 0,
     0,  0,  1, 0,  x   Nx , Ny , Nz , 0,
     -Px,-Py,-Pz,1}      0 ,  0 ,  0 , 1}

// The multiply the vertex, v, to change it's coordinate system.
v = v * A

If you can get things to this stage, you can transform all your points to the new coordinate system. One thing to note, the normal is now aligned with the z axis, if you want it to be aligned with the y, swap N and B in the TBN matrix.

EDIT: Final matrix calculation was slightly wrong. Fixed.

TBN calculation.


问:
web.config issues when migrating old .net 4.6.1 web api to .net 6
We have a legacy web api project developed years ago, it is supposed to be consumed by other internal projects (so not something to be exposed by users over Internet).

The prject was developed in .net 4.6.1 and I am looking at moving it to .net 6. By reading the code and web.config, I got confused with these:

Is it acceptable or best practice to keep on using web.config in .net 6 for these settings or it is better to do in other places? (seems I can't type web.config in stackoverflow and have to make a screenshot)

In our web.config, we have this: <httpCookies httpOnlyCookies="true" requireSSL="true" />

For this web api, we just send some response back and I can't think a place that we use cookie. For authentication, as this web api is consumed by other internal products, we just authenticate the bear token each request sent with the identity server. So is this line really needed? I can't find an equivalent line in .net 6's web.config

答:
There are different ways on specifying application settings in .NET 6, depending on what kind of setting it is and how you want to structure your project. As Marc says the most common application configuration file for .NET Core is that I have seen is: appSettings.json.
You might want to configure some settings directly in your Program.cs and other settings (especially settings that need to be transformed between environments) could be in a transformable settings file like appSettings.json or lauchSettings.json. Read more about configuration in .NET 6 here.
To conclude I would say that it is not best practice to keep the web.config but rather to extract the configuration to the place you see fit. If you don't host you app on a server that needs web.config to run then remove it.

This is a bit harder to answer. If you don't think you need this setting then you can try to omit it when you migrate your application to .NET 6. If you have multiple environments you should test your application (the .NET 6 version) in a non production environment and then you will get your answer if you need to configure that setting or not in the migrated application.

I wish you good luck in your migration journey! :)


问:
How can I remove all the tags in a beautiful object without remove specific tags like  or ?
Given the following html, how can I remove all the tags, except stylistic tags, like  or , in BeautifulSoup?

A. Gilad Kusne, Heshan Yu, Changming Wu, Huairuo Zhang, Jason Hattrick-Simpers, Brian
DeCost, Suchismita Sarker, Corey Oses, Cormac Toher, Stefano Curtarolo, Albert V. Davydov,
Ritesh Agarwal, Leonid A. Bendersky, Mo Li, Apurva Mehta, Ichiro Takeuchi. On-the-fly
closed-loop materials discovery via Bayesian active learning. Nature Communications, 2020; 11 (1) DOI: 10.1038/s41467-020-19597-w

```

I know I could use regex to remove specific tags, but is there any elegant way to remove some tags while excluding others in BeautifulSoup?

答:
Try this:

import re
from bs4 import BeautifulSoup as bs

html = """

A. Gilad Kusne, Heshan Yu, Changming Wu, Huairuo Zhang, Jason
Hattrick-Simpers, Brian DeCost, Suchismita Sarker, Corey Oses, Cormac Toher,
Stefano Curtarolo, Albert V. Davydov, Ritesh Agarwal, Leonid A. Bendersky,
Mo Li, Apurva Mehta, Ichiro Takeuchi. On-the-fly closed-loop
materials discovery via Bayesian active learning.
Nature Communications, 2020; 11 (1) DOI:
10.1038/s41467-020-19597-w

"""
soup = bs(html, features='xml')
tags = [tag.name for tag in soup.find_all(True) if tag.name not in ['strong', 'em']]
for tag in tags:
    html = re.sub(f'</?{tag}[^>]*>', '', html)
print(html)
```
<p>The output:</p>
<pre class="lang-sh prettyprint-override"><code>A. Gilad Kusne, Heshan Yu, Changming Wu, Huairuo Zhang, Jason Hattrick-Simpers,
Brian DeCost, Suchismita Sarker, Corey Oses, Cormac Toher, Stefano Curtarolo,
Albert V. Davydov, Ritesh Agarwal, Leonid A. Bendersky, Mo Li, Apurva Mehta,
Ichiro Takeuchi. <strong>On-the-fly closed-loop materials discovery
via Bayesian active learning</strong>. <em>Nature Communications</em>,
2020; 11 (1) DOI: 10.1038/s41467-020-19597-w
</code>```

Title: How can I remove all the tags in a beautiful object without remove specific tags like <strong> or <em>?

Body:
Given the following html, how can I remove all the tags, except stylistic tags, like  or , in BeautifulSoup?

A. Gilad Kusne, Heshan Yu, Changming Wu, Huairuo Zhang, Jason Hattrick-Simpers, Brian
DeCost, Suchismita Sarker, Corey Oses, Cormac Toher, Stefano Curtarolo, Albert V. Davydov,
Ritesh Agarwal, Leonid A. Bendersky, Mo Li, Apurva Mehta, Ichiro Takeuchi. On-the-fly
closed-loop materials discovery via Bayesian active learning. Nature Communications, 2020; 11 (1) DOI: 10.1038/s41467-020-19597-w

I know I could use regex to remove specific tags, but is there any elegant way to remove some tags while excluding others in BeautifulSoup?

Body:
Try this:

import re
from bs4 import BeautifulSoup as bs

html = """<ol class="journal">
    <li>A. Gilad Kusne, Heshan Yu, Changming Wu, Huairuo Zhang, Jason
Hattrick-Simpers, Brian DeCost, Suchismita Sarker, Corey Oses, Cormac Toher,
Stefano Curtarolo, Albert V. Davydov, Ritesh Agarwal, Leonid A. Bendersky,
Mo Li, Apurva Mehta, Ichiro Takeuchi. <strong>On-the-fly closed-loop
materials discovery via Bayesian active learning</strong>.
<em>Nature Communications</em>, 2020; 11 (1) DOI:
<a href="http://dx.doi.org/10.1038/s41467-020-19597-w" rel="nofollow"
target="_blank">10.1038/s41467-020-19597-w</a>
    </li>
    </ol>"""
soup = bs(html, features='xml')
tags = [tag.name for tag in soup.find_all(True) if tag.name not in ['strong', 'em']]
for tag in tags:
    html = re.sub(f'</?{tag}[^>]*>', '', html)
print(html)

The output:

A. Gilad Kusne, Heshan Yu, Changming Wu, Huairuo Zhang, Jason Hattrick-Simpers,
Brian DeCost, Suchismita Sarker, Corey Oses, Cormac Toher, Stefano Curtarolo,
Albert V. Davydov, Ritesh Agarwal, Leonid A. Bendersky, Mo Li, Apurva Mehta,
Ichiro Takeuchi. <strong>On-the-fly closed-loop materials discovery
via Bayesian active learning</strong>. <em>Nature Communications</em>,
2020; 11 (1) DOI: 10.1038/s41467-020-19597-w


问:
html does not respect the font-family set in a style
I have reduced my problem to a trivial example:

<!DOCTYPE html>

    <meta charset="utf-8" />

     a simple text w

 a simple h1 text w

 a simple h2 text w

```

Which I would expect to produce three lines of sans-serif text. The web inspector indicates that all three lines should be sans-serif.

Tested on Chromium and Firefox, I get three lines of text, one sans-serif, and two more, for h1 and h2 in serif font:

What is the explanation of this behavior? What is my misunderstanding of the way font appearances are inherited and applied?

答:
Since you declared Times New Roman for both, the h1 and the h2 elements, they both render with this font.

And since the last definition in CSS has a higher order than the first one, the a elements inherits the style set for the body selector, which is: sans-serif.

This is not an issue, it is as expected.

If you would wrap the  element inside a (for example)

, you will see, that it will inherit the styles from its parent and displays as serif Times New Roman as well.

<!DOCTYPE html>

    <meta charset="utf-8" />

     a simple text w

 a simple h1 text w

 a simple h2 text w

         a simple text w

```

Body:
I have reduced my problem to a trivial example:

<!DOCTYPE html>

    <meta charset="utf-8" />

     a simple text w

 a simple h1 text w

 a simple h2 text w

Which I would expect to produce three lines of sans-serif text. The web inspector indicates that all three lines should be sans-serif.

Tested on Chromium and Firefox, I get three lines of text, one sans-serif, and two more, for h1 and h2 in serif font:

What is the explanation of this behavior? What is my misunderstanding of the way font appearances are inherited and applied?

Body:
Since you declared Times New Roman for both, the h1 and the h2 elements, they both render with this font.

And since the last definition in CSS has a higher order than the first one, the a elements inherits the style set for the body selector, which is: sans-serif.

This is not an issue, it is as expected.

If you would wrap the <a></a> element inside a (for example) <h3></h3>, you will see, that it will inherit the styles from its parent and displays as serif Times New Roman as well.

<!DOCTYPE html>
<html lang="en_US">

<head>
    <meta charset="utf-8" />
    <style>
        body,
        h1,
        h2,
        h3,
        h4,
        h5 {
            font-family: 'Times New Roman', sans-serif
        }

        body {
            font-size: 16px;
            font-family: sans-serif;
        }
    </style>
</head>

<body>
    <a> a simple text w </a>
    <h1> a simple h1 text w </h1>
    <h2> a simple h2 text w </h2>

    <h3>
        <a> a simple text w </a>
    </h3>
</body>

</html>


问:
Multiple controls with the same ID 'add0' were found. FindControl requires that controls have unique IDs
Previously Called: How to deal with dynamically created controls under load in aspx

in  response to a question below: the information required to determine which controls to restore is contained in a dedicated viewstate object.

I am dynamically creating controls in the codebehind page - these controls are all hooked up to click handlers so when a postback occurs I must re-create the previous set of controls, then clear the controls down and generate the new set of controls based on the previous click.

This is coded and working correctly under normal circumstances esentially as follows:

```<code>in Page_Load
if not postback generate default buttons
else if postback re-generate buttons that were shown on last page

in click_handler
Clear the dynamically generated buttons created in the Page_Load
generate new buttons based on the specific click being handled
</code>```

however when the server comes under load we start getting problems:

With 5 users per second we start getting the exception:
Multiple controls with the same ID 'add0' were found. FindControl requires that controls have unique IDs.

With 100 users per second we start getting the exception:
The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.

Once this occurs all subsequent requests get the same error and IIS has to be re-started.

What could be causeing this and how can I avoid it?  Do html requests possibly overwrite and interfere with each other when under load? do objects somehow hand around after a page unload in a manner that would allow the next page load to trip over them?

答:
How are you storing information about the controls you need to restore? If you are using ViewState or ControlState, then I don't see how load could affect things. That's how any of the composite controls do things.

I will say that I saw your second error while using the Infragistics UltraWebGrid, and never was able to track it down. From the call stack, it appeared that EnsureChildControls was being called during the Load phase (or maybe LoadViewState).

OwnerDisplayName: dice

ContentLicense: CC BY-SA 2.5

Body:
Previously Called: How to deal with dynamically created controls under load in aspx

in  response to a question below: the information required to determine which controls to restore is contained in a dedicated viewstate object.

I am dynamically creating controls in the codebehind page - these controls are all hooked up to click handlers so when a postback occurs I must re-create the previous set of controls, then clear the controls down and generate the new set of controls based on the previous click.

This is coded and working correctly under normal circumstances esentially as follows:

in Page_Load
if not postback generate default buttons
else if postback re-generate buttons that were shown on last page

in click_handler
Clear the dynamically generated buttons created in the Page_Load
generate new buttons based on the specific click being handled

however when the server comes under load we start getting problems:

With 5 users per second we start getting the exception:
Multiple controls with the same ID 'add0' were found. FindControl requires that controls have unique IDs.

With 100 users per second we start getting the exception:
The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.

Once this occurs all subsequent requests get the same error and IIS has to be re-started.

What could be causeing this and how can I avoid it?  Do html requests possibly overwrite and interfere with each other when under load? do objects somehow hand around after a page unload in a manner that would allow the next page load to trip over them?

LastEditorDisplayName: dice

OwnerDisplayName: John Saunders


问:
Error occured during running for loop in filter
Am using this belowenter code here code to apply filter and copying the filtered values in the next sheet it is working fine when i have multiple values to filter, when i put single value it is causing an error in the for loop "For Each x In arNames".Can anyone Please help me to get out this issue.Thanks in advance.</p>
```<code>Sub splittinggroupsheets()
Dim rng As Range, rngCopy As Range, x, arNames
Dim last As Long, sht As String, n As Long
sht = "Sheet1"

' filter on column A
With Sheets(sht)
.AutoFilterMode = False

last = .Cells(Rows.Count, "A").End(xlUp).Row
Set rng = .Range("A1:F" & last)
.Columns("AA:AA").Clear
.Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, _
CopyToRange:=.Range("AA1"), Unique:=True
last = .Cells(Rows.Count, "AA").End(xlUp).Row

' list of filter names
arNames = .Range("AA2:AA" & last).Value
.Columns("AA:AA").Clear
End With

Application.ScreenUpdating = False

' aply filter for each name
For Each x In arNames

With rng
.AutoFilter
.AutoFilter field:=1, Criteria1:=x
Set rngCopy = .SpecialCells(xlCellTypeVisible)
End With

Sheets.Add(after:=Sheets(Sheets.Count)).Name = x
rngCopy.Copy
ActiveSheet.Paste
ActiveSheet.Range("A1").Select
n = n + 1

Next x

' Turn off filter
Sheets(sht).AutoFilterMode = False
Sheets(sht).Activate

With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
'MsgBox n & " sheets created", vbInformation
End Sub
</code>```

答:
Single cells don't create an array so you have to do it explicitly.

        ' list of filter names
        If last = 2 Then
            ReDim arNames(1 To 1, 1 To 1)
            arNames(1, 1) = .Range("AA2").Value
        Else
            arNames = .Range("AA2:AA" & last).Value
        End If
```

Body:
Am using this belowenter code here code to apply filter and copying the filtered values in the next sheet it is working fine when i have multiple values to filter, when i put single value it is causing an error in the for loop "For Each x In arNames".Can anyone Please help me to get out this issue.Thanks in advance.

Sub splittinggroupsheets()
Dim rng As Range, rngCopy As Range, x, arNames
Dim last As Long, sht As String, n As Long
sht = "Sheet1"

' filter on column A
With Sheets(sht)
.AutoFilterMode = False

last = .Cells(Rows.Count, "A").End(xlUp).Row
Set rng = .Range("A1:F" & last)
.Columns("AA:AA").Clear
.Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, _
CopyToRange:=.Range("AA1"), Unique:=True
last = .Cells(Rows.Count, "AA").End(xlUp).Row

' list of filter names
arNames = .Range("AA2:AA" & last).Value
.Columns("AA:AA").Clear
End With

Application.ScreenUpdating = False

' aply filter for each name
For Each x In arNames

With rng
.AutoFilter
.AutoFilter field:=1, Criteria1:=x
Set rngCopy = .SpecialCells(xlCellTypeVisible)
End With

Sheets.Add(after:=Sheets(Sheets.Count)).Name = x
rngCopy.Copy
ActiveSheet.Paste
ActiveSheet.Range("A1").Select
n = n + 1

Next x

' Turn off filter
Sheets(sht).AutoFilterMode = False
Sheets(sht).Activate

With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
'MsgBox n & " sheets created", vbInformation
End Sub


答:
Something like this one:

```<code>library(tidyverse)
df |>
  mutate(voiceOrd = as.numeric(substring(Voice1, 3, 5))) |>
  arrange(voiceOrd) |>
  pivot_wider(names_from = Voice2,
              values_from = response, names_sort = TRUE) |>
  relocate(c("S010", "S011", "S012"), .after = "S09") |>
  arrange(subject, voiceOrd) |>
 select(-voiceOrd, -Spreadsheet)
#> # A tibble: 36 × 14
#>    subject Voice1   S01   S02   S03   S04   S05   S06   S07   S08   S09  S010
#>      <dbl> <chr>  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#>  1 5598758 S01        3     3    NA     9     6    NA    NA    NA    NA    NA
#>  2 5598758 S02       NA     1    NA     8     9     4     6    NA     6    NA
#>  3 5598758 S03        7     6     9    NA     3     1    NA    NA    NA     2
#>  4 5598758 S04       NA    NA     1     2    NA     9    NA    NA    NA     8
#>  5 5598758 S05       NA    NA    NA     9     1     7    NA     1     7    NA
#>  6 5598758 S06        1    NA    NA    NA    NA     5     2    NA    NA    NA
#>  7 5598758 S07        3    NA     3     1     8    NA     8     9    NA     3
#>  8 5598758 S08        7     8     3     1    NA     4    NA     1     6    NA
#>  9 5598758 S09        5    NA     6     8    NA     8     5    NA     1    NA
#> 10 5598758 S010       4     5    NA    NA     6     7    NA     5     4     7
#> # … with 26 more rows, and 2 more variables: S011 <dbl>, S012 <dbl>
</code>```

Created on 2022-02-06 by the reprex package (v2.0.1)

Title: How can I create a triangle of similarity judgements by multiple subjects from a data frame in R?

Body:
I have a dataframe containing similarity judgements made by some subjects, judging how similar two files are.
Here is the df:

>dput(df)
    structure(list(subject = c(5598758, 5598758, 5598758, 5598758,
5598758, 5598758, 5598758, 5598758, 5598758, 5598758, 5598758,
5598758, 5598758, 5598758, 5598758, 5598758, 5598758, 5598758,
5598758, 5598758, 5598758, 5598758, 5598758, 5598758, 5598758,
5598758, 5598758, 5598758, 5598758, 5598758, 5598758, 5598758,
5598758, 5598758, 5598758, 5598758, 5598758, 5598758, 5598758,
5598758, 5598758, 5598758, 5598758, 5598758, 5598758, 5598758,
5598758, 5598758, 5598758, 5598758, 5598758, 5598758, 5598758,
5598758, 5598758, 5598758, 5598758, 5598758, 5598758, 5598758,
5598758, 5598758, 5598758, 5598758, 5598758, 5598758, 5598758,
5598758, 5598758, 5598758, 5598758, 5598758, 5598758, 5598758,
5598758, 5598758, 5598758, 5598758, 5598778, 5598778, 5598778,
5598778, 5598778, 5598778, 5598778, 5598778, 5598778, 5598778,
5598778, 5598778, 5598778, 5598778, 5598778, 5598778, 5598778,
5598778, 5598778, 5598778, 5598778, 5598778, 5598778, 5598778,
5598778, 5598778, 5598778, 5598778, 5598778, 5598778, 5598778,
5598778, 5598778, 5598778, 5598778, 5598778, 5598778, 5598778,
5598778, 5598778, 5598778, 5598778, 5598778, 5598778, 5598778,
5598778, 5598778, 5598778, 5598778, 5598778, 5598778, 5598778,
5598778, 5598778, 5598778, 5598778, 5598778, 5598778, 5598778,
5598778, 5598778, 5598778, 5598778, 5598778, 5598778, 5598778,
5598778, 5598778, 5598778, 5598778, 5598778, 5598778, 5598778,
5598778, 5598778, 5598778, 5598778, 5598778, 5598928, 5598928,
5598928, 5598928, 5598928, 5598928, 5598928, 5598928, 5598928,
5598928, 5598928, 5598928, 5598928, 5598928, 5598928, 5598928,
5598928, 5598928, 5598928, 5598928, 5598928, 5598928, 5598928,
5598928, 5598928, 5598928, 5598928, 5598928, 5598928, 5598928,
5598928, 5598928, 5598928, 5598928, 5598928, 5598928, 5598928,
5598928, 5598928, 5598928, 5598928, 5598928, 5598928, 5598928,
5598928, 5598928, 5598928, 5598928, 5598928, 5598928, 5598928,
5598928, 5598928, 5598928, 5598928, 5598928, 5598928, 5598928,
5598928, 5598928, 5598928, 5598928, 5598928, 5598928, 5598928,
5598928, 5598928, 5598928, 5598928, 5598928, 5598928, 5598928,
5598928, 5598928, 5598928, 5598928, 5598928, 5598928), Voice1 = c("S01",
"S08", "S012", "S03", "S03", "S010", "S09", "S07", "S02", "S010",
"S03", "S01", "S05", "S012", "S08", "S011", "S07", "S05", "S06",
"S08", "S012", "S07", "S010", "S07", "S04", "S010", "S03", "S02",
"S010", "S012", "S05", "S08", "S06", "S03", "S09", "S05", "S03",
"S07", "S07", "S011", "S05", "S01", "S02", "S08", "S010", "S08",
"S011", "S010", "S08", "S04", "S02", "S06", "S04", "S09", "S02",
"S011", "S02", "S09", "S012", "S01", "S03", "S02", "S010", "S09",
"S09", "S011", "S05", "S012", "S06", "S01", "S08", "S08", "S04",
"S07", "S010", "S07", "S09", "S05", "S012", "S05", "S04", "S05",
"S06", "S012", "S011", "S09", "S08", "S08", "S07", "S02", "S07",
"S09", "S07", "S04", "S03", "S06", "S08", "S08", "S05", "S06",
"S011", "S010", "S01", "S08", "S010", "S07", "S010", "S012",
"S07", "S03", "S011", "S02", "S08", "S08", "S09", "S010", "S02",
"S07", "S012", "S03", "S010", "S02", "S05", "S01", "S02", "S09",
"S09", "S01", "S010", "S09", "S08", "S05", "S07", "S03", "S010",
"S011", "S05", "S010", "S01", "S01", "S03", "S012", "S03", "S010",
"S08", "S06", "S04", "S02", "S04", "S05", "S011", "S02", "S012",
"S07", "S09", "S03", "S03", "S012", "S05", "S09", "S011", "S02",
"S01", "S010", "S07", "S08", "S03", "S04", "S03", "S02", "S09",
"S04", "S05", "S010", "S010", "S08", "S08", "S01", "S012", "S09",
"S012", "S01", "S08", "S08", "S05", "S07", "S07", "S010", "S09",
"S06", "S011", "S09", "S010", "S07", "S01", "S04", "S06", "S05",
"S02", "S010", "S01", "S011", "S07", "S010", "S08", "S03", "S05",
"S06", "S08", "S04", "S08", "S09", "S02", "S02", "S010", "S012",
"S012", "S07", "S02", "S03", "S07", "S05", "S07", "S06", "S08",
"S09", "S012", "S03", "S02", "S011", "S03", "S010", "S011", "S05"
), Voice2 = c("S02", "S04", "S012", "S05", "S011", "S010", "S01",
"S011", "S09", "S06", "S01", "S012", "S011", "S07", "S012", "S01",
"S01", "S012", "S012", "S06", "S011", "S010", "S012", "S03",
"S03", "S09", "S03", "S06", "S01", "S03", "S08", "S011", "S07",
"S02", "S06", "S06", "S06", "S07", "S04", "S011", "S09", "S04",
"S02", "S02", "S011", "S03", "S09", "S08", "S08", "S06", "S011",
"S06", "S04", "S07", "S07", "S04", "S05", "S03", "S04", "S05",
"S010", "S04", "S05", "S04", "S012", "S06", "S04", "S02", "S01",
"S01", "S01", "S09", "S010", "S08", "S02", "S05", "S09", "S05",
"S07", "S011", "S06", "S08", "S06", "S011", "S011", "S01", "S03",
"S012", "S07", "S02", "S08", "S04", "S04", "S03", "S01", "S01",
"S011", "S04", "S05", "S07", "S06", "S01", "S01", "S01", "S09",
"S011", "S011", "S012", "S01", "S03", "S09", "S09", "S08", "S09",
"S012", "S012", "S07", "S010", "S02", "S05", "S06", "S05", "S04",
"S04", "S04", "S07", "S09", "S02", "S010", "S03", "S06", "S09",
"S03", "S010", "S05", "S04", "S012", "S08", "S012", "S05", "S06",
"S04", "S011", "S02", "S02", "S012", "S04", "S011", "S010", "S06",
"S01", "S06", "S03", "S05", "S06", "S02", "S03", "S04", "S08",
"S04", "S01", "S011", "S012", "S02", "S01", "S04", "S01", "S04",
"S06", "S05", "S012", "S03", "S011", "S012", "S06", "S012", "S09",
"S01", "S02", "S06", "S012", "S04", "S011", "S08", "S04", "S08",
"S05", "S08", "S09", "S06", "S09", "S03", "S011", "S07", "S02",
"S010", "S012", "S09", "S04", "S010", "S05", "S011", "S03", "S09",
"S06", "S010", "S05", "S01", "S02", "S06", "S01", "S07", "S09",
"S06", "S01", "S03", "S011", "S010", "S02", "S02", "S04", "S012",
"S011", "S07", "S03", "S01", "S07", "S05", "S07", "S06", "S011",
"S05", "S04", "S06"), response = c(3, 1, 9, 3, 3, 7, 5, 2, 6,
7, 7, 6, 5, 4, 2, 8, 3, 2, 3, 4, 4, 3, 2, 3, 1, 4, 9, 4, 4, 4,
1, 3, 2, 6, 8, 7, 1, 8, 1, 8, 7, 9, 1, 8, 7, 3, 5, 5, 1, 9, 8,
5, 2, 5, 6, 9, 9, 6, 9, 6, 2, 8, 6, 8, 7, 6, 9, 9, 1, 3, 7, 6,
8, 9, 5, 8, 1, 1, 9, 2, 9, 9, 1, 6, 1, 5, 3, 9, 1, 1, 7, 9, 8,
9, 6, 1, 8, 9, 1, 5, 6, 8, 1, 4, 4, 9, 3, 1, 9, 1, 3, 7, 1, 9,
9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 7, 1, 7, 1, 9, 3, 9, 9, 3, 9,
9, 9, 9, 4, 9, 3, 5, 3, 3, 7, 9, 1, 8, 4, 7, 9, 3, 8, 9, 9, 6,
1, 6, 7, 6, 7, 7, 3, 8, 5, 8, 7, 1, 6, 9, 2, 8, 7, 8, 3, 6, 4,
1, 7, 2, 1, 9, 3, 1, 9, 8, 9, 7, 1, 1, 4, 6, 2, 1, 8, 9, 9, 9,
6, 1, 8, 1, 6, 4, 3, 1, 1, 3, 5, 9, 9, 5, 7, 6, 4, 7, 3, 6, 1,
5, 3, 5, 7, 3, 1, 2, 4, 8, 8, 7, 5, 9, 9, 7), Spreadsheet = c("Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1", "Order1", "Order1", "Order1", "Order1", "Order1",
"Order1", "Order1")), row.names = c(NA, -234L), class = c("tbl_df",
"tbl", "data.frame"))

I want to create a similarity matrix triangle of the sort below (from a different data set):

# A tibble: 12 x 13
   subject   Voice      S01   S02   S03   S04   S05   S06   S07   S08   S09  S010  S011  S012
     <dbl>    <chr>    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1 5456381     S01       1    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA
 2 5456381     S02       8     1    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA
 3 5456381     S03       8     2     1    NA    NA    NA    NA    NA    NA    NA    NA    NA
 4 5456381     S04       7     9     7     1    NA    NA    NA    NA    NA    NA    NA    NA
 5 5456381     S05       8     9     9     7     1    NA    NA    NA    NA    NA    NA    NA
 6 5456381     S06       3     7     3     8     6     1    NA    NA    NA    NA    NA    NA
 7 5456381     S07       7     9     8     7     8     7     1    NA    NA    NA    NA    NA
 8 5456381     S08       7     4     2     9     9     3     9     1    NA    NA    NA    NA
 9 5456381     S09       1     4     9     8     8     2     4     4     1    NA    NA    NA
10 5456381     S010      6     5     2     8     8     6     4     2     5     1    NA    NA
11 5456381     S011      4     6     3     6     7     6     6     3     6     2     2    NA
12 5456381     S012      7     9     8     4     7     4     2     8     7     8     3     1

But I want to have several triangles of this sort stacked in the data frame by subject.

I have tried the following code:

tri<-order1%>%
  pivot_wider(names_from = Voice2,values_from=response, names_sort=TRUE)

which gave me the following:

# A tibble: 192 x 15
   subject Voice1 Spreadsheet   S01  S010  S011  S012   S02   S03   S04   S05   S06   S07   S08   S09
     <dbl> <chr>  <chr>       <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1 5598758 S01    Order1          3    NA    NA     6     3    NA     9     6    NA    NA    NA    NA
 2 5598758 S08    Order1          7    NA     3     2     8     3     1    NA     4    NA     1     6
 3 5598758 S012   Order1         NA    NA     4     9     9     4     9    NA    NA     4    NA    NA
 4 5598758 S03    Order1          7     2     3    NA     6     9    NA     3     1    NA    NA    NA
 5 5598758 S010   Order1          4     7     7     2     5    NA    NA     6     7    NA     5     4
 6 5598758 S09    Order1          5    NA    NA     7    NA     6     8    NA     8     5    NA     1
 7 5598758 S07    Order1          3     3     2    NA    NA     3     1     8    NA     8     9    NA
 8 5598758 S02    Order1         NA    NA     8    NA     1    NA     8     9     4     6    NA     6
 9 5598758 S05    Order1         NA    NA     5     2    NA    NA     9     1     7    NA     1     7
10 5598758 S011   Order1          8    NA     8    NA    NA    NA     9    NA     6    NA    NA     5
# ... with 182 more rows

How can I do this so that I have a lower triangle for each subject stacked in a data frame?

TIA!

Body:
Something like this one:

library(tidyverse)
df |>
  mutate(voiceOrd = as.numeric(substring(Voice1, 3, 5))) |>
  arrange(voiceOrd) |>
  pivot_wider(names_from = Voice2,
              values_from = response, names_sort = TRUE) |>
  relocate(c("S010", "S011", "S012"), .after = "S09") |>
  arrange(subject, voiceOrd) |>
 select(-voiceOrd, -Spreadsheet)
#> # A tibble: 36 × 14
#>    subject Voice1   S01   S02   S03   S04   S05   S06   S07   S08   S09  S010
#>      <dbl> <chr>  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#>  1 5598758 S01        3     3    NA     9     6    NA    NA    NA    NA    NA
#>  2 5598758 S02       NA     1    NA     8     9     4     6    NA     6    NA
#>  3 5598758 S03        7     6     9    NA     3     1    NA    NA    NA     2
#>  4 5598758 S04       NA    NA     1     2    NA     9    NA    NA    NA     8
#>  5 5598758 S05       NA    NA    NA     9     1     7    NA     1     7    NA
#>  6 5598758 S06        1    NA    NA    NA    NA     5     2    NA    NA    NA
#>  7 5598758 S07        3    NA     3     1     8    NA     8     9    NA     3
#>  8 5598758 S08        7     8     3     1    NA     4    NA     1     6    NA
#>  9 5598758 S09        5    NA     6     8    NA     8     5    NA     1    NA
#> 10 5598758 S010       4     5    NA    NA     6     7    NA     5     4     7
#> # … with 26 more rows, and 2 more variables: S011 <dbl>, S012 <dbl>

Created on 2022-02-06 by the reprex package (v2.0.1)


问:
Accesing superclass attribute during subclass construction in Python
Is it possible to access superclass's attributes during class construction?
Here's my code:

```<code>class A:
   x = 1

class B(A):
   x += 1   # <- error
</code>```

The increment line x += ... is not valid, because x is not defined at this moment. You may suggest doing it in __init__, but I need to initialize the values before the constructor and want to minimize the code.

The code x = A.x + 1 will not work in my case because the A is generated in run-time. So the real code for B looks like

```<code>class A:
  x: int

def class_gen(params):
  class SubA(A):
    x = 1
  return SubA

class B(class_gen(some_params)):
  x += 1
</code>```

I've found a weird workaround:
x = A.__subclasses__()[-1].x + 1 (indeed the last subclass of A will be the generated super), but it looks too dirty and unstable.

Another workaround is declaring the a 'stub' class variable:

```<code>...
_Stub = class_gen(some_params)
class B(_Stub):
  x = _Stub.x + 1
</code>```

but is it also looks urgly. Is there a better way for a perfectionist?

答:
There's no easy way to do this. Probably the best is to give your B class a metaclass that handles incrementing of the x attribute for you:

```<code>class XIncrementerMeta(type):
    def __new__(mcls, name, bases, namespace):
        namespace['x'] = bases[0].x + 1
        return super().__new__(mcls, name, bases, namespace)

class B(class_gen("some_params"), metaclass=XIncrementerMeta):
    pass

print(B.x) # prints 2
</code>```

If you need each B-like class to have its own kind of manipulation of the x value, you could put it in a classmethod and have an inherited metaclass call it. Or you could even have an __init_subclass__ method in A that calls methods to set the value on its subclasses:

```<code>class A:
    def __init_subclass__(cls):
        cls.set_X()

class SubA(A):
    @classmethod
    def set_X(cls):
        cls.x = 1

class B(SubA):
    @classmethod
    def set_X(cls):
        super().set_X()  # get SubA to set an initial value
        cls.x += 1       # then update it

print(B.x) # prints 2
</code>```

Body:
Is it possible to access superclass's attributes during class construction?
Here's my code:

class A:
   x = 1

class B(A):
   x += 1   # <- error

The increment line x += ... is not valid, because x is not defined at this moment. You may suggest doing it in __init__, but I need to initialize the values before the constructor and want to minimize the code.

The code x = A.x + 1 will not work in my case because the A is generated in run-time. So the real code for B looks like

class A:
  x: int

def class_gen(params):
  class SubA(A):
    x = 1
  return SubA

class B(class_gen(some_params)):
  x += 1

I've found a weird workaround:
x = A.__subclasses__()[-1].x + 1 (indeed the last subclass of A will be the generated super), but it looks too dirty and unstable.

Another workaround is declaring the a 'stub' class variable:

...
_Stub = class_gen(some_params)
class B(_Stub):
  x = _Stub.x + 1

but is it also looks urgly. Is there a better way for a perfectionist?

Body:
There's no easy way to do this. Probably the best is to give your B class a metaclass that handles incrementing of the x attribute for you:

class XIncrementerMeta(type):
    def __new__(mcls, name, bases, namespace):
        namespace['x'] = bases[0].x + 1
        return super().__new__(mcls, name, bases, namespace)

class B(class_gen("some_params"), metaclass=XIncrementerMeta):
    pass

print(B.x) # prints 2

If you need each B-like class to have its own kind of manipulation of the x value, you could put it in a classmethod and have an inherited metaclass call it. Or you could even have an __init_subclass__ method in A that calls methods to set the value on its subclasses:

class A:
    def __init_subclass__(cls):
        cls.set_X()

class SubA(A):
    @classmethod
    def set_X(cls):
        cls.x = 1

class B(SubA):
    @classmethod
    def set_X(cls):
        super().set_X()  # get SubA to set an initial value
        cls.x += 1       # then update it

print(B.x) # prints 2


问:
ORA-02396: exceeded maximum idle time, please connect again error
I have a ASP.Net MVC Application connecting to Oracle DB. I am using LINQ in my controller to pull data from Oracle DB.

If that page is loaded, after several minutes if its idle, it gives the above error.

Now I can't ask my DBA to increase the idle time. In my research I saw mention of Pooling in Web.config file. My understanding is that, because of Pooling, some of these connections are still active. I have removed this portion

Min Pool Size=1;Max Pool Size=20;Pooling=true

Do I have to explicitly say in my Web.config:

Pooling=false

I also have in my Controller, Dispose function as below but that doesn't help:

```<code>protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }

            base.Dispose(disposing);
        }
</code>```

Please help.

答:
Here's an approach. When you resume using your connection after a potential idle delay, such as waiting for an incoming request, do this:

Run some cheap no-op query like SELECT 1 FROM DUAL;

If you get the error you mentioned, make sure the connection is completely closed, then open a new one.

Use the connection as normal.

This is a bit of a hack compared to organizing your connection pool properly, but it's better than opening up a new connection every time you need one.

Body:
I have a ASP.Net MVC Application connecting to Oracle DB. I am using LINQ in my controller to pull data from Oracle DB.

If that page is loaded, after several minutes if its idle, it gives the above error.

Now I can't ask my DBA to increase the idle time. In my research I saw mention of Pooling in Web.config file. My understanding is that, because of Pooling, some of these connections are still active. I have removed this portion

Min Pool Size=1;Max Pool Size=20;Pooling=true

Do I have to explicitly say in my Web.config:

Pooling=false

I also have in my Controller, Dispose function as below but that doesn't help:

protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }

            base.Dispose(disposing);
        }

Please help.


问:
A resource with the ID already exists - to be managed via Terraform this resource needs to be imported into the State
I would not normally ask a question like this, however I feel stuck and I do not want to hack things, but rather take the time to understand. I am new to terraform and trying to learn it, a simple task that I have set myself is to create a SQL server.

My Environment

I have some resource groups created before, anytime I try to use the same name, I get the error.

```<code> Error: A resource with the ID "/subscriptions/000000-0000-0000-0000-00000000005/resourceGroups/tf_learning" already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_resource_group" for more information.
</code>```

Now, you look at the error and after 2 days of google research, i followed the steps here.
Using Terraform to import existing resources on Azure
and https://gmusumeci.medium.com/how-to-import-an-existing-azure-resource-in-terraform-6d585f93ea02 and Terraform resource with the ID already exists

I create a file called existing_statee.tf with the content below.

```<code>resource "azurerm_resource_group" "tf_learning" {
}
</code>```

Ran

```<code>terraform import azurerm_resource_group.tf_learning /subscriptions/000000-0000-0000-0000-00000000005/resourceGroups/tf_learningterraform import azurerm_resource_group.tf_learning /subscriptions/000000-0000-0000-0000-00000000005/resourceGroups/tf_learning
</code>```

I edited the file again and saved it.

```<code>resource "azurerm_resource_group" "tf_learning" {
  # (resource arguments)
  name = "tf_learning"
  location = "UK South"
}
</code>```

Then ran the following.

```<code>terraform init
terraform plan
terraform apply
</code>```

To my surprise I am still getting the error.

```<code> Error: A resource with the ID "/subscriptions/00000-00000-0000-0000-00000000000/resourceGroups/tf_learning" already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_resource_group" for more information.
│
│   with azurerm_resource_group.RG-Terraform,
│   on main.tf line 1, in resource "azurerm_resource_group" "RG-Terraform":
│    1: resource "azurerm_resource_group" "RG-Terraform" {
</code>```

My tf.main file.

```<code>resource "azurerm_resource_group" "RG-Terraform" {
  name     = var.resource-group-name
  location = var.my_location
}

resource "azurerm_sql_server" "test" {
  name                         = var.my_dev_server
  resource_group_name          = azurerm_resource_group.RG-Terraform.name
  location                     = azurerm_resource_group.RG-Terraform.location
  version                      = var.my_dev_sql_version
  administrator_login          = var.my_dev_sql_login
  administrator_login_password = "change_me"
}

resource "azurerm_sql_database" "test" {
  name                = var.my_dev_sql_database
  resource_group_name = azurerm_resource_group.RG-Terraform.name
  location            = azurerm_resource_group.RG-Terraform.location
  server_name         = azurerm_sql_server.test.name
  edition                          = var.my_dev_sql_database_sku
  requested_service_objective_name = var.my_dev_sql_database_objective

  tags = {
    environment = "dev_database_build"
  }
}
</code>```

variables.tf file

```<code>variable "resource-group-name" {
  default     = "tf_learning"
  description = "The prefix used for all resources in this example"
}

variable "app-service-name" {
  default     = "terraform-app-service"
  description = "The name of the Web App"
}

variable "location" {
  default     = "UK South"
  description = "The Azure location where all resources in this example should be created"
}

variable "my_location" {
  type = string
  default = "UK South"
}

variable "my_dev_server"{
  type = string
  default = "test-server-test"
}

variable "my_dev_sql_login" {
  type = string
  default = "mylogin"
}

variable "my_dev_sql_version" {
  type = string
  default = "12.0"
}

variable "my_dev_sql_database" {
  type = string
  default = "dev_db"
}

variable "my_dev_sql_database_tag" {
  type = string
  default = "dev sql database from TF"
}

variable "my_dev_sql_database_sku" {
  type = string
  default = "Basic"
}

variable "my_dev_sql_database_objective" {
  type = string
  default = "Basic"
}
</code>```

I am lost as to what to do next, for now I will carry on researching.

答:
I would like to point out this, you have configured in existing_statee.tf after importing the state

```<code>resource "azurerm_resource_group" "tf_learning" {
   name = "tf_learning"
   location = "UK South"
}
</code>```

But in main.tf you also define again

```<code>resource "azurerm_resource_group" "RG-Terraform" {
  name     = var.resource-group-name
  location = var.my_location
}
variable "resource-group-name" {
  default     = "tf_learning"
  description = "The prefix used for all resources in this example"
}
variable "my_location" {
  type = string
  default = "UK South"
}
</code>```

Since you have already declared this resource in existing_statee.tf, maybe you should remove it from main.tf

Body:
I would not normally ask a question like this, however I feel stuck and I do not want to hack things, but rather take the time to understand. I am new to terraform and trying to learn it, a simple task that I have set myself is to create a SQL server.

My Environment

I have some resource groups created before, anytime I try to use the same name, I get the error.

 Error: A resource with the ID "/subscriptions/000000-0000-0000-0000-00000000005/resourceGroups/tf_learning" already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_resource_group" for more information.

Now, you look at the error and after 2 days of google research, i followed the steps here.
Using Terraform to import existing resources on Azure
and https://gmusumeci.medium.com/how-to-import-an-existing-azure-resource-in-terraform-6d585f93ea02 and Terraform resource with the ID already exists

I create a file called existing_statee.tf with the content below.

resource "azurerm_resource_group" "tf_learning" {
}

Ran

terraform import azurerm_resource_group.tf_learning /subscriptions/000000-0000-0000-0000-00000000005/resourceGroups/tf_learningterraform import azurerm_resource_group.tf_learning /subscriptions/000000-0000-0000-0000-00000000005/resourceGroups/tf_learning

I edited the file again and saved it.

resource "azurerm_resource_group" "tf_learning" {
  # (resource arguments)
  name = "tf_learning"
  location = "UK South"
}

Then ran the following.

terraform init
terraform plan
terraform apply

To my surprise I am still getting the error.

 Error: A resource with the ID "/subscriptions/00000-00000-0000-0000-00000000000/resourceGroups/tf_learning" already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_resource_group" for more information.
│
│   with azurerm_resource_group.RG-Terraform,
│   on main.tf line 1, in resource "azurerm_resource_group" "RG-Terraform":
│    1: resource "azurerm_resource_group" "RG-Terraform" {

My tf.main file.

resource "azurerm_resource_group" "RG-Terraform" {
  name     = var.resource-group-name
  location = var.my_location
}

resource "azurerm_sql_server" "test" {
  name                         = var.my_dev_server
  resource_group_name          = azurerm_resource_group.RG-Terraform.name
  location                     = azurerm_resource_group.RG-Terraform.location
  version                      = var.my_dev_sql_version
  administrator_login          = var.my_dev_sql_login
  administrator_login_password = "change_me"
}

resource "azurerm_sql_database" "test" {
  name                = var.my_dev_sql_database
  resource_group_name = azurerm_resource_group.RG-Terraform.name
  location            = azurerm_resource_group.RG-Terraform.location
  server_name         = azurerm_sql_server.test.name
  edition                          = var.my_dev_sql_database_sku
  requested_service_objective_name = var.my_dev_sql_database_objective

  tags = {
    environment = "dev_database_build"
  }
}

variables.tf file

variable "resource-group-name" {
  default     = "tf_learning"
  description = "The prefix used for all resources in this example"
}

variable "app-service-name" {
  default     = "terraform-app-service"
  description = "The name of the Web App"
}

variable "location" {
  default     = "UK South"
  description = "The Azure location where all resources in this example should be created"
}

variable "my_location" {
  type = string
  default = "UK South"
}

variable "my_dev_server"{
  type = string
  default = "test-server-test"
}

variable "my_dev_sql_login" {
  type = string
  default = "mylogin"
}

variable "my_dev_sql_version" {
  type = string
  default = "12.0"
}

variable "my_dev_sql_database" {
  type = string
  default = "dev_db"
}

variable "my_dev_sql_database_tag" {
  type = string
  default = "dev sql database from TF"
}

variable "my_dev_sql_database_sku" {
  type = string
  default = "Basic"
}

variable "my_dev_sql_database_objective" {
  type = string
  default = "Basic"
}

I am lost as to what to do next, for now I will carry on researching.

Body:
I would like to point out this, you have configured in existing_statee.tf after importing the state

resource "azurerm_resource_group" "tf_learning" {
   name = "tf_learning"
   location = "UK South"
}

But in main.tf you also define again

resource "azurerm_resource_group" "RG-Terraform" {
  name     = var.resource-group-name
  location = var.my_location
}
variable "resource-group-name" {
  default     = "tf_learning"
  description = "The prefix used for all resources in this example"
}
variable "my_location" {
  type = string
  default = "UK South"
}

Since you have already declared this resource in existing_statee.tf, maybe you should remove it from main.tf