问:
Error using SciPy: ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject
I'm trying to install SciPy using a bootstrap script to use it to calculate a new field in a dataframe, running Spark on AWS EMR.

Although the SciPy website states that only NumPy is needed, when I tried to install SciPy using pip, pip kept failing, complaining about missing software, until I ended up with this bootstrap script:

```<code>sudo yum install -y python3-devel
sudo pip3 install -U Cython
sudo pip3 install -U pybind11
sudo pip3 install -U pythran
sudo pip3 install -U numpy
sudo pip3 install -U scipy
</code>```

At this point, the bootstrap seems to be successful, but then at this line:

```<code>from scipy.stats import norm
</code>```

I get the following error:

```<code>ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject
</code>```

I tried --no-binary :all:, but that made no difference.

Any advice? Thanks!

Best, Oliver

Body:
I'm trying to install SciPy using a bootstrap script to use it to calculate a new field in a dataframe, running Spark on AWS EMR.

Although the SciPy website states that only NumPy is needed, when I tried to install SciPy using pip, pip kept failing, complaining about missing software, until I ended up with this bootstrap script:

sudo yum install -y python3-devel
sudo pip3 install -U Cython
sudo pip3 install -U pybind11
sudo pip3 install -U pythran
sudo pip3 install -U numpy
sudo pip3 install -U scipy

At this point, the bootstrap seems to be successful, but then at this line:

from scipy.stats import norm

I get the following error:

ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject

I tried --no-binary :all:, but that made no difference.

Any advice? Thanks!

Best, Oliver


来源: stackexchange

问:
How to connect to Redis server using DNS?
We have a requirement to have a globalized cache machine i.e. Redis to be running on one server and the docker services running on other servers need to be able to access it. So we have created a docker container in Ec2 instance A and all the other services are in Instance B & C. We have installed redis-cli IP on Instnace A & Instance B and it's working. But we have a requirement to have DNS instead of IP here. So we have configured the records in Bastian host in the below format.

```<code>
server {
        listen 80 ;
        server_name devtest-redis.xyz.com;
        return 301 https://$server_name$request_uri ;
}
server {
        listen 443;
        server_name devtest-redis.xyz.com;
        ssl on;
        ssl_certificate /etc/letsencrypt/live/xyz.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/xyz.com/privkey.pem;
        ssl_session_timeout 5m;
        ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers "HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES";
        ssl_prefer_server_ciphers on;
        add_header 'Access-Control-Allow-Origin' '*';
        location / {
                proxy_pass http://10.63.3.10:6379;
        }
   }
</code>```

But when we type redis-cli -h devtest-redis.xyz.com, I'm getting the below error. Even if I give  redis-cli -h IP:PORT , I get the same error. I'm missing something here or how can this be resolved?

```<code>Could not connect to Redis at https://devtest-redis.xyz.com:6379: Name or service not known
</code>```

ContentLicense: CC BY-SA 4.0

Body:
We have a requirement to have a globalized cache machine i.e. Redis to be running on one server and the docker services running on other servers need to be able to access it. So we have created a docker container in Ec2 instance A and all the other services are in Instance B & C. We have installed redis-cli IP on Instnace A & Instance B and it's working. But we have a requirement to have DNS instead of IP here. So we have configured the records in Bastian host in the below format.

server {
        listen 80 ;
        server_name devtest-redis.xyz.com;
        return 301 https://$server_name$request_uri ;
}
server {
        listen 443;
        server_name devtest-redis.xyz.com;
        ssl on;
        ssl_certificate /etc/letsencrypt/live/xyz.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/xyz.com/privkey.pem;
        ssl_session_timeout 5m;
        ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers "HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES";
        ssl_prefer_server_ciphers on;
        add_header 'Access-Control-Allow-Origin' '*';
        location / {
                proxy_pass http://10.63.3.10:6379;
        }
   }

But when we type redis-cli -h devtest-redis.xyz.com, I'm getting the below error. Even if I give  redis-cli -h IP:PORT , I get the same error. I'm missing something here or how can this be resolved?

Could not connect to Redis at https://devtest-redis.xyz.com:6379: Name or service not known


问:
Getting The bean 'authenticationManagerBuilder', defined in class path resource ... could not be registered
Im trying to implement authentication with Spring boot 3 like this :

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authz) -> authz

                .requestMatchers("/webjars/**", "/resources/**", "/css/**", "/images/**").permitAll().anyRequest()
                .authenticated()).formLogin((form) -> form.loginPage("/login").usernameParameter("email").permitAll())
                .httpBasic(withDefaults());
        return http.build();
    }

    @Bean
    public UserDetailsService UserDetailsService() {
        return new UserDetailsService();
    }

    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(UserDetailsService());
        authenticationProvider.setPasswordEncoder(passwordEncoder());

        return authenticationProvider;
    }

    @Bean
    public void authenticationManagerBuilder(AuthenticationManagerBuilder authConfiguration) throws Exception {
        authConfiguration.authenticationProvider(authenticationProvider());
    }

}
</code>```

and getting this error :

*************************** APPLICATION FAILED TO START

Description:

The bean 'authenticationManagerBuilder', defined in class path
resource [com/test/admin/security/WebSecurityConfig.class], could not
be registered. A bean with that name has already been defined in class
path resource
[org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfiguration.class]
and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting
spring.main.allow-bean-definition-overriding=true

from this document :

https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter

they've changed the WebSecurityConfigurerAdapter. so ive changed this :

```<code>@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    return auth.getAuthenticationManager();
}
</code>```

to this :

```<code>    @Bean
    public void authenticationManagerBuilder(AuthenticationManagerBuilder authConfiguration) throws Exception {
        authConfiguration.authenticationProvider(authenticationProvider());
    }
</code>```

and now getting error.

also if i change it to this :

```<code>@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfiguration) throws Exception {
    return authConfiguration.getAuthenticationManager();
}
</code>```

my error goes away?!

Body:
Im trying to implement authentication with Spring boot 3 like this :

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authz) -> authz

                .requestMatchers("/webjars/**", "/resources/**", "/css/**", "/images/**").permitAll().anyRequest()
                .authenticated()).formLogin((form) -> form.loginPage("/login").usernameParameter("email").permitAll())
                .httpBasic(withDefaults());
        return http.build();
    }

    @Bean
    public UserDetailsService UserDetailsService() {
        return new UserDetailsService();
    }

    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(UserDetailsService());
        authenticationProvider.setPasswordEncoder(passwordEncoder());

        return authenticationProvider;
    }

    @Bean
    public void authenticationManagerBuilder(AuthenticationManagerBuilder authConfiguration) throws Exception {
        authConfiguration.authenticationProvider(authenticationProvider());
    }

}

and getting this error :

*************************** APPLICATION FAILED TO START

Description:

The bean 'authenticationManagerBuilder', defined in class path
resource [com/test/admin/security/WebSecurityConfig.class], could not
be registered. A bean with that name has already been defined in class
path resource
[org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfiguration.class]
and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting
spring.main.allow-bean-definition-overriding=true

from this document :

https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter

they've changed the WebSecurityConfigurerAdapter. so ive changed this :

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    return auth.getAuthenticationManager();
}

to this :

    @Bean
    public void authenticationManagerBuilder(AuthenticationManagerBuilder authConfiguration) throws Exception {
        authConfiguration.authenticationProvider(authenticationProvider());
    }

and now getting error.

also if i change it to this :

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfiguration) throws Exception {
    return authConfiguration.getAuthenticationManager();
}

my error goes away?!


问:
Passing down dynamic props to a component in TS
I am trying to dynamically pass down data that has a "dynamic" type but getting an error:
Heres my code:

```<code>const tableData: ITableData[] = useUserSubCollection({dbPath: slot.dbPath})
const ComponentSlots = {
    ContactSlot: ContactSlot,
    InvoiceSlot: InvoiceSlot,
    EstimateSlot: EstimateSlot
}
const dataRender = tableData.map((el)=> {
    const Comp = ComponentSlots[slot.componentName]

    return <Comp slotData={el} />
})
</code>```

In ContactSlot component, slotData is of type IContact.

In InvoiceSlot component, slotData is of type IInvoice.

In EstimateSlot component, slotData is of type IEstimate

Note, ITableData is of type IContact | IInvoice | IEstimate

The issue I am facing is that when passing el to Comp I get a type error.

Note: slot.componentName is of type ContactSlot | InvoiceSlot | EstimateSlot

Hovering on slotData in VS Code, I get this error:

```<code>Type 'ITableData' is not assignable to type 'IContact'.
  Type 'IEstimate' is missing the following properties from type 'IContact': address, city, companyName, country, and 8 more.ts(2322)
</code>```

One solution I found is doing this:

```<code>const dataRender = tableData.map((el: any)=> {
    const Comp = ComponentSlots[slot.componentName]

    return <Comp slotData={el} />
})
</code>```

Here I declare el is any type but I don't think this is a good TypeScript solution and I am learning TS so want to come across the best practice.

Body:
I am trying to dynamically pass down data that has a "dynamic" type but getting an error:
Heres my code:

const tableData: ITableData[] = useUserSubCollection({dbPath: slot.dbPath})
const ComponentSlots = {
    ContactSlot: ContactSlot,
    InvoiceSlot: InvoiceSlot,
    EstimateSlot: EstimateSlot
}
const dataRender = tableData.map((el)=> {
    const Comp = ComponentSlots[slot.componentName]

    return <Comp slotData={el} />
})

In ContactSlot component, slotData is of type IContact.

In InvoiceSlot component, slotData is of type IInvoice.

In EstimateSlot component, slotData is of type IEstimate

Note, ITableData is of type IContact | IInvoice | IEstimate

The issue I am facing is that when passing el to Comp I get a type error.

Note: slot.componentName is of type ContactSlot | InvoiceSlot | EstimateSlot

Hovering on slotData in VS Code, I get this error:

Type 'ITableData' is not assignable to type 'IContact'.
  Type 'IEstimate' is missing the following properties from type 'IContact': address, city, companyName, country, and 8 more.ts(2322)

One solution I found is doing this:

const dataRender = tableData.map((el: any)=> {
    const Comp = ComponentSlots[slot.componentName]

    return <Comp slotData={el} />
})

Here I declare el is any type but I don't think this is a good TypeScript solution and I am learning TS so want to come across the best practice.


问:
SnowSQL How to get all records, including unmatched records from a join using a date range
Table_Two (T2) contains records with IDs that aren't within Table_One (T1), however, I still want these records.

Furthermore, I'm trying to do this within a date range, which means the IDs present in T2 that aren't present in T1 vary on a day by day basis.

I've tried quite a few queries, and currently I'm attempting:

```<code>select t1.id
  , t1.date
  , t1.col1
  , t2.col2
from table_one t1
join table_two t2 on
  t1.id=t2.id
  and t1.date=t2.date
where date>='2022-11-01' and date<='2022-11-03'
group by t1.id
  , t1.date
union
select t1.id
  , t1.date
  , t1.col1
  , t2.col2
from table_one t1
join table_two t2 on
  t1.id=t2.id
  and t1.date=t2.date
where date>='2022-11-01' and date<='2022-11-03'
  t1.id=NULL
group by t1.id
  , t1.date
</code>```

However, the second query is not returning any records.

Am I missing something? I believe this is how I would handle this. Does SnowSQL have a different manner or is this approach just wrong?

Edit - Adding example input and output.

T1:

id
date
col_1

1
2022-11-01
1

2
2022-11-01
2

1
2022-11-02
3

3
2022-11-03
4

T2:

id
date
col_2

1
2022-11-01
5

2
2022-11-01
6

3
2022-11-01
7

1
2022-11-02
8

2
2022-11-02
9

1
2022-11-03
10

2
2022-11-03
11

3
2022-11-03
12

The first query results in:

id
date
col_1
col_2

1
2022-11-01
1
5

2
2022-11-01
2
6

1
2022-11-02
3
8

3
2022-11-03
4
12

So I'm attempting to grab the following and UNION it:

id
date
col_1
col_2

3
2022-11-01
NULL
7

2
2022-11-02
NULL
9

1
2022-11-03
NULL
10

2
2022-11-03
NULL
11

Full Desired Output (Ordered by date):

id
date
col_1
col_2

1
2022-11-01
1
5

2
2022-11-01
2
6

3
2022-11-01
NULL
7

1
2022-11-02
3
8

2
2022-11-02
NULL
9

1
2022-11-03
NULL
10

2
2022-11-03
NULL
11

3
2022-11-03
4
12

Edit 2 - RESOLVED

So sorry, it was the GROUP BY statement, as it was grouping a NULL ID.

Body:
Table_Two (T2) contains records with IDs that aren't within Table_One (T1), however, I still want these records.

Furthermore, I'm trying to do this within a date range, which means the IDs present in T2 that aren't present in T1 vary on a day by day basis.

I've tried quite a few queries, and currently I'm attempting:

select t1.id
  , t1.date
  , t1.col1
  , t2.col2
from table_one t1
join table_two t2 on
  t1.id=t2.id
  and t1.date=t2.date
where date>='2022-11-01' and date<='2022-11-03'
group by t1.id
  , t1.date
union
select t1.id
  , t1.date
  , t1.col1
  , t2.col2
from table_one t1
join table_two t2 on
  t1.id=t2.id
  and t1.date=t2.date
where date>='2022-11-01' and date<='2022-11-03'
  t1.id=NULL
group by t1.id
  , t1.date

However, the second query is not returning any records.

Am I missing something? I believe this is how I would handle this. Does SnowSQL have a different manner or is this approach just wrong?

Edit - Adding example input and output.

T1:

id
date
col_1

1
2022-11-01
1

2
2022-11-01
2

1
2022-11-02
3

3
2022-11-03
4

T2:

id
date
col_2

1
2022-11-01
5

2
2022-11-01
6

3
2022-11-01
7

1
2022-11-02
8

2
2022-11-02
9

1
2022-11-03
10

2
2022-11-03
11

3
2022-11-03
12

The first query results in:

id
date
col_1
col_2

1
2022-11-01
1
5

2
2022-11-01
2
6

1
2022-11-02
3
8

3
2022-11-03
4
12

So I'm attempting to grab the following and UNION it:

id
date
col_1
col_2

3
2022-11-01
NULL
7

2
2022-11-02
NULL
9

1
2022-11-03
NULL
10

2
2022-11-03
NULL
11

Full Desired Output (Ordered by date):

id
date
col_1
col_2

1
2022-11-01
1
5

2
2022-11-01
2
6

3
2022-11-01
NULL
7

1
2022-11-02
3
8

2
2022-11-02
NULL
9

1
2022-11-03
NULL
10

2
2022-11-03
NULL
11

3
2022-11-03
4
12

Edit 2 - RESOLVED

So sorry, it was the GROUP BY statement, as it was grouping a NULL ID.


问:
How to display local storage data into webforms
In my React application there are multiple webforms which are coming from Hubspot and below is code snippet which is responsible for displaying webforms:

```<code>case "hubspot_form":
              if (paragraphEntity.entityRendered) {
                returnElement = parseToReact(paragraphEntity.entityRendered);
              }
              break;
</code>```

I want to pre-filled firstname, lastname and email from my localstorage into webforms. How can I add condition to above code so I can pre-filled those values into webforms using local storage?

I know I can do this using:

```<code>Fielditems = JSON.parse(localStorage.getItem('firstname','lastname','email'));
</code>```

But I am new to localstorage things.

Body:
In my React application there are multiple webforms which are coming from Hubspot and below is code snippet which is responsible for displaying webforms:

case "hubspot_form":
              if (paragraphEntity.entityRendered) {
                returnElement = parseToReact(paragraphEntity.entityRendered);
              }
              break;

I want to pre-filled firstname, lastname and email from my localstorage into webforms. How can I add condition to above code so I can pre-filled those values into webforms using local storage?

I know I can do this using:

Fielditems = JSON.parse(localStorage.getItem('firstname','lastname','email'));

But I am new to localstorage things.


问:
PyTorch: Scattering a 3D tensor using scatter_reduce()
I have the following 3x3x3 tensor (tensor_3D), which I want to scatter (product) over the first two dimensions using the index (index).

```<code>import torch
# create a 3D tensor of size 3x3x3 with numbers from 1 to 27
tensor_3D = torch.arange(1,28).reshape(3,3,3)
#tensor([[[ 1,  2,  3],
#         [ 4,  5,  6],
#         [ 7,  8,  9]],
#
#        [[10, 11, 12],
#         [13, 14, 15],
#         [16, 17, 18]],
#
#        [[19, 20, 21],
#         [22, 23, 24],
#         [25, 26, 27]]])

# create a 1D tensor of size 3 to be used as index when scattering
index = torch.tensor([0,0,1]).reshape(3,1)
#tensor([[0],
#        [0],
#        [1]])
</code>```

This is my desired tensor (res) is illustrated below. It has dimensions 2x3x3.

```<code># permute the result to get the desired output
d1 = torch.tensor ([4,  10,  18, 7,   8,   9 ]).reshape(2,3)
d2 = torch.tensor ([130, 154, 180, 16,  17,  18 ]).reshape(2,3)
d3 = torch.tensor ([418, 460, 504, 25,  26,  27 ]).reshape(2,3)
desired = torch.stack([d1,d2,d3], dim=2)
#tensor([[[  4, 130, 418],
#         [ 10, 154, 460],
#         [ 18, 180, 504]],
#
#        [[  7,  16,  25],
#         [  8,  17,  26],
#         [  9,  18,  27]]])
</code>```

As of now, I am doing the following but I am not getting the correct dimensions

```<code>import torch
# create a 3D tensor of size 3x3x3 with numbers from 1 to 27 uisng torch.arange
tensor_3D = torch.arange(1,28).reshape(3,3,3)
# create a 1D tensor of size 3 with numbers
index = torch.tensor([0,0,1]).reshape(3,1)
#Expand index to 3x3x3
index_expand = index.expand(3,3,3)
print(index_expand)
# use index to scatter_reduce product the values of tensor_3D to a new tensor of size 3x2x3
new_tensor = torch.ones(3,2,3, dtype=torch.int64)
print(new_tensor)
res = new_tensor.scatter_reduce(
    1,
    index_expand,
    tensor_3D,
    reduce="prod")
</code>```

Body:
I have the following 3x3x3 tensor (tensor_3D), which I want to scatter (product) over the first two dimensions using the index (index).

import torch
# create a 3D tensor of size 3x3x3 with numbers from 1 to 27
tensor_3D = torch.arange(1,28).reshape(3,3,3)
#tensor([[[ 1,  2,  3],
#         [ 4,  5,  6],
#         [ 7,  8,  9]],
#
#        [[10, 11, 12],
#         [13, 14, 15],
#         [16, 17, 18]],
#
#        [[19, 20, 21],
#         [22, 23, 24],
#         [25, 26, 27]]])

# create a 1D tensor of size 3 to be used as index when scattering
index = torch.tensor([0,0,1]).reshape(3,1)
#tensor([[0],
#        [0],
#        [1]])

This is my desired tensor (res) is illustrated below. It has dimensions 2x3x3.

# permute the result to get the desired output
d1 = torch.tensor ([4,  10,  18, 7,   8,   9 ]).reshape(2,3)
d2 = torch.tensor ([130, 154, 180, 16,  17,  18 ]).reshape(2,3)
d3 = torch.tensor ([418, 460, 504, 25,  26,  27 ]).reshape(2,3)
desired = torch.stack([d1,d2,d3], dim=2)
#tensor([[[  4, 130, 418],
#         [ 10, 154, 460],
#         [ 18, 180, 504]],
#
#        [[  7,  16,  25],
#         [  8,  17,  26],
#         [  9,  18,  27]]])

As of now, I am doing the following but I am not getting the correct dimensions

import torch
# create a 3D tensor of size 3x3x3 with numbers from 1 to 27 uisng torch.arange
tensor_3D = torch.arange(1,28).reshape(3,3,3)
# create a 1D tensor of size 3 with numbers
index = torch.tensor([0,0,1]).reshape(3,1)
#Expand index to 3x3x3
index_expand = index.expand(3,3,3)
print(index_expand)
# use index to scatter_reduce product the values of tensor_3D to a new tensor of size 3x2x3
new_tensor = torch.ones(3,2,3, dtype=torch.int64)
print(new_tensor)
res = new_tensor.scatter_reduce(
    1,
    index_expand,
    tensor_3D,
    reduce="prod")


Title: Why does SDO_LRS.CONCATENATE_GEOM_SEGMENTS_3D zero out the Z index?

Body:
Please look at following query (run on Oracle 19c):

SELECT SDO_LRS.CONCATENATE_GEOM_SEGMENTS_3D ( MDSYS.SDO_GEOMETRY( 4402, 4327, NULL, MDSYS.SDO_ELEM_INFO_ARRAY(1, 2, 1), MDSYS.SDO_ORDINATE_ARRAY(-87.5581857869439, 41.6569754435628, 589.31538218591, 507.27401, -87.5582131677029, 41.6570011677706, 589.35568218591, 507.27623) ), MDSYS.SDO_GEOMETRY( 4402, 4327, NULL, MDSYS.SDO_ELEM_INFO_ARRAY(1, 2, 1), MDSYS.SDO_ORDINATE_ARRAY(-87.5582131677030, 41.6570011677707, 589.35568218592, 507.27624, -87.5582454317806, 41.6570319021015, 589.40968218591, 507.27886) ), .005 )  from DUAL;

The two input SDO_GEOMETRY's are contiguous, i.e. the last point of the first geometry coincides with the first point of the second geometry...

It returns:

MDSYS.SDO_GEOMETRY(4402, 4327, NULL, MDSYS.SDO_ELEM_INFO_ARRAY(1, 2, 1), MDSYS.SDO_ORDINATE_ARRAY(-87.5581857869439, 41.6569754435628, 0, 507.27401, -87.558213167703, 41.6570011677707, 0, 507.27623, -87.5582454317806, 41.6570319021015, 0, 507.27885))

It 0's out the third values, i.e. the Z values...

Why does this do this?

On the other hand if use NULL values for the input geometry SRID's, it does not 0 out the Z values...

SELECT SDO_LRS.CONCATENATE_GEOM_SEGMENTS_3D ( MDSYS.SDO_GEOMETRY( 4402, NULL, NULL, MDSYS.SDO_ELEM_INFO_ARRAY(1, 2, 1), MDSYS.SDO_ORDINATE_ARRAY(-87.5581857869439, 41.6569754435628, 589.31538218591, 507.27401, -87.5582131677029, 41.6570011677706, 589.35568218591, 507.27623) ), MDSYS.SDO_GEOMETRY( 4402, NULL, NULL, MDSYS.SDO_ELEM_INFO_ARRAY(1, 2, 1), MDSYS.SDO_ORDINATE_ARRAY(-87.5582131677029, 41.6570011677706, 589.35568218591, 507.27623, -87.5582454317806, 41.6570319021015, 589.40968218591, 507.27886) ), .005 )  from DUAL;

In fact I tried SRID values of 5706, 43229, even 44444 (made up) and they work... but not 4327, 4329, 4979...

Expecting the Z values not to be 0...


问:
How do i add ssl certificate while calling post service from karate framework
Im trying to call a post service using karate framwork .This service requires ssl certificate .I have the .pfx file .

trust all server certificates, in the feature file

configure ssl = { trustAll: true }

// trust all server certificates, global configuration in 'karate-config.js'
karate.configure('ssl', { trustAll: true });


问:
Failed to initialize Flutter renderer
I am developing my flutter application on linux. But when I run the project I get an error like this:

Starting lib/main.dart in debug mode on Linux...
Creating a Linux application...
Gtk-Message: 20:43:51.812: Failed to load module "canberra-gtk-module"
Gtk-Message: 20:43:51.813: Failed to load module "canberra-gtk-module"
libGL error: MESA-LOADER: unable to open swrast: /usr/lib/x86_64-linux-gnu/libpthread.so.0: version 'GLIBC_PRIVATE' not found (required by /snap/flutter/current/usr/lib/x86_64) -linux -gnu/dri/../../../../lib/x86_64-linux-gnu/librt.so.1) (search paths: /usr/lib/x86_64-linux-gnu/dri: /snap /flutter/current/usr/lib/x86_64-linux-gnu/dri:, suffix _dri)
libGL error: driver failed to load: swrast
(my_project:987): WARNING : 20:43:51.980: Failed to initialize Flutter renderer: Failed to create GL context

Title: Failed to initialize Flutter renderer


问:
Can I use constants to avoid Class instance variables?
To become thread-safe, I need to refactor the Class instance variables in my code.

original

# frozen_string_literal: true

class Score < ApplicationRecord

  def self.init_score
    return @init_score if @init_score.present?

    @init_score = new(multiplier: 4.0)

    @init_score.readonly!
    @init_score
  end
end
```
<p><code>Score.init_score</code></p>
<h3>refactored</h3>
<pre class="lang-rb prettyprint-override"><code>
# frozen_string_literal: true

class Score < ApplicationRecord

  INIT_SCORE = self.init_score.freeze

  def self.init_score
    init_score = new(multiplier: 4.0)
    init_score.readonly!
  end
end

</code>```

Score::INIT_SCORE

So this approach makes sense, is this a good solution?

I want to know if a const can be used as a cache.

Body:
To become thread-safe, I need to refactor the Class instance variables in my code.

original

# frozen_string_literal: true

class Score < ApplicationRecord

  def self.init_score
    return @init_score if @init_score.present?

    @init_score = new(multiplier: 4.0)

    @init_score.readonly!
    @init_score
  end
end

Score.init_score

refactored

# frozen_string_literal: true

class Score < ApplicationRecord

  INIT_SCORE = self.init_score.freeze

  def self.init_score
    init_score = new(multiplier: 4.0)
    init_score.readonly!
  end
end

Score::INIT_SCORE

So this approach makes sense, is this a good solution?

I want to know if a const can be used as a cache.


问:
TensorFlow 2 print if object is detected
I'm trying to print "test" while detecting an object with leable id 1. The word test is printed non-stop :(

```<code>if 1 in detections['detection_classes']:
        print("test")
</code>```
```<code>
cap = cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

while cap.isOpened():
    ret, frame = cap.read()
    image_np = np.array(frame)

    input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
    detections = detect_fn(input_tensor)

    num_detections = int(detections.pop('num_detections'))
    detections = {key: value[0, :num_detections].numpy()
                  for key, value in detections.items()}
    detections['num_detections'] = num_detections

    # detection_classes should be ints.
    detections['detection_classes'] = detections['detection_classes'].astype(np.int64)

    label_id_offset = 1
    image_np_with_detections = image_np.copy()

    viz_utils.visualize_boxes_and_labels_on_image_array(
                image_np_with_detections,
                detections['detection_boxes'],
                detections['detection_classes']+label_id_offset,
                detections['detection_scores'],
                category_index,
                use_normalized_coordinates=True,
                max_boxes_to_draw=5,
                min_score_thresh=.8,
                agnostic_mode=False)

    cv2.imshow('object detection',  cv2.resize(image_np_with_detections, (800, 600)))

    if cv2.waitKey(10) & 0xFF == ord('q'):
        cap.release()
        cv2.destroyAllWindows()
        break
</code>```

I am interested in printing the name id actually gets detected on the screen.

Body:
I'm trying to print "test" while detecting an object with leable id 1. The word test is printed non-stop :(

if 1 in detections['detection_classes']:
        print("test")

cap = cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

while cap.isOpened():
    ret, frame = cap.read()
    image_np = np.array(frame)

    input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
    detections = detect_fn(input_tensor)

    num_detections = int(detections.pop('num_detections'))
    detections = {key: value[0, :num_detections].numpy()
                  for key, value in detections.items()}
    detections['num_detections'] = num_detections

    # detection_classes should be ints.
    detections['detection_classes'] = detections['detection_classes'].astype(np.int64)

    label_id_offset = 1
    image_np_with_detections = image_np.copy()

    viz_utils.visualize_boxes_and_labels_on_image_array(
                image_np_with_detections,
                detections['detection_boxes'],
                detections['detection_classes']+label_id_offset,
                detections['detection_scores'],
                category_index,
                use_normalized_coordinates=True,
                max_boxes_to_draw=5,
                min_score_thresh=.8,
                agnostic_mode=False)

    cv2.imshow('object detection',  cv2.resize(image_np_with_detections, (800, 600)))

    if cv2.waitKey(10) & 0xFF == ord('q'):
        cap.release()
        cv2.destroyAllWindows()
        break

I am interested in printing the name id actually gets detected on the screen.


问:
How can I check the API Authorization role using Azure RBAC with Managed Identities?
I'm trying to use managed identities in an single-tenant Azure environment.

I have the roles on the API being called and have them assigned to managed identities:
Role Assignments on called API

I have the identities assigned to the application calling the API:
Managed identity assignments on calling API

In my API Controller, I have the Authorize attribute looking for these roles I've assigned in Azure:

```<code>using <<the app namespace>>.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace <<the app namespace>>.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class NamesController : ControllerBase
    {
        [Authorize(Roles = "Api.Read,Api.ReadWrite")]
        [HttpGet()]
        public IActionResult GetNames()
        {
            return Ok(Data.NameList);
        }

        [Authorize(Roles = "Api.ReadWrite")]
        [HttpPost()]
        public IActionResult PostName([FromBody] NamesModel nameModel)
        {
            Data.NameList.Add(nameModel);
            return Ok(Data.NameList);
        }

        [Authorize(Roles = "Api.InvalidScope")]
        [HttpGet("Unreachable")]
        public IActionResult UnreachableName([FromBody] NamesModel nameModel)
        {
            Data.NameList.Add(nameModel);
            return Ok(Data.NameList);
        }
    }
}
</code>```

In the appsettings of my API, I have an AzureAd section including the app registration associated with the API and the tenant it is hosted on:

```<code>{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "<<the guid of my app registration>>",
    "TenantId": "<<the guid of the tenant>>"
  },
  "AllowedHosts": "*"
}
</code>```

I am adding Authentication with JwtBearerDefaults, and adding Authentication and Authorization:

```<code>using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;

namespace <<the namespace of the project>>
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApi(Configuration);

            services.AddControllers();
            services.AddEndpointsApiExplorer();
            services.AddSwaggerGen();

            services
                .AddApplicationInsightsTelemetry()
                .AddHealthChecks()
                .AddApplicationInsightsPublisher(saveDetailedReport: true);

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger();
            app.UseSwaggerUI();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHealthChecks("/healthz");
            });

        }
    }
}

</code>```

In the application (also an API) calling the api, I made this endpoint for testing.  I'm generating a managed identity credential and getting a JWT token (verified when sending -1 as the clientIndex).

```<code>    [ApiController]
    [Route("[controller]")]
    public class PocController : ControllerBase
    {
        private static readonly string readOnlyClient = "<<guid of managed identity with Api.Read role>>";
        private static readonly string readWriteClient = "<<guid of managed identity with Api.ReadWrite role>>";
        private static readonly string nonsenseClient = "aaaaaaaa-bbbb-cccc-dddd-efghijklmnop";
        private static readonly string[] clientArray = { nonsenseClient, readOnlyClient, readWriteClient };
        private static readonly string _baseApiUrl = "https://<<my api name>>.azurewebsites.net";        private static readonly string _apiScopeWithDefault = "api://<<app registration guid>>/.default";

        private readonly IHttpClientFactory _clientFactory;

        public PocController(IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
        }

        [HttpGet("{clientIndex}")]
        public async Task<IActionResult> GetEndpoint([FromRoute] int clientIndex)
        {
            var client = _clientFactory.CreateClient("MiAuthPoc");

            var clientID = clientArray[Math.Abs(clientIndex)];

            var credential = new ManagedIdentityCredential(clientID);

            if (clientIndex == -2)
                return Ok(credential);

            Azure.Core.AccessToken accessToken;

            try
            {
                var requestContext = new Azure.Core.TokenRequestContext(new string[] { _apiScopeWithDefault });
                accessToken = await credential.GetTokenAsync(requestContext);
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"{ex.Message}: {ex.InnerException?.Message}");
            }

            if (clientIndex == -1)
                return Ok(accessToken);

            HttpResponseMessage response = default;

            try
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");

                response = await client.GetAsync($"{_baseApiUrl}/api/names");

                return Ok(response);
            }
            catch (Exception ex)
            {
                return StatusCode(response != default ? (int)response?.StatusCode : 500, $"{ex.Message}: {ex.InnerException?.Message}");
            }
        }

    }
</code>```
```<code>{
  "aud": "api://<<app registration guid>>",
  "iss": "https://sts.windows.net/<<tenant id>>/",
  "iat": 1672953132,
  "nbf": 1672953132,
  "exp": 1673039832,
  "aio": "<<characters I don't understand>>",
  "appid": "<<clientid of managed identity>>",
  "appidacr": "2",
  "idp": "https://sts.windows.net/<<tenant id>>/",
  "oid": "<<object id of managed identity>>",
  "rh": "<<characters I don't understand>>",
  "sub": "<<object id of managed identity>>",
  "tid": "<<tenant id>>",
  "uti": "<<characters I don't understand>>",
  "ver": "1.0"
}
</code>```

Unfortunately, once it hits the api get request, I just get this 500 back with no information:
empty 500

When I try using the token I get in the example sending -1 and hitting the target API directly from Postman, I'm getting a 401.
unauthorized using token retrieved

This makes me think the target API doesn't know how to verify that the role assignment that shows in Azure is even there.

How do I get my API to recognize the Azure Role Assignment from the bearer token sent by the managed identity?

TIA.

Body:
I'm trying to use managed identities in an single-tenant Azure environment.

I have the roles on the API being called and have them assigned to managed identities:
Role Assignments on called API

I have the identities assigned to the application calling the API:
Managed identity assignments on calling API

In my API Controller, I have the Authorize attribute looking for these roles I've assigned in Azure:

using <<the app namespace>>.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace <<the app namespace>>.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class NamesController : ControllerBase
    {
        [Authorize(Roles = "Api.Read,Api.ReadWrite")]
        [HttpGet()]
        public IActionResult GetNames()
        {
            return Ok(Data.NameList);
        }

        [Authorize(Roles = "Api.ReadWrite")]
        [HttpPost()]
        public IActionResult PostName([FromBody] NamesModel nameModel)
        {
            Data.NameList.Add(nameModel);
            return Ok(Data.NameList);
        }

        [Authorize(Roles = "Api.InvalidScope")]
        [HttpGet("Unreachable")]
        public IActionResult UnreachableName([FromBody] NamesModel nameModel)
        {
            Data.NameList.Add(nameModel);
            return Ok(Data.NameList);
        }
    }
}

In the appsettings of my API, I have an AzureAd section including the app registration associated with the API and the tenant it is hosted on:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "<<the guid of my app registration>>",
    "TenantId": "<<the guid of the tenant>>"
  },
  "AllowedHosts": "*"
}

I am adding Authentication with JwtBearerDefaults, and adding Authentication and Authorization:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;

namespace <<the namespace of the project>>
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApi(Configuration);

            services.AddControllers();
            services.AddEndpointsApiExplorer();
            services.AddSwaggerGen();

            services
                .AddApplicationInsightsTelemetry()
                .AddHealthChecks()
                .AddApplicationInsightsPublisher(saveDetailedReport: true);

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger();
            app.UseSwaggerUI();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHealthChecks("/healthz");
            });

        }
    }
}

In the application (also an API) calling the api, I made this endpoint for testing.  I'm generating a managed identity credential and getting a JWT token (verified when sending -1 as the clientIndex).

    [ApiController]
    [Route("[controller]")]
    public class PocController : ControllerBase
    {
        private static readonly string readOnlyClient = "<<guid of managed identity with Api.Read role>>";
        private static readonly string readWriteClient = "<<guid of managed identity with Api.ReadWrite role>>";
        private static readonly string nonsenseClient = "aaaaaaaa-bbbb-cccc-dddd-efghijklmnop";
        private static readonly string[] clientArray = { nonsenseClient, readOnlyClient, readWriteClient };
        private static readonly string _baseApiUrl = "https://<<my api name>>.azurewebsites.net";        private static readonly string _apiScopeWithDefault = "api://<<app registration guid>>/.default";

        private readonly IHttpClientFactory _clientFactory;

        public PocController(IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
        }

        [HttpGet("{clientIndex}")]
        public async Task<IActionResult> GetEndpoint([FromRoute] int clientIndex)
        {
            var client = _clientFactory.CreateClient("MiAuthPoc");

            var clientID = clientArray[Math.Abs(clientIndex)];

            var credential = new ManagedIdentityCredential(clientID);

            if (clientIndex == -2)
                return Ok(credential);

            Azure.Core.AccessToken accessToken;

            try
            {
                var requestContext = new Azure.Core.TokenRequestContext(new string[] { _apiScopeWithDefault });
                accessToken = await credential.GetTokenAsync(requestContext);
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"{ex.Message}: {ex.InnerException?.Message}");
            }

            if (clientIndex == -1)
                return Ok(accessToken);

            HttpResponseMessage response = default;

            try
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");

                response = await client.GetAsync($"{_baseApiUrl}/api/names");

                return Ok(response);
            }
            catch (Exception ex)
            {
                return StatusCode(response != default ? (int)response?.StatusCode : 500, $"{ex.Message}: {ex.InnerException?.Message}");
            }
        }

    }

{
  "aud": "api://<<app registration guid>>",
  "iss": "https://sts.windows.net/<<tenant id>>/",
  "iat": 1672953132,
  "nbf": 1672953132,
  "exp": 1673039832,
  "aio": "<<characters I don't understand>>",
  "appid": "<<clientid of managed identity>>",
  "appidacr": "2",
  "idp": "https://sts.windows.net/<<tenant id>>/",
  "oid": "<<object id of managed identity>>",
  "rh": "<<characters I don't understand>>",
  "sub": "<<object id of managed identity>>",
  "tid": "<<tenant id>>",
  "uti": "<<characters I don't understand>>",
  "ver": "1.0"
}

Unfortunately, once it hits the api get request, I just get this 500 back with no information:
empty 500

When I try using the token I get in the example sending -1 and hitting the target API directly from Postman, I'm getting a 401.
unauthorized using token retrieved

This makes me think the target API doesn't know how to verify that the role assignment that shows in Azure is even there.

How do I get my API to recognize the Azure Role Assignment from the bearer token sent by the managed identity?

TIA.


问:
How to manage states of a shared component where we want to retain the states based on the place the component is being used?
For example: let's say we have a table component used on multiple pages or in a page multiple times. Now,  we want to maintain the selected items from the table for each table and highlight them.

So, currently, I am using an object to store the selected items based on the place it's being used:

```<code>{
  place1: {selectedItemId1: selectedItem1, selectedItemId2: selectedItem2},
  place2: {selectedItemId1: selectedItem1, selectedItemId2: selectedItem2},
  place3: {selectedItemId1: selectedItem1, selectedItemId2: selectedItem2}
}
</code>```

Please let me know if you've any other better solution.

Body:
For example: let's say we have a table component used on multiple pages or in a page multiple times. Now,  we want to maintain the selected items from the table for each table and highlight them.

So, currently, I am using an object to store the selected items based on the place it's being used:

{
  place1: {selectedItemId1: selectedItem1, selectedItemId2: selectedItem2},
  place2: {selectedItemId1: selectedItem1, selectedItemId2: selectedItem2},
  place3: {selectedItemId1: selectedItem1, selectedItemId2: selectedItem2}
}

Please let me know if you've any other better solution.


问:
python subprocess behaviour changed between ubuntu 20 and 22?
I upgraded my ubuntu installation to 22.04 from 18.04 yesterday. Now I notice that python virtual environment is no longer working as expect.

I use python to run a lot of tools, and hence am highly dependent on subprocess library.

However to my "horror"  I notice that it changed quite a lot, even when I keep using python 3.8. Mostly I notice I can no longer interact and the output is no longer piped to the shell that executes the python script.

```<code>import subprocess

def main():
    proc = subprocess.run(["echo", "test"], check=True, stdout=subprocess.PIPE)
    print('-------')
    print(proc.stdout)
    print("FINISH")

if __name__ == "__main__":
    main()
</code>```

If I call this with python3.8 test.py I notice that the output isn't displayed in the shell. However it is displayed when the prints happen.

What changed and how do I fix this? So output of the subprocess is piped to the output and can be seen?

Especially since a lot of tools are just running dockers (which in turn run git/javascript programs) and having output while the process is busy is kind of useful.

Body:
I upgraded my ubuntu installation to 22.04 from 18.04 yesterday. Now I notice that python virtual environment is no longer working as expect.

I use python to run a lot of tools, and hence am highly dependent on subprocess library.

However to my "horror"  I notice that it changed quite a lot, even when I keep using python 3.8. Mostly I notice I can no longer interact and the output is no longer piped to the shell that executes the python script.

import subprocess

def main():
    proc = subprocess.run(["echo", "test"], check=True, stdout=subprocess.PIPE)
    print('-------')
    print(proc.stdout)
    print("FINISH")

if __name__ == "__main__":
    main()

If I call this with python3.8 test.py I notice that the output isn't displayed in the shell. However it is displayed when the prints happen.

What changed and how do I fix this? So output of the subprocess is piped to the output and can be seen?

Especially since a lot of tools are just running dockers (which in turn run git/javascript programs) and having output while the process is busy is kind of useful.


问:
The following assertion was thrown during performLayout(): RenderCustomMultiChildLayoutBox object was given an infinite size duringlayout
I get this error when running the following code. I don't know what's wrong

```<code>The following assertion was thrown during performLayout():
RenderCustomMultiChildLayoutBox object was given an infinite size duringlayout
</code>```

```<code>import 'package:flutter/material.dart';
import 'package:nle_app/models/stall.dart';
import 'package:nle_app/constants/colors.dart';

class StallInfo extends StatelessWidget {
  final stall = Stall.generateRestaurant();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        margin: const EdgeInsets.only(top: 40),
        padding: const EdgeInsets.symmetric(horizontal: 25),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      stall.name,
                      style: const TextStyle(
                        fontSize: 25,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 10),
                    Row(
                      children: [
                        Container(
                            padding: EdgeInsets.all(5),
                            decoration: BoxDecoration(
                              color: Colors.blueGrey.withOpacity(0.4),
                              borderRadius: BorderRadius.circular(5),
                            ),
                            child: Text(
                              stall.label,
                              style: const TextStyle(
                                color: Colors.white,
                              ),
                            )),
                        const SizedBox(
                          width: 10,
                        ),
                      ],
                    )
                  ],
                ),
                ClipRRect(
                  borderRadius: BorderRadius.circular(50),
                  child: Image.asset(
                    stall.logoUrl,
                    width: 80,
                  ),
                ),
              ],
            ),
            const SizedBox(
              height: 5,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  stall.desc,
                  style: const TextStyle(fontSize: 16),
                ),
                Row(
                  children: [
                    const Icon(
                      Icons.star_outline,
                      color: Colors.amber,
                    ),
                    Text(
                      '${stall.score}',
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(width: 15),
                  ],
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
</code>```

"This probably means that it is a render object that tries to be as big

as possible, but it was put inside another render object that allows its children to pick their own
size."

But I don't know where this error is coming from

"The constraints that applied to the RenderCustomMultiChildLayoutBox were:

```<code>BoxConstraints(0.0<=w<=600.0, 0.0<=h<=Infinity)"
</code>```

"The exact size it was given was:

```<code>Size(600.0, Infinity)"
</code>```

Body:
I get this error when running the following code. I don't know what's wrong

The following assertion was thrown during performLayout():
RenderCustomMultiChildLayoutBox object was given an infinite size duringlayout

import 'package:flutter/material.dart';
import 'package:nle_app/models/stall.dart';
import 'package:nle_app/constants/colors.dart';

class StallInfo extends StatelessWidget {
  final stall = Stall.generateRestaurant();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        margin: const EdgeInsets.only(top: 40),
        padding: const EdgeInsets.symmetric(horizontal: 25),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      stall.name,
                      style: const TextStyle(
                        fontSize: 25,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 10),
                    Row(
                      children: [
                        Container(
                            padding: EdgeInsets.all(5),
                            decoration: BoxDecoration(
                              color: Colors.blueGrey.withOpacity(0.4),
                              borderRadius: BorderRadius.circular(5),
                            ),
                            child: Text(
                              stall.label,
                              style: const TextStyle(
                                color: Colors.white,
                              ),
                            )),
                        const SizedBox(
                          width: 10,
                        ),
                      ],
                    )
                  ],
                ),
                ClipRRect(
                  borderRadius: BorderRadius.circular(50),
                  child: Image.asset(
                    stall.logoUrl,
                    width: 80,
                  ),
                ),
              ],
            ),
            const SizedBox(
              height: 5,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  stall.desc,
                  style: const TextStyle(fontSize: 16),
                ),
                Row(
                  children: [
                    const Icon(
                      Icons.star_outline,
                      color: Colors.amber,
                    ),
                    Text(
                      '${stall.score}',
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(width: 15),
                  ],
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}

"This probably means that it is a render object that tries to be as big

as possible, but it was put inside another render object that allows its children to pick their own
size."

But I don't know where this error is coming from

"The constraints that applied to the RenderCustomMultiChildLayoutBox were:

BoxConstraints(0.0<=w<=600.0, 0.0<=h<=Infinity)"

"The exact size it was given was:

Size(600.0, Infinity)"


问:
Tensorflow RNN-like neural network does not train as except on Mac M1
I am learning python deep learning tools on Tensorflow official websites.

Trying to build several Text-Classification network, do as tutorials. But LSTM does not work as except.

import numpy as np
import tensorflow_datasets as tfds
import tensorflow as tf
from tensorflow.keras import utils
from tensorflow.keras import losses
import matplotlib.pyplot as plt

seed = 42
BATCH_SIZE = 64

train_ds = utils.text_dataset_from_directory(
    'stack_overflow_16k/train',
    validation_split=0.2,
    subset='training',
    batch_size=BATCH_SIZE,
    seed=seed)
val_ds = utils.text_dataset_from_directory(
    'stack_overflow_16k/train',
    validation_split=0.2,
    subset='validation',
    batch_size=BATCH_SIZE,
    seed=seed)
test_ds = utils.text_dataset_from_directory(
    'stack_overflow_16k/test',
    batch_size=BATCH_SIZE)

class_names = train_ds.class_names
train_ds = train_ds.prefetch(buffer_size=tf.data.AUTOTUNE)
val_ds = val_ds.prefetch(buffer_size=tf.data.AUTOTUNE)
test_ds = test_ds.prefetch(buffer_size=tf.data.AUTOTUNE)

VOCAB_SIZE = 1000
MAX_SEQUENCE_LENGTH = 500

encoder = tf.keras.layers.TextVectorization(
    max_tokens=VOCAB_SIZE,
    output_sequence_length=MAX_SEQUENCE_LENGTH)

encoder.adapt(train_ds.map(lambda text, label: text))

model = tf.keras.Sequential([
    encoder,
    tf.keras.layers.Embedding(VOCAB_SIZE, 64, mask_zero=True),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),
#     tf.keras.layers.LSTM(128),
#     tf.keras.layers.Dense(64, activation='relu'),
#     tf.keras.layers.Conv1D(64, 5, padding="valid", activation="relu", strides=2),
#     tf.keras.layers.GlobalMaxPooling1D(),
#     tf.keras.layers.GRU(64),
#     tf.keras.layers.SimpleRNN(64),
#     tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(4)
])
model.summary()

model.compile(loss='sparse_categorical_crossentropy',
              optimizer='sgd',
              metrics=['accuracy'])

history = model.fit(train_ds, epochs=10,
                    validation_data=val_ds)
```
<p>This is my complete code, the core part is same as tutorials.</p>
<p>But the training output as follow:</p>
```Epoch 1/10
100/100 [==============================] - 33s 273ms/step - loss: 9.6882 - accuracy: 0.2562 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 2/10
100/100 [==============================] - 25s 250ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 3/10
100/100 [==============================] - 25s 252ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 4/10
100/100 [==============================] - 25s 254ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 5/10
100/100 [==============================] - 25s 255ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 6/10
100/100 [==============================] - 26s 256ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 7/10
100/100 [==============================] - 26s 257ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 8/10
100/100 [==============================] - 26s 258ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 9/10
100/100 [==============================] - 26s 258ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 10/10
100/100 [==============================] - 26s 256ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587

```
<p>The accuracy does not increase and loss does not decrease at all, like not trained. And the accuracy just same as the reciprocal of the number of classes. (E.g. If it's a binary classification problem then the accuracy would keep aroud 0.5, four classification problem 0.25)</p>
<p>Later I compare with CNN, just change the LSTM layers to CNN layers as tutorials, it works as expect. (Same datasets, same params of <code>model.compile()</code> and <code>model.fit()</code>)</p>
<p>I also tried GRU, same problem occurs.</p>
<p>I don't get it.</p>
<p>Am I missing some configuration with RNN-like model? Can somebody help me with this problem? Thanks!</p>
<p>P.S.</p>
<ul>
<li>tensorflow-macos 2.9</li>
<li>tensorflow-metal 0.5.0</li>
<li>Chip: Apple M1</li>
<li>Datasets: https://storage.googleapis.com/download.tensorflow.org/data/stack_overflow_16k.tar.gz Same as tutorials.</li>
</ul>
<p>I tried config the optimizer(sgd, adam) and learning rate, does not work. It is not like overfitting.</p>
<p>Methods I tried:</p>
<ul>
<li>Keras accuracy does not change</li>
</ul>
<hr />
<h3>Update 2023-01-30</h3>
<p>I run the same code on my linux server it work expected. It maybe a bug of tensorflow-macos.</p>
<hr />
<h3>Update 2023-02-01</h3>
<p>Tried the official version of tensorflow for macos m1, just</p>
```conda install tensorflow
```

it works. Suppposed to be the problem of tensorflow-macos GPU support. And I try again by using CPU only on tensorflow-macos, it works.

Conclusion:

The RNN-like model have problem on tensorflow-macos with GPU.

Body:
I am learning python deep learning tools on Tensorflow official websites.

Trying to build several Text-Classification network, do as tutorials. But LSTM does not work as except.

import numpy as np
import tensorflow_datasets as tfds
import tensorflow as tf
from tensorflow.keras import utils
from tensorflow.keras import losses
import matplotlib.pyplot as plt

seed = 42
BATCH_SIZE = 64

train_ds = utils.text_dataset_from_directory(
    'stack_overflow_16k/train',
    validation_split=0.2,
    subset='training',
    batch_size=BATCH_SIZE,
    seed=seed)
val_ds = utils.text_dataset_from_directory(
    'stack_overflow_16k/train',
    validation_split=0.2,
    subset='validation',
    batch_size=BATCH_SIZE,
    seed=seed)
test_ds = utils.text_dataset_from_directory(
    'stack_overflow_16k/test',
    batch_size=BATCH_SIZE)

class_names = train_ds.class_names
train_ds = train_ds.prefetch(buffer_size=tf.data.AUTOTUNE)
val_ds = val_ds.prefetch(buffer_size=tf.data.AUTOTUNE)
test_ds = test_ds.prefetch(buffer_size=tf.data.AUTOTUNE)

VOCAB_SIZE = 1000
MAX_SEQUENCE_LENGTH = 500

encoder = tf.keras.layers.TextVectorization(
    max_tokens=VOCAB_SIZE,
    output_sequence_length=MAX_SEQUENCE_LENGTH)

encoder.adapt(train_ds.map(lambda text, label: text))

model = tf.keras.Sequential([
    encoder,
    tf.keras.layers.Embedding(VOCAB_SIZE, 64, mask_zero=True),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),
#     tf.keras.layers.LSTM(128),
#     tf.keras.layers.Dense(64, activation='relu'),
#     tf.keras.layers.Conv1D(64, 5, padding="valid", activation="relu", strides=2),
#     tf.keras.layers.GlobalMaxPooling1D(),
#     tf.keras.layers.GRU(64),
#     tf.keras.layers.SimpleRNN(64),
#     tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(4)
])
model.summary()

model.compile(loss='sparse_categorical_crossentropy',
              optimizer='sgd',
              metrics=['accuracy'])

history = model.fit(train_ds, epochs=10,
                    validation_data=val_ds)

This is my complete code, the core part is same as tutorials.

But the training output as follow:

Epoch 1/10
100/100 [==============================] - 33s 273ms/step - loss: 9.6882 - accuracy: 0.2562 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 2/10
100/100 [==============================] - 25s 250ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 3/10
100/100 [==============================] - 25s 252ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 4/10
100/100 [==============================] - 25s 254ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 5/10
100/100 [==============================] - 25s 255ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 6/10
100/100 [==============================] - 26s 256ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 7/10
100/100 [==============================] - 26s 257ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 8/10
100/100 [==============================] - 26s 258ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 9/10
100/100 [==============================] - 26s 258ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587
Epoch 10/10
100/100 [==============================] - 26s 256ms/step - loss: 12.1238 - accuracy: 0.2478 - val_loss: 11.9475 - val_accuracy: 0.2587

The accuracy does not increase and loss does not decrease at all, like not trained. And the accuracy just same as the reciprocal of the number of classes. (E.g. If it's a binary classification problem then the accuracy would keep aroud 0.5, four classification problem 0.25)

Later I compare with CNN, just change the LSTM layers to CNN layers as tutorials, it works as expect. (Same datasets, same params of model.compile() and model.fit())

I also tried GRU, same problem occurs.

I don't get it.

Am I missing some configuration with RNN-like model? Can somebody help me with this problem? Thanks!

P.S.

tensorflow-macos 2.9

tensorflow-metal 0.5.0

Chip: Apple M1

Datasets: https://storage.googleapis.com/download.tensorflow.org/data/stack_overflow_16k.tar.gz Same as tutorials.

I tried config the optimizer(sgd, adam) and learning rate, does not work. It is not like overfitting.

Methods I tried:

Keras accuracy does not change

Update 2023-01-30

I run the same code on my linux server it work expected. It maybe a bug of tensorflow-macos.

Update 2023-02-01

Tried the official version of tensorflow for macos m1, just

conda install tensorflow

it works. Suppposed to be the problem of tensorflow-macos GPU support. And I try again by using CPU only on tensorflow-macos, it works.

Conclusion:

The RNN-like model have problem on tensorflow-macos with GPU.


问:
Lapack routine dgesv: system is exactly singular in mult.chart from msqc library
I am trying to use MSQC library for multivariate process control, but I am running in to this error. I have 8 columns which are correlate for the most part.
the mult.chart function runs fine for phase 1 but gives me error for phase 2. Any solution for handing this?</p>


问:
In a functional component how to get a stack trace of the parent component that called child?
Looking to debug a parent and child component, given the example of:

Parent:

```<code>import React from 'react';
import PropTypes from 'prop-types';

// Child Component
import Bar from './Bar'

const Foo =  (props) => {
  // removed code
  return <Bar data={data} />
}

Foo.propTypes = {
  // code
};

Foo.defaultProps = {
  // code
};

export default Foo;
</code>```

Child:

```<code>import React from 'react';
import PropTypes from 'prop-types';

const Bar =  ({data}) => {
  const stack = React["__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED"].ReactDebugCurrentFrame.getCurrentStack()
  console.log('stack', stack)
}

Bar.propTypes = {
  // code
};

Bar.defaultProps = {
  // code
};

export default Bar;
</code>```

it doesn't log me the Parent Component name or any info.

Research

Formatting React Stack Trace in the browser as a component?

Minified component stack trace in create-react-app (dev mode)

How to use stack trace to find where in the code error is?

Details

```<code>"react": "^18.2.0",
</code>```

In a React functional component how can I get a trace on what parent called the child component?

Body:
Looking to debug a parent and child component, given the example of:

Parent:

import React from 'react';
import PropTypes from 'prop-types';

// Child Component
import Bar from './Bar'

const Foo =  (props) => {
  // removed code
  return <Bar data={data} />
}

Foo.propTypes = {
  // code
};

Foo.defaultProps = {
  // code
};

export default Foo;

Child:

import React from 'react';
import PropTypes from 'prop-types';

const Bar =  ({data}) => {
  const stack = React["__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED"].ReactDebugCurrentFrame.getCurrentStack()
  console.log('stack', stack)
}

Bar.propTypes = {
  // code
};

Bar.defaultProps = {
  // code
};

export default Bar;

it doesn't log me the Parent Component name or any info.

Research

Formatting React Stack Trace in the browser as a component?

Minified component stack trace in create-react-app (dev mode)

How to use stack trace to find where in the code error is?

Details

"react": "^18.2.0",

In a React functional component how can I get a trace on what parent called the child component?


问:
Impersonal mobile app, how can it be authenticated to avoid bots? maybe reCAPTCHA?
question,  I have  a mobile app, where any mobile phone can ask a otp. How can I prevent calls to my otp endpoint from bots? and be sure is a real user behind?
Thanks a lot</p>


问:
Laravel hasOne()->orderBy() vs hasOne()->ofMany()
One bit of "magic" in the Laravel codebase is here in HasOneOrMany.php where if the underlying query behind a hasOne relationship technically fetches multiple rows, it will just return the first row instead.

protected function getRelationValue(array $dictionary, $key, $type)
{
    $value = $dictionary[$key];
    return $type === 'one' ? reset($value) : $this->related->newCollection($value);
}
```
<p>This got me thinking that, given a related model that is normally <code>hasMany</code>, an <code>oldestOfMany()</code> relation can be simulated with just an <code>orderBy</code>, e.g.</p>
<pre class="lang-php prettyprint-override"><code>public function models()
{
    return $this->hasMany(Model::class);
}

public function firstModel()
{
    return $this->hasOne(Model::class)->orderBy('created_at');
}
</code>```

Are there any downsides to this shortcut approach?

As pointed out in the comments, calling ->first() on the many relationship works just fine for actually retrieving a model.  In our app it's common to build relations from other relations, and I want to do that here.  e.g.

public function firstActiveModel()
{
    return $this->firstModel()->active();
}
```

Body:
One bit of "magic" in the Laravel codebase is here in HasOneOrMany.php where if the underlying query behind a hasOne relationship technically fetches multiple rows, it will just return the first row instead.

protected function getRelationValue(array $dictionary, $key, $type)
{
    $value = $dictionary[$key];
    return $type === 'one' ? reset($value) : $this->related->newCollection($value);
}

This got me thinking that, given a related model that is normally hasMany, an oldestOfMany() relation can be simulated with just an orderBy, e.g.

public function models()
{
    return $this->hasMany(Model::class);
}

public function firstModel()
{
    return $this->hasOne(Model::class)->orderBy('created_at');
}

Are there any downsides to this shortcut approach?

As pointed out in the comments, calling ->first() on the many relationship works just fine for actually retrieving a model.  In our app it's common to build relations from other relations, and I want to do that here.  e.g.

public function firstActiveModel()
{
    return $this->firstModel()->active();
}


问:
How do get maxspeed values over the length of a motorway?
I have been stuck with a question for quite a while now. I am trying to get maxspeed data of the motorway A95 in Germany with coordinates. I am still new to Overpass Api and have tried to access this data with the following code:

https://overpass-turbo.eu/s/1pO2

[out:csv(maxspeed,
         conditional,
         wet,
         length,
         ::lat,
         ::lon)]
[timeout:500];
area["ISO3166-2"="DE-BY"]->.a;
way(area.a)["highway"][highway=motorway][ref="A 95"];
convert result ::=::,::geom=geom(),length=length();
out geom;
```

I cross checked the coordinates I currently get (I have an existing set of data) and they don't really make sense, I think they represent the middle of the way tagged with a speed limit. Is there a way to extract the coordinates at the beginning/ending of the maxspeed tag?

The goal is to get a csv output listing all speed limits on the motorway with coordinates of their beginning and/or ending. Ideally, I would also want to include data on conditional speed limits.

Thank you very much, I look forward to hearing your opinions!

Body:
I have been stuck with a question for quite a while now. I am trying to get maxspeed data of the motorway A95 in Germany with coordinates. I am still new to Overpass Api and have tried to access this data with the following code:

https://overpass-turbo.eu/s/1pO2

[out:csv(maxspeed,
         conditional,
         wet,
         length,
         ::lat,
         ::lon)]
[timeout:500];
area["ISO3166-2"="DE-BY"]->.a;
way(area.a)["highway"][highway=motorway][ref="A 95"];
convert result ::=::,::geom=geom(),length=length();
out geom;

I cross checked the coordinates I currently get (I have an existing set of data) and they don't really make sense, I think they represent the middle of the way tagged with a speed limit. Is there a way to extract the coordinates at the beginning/ending of the maxspeed tag?

The goal is to get a csv output listing all speed limits on the motorway with coordinates of their beginning and/or ending. Ideally, I would also want to include data on conditional speed limits.

Thank you very much, I look forward to hearing your opinions!


问:
Update 'profiles' on Supabase with RLS
I'm currently attempting to use Supabase's JavaScript API to update a row in my 'profiles' database, which has RLS on, via my backend.

This is being done following Stripe sending me a webhook indicating a payment has been successful.

I won't put the full API call in, but here is my Supabase code:

```<code>const supabaseUrl = process.env.REACT_APP_SUPABASE_URL
const supabaseAnonKey = process.env.REACT_APP_SUPABASE_ANON_KEY

const supabase = createClient(supabaseUrl, supabaseAnonKey)

module.exports = async (req, res) => {

   if (event.type === "checkout.session.completed") {
    const userId = String(event.data.object.client_reference_id)

    const { error } = await supabase.from('profiles').update({ premium: 'true' }).eq('id', userId)

    if (error) {
      console.log(error)
    }
   }
}
</code>```

However, every time I try to run this, I get a 404 error. This seems to be because I have RLS on.

As a result, I have two questions:

Is it safe for me to turn RLS off?

How can I adjust my code / apply a new database policy to allow this to be accepted?

Title: Update 'profiles' on Supabase with RLS

Body:
I'm currently attempting to use Supabase's JavaScript API to update a row in my 'profiles' database, which has RLS on, via my backend.

This is being done following Stripe sending me a webhook indicating a payment has been successful.

I won't put the full API call in, but here is my Supabase code:

const supabaseUrl = process.env.REACT_APP_SUPABASE_URL
const supabaseAnonKey = process.env.REACT_APP_SUPABASE_ANON_KEY

const supabase = createClient(supabaseUrl, supabaseAnonKey)

module.exports = async (req, res) => {

   if (event.type === "checkout.session.completed") {
    const userId = String(event.data.object.client_reference_id)

    const { error } = await supabase.from('profiles').update({ premium: 'true' }).eq('id', userId)

    if (error) {
      console.log(error)
    }
   }
}

However, every time I try to run this, I get a 404 error. This seems to be because I have RLS on.

As a result, I have two questions:

Is it safe for me to turn RLS off?

How can I adjust my code / apply a new database policy to allow this to be accepted?


问:
redis cluster returning different key amounts then laravel (phpredis)
Maybe someone is able to take a look onto my redis config / figure out what is going wrong.

I'm running a redis-cluster with 6 nodes. phpredis extension is loaded.
When I run the following command in laravel:

```<code>    dd(Redis::connection('default')->command('DBSIZE', ['*']));
</code>```

it returns f.e. 34
meanwhile when running it on the same redis node, laravel is using it returns:

```<code> 127.0.0.1:6379> dbsize
 (integer) 24
</code>```

My database.php

.env contains:

```<code>  - REDIS_CLIENT=phpredis
  - REDIS_TYPE=cluster //required so production setup will switch to use redis-cluster, local dev setup won't
  - REDIS_QUEUE={default} //required to use {}, otherwise will cause problems with redis-cluster
</code>```

Any idea if the redis-cluster config inside laravel is incorrect or any idea why laravel returns a different amount of keys then redis-cli inside cluster?

Body:
Maybe someone is able to take a look onto my redis config / figure out what is going wrong.

I'm running a redis-cluster with 6 nodes. phpredis extension is loaded.
When I run the following command in laravel:

    dd(Redis::connection('default')->command('DBSIZE', ['*']));

it returns f.e. 34
meanwhile when running it on the same redis node, laravel is using it returns:

 127.0.0.1:6379> dbsize
 (integer) 24

My database.php

.env contains:

  - REDIS_CLIENT=phpredis
  - REDIS_TYPE=cluster //required so production setup will switch to use redis-cluster, local dev setup won't
  - REDIS_QUEUE={default} //required to use {}, otherwise will cause problems with redis-cluster

Any idea if the redis-cluster config inside laravel is incorrect or any idea why laravel returns a different amount of keys then redis-cli inside cluster?


Title: Can I use .json dataset on yolo

Body:
I'm currently using .txt dataset on yolo and I want to use .json dataset on yolov4.
Can I do that?

example for .txt format

0 0.542720 0.415254 0.409610 0.355932

example for .json format

{"info":{"description":"my-project-name"},"images":[{"id":1,"width":1280,"height":854,"file_name":"a.jpg"}],"annotations":[{"id":0,"iscrowd":0,"image_id":1,"category_id":1,"segmentation":[[572.45197740113,270.1920903954802,628.7419962335217,244.45951035781542,738.105461393597,286.2749529190207,776.7043314500942,369.90583804143125,775.0960451977401,453.53672316384177,545.1111111111111,511.4350282485875,506.512241054614,482.48587570621464,487.21280602636534,357.03954802259886,514.5536723163842,299.14124293785306,562.8022598870057,283.0583804143126]],"bbox":[487.21280602636534,244.45951035781542,289.49152542372883,266.9755178907721],"area":57054.884640074306}],"categories":[{"id":1,"name":"a"}]}```


问:
Did handling of "operator<<" in g++ change between v4.8.5 and v8.4.1?
I have a large code that compiled fine in g++ 4.8.5 (on RHEL7) but fails in 8.4.1 (on RHEL8) (I do not have any intermediate g++ versions currently available). The compiling fails in a certain file that uses operator overloading for "<<". Specifically, the v8.4.1 compiler has issues with a line of code like this:

```<code>out << robj.print( out );
</code>```

v4.8.5 does not issue any warning/error at all. It simply creates an o file. However, v8.4.1 issues the following error:

```<code>no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘std::ostream’ {aka ‘std::basic_ostream<char>’})
cout << out;
</code>```

My code is too long to post, but I found a similar issue here (C++ class with ostream operator works with VS and fails to compile with gcc) which I modified to show my particular issue. I also included the suggestions/updates from "osgx" from that post. I am posting the modified files:

rational.h

```<code>#ifndef  RATIONAL_H
#define RATIONAL_H
#include <iostream>
#include <ostream>
#include <cmath>
#include <cstdlib>
using namespace std;

class rational
{
public:
    rational(int n = 0, int d = 1);
    rational multiply(const rational &r2) const;

    friend ostream& operator<<(ostream &out, const rational &);

    ostream& print(ostream& out) const {
        cout << out;
    };

private:
    int num;    // numerator
    int denom;  // denominator
};

#endif
</code>```

rational.cpp (the compiling error occurs in this file)

```<code>#include "rational.h"
using namespace std;

rational::rational(int n, int d)
{
    num = n;
    denom = d;
}

rational rational::multiply(const rational &r2) const
{
    rational multi;
    multi.denom = (*this).denom * r2.denom;
    multi.num = (*this).num * r2.num;
    return multi;
}

ostream& operator<<(ostream &out, const rational &robj)
{
    out << robj.num << "/" << robj.denom;
    // The v8.4.1 compiler complains about this next line
    out << robj.print( out );

    return out;
}
</code>```

main.cpp

```<code>#include "rational.h"

using namespace std;

int main()
{
    rational r1(1,4), r2(1,3),r3;

    cout << "r1 initialized to: " << r1 << endl;
    cout << "r2 initialized to: " << r2 << endl << endl;

    cout << "Testing multiplication function:" << endl;
    cout << "\tr1 * r2 = " << r1 << " * " << r2 << " = " << r1.multiply(r2) << endl;
}
</code>```

Compiling command: g++ -c main.cpp rational.cpp

Hoping someone can spot the issue. Thanks!

Body:
I have a large code that compiled fine in g++ 4.8.5 (on RHEL7) but fails in 8.4.1 (on RHEL8) (I do not have any intermediate g++ versions currently available). The compiling fails in a certain file that uses operator overloading for "<<". Specifically, the v8.4.1 compiler has issues with a line of code like this:

out << robj.print( out );

v4.8.5 does not issue any warning/error at all. It simply creates an o file. However, v8.4.1 issues the following error:

no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘std::ostream’ {aka ‘std::basic_ostream<char>’})
cout << out;

My code is too long to post, but I found a similar issue here (C++ class with ostream operator works with VS and fails to compile with gcc) which I modified to show my particular issue. I also included the suggestions/updates from "osgx" from that post. I am posting the modified files:

rational.h

#ifndef  RATIONAL_H
#define RATIONAL_H
#include <iostream>
#include <ostream>
#include <cmath>
#include <cstdlib>
using namespace std;

class rational
{
public:
    rational(int n = 0, int d = 1);
    rational multiply(const rational &r2) const;

    friend ostream& operator<<(ostream &out, const rational &);

    ostream& print(ostream& out) const {
        cout << out;
    };

private:
    int num;    // numerator
    int denom;  // denominator
};

#endif

rational.cpp (the compiling error occurs in this file)

#include "rational.h"
using namespace std;

rational::rational(int n, int d)
{
    num = n;
    denom = d;
}

rational rational::multiply(const rational &r2) const
{
    rational multi;
    multi.denom = (*this).denom * r2.denom;
    multi.num = (*this).num * r2.num;
    return multi;
}

ostream& operator<<(ostream &out, const rational &robj)
{
    out << robj.num << "/" << robj.denom;
    // The v8.4.1 compiler complains about this next line
    out << robj.print( out );

    return out;
}

main.cpp

#include "rational.h"

using namespace std;

int main()
{
    rational r1(1,4), r2(1,3),r3;

    cout << "r1 initialized to: " << r1 << endl;
    cout << "r2 initialized to: " << r2 << endl << endl;

    cout << "Testing multiplication function:" << endl;
    cout << "\tr1 * r2 = " << r1 << " * " << r2 << " = " << r1.multiply(r2) << endl;
}

Compiling command: g++ -c main.cpp rational.cpp

Hoping someone can spot the issue. Thanks!


问:
I have JavaScript menu code that is working but I don't know how to get the values into a form input field
I am not at all proficient in JavaScript. I have tried many ways to get the menu values into an html input form.

Here is the JavaScript and HTML code. I want the values to go into these input fields...

function ShowHideDiv() {
  var options = document.getElementById("options");
  var requestName = document.getElementById("requestName");
  requestName.style.display = options.value == "Licensing" ? "block" : "none";
  requestName1.style.display = options.value == "Reporting" ? "block" : "none";
  requestName2.style.display = options.value == "Specification / Compatibility" ? "block" : "none";
  requestName3.style.display = options.value == "Operation / How To" ? "block" : "none";
  requestName4.style.display = options.value == "Installation / Uninstallation" ? "block" : "none";
  requestName5.style.display = options.value == "Upgrade / Downgrade" ? "block" : "none";
  requestName6.style.display = options.value == "Configuration / Workflow" ? "block" : "none";
  requestName7.style.display = options.value == "Administration" ? "block" : "none";
  requestName8.style.display = options.value == "Ordering / Replacing" ? "block" : "none";
  requestName9.style.display = options.value == "Documentation" ? "block" : "none";
  requestName10.style.display = options.value == "Security / Vulnerabilities" ? "block" : "none";
  requestName11.style.display = options.value == "Training" ? "block" : "none";
  requestName12.style.display = options.value == "Testing" ? "block" : "none";
}

var requestTypes = {
  'Licensing': ["Request", "Reset", "Renewal", "Upgrade / Downgrade", "Transfer", "How-To"],
  'Reporting': ["Creation", "Modification"],
  'Specification / Compatibility': ["NA"],
  'Operation / How To': ["Administration", "User assistance"],
  'Installation / Uninstallation': ["NA"],
  'Upgrade / Downgrade': ["Software Request"],
  'Configuration / Workflow': ["Modification", "Creation"],
  'Administration': ["NA"],
  'Ordering / Replacing': ["NA"],
  'Documentation': ["NA"],
  'Security / Vulnerabilities': ["NA"],
  'Training': ["NA"],
  'Testing': ["NA"],
}

function changecat(value) {
  if (value.length == 0) document.getElementById("category").innerHTML = "<option></option>";
  else {
    var catOptions = "";
    for (categoryId in requestTypes[value]) {
      catOptions += "<option value='" + requestTypes[value][categoryId] + "'>" + requestTypes[value][categoryId] + "</option>";
    }
    document.getElementById("category").innerHTML = catOptions;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="hidden" name="requestName" id="requestName" value=""></input>
<input type="hidden" name="requestTypes" id="requestTypes" value=""></input></code>```

Body:
I am not at all proficient in JavaScript. I have tried many ways to get the menu values into an html input form.

Here is the JavaScript and HTML code. I want the values to go into these input fields...

function ShowHideDiv() {
  var options = document.getElementById("options");
  var requestName = document.getElementById("requestName");
  requestName.style.display = options.value == "Licensing" ? "block" : "none";
  requestName1.style.display = options.value == "Reporting" ? "block" : "none";
  requestName2.style.display = options.value == "Specification / Compatibility" ? "block" : "none";
  requestName3.style.display = options.value == "Operation / How To" ? "block" : "none";
  requestName4.style.display = options.value == "Installation / Uninstallation" ? "block" : "none";
  requestName5.style.display = options.value == "Upgrade / Downgrade" ? "block" : "none";
  requestName6.style.display = options.value == "Configuration / Workflow" ? "block" : "none";
  requestName7.style.display = options.value == "Administration" ? "block" : "none";
  requestName8.style.display = options.value == "Ordering / Replacing" ? "block" : "none";
  requestName9.style.display = options.value == "Documentation" ? "block" : "none";
  requestName10.style.display = options.value == "Security / Vulnerabilities" ? "block" : "none";
  requestName11.style.display = options.value == "Training" ? "block" : "none";
  requestName12.style.display = options.value == "Testing" ? "block" : "none";
}

var requestTypes = {
  'Licensing': ["Request", "Reset", "Renewal", "Upgrade / Downgrade", "Transfer", "How-To"],
  'Reporting': ["Creation", "Modification"],
  'Specification / Compatibility': ["NA"],
  'Operation / How To': ["Administration", "User assistance"],
  'Installation / Uninstallation': ["NA"],
  'Upgrade / Downgrade': ["Software Request"],
  'Configuration / Workflow': ["Modification", "Creation"],
  'Administration': ["NA"],
  'Ordering / Replacing': ["NA"],
  'Documentation': ["NA"],
  'Security / Vulnerabilities': ["NA"],
  'Training': ["NA"],
  'Testing': ["NA"],
}

function changecat(value) {
  if (value.length == 0) document.getElementById("category").innerHTML = "<option></option>";
  else {
    var catOptions = "";
    for (categoryId in requestTypes[value]) {
      catOptions += "<option value='" + requestTypes[value][categoryId] + "'>" + requestTypes[value][categoryId] + "</option>";
    }
    document.getElementById("category").innerHTML = catOptions;
  }
}

<input type="hidden" name="requestName" id="requestName" value=""></input>
<input type="hidden" name="requestTypes" id="requestTypes" value=""></input>


问:
How to ask login with middleware everytime I refresh the page or open new tab?
I work in Kubernetes and I have an app I can access with a K8S service and ingress traefik with the following yaml script:

```<code>---
apiVersion: v1
kind: Secret
metadata:
  name: whoami-login
  namespace: XXX
data:
  users: XXX       # Had it with: htpasswd -nb XX XX| base64
---
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: whoami-login
  namespace: XXX
spec:
  basicAuth:
    secret: whoami-login
    removeHeader: true
---
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: login
  namespace: XXX
spec:
  entryPoints:
    - websecure
  routes:
  - match: Host(`testnifi.com`)  && Pathprefix(`/nifi`)
    kind: Rule
    services:
    - name: nifi
      port: 8080
    middlewares:
    - name: whoami-login
  tls: {}
</code>```

The url is working well and I have a popup asking me to enter a login and password. When I open the link or refresh the page it doesn't ask me to login again. How can I do to achieve it ? To being asked to login everytime when I refresh the url or open the url on other tab ?

Body:
I work in Kubernetes and I have an app I can access with a K8S service and ingress traefik with the following yaml script:

---
apiVersion: v1
kind: Secret
metadata:
  name: whoami-login
  namespace: XXX
data:
  users: XXX       # Had it with: htpasswd -nb XX XX| base64
---
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: whoami-login
  namespace: XXX
spec:
  basicAuth:
    secret: whoami-login
    removeHeader: true
---
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: login
  namespace: XXX
spec:
  entryPoints:
    - websecure
  routes:
  - match: Host(`testnifi.com`)  && Pathprefix(`/nifi`)
    kind: Rule
    services:
    - name: nifi
      port: 8080
    middlewares:
    - name: whoami-login
  tls: {}

The url is working well and I have a popup asking me to enter a login and password. When I open the link or refresh the page it doesn't ask me to login again. How can I do to achieve it ? To being asked to login everytime when I refresh the url or open the url on other tab ?


问:
get the name of the argument that was sent
I need a way to get the parameter that was sent name.

for example

```<code>class Message:
    I = 1
    LIKE = 2
    COODING = 3

sendData(Message.LIKE)

def sendData(arg):
    print(arg.name) -> Message.LIKE
    print(arg.value) -> 2
</code>```

And before some says use class Message(Enum):  this is prebuilt Class so I can't change the class itself.

I have tried stuff like

```<code>sendData(enum(Message.LIKE))
</code>```

and check via inspect module the method call signature with no luck

EDIT:
This is no duplicated, as I says. I cant change class Message to class Message(Enum)

Body:
I need a way to get the parameter that was sent name.

for example

class Message:
    I = 1
    LIKE = 2
    COODING = 3

sendData(Message.LIKE)

def sendData(arg):
    print(arg.name) -> Message.LIKE
    print(arg.value) -> 2

And before some says use class Message(Enum):  this is prebuilt Class so I can't change the class itself.

I have tried stuff like

sendData(enum(Message.LIKE))

and check via inspect module the method call signature with no luck

EDIT:
This is no duplicated, as I says. I cant change class Message to class Message(Enum)


问:
What happens with the Akka cluster when the Kafka cluster goes down?
Does Akka cluster also goes down when the Kafka cluster is down?</p>