问:
Append date from another table without joining
I have two tables in oracle that has data for different years.

Table 1: This has data for years 2016 - 2018. This is a static table ie wont be refreshed again.
Table 2: This table has data for years >= 2019. This table is being refreshed 3 times a week and has a column REFRESH_DATE that contains the last refreshed date.

Now I have to do a union of table 1 and table 2 but since table 1 is static how do I take table 2's refresh date to table 1?

For example 1) Current Scenario:

```<code>with tABLE_1 as

( select  '99WC2008' as pol_id, to_date( '1/23/2016','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '-1' as Model from dual Union all
select  '96WC2003' as pol_id,  to_date('1/22/2016','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.34' as Model from dual Union all
select  '90WC2003' as pol_id,  to_date('1/21/2017','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.55' as Model from dual Union all
select  '10XYZ23' as pol_id,  to_date('1/12/2017','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0' as Model from dual Union all
select  '09XYZ23' as pol_id,  to_date('1/11/2018','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0.3' as Model from dual)
,
TABLE_2 AS

( select  'XWG5564' as pol_id, to_date( '1/23/2019','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '-1' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
select  'TTFG556' as pol_id,  to_date('1/22/2020','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.34' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
select  'TTH676Y' as pol_id,  to_date('1/21/2021','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.55' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
Select  'DFE5756' as pol_id,  to_date('2/01/2022','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
select  '567HNG6' as pol_id,  to_date('2/08/2022','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0.3' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual)

SELECT * FROM
(
select pol_id,  Eff_dt, industry, model  from TABLE_1
UNION ALL
select pol_id,  Eff_dt, industry, model  from TABLE_2
)
ORDER BY EFF_DT DESC

2) Required_output: Always taking the Refresh date from Table_2 and display it in Table_1 as well.

    with tABLE_1 as

    ( select  '99WC2008' as pol_id, to_date( '1/23/2016','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '-1' as Model from dual Union all
    select  '96WC2003' as pol_id,  to_date('1/22/2016','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.34' as Model from dual Union all
    select  '90WC2003' as pol_id,  to_date('1/21/2017','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.55' as Model from dual Union all
    select  '10XYZ23' as pol_id,  to_date('1/12/2017','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0' as Model from dual Union all
    select  '09XYZ23' as pol_id,  to_date('1/11/2018','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0.3' as Model from dual)
    ,
    TABLE_2 AS

    ( select  'XWG5564' as pol_id, to_date( '1/23/2019','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '-1' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
    select  'TTFG556' as pol_id,  to_date('1/22/2020','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.34' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
    select  'TTH676Y' as pol_id,  to_date('1/21/2021','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.55' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
    Select  'DFE5756' as pol_id,  to_date('2/01/2022','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
    select  '567HNG6' as pol_id,  to_date('2/08/2022','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0.3' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual)

    SELECT * FROM
    (
    select pol_id,  Eff_dt, industry, model ,  to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from TABLE_1
    UNION ALL
    select pol_id,  Eff_dt, industry, model ,REFRESH_DATE  from TABLE_2
    )
    ORDER BY EFF_DT DESC
</code>```

Is it possible to get data from another table without joining? In the above Union step i am hardcoding the date for table_1, the requirement is to automatically pull that date from table_2.

答:
Since all the REFRESH_DATEs are identical, you can use:

SELECT pol_id,
       Eff_dt,
       industry,
       model,
       (SELECT REFRESH_DATE FROM table_2 WHERE ROWNUM = 1) as REFRESH_DATE
from   TABLE_1
UNION ALL
SELECT pol_id,
       Eff_dt,
       industry,
       model,
       REFRESH_DATE
from   TABLE_2
ORDER BY EFF_DT DESC
```

Alternatively, you could use FETCH FIRST ROW ONLY or MAX(refresh_date).

db<>fiddle here

Body:
I have two tables in oracle that has data for different years.

Table 1: This has data for years 2016 - 2018. This is a static table ie wont be refreshed again.
Table 2: This table has data for years >= 2019. This table is being refreshed 3 times a week and has a column REFRESH_DATE that contains the last refreshed date.

Now I have to do a union of table 1 and table 2 but since table 1 is static how do I take table 2's refresh date to table 1?

For example 1) Current Scenario:

with tABLE_1 as

( select  '99WC2008' as pol_id, to_date( '1/23/2016','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '-1' as Model from dual Union all
select  '96WC2003' as pol_id,  to_date('1/22/2016','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.34' as Model from dual Union all
select  '90WC2003' as pol_id,  to_date('1/21/2017','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.55' as Model from dual Union all
select  '10XYZ23' as pol_id,  to_date('1/12/2017','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0' as Model from dual Union all
select  '09XYZ23' as pol_id,  to_date('1/11/2018','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0.3' as Model from dual)
,
TABLE_2 AS

( select  'XWG5564' as pol_id, to_date( '1/23/2019','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '-1' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
select  'TTFG556' as pol_id,  to_date('1/22/2020','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.34' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
select  'TTH676Y' as pol_id,  to_date('1/21/2021','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.55' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
Select  'DFE5756' as pol_id,  to_date('2/01/2022','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
select  '567HNG6' as pol_id,  to_date('2/08/2022','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0.3' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual)

SELECT * FROM
(
select pol_id,  Eff_dt, industry, model  from TABLE_1
UNION ALL
select pol_id,  Eff_dt, industry, model  from TABLE_2
)
ORDER BY EFF_DT DESC

2) Required_output: Always taking the Refresh date from Table_2 and display it in Table_1 as well.

    with tABLE_1 as

    ( select  '99WC2008' as pol_id, to_date( '1/23/2016','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '-1' as Model from dual Union all
    select  '96WC2003' as pol_id,  to_date('1/22/2016','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.34' as Model from dual Union all
    select  '90WC2003' as pol_id,  to_date('1/21/2017','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.55' as Model from dual Union all
    select  '10XYZ23' as pol_id,  to_date('1/12/2017','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0' as Model from dual Union all
    select  '09XYZ23' as pol_id,  to_date('1/11/2018','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0.3' as Model from dual)
    ,
    TABLE_2 AS

    ( select  'XWG5564' as pol_id, to_date( '1/23/2019','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '-1' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
    select  'TTFG556' as pol_id,  to_date('1/22/2020','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.34' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
    select  'TTH676Y' as pol_id,  to_date('1/21/2021','mm/dd/yyyy') as Eff_dt , 'RETAIL' as industry , '0.55' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
    Select  'DFE5756' as pol_id,  to_date('2/01/2022','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual Union all
    select  '567HNG6' as pol_id,  to_date('2/08/2022','mm/dd/yyyy') as Eff_dt , 'TECH' as industry , '0.3' as Model, to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from dual)

    SELECT * FROM
    (
    select pol_id,  Eff_dt, industry, model ,  to_date( '2/08/2022','mm/dd/yyyy') as REFRESH_DATE from TABLE_1
    UNION ALL
    select pol_id,  Eff_dt, industry, model ,REFRESH_DATE  from TABLE_2
    )
    ORDER BY EFF_DT DESC

Is it possible to get data from another table without joining? In the above Union step i am hardcoding the date for table_1, the requirement is to automatically pull that date from table_2.

Body:
Since all the REFRESH_DATEs are identical, you can use:

SELECT pol_id,
       Eff_dt,
       industry,
       model,
       (SELECT REFRESH_DATE FROM table_2 WHERE ROWNUM = 1) as REFRESH_DATE
from   TABLE_1
UNION ALL
SELECT pol_id,
       Eff_dt,
       industry,
       model,
       REFRESH_DATE
from   TABLE_2
ORDER BY EFF_DT DESC

Alternatively, you could use FETCH FIRST ROW ONLY or MAX(refresh_date).

db<>fiddle here


来源: stackexchange

问:
Error creating RegionNetworkEndpointGroup: googleapi: Error 403: Required 'compute.regionNetworkEndpointGroups.create' permission for 'projects/myproj
On GCP, I'm trying to create a Serverless Network Endpoint Group for Cloud Run with this Terraform code below:

resource "google_compute_region_network_endpoint_group" "cloudrun_neg" {
  name                  = "neg"
  network_endpoint_type = "SERVERLESS"
  region                = "asia-northeast1"
  cloud_run {
    service = google_cloud_run_service.default.name
  }
}
```

But I got this error below:

Error creating RegionNetworkEndpointGroup: googleapi: Error 403:
Required 'compute.regionNetworkEndpointGroups.create' permission for
'projects/myproject-813731/regions/asia-northeast1/networkEndpointGroups/neg',
forbidden

So now, I'm trying to add a role to solve this error above but there are too many roles to choose:

What role do I need to choose?

答:
You need to choose the role either "Compute Instance Admin (v1)":

Or "Compute Instance Admin (beta)" to create a Serverless Network Endpoint Group for Cloud Run:

In addition, you can choose the more abstract role "Compute Admin" to create a Serverless Network Endpoint Group for Cloud Run:

ContentLicense: CC BY-SA 4.0

Body:
On GCP, I'm trying to create a Serverless Network Endpoint Group for Cloud Run with this Terraform code below:

resource "google_compute_region_network_endpoint_group" "cloudrun_neg" {
  name                  = "neg"
  network_endpoint_type = "SERVERLESS"
  region                = "asia-northeast1"
  cloud_run {
    service = google_cloud_run_service.default.name
  }
}

But I got this error below:

Error creating RegionNetworkEndpointGroup: googleapi: Error 403:
Required 'compute.regionNetworkEndpointGroups.create' permission for
'projects/myproject-813731/regions/asia-northeast1/networkEndpointGroups/neg',
forbidden

So now, I'm trying to add a role to solve this error above but there are too many roles to choose:

What role do I need to choose?


问:
$.getJSON for progress bar NOT working in Safari and Chrome (but OK in IE6+ and FF)
This one's perhaps a little long-winded, but it's really baffling me and a couple of other people.

We've got a progress bar that's updated during file uploads. The JS is here (too much to paste into this body).

Basically, the form submit event starts a timer loop which, every 2 secs, fires a $.getJSON() call to the server to retrieve a pair of values about the status of the upload. These values are then passed to a function that updates the progress bar. The JSON values returned are def valid JSON.

Now, this code works fine on Firefox and all IEs (even 6), so I'm pretty confident that the server-side code is robust, but... in Safari and Chrome, the progress bar just doesn't update at all.

The upload is processed by Apache fine, and console.log() debugging shows that the timer loop is definitely running -- it's just that getJSON seems not to be firing (the web inspectors don't show the call, and neither does the Apache log.

As said, it's a bit baffling. Anyone come across this before with Chrome/Safari/Webkit?

答:
It seems that Chrome's JSON.parse barfs on escaped apostrophe:

```<code>[ "barf\'" ]
</code>```

while unescaped apostrophe works fine:

```<code>[ "accept'" ]
</code>```

I have been able to circumvent similar problem by leaving the apostrophe unquoted for Webkit based browsers. It might be something similar in your case.

ContentLicense: CC BY-SA 2.5

Body:
It seems that Chrome's JSON.parse barfs on escaped apostrophe:

[ "barf\'" ]

while unescaped apostrophe works fine:

[ "accept'" ]

I have been able to circumvent similar problem by leaving the apostrophe unquoted for Webkit based browsers. It might be something similar in your case.

ContentLicense: CC BY-SA 3.0


问:
Rng getting randomness from operating system vs crypto rng's
this is a question that does have a lot of overlap with what might be posted on cryptography stack exchange,but it's mostly Rust-specific, and thus I posted it here.

So I have an application that needs to use a DH keypair.

It's important that this project is academic only,  this code will not be used in any prod environments.

I'm working in a context that already uses a crate called x25519_dalek and thus it makes sense to keep using that resource for my own creation of keypairs.

The documentiation gives this example of key creation:

```<code>use rand_core::OsRng;
use x25519_dalek::{EphemeralSecret, PublicKey};

let alice_secret = EphemeralSecret::new(OsRng);
let alice_public = PublicKey::from(&alice_secret);
</code>```

Which is nice and straight forward, we simply pass a rng to the ephemeral secret to get a secret key, and form there get the PK.

But this is where I start to wonder. The Osrng uses the OS to generate some randomness. But the docs for rand_core does'nt mention anything about it being a cryptographically secure CSPRG.

On the other hand, I have before used the rand package and it's Stdrng rng, to  create random lists of numbers for IV's. Since this this rng is mentioned specifically as a crypto secure rng

```<code>use rand::{rngs::StdRng, Rng, SeedableRng,};
use rand_core::{RngCore, OsRng, CryptoRng,};
fn main() {
  let mut rng : StdRng = StdRng::from_entropy();
  let seed = rng.gen::<[u8;32]>();
}
</code>```

This makes me wonder whether the usage of a bare-bones rng like OSrng is likely safe to use for creation of keying material. Or if I should perhaps rather shoot for a rng that has is made for usage in crypto.

If it is the case that I should find another source of randomness for the creation of keying material, then I have a question about how to do this in rust (I'm quite new to rust).

It's a little unclear to me which kinds of rngs that I should be able to give the the constructor on EphemeralSecret. The signature of it looks like this:

```<code>pub fn new<T: RngCore + CryptoRng>(mut csprng: T) -> Self {
</code>```

I then tried to pass in the Stdrng from the rand crate:

```<code>use rand::{rngs::StdRng, Rng, SeedableRng,};
use rand_core::{RngCore, OsRng, CryptoRng,};
fn main() {

  let secretk = EphemeralSecret::new(StdRng);
}
</code>```

Which fails with the message "expected value, found struct StdRng" which is strange to me, because the OsRng is also a struct.

I also tried initializing a rng and passing it:

```<code>  let mut rng : StdRng = StdRng::from_entropy();
  let seed = rng.gen::<[u8;32]>();

  let secretk = EphemeralSecret::new(rng);
</code>```

So the second question is, does anyone know if there is a way for me to create keying material in with x25519_dalek, using a crpytographically secure source of randomness in the standard rand crate?

答:
OsRng should be cryptographically secure.  It implements CryptoRng, which is a trait only implemented for cryptographically secure PRNGs, and it's backed by the getrandom crate, which always uses the system's (or, in the case of WebAssembly, the environment's) CSPRNG.

It is always a sensible choice for a CSPRNG, but as mentioned in the comments, it isn't always very fast, since it involves a system call per operation, and the system's CSPRNG isn't always very fast, either.  In such a case, you can use ThreadRng, which will be faster and is also cryptographically secure.

Body:
this is a question that does have a lot of overlap with what might be posted on cryptography stack exchange,but it's mostly Rust-specific, and thus I posted it here.

So I have an application that needs to use a DH keypair.

It's important that this project is academic only,  this code will not be used in any prod environments.

I'm working in a context that already uses a crate called x25519_dalek and thus it makes sense to keep using that resource for my own creation of keypairs.

The documentiation gives this example of key creation:

use rand_core::OsRng;
use x25519_dalek::{EphemeralSecret, PublicKey};

let alice_secret = EphemeralSecret::new(OsRng);
let alice_public = PublicKey::from(&alice_secret);

Which is nice and straight forward, we simply pass a rng to the ephemeral secret to get a secret key, and form there get the PK.

But this is where I start to wonder. The Osrng uses the OS to generate some randomness. But the docs for rand_core does'nt mention anything about it being a cryptographically secure CSPRG.

On the other hand, I have before used the rand package and it's Stdrng rng, to  create random lists of numbers for IV's. Since this this rng is mentioned specifically as a crypto secure rng

use rand::{rngs::StdRng, Rng, SeedableRng,};
use rand_core::{RngCore, OsRng, CryptoRng,};
fn main() {
  let mut rng : StdRng = StdRng::from_entropy();
  let seed = rng.gen::<[u8;32]>();
}

This makes me wonder whether the usage of a bare-bones rng like OSrng is likely safe to use for creation of keying material. Or if I should perhaps rather shoot for a rng that has is made for usage in crypto.

If it is the case that I should find another source of randomness for the creation of keying material, then I have a question about how to do this in rust (I'm quite new to rust).

It's a little unclear to me which kinds of rngs that I should be able to give the the constructor on EphemeralSecret. The signature of it looks like this:

pub fn new<T: RngCore + CryptoRng>(mut csprng: T) -> Self {

I then tried to pass in the Stdrng from the rand crate:

use rand::{rngs::StdRng, Rng, SeedableRng,};
use rand_core::{RngCore, OsRng, CryptoRng,};
fn main() {

  let secretk = EphemeralSecret::new(StdRng);
}

Which fails with the message "expected value, found struct StdRng" which is strange to me, because the OsRng is also a struct.

I also tried initializing a rng and passing it:

  let mut rng : StdRng = StdRng::from_entropy();
  let seed = rng.gen::<[u8;32]>();

  let secretk = EphemeralSecret::new(rng);

So the second question is, does anyone know if there is a way for me to create keying material in with x25519_dalek, using a crpytographically secure source of randomness in the standard rand crate?


问:
Hello! How to do this with a function for date and year?
--7. Create a query which lists out all of the events which took place in February 2005:--</p>
```<code>SELECT *
FROM tblEvent
WHERE EventDate BETWEEN '2005-02-01' AND '20050228';
</code>```

答:
try this:

```<code>SELECT * FROM tblEvent WHERE year(EventDate)=2005 and month(EventDate)=2
</code>```

in SQL Server

Body:
--7. Create a query which lists out all of the events which took place in February 2005:--

SELECT *
FROM tblEvent
WHERE EventDate BETWEEN '2005-02-01' AND '20050228';

Body:
try this:

SELECT * FROM tblEvent WHERE year(EventDate)=2005 and month(EventDate)=2

in SQL Server


问:
Xcode : failed to get the task for process
This is for an existing app that compiled and distributed multiple times. Since updating to Xcode 5 I have this error popping.

I have my developers profile selected in the Code Signing for debug.

Deleted the Derived Data a few times.

Quit a few times

Downloaded and tried to re-add my Developers certificates.

Reset my computer! And checked updates

Tried using black magic!

The Scheme > Build Configuration is set to Debug

The odd circumstances I am compiling to compile to iOS 6.1 so I can run on my iPhone 3GS - the base is SDK iOS 7? Could this be an issue? I just need to test it before finding a newer phone to before change it to iOS 7.

答:
I had the same issue and solved it , basically to understand what happened see this answer here, and adding to it you can :

select your schema and press Edit schema

On Run tab make sure to set Build Configuration to Debug


问:
How to set up a basic Peerjs connection?
I am quite new to Javascript so please bear in mind I may be quite slow to understand things. I have spent several hours trying to get a very simple peerjs connection where there are two users who run a html file in the browser, connect and then send hello to eachother. I've tried everything I can think of and have looked at all the documentation but can't seem to even get a connection to work. This is what I have so far (largely taken from this page https://peerjs.com/docs.html):

For User1:

```<code><html>
    <body>
        <script src="https://unpkg.com/peerjs@1.3.1/dist/peerjs.min.js"></script>
        <script src="test1.js"></script>
    </body>
</html>

__test1.js__
var peer = new Peer("User1");
peer.on('open', function(id) {
  console.log('My peer ID is: ' + id);
});
var conn = peer.connect('User2');
</code>```

For User2:

```<code><html>
    <body>
        <script src="https://unpkg.com/peerjs@1.3.1/dist/peerjs.min.js"></script>
        <script src="test2.js"></script>
    </body>
</html>

__test2.js__
var peer = new Peer("User2");
peer.on('open', function(id) {
  console.log('My peer ID is: ' + id);
});
peer.on('connection', function(conn) { console.log("Connected") });
</code>```

When I run the second HTML file followed by the first, I correctly get their ID's outputted but the connection never happens. What am I doing wrong? Thank you.

答:
You need to connect to a peer after connection to the server is established.

This means you need to invoke connect after the open callback:

```<code>var peer = new Peer("User1");
peer.on('open', function(id) {
  console.log('My peer ID is: ' + id);
  var conn = peer.connect('User2');
});
</code>```

Body:
I am quite new to Javascript so please bear in mind I may be quite slow to understand things. I have spent several hours trying to get a very simple peerjs connection where there are two users who run a html file in the browser, connect and then send hello to eachother. I've tried everything I can think of and have looked at all the documentation but can't seem to even get a connection to work. This is what I have so far (largely taken from this page https://peerjs.com/docs.html):

For User1:

__test1.js__
var peer = new Peer("User1");
peer.on('open', function(id) {
  console.log('My peer ID is: ' + id);
});
var conn = peer.connect('User2');

For User2:

__test2.js__
var peer = new Peer("User2");
peer.on('open', function(id) {
  console.log('My peer ID is: ' + id);
});
peer.on('connection', function(conn) { console.log("Connected") });

When I run the second HTML file followed by the first, I correctly get their ID's outputted but the connection never happens. What am I doing wrong? Thank you.

Body:
You need to connect to a peer after connection to the server is established.

This means you need to invoke connect after the open callback:

var peer = new Peer("User1");
peer.on('open', function(id) {
  console.log('My peer ID is: ' + id);
  var conn = peer.connect('User2');
});


问:
Sympy function evaluated at symbol
I have a problem with the symbolic Python package Sympy.
Perhaps I am missing some obvious tools in Sympy but I have read through the documentation and not come across a solution.

My question is can the derivative of g(f(y)) = g(f(x))|_(x=y) with respect to x be obtained in the form Derivative(f(x), x)(y) in Sympy? And if so how?

Here is a simple example: I have a symbolic function of one variable e.g. f(x).
I have another expression g, which calls this function with input arguments
represented by other symbols, i.e. g(f(y)) where y = Symbol('y').
I implement this with the following:

```<code>x = Symbol('x')
f = Function('f')(x)
y = Symbol('y')
g = Function('g')(f).subs('x','y')
</code>```

My goal is then to evaluate the derivative of g wrt x at x=y, something like

Derivative(f(x), x)(y) * Derivative(g(f), f)(f(y))

This can be roughly achieved with

diff(g, y) = Derivative(f(y), y)*Derivative(g(f(y)), f(y)).

The problem here is that the term Derivative(f(y), y) in this case is the derivative evaluated at y.
I have expressions for the derivatives of functions wrt all input variables, i.e. Derivative(f(x), x) in this case, and not wrt y since it is not a variable of f. Hence, I would like the derivative expressed in the form Derivative(f(x), x)(y) to avoid repeating the same expression for all the possible variables used.
(For completeness, the term diff(g, x)=0 since any instances of x have been replaced by y.)

To enforce the notion that g is a function of x evaluated at y, replacing the method subs of the fourth line above with the evalf method could be the right path. But it seems that expression can only be evaluated at particular values and not other symbolic variables.

Any help and advice is most appreciated.

答:
Wrapping the differentiation in Subs seems to work; it is a delayed substitution.

```<code>>>> from sympy import Subs, sin, cos
>>> from sympy.abc import x, y
>>> f, g = symbols('f g', cls=Function)
>>> Subs(g(f(x)).diff(x),x,y).subs(g,sin).subs(f,cos).doit(
... ) == Subs(sin(cos(x)).diff(x),x,y).doit()
True
</code>```

Title: Sympy function evaluated at symbol

Body:
I have a problem with the symbolic Python package Sympy.
Perhaps I am missing some obvious tools in Sympy but I have read through the documentation and not come across a solution.

My question is can the derivative of g(f(y)) = g(f(x))|_(x=y) with respect to x be obtained in the form Derivative(f(x), x)(y) in Sympy? And if so how?

Here is a simple example: I have a symbolic function of one variable e.g. f(x).
I have another expression g, which calls this function with input arguments
represented by other symbols, i.e. g(f(y)) where y = Symbol('y').
I implement this with the following:

x = Symbol('x')
f = Function('f')(x)
y = Symbol('y')
g = Function('g')(f).subs('x','y')

My goal is then to evaluate the derivative of g wrt x at x=y, something like

Derivative(f(x), x)(y) * Derivative(g(f), f)(f(y))

This can be roughly achieved with

diff(g, y) = Derivative(f(y), y)*Derivative(g(f(y)), f(y)).

The problem here is that the term Derivative(f(y), y) in this case is the derivative evaluated at y.
I have expressions for the derivatives of functions wrt all input variables, i.e. Derivative(f(x), x) in this case, and not wrt y since it is not a variable of f. Hence, I would like the derivative expressed in the form Derivative(f(x), x)(y) to avoid repeating the same expression for all the possible variables used.
(For completeness, the term diff(g, x)=0 since any instances of x have been replaced by y.)

To enforce the notion that g is a function of x evaluated at y, replacing the method subs of the fourth line above with the evalf method could be the right path. But it seems that expression can only be evaluated at particular values and not other symbolic variables.

Any help and advice is most appreciated.

Body:
Wrapping the differentiation in Subs seems to work; it is a delayed substitution.

>>> from sympy import Subs, sin, cos
>>> from sympy.abc import x, y
>>> f, g = symbols('f g', cls=Function)
>>> Subs(g(f(x)).diff(x),x,y).subs(g,sin).subs(f,cos).doit(
... ) == Subs(sin(cos(x)).diff(x),x,y).doit()
True


问:
Header and footer by uploading PDF
I have multiple PDFs for which I want to insert Header and footer to them automatically while taking printout. Please suggest how to proceed.

Header and footer should display in background and body of PDF should not get altered.

答:
A solution for Windows:
You can use CIB pdf brewer, which is available at https://pdfbrewer.cib.de/. It is a free PDF processor.
Just select all PDFs, which should be processed in the file explorer and right click on CIB pdf brewer => convert. Then you can define a profile with a stationery paper (as pdf or png) which should contain your footer and header and all files will be processed according to that profile.

As a post-Action you could also define to print the resulting pdf to a printer directly.

Title: Header and footer by uploading PDF


问:
Python, Determine if a string should be converted into Int or Float
I want to convert a string to the tightest possible datatype: int or float.

I have two strings:

```<code>value1="0.80"     #this needs to be a float
value2="1.00"     #this needs to be an integer.
</code>```

How I can determine that value1 should be Float and value2 should be Integer in Python?

答:
Example for a short function:
Returns the numeric type of a string (float or int),
for non-numeric strings the str type is returned.

```<code>def numeric_type_of_string(string: str):
    if string.isnumeric():
        return int
    try:
        val = float(string)
        return int if val == int(val) else float
    except (TypeError, ValueError):
        return str
</code>```

In case you directly want the converted value simply modify the return value:

```<code>def string_to_numeric_if_possible(string: str):
    if string.isnumeric():
        return int(string)
    try:
        val = float(string)
        return int(val) if val == int(val) else val
    except (TypeError, ValueError):
        return string
</code>```

Body:
I want to convert a string to the tightest possible datatype: int or float.

I have two strings:

value1="0.80"     #this needs to be a float
value2="1.00"     #this needs to be an integer.

How I can determine that value1 should be Float and value2 should be Integer in Python?

Body:
Example for a short function:
Returns the numeric type of a string (float or int),
for non-numeric strings the str type is returned.

def numeric_type_of_string(string: str):
    if string.isnumeric():
        return int
    try:
        val = float(string)
        return int if val == int(val) else float
    except (TypeError, ValueError):
        return str

In case you directly want the converted value simply modify the return value:

def string_to_numeric_if_possible(string: str):
    if string.isnumeric():
        return int(string)
    try:
        val = float(string)
        return int(val) if val == int(val) else val
    except (TypeError, ValueError):
        return string


问:
Converting "Stream<String>" to "String" in java8 to combine group of strings in a stream
I want to convert Stream<String> to String and print all the string.

```<code>Stream<String> result= Stream.of("do","re","ma","po","fa","si")
                             .filter(str -> str.length()>5)
                             .peek(System.out:: println);
                           //.allMatch(str -> str.length() >5);

System.out.println(result);
</code>```

Here down output i get

java.util.Spliterators$1Adapter@63961c42

The result is printing an object but not a String and while converting to toString() also printing the same but how to print as a String

答:
Do you looking for something like this?

```<code>    String result = Stream.of("do","re","ma","po","fa","si").
                collect(Collectors.joining(""));
    System.out.println(result);
</code>```

Output:

```<code>doremapofasi
</code>```

Or:

```<code>        String result = Stream.of("do", "re", "ma", "po", "fa", "si")
            .filter(str -> str.length() > 1)
            .peek(System.out::println)
            .collect(Collectors.joining(""));
        System.out.println(result);
</code>```

Output:

```<code>do
re
ma
po
fa
si
doremapofasi
</code>```

Body:
I want to convert Stream<String> to String and print all the string.

Stream<String> result= Stream.of("do","re","ma","po","fa","si")
                             .filter(str -> str.length()>5)
                             .peek(System.out:: println);
                           //.allMatch(str -> str.length() >5);

System.out.println(result);

Here down output i get

java.util.Spliterators$1Adapter@63961c42

The result is printing an object but not a String and while converting to toString() also printing the same but how to print as a String

Body:
Do you looking for something like this?

    String result = Stream.of("do","re","ma","po","fa","si").
                collect(Collectors.joining(""));
    System.out.println(result);

Output:

doremapofasi

Or:

        String result = Stream.of("do", "re", "ma", "po", "fa", "si")
            .filter(str -> str.length() > 1)
            .peek(System.out::println)
            .collect(Collectors.joining(""));
        System.out.println(result);

Output:

do
re
ma
po
fa
si
doremapofasi


问:
argparse argument order issue
I am using subparsers to implement the following function:

```<code>import argparse

parser = argparse.ArgumentParser(prog='dj')
parser.add_argument('--log','-l',type=str, help='log file')
parser.add_argument('--parser','-p',type=bool, nargs='?', const=True, default=False, help='wheher parsing a dj file or not')
subparsers = parser.add_subparsers(help='execute specified command')
###############################################################################
parser_rt = subparsers.add_parser('run_test', help='kick off a case')
parser_rt.add_argument('--test', '-t', type=str, help='test case name')
parser_rt.add_argument('--config','-c', type=str, help='config name')
parser_rt.set_defaults(func=run_test)
</code>```

everything is fine when kicking off the command:

```<code>dj -p -l dj.log run_test -t testa -c configa
</code>```

or

```<code>dj -l dj.log run_test -t testa -c configa
</code>```

However, issue was popping up when running the command:

```<code>dj -l dj.log -p run_test -t testa -c configa
</code>```

Here is error:

```<code>usage: dj [-h] [--log log] [--parser [PARSER]]
       {run_test}...
dj: error: invalid choice: 'testa' (choose from 'run_test')
</code>```

It seems that the issue is related to the position of -p.

答:
In your code, -p might take an argument. Is that intended or do you rather want just a flag?

    parser.add_argument('--parser','-p', action="store_true", help='whether parsing a dj file or not')
```

When you run dj -l dj.log -p run_test -t testa -c configa the parser thinks that run_test is an argument to -p.

Title: argparse argument order issue

Body:
I am using subparsers to implement the following function:

import argparse

parser = argparse.ArgumentParser(prog='dj')
parser.add_argument('--log','-l',type=str, help='log file')
parser.add_argument('--parser','-p',type=bool, nargs='?', const=True, default=False, help='wheher parsing a dj file or not')
subparsers = parser.add_subparsers(help='execute specified command')
###############################################################################
parser_rt = subparsers.add_parser('run_test', help='kick off a case')
parser_rt.add_argument('--test', '-t', type=str, help='test case name')
parser_rt.add_argument('--config','-c', type=str, help='config name')
parser_rt.set_defaults(func=run_test)

everything is fine when kicking off the command:

dj -p -l dj.log run_test -t testa -c configa

or

dj -l dj.log run_test -t testa -c configa

However, issue was popping up when running the command:

dj -l dj.log -p run_test -t testa -c configa

Here is error:

usage: dj [-h] [--log log] [--parser [PARSER]]
       {run_test}...
dj: error: invalid choice: 'testa' (choose from 'run_test')

It seems that the issue is related to the position of -p.

Body:
In your code, -p might take an argument. Is that intended or do you rather want just a flag?

    parser.add_argument('--parser','-p', action="store_true", help='whether parsing a dj file or not')

When you run dj -l dj.log -p run_test -t testa -c configa the parser thinks that run_test is an argument to -p.


问:
Sending calculated data from one component to another without Services
I want to send the value from one component to another, they are not related so all solutions are saying that I must use shared service to do that. But these services are using templates (if I'm right). Is there a way to do this sharing without services?

I want to send the BMI value from homepage.component.ts to result.component.ts.

homepage.component.ts:

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

constructor() { }

myHeight!:number;
myWeight!:number;

bmi!:number;
  ngOnInit(): void {
  }

  onGenerate(  height:string,width:string){

    this.myHeight = +height;
    this.myHeight=Math.pow(this.myHeight/100,2);

    this.myWeight = +width;
    this.bmi=this.myWeight/this.myHeight

console.log(this.bmi); //this is the calculated value to send

  }
}
</code>```

result.component.ts:

```<code>    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-result',
      templateUrl: './result.component.html',
      styleUrls: ['./result.component.css']
    })
    export class ResultComponent implements OnInit {
      constructor() { }

//I want to get the bmi here
      ngOnInit(): void {
      }

    }
</code>```

答:
Solution: To pass the data from one component to another we can store it in a session storage or a local storage and then access it in other components from that storage. Here I have provided a sample code using local storage for your reference.

homepage.component.ts:

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

constructor() { }

myHeight!:number;
myWeight!:number;
data:string='';

bmi!:number;
  ngOnInit(): void {
  }

  onGenerate(  height:string,width:string){

    this.myHeight = +height;
    this.myHeight=Math.pow(this.myHeight/100,2);

    this.myWeight = +width;
    this.bmi=this.myWeight/this.myHeight;
    this.data=localStorage.setItem('bmi',this.bmi);

    console.log(this.bmi); //this is the calculated value to send

    }
    }
</code>```

resultcomponent.ts:

```<code>  import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-result',
      templateUrl: './result.component.html',
      styleUrls: ['./result.component.css']
    })
    export class ResultComponent implements OnInit {
     data:any;
      constructor() { this.data=localstorage.getItem('bmi')}

      //Access the bmi using the data variable here

      ngOnInit(): void {
      }

    }
</code>```

Body:
I want to send the value from one component to another, they are not related so all solutions are saying that I must use shared service to do that. But these services are using templates (if I'm right). Is there a way to do this sharing without services?

I want to send the BMI value from homepage.component.ts to result.component.ts.

homepage.component.ts:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

constructor() { }

myHeight!:number;
myWeight!:number;

bmi!:number;
  ngOnInit(): void {
  }

  onGenerate(  height:string,width:string){

    this.myHeight = +height;
    this.myHeight=Math.pow(this.myHeight/100,2);

    this.myWeight = +width;
    this.bmi=this.myWeight/this.myHeight

console.log(this.bmi); //this is the calculated value to send

  }
}

result.component.ts:

    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-result',
      templateUrl: './result.component.html',
      styleUrls: ['./result.component.css']
    })
    export class ResultComponent implements OnInit {
      constructor() { }

//I want to get the bmi here
      ngOnInit(): void {
      }

    }

Body:
Solution: To pass the data from one component to another we can store it in a session storage or a local storage and then access it in other components from that storage. Here I have provided a sample code using local storage for your reference.

homepage.component.ts:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

constructor() { }

myHeight!:number;
myWeight!:number;
data:string='';

bmi!:number;
  ngOnInit(): void {
  }

  onGenerate(  height:string,width:string){

    this.myHeight = +height;
    this.myHeight=Math.pow(this.myHeight/100,2);

    this.myWeight = +width;
    this.bmi=this.myWeight/this.myHeight;
    this.data=localStorage.setItem('bmi',this.bmi);

    console.log(this.bmi); //this is the calculated value to send

    }
    }

resultcomponent.ts:

  import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-result',
      templateUrl: './result.component.html',
      styleUrls: ['./result.component.css']
    })
    export class ResultComponent implements OnInit {
     data:any;
      constructor() { this.data=localstorage.getItem('bmi')}

      //Access the bmi using the data variable here

      ngOnInit(): void {
      }

    }


问:
Collapsible seems to be working, however, content not being shown
I am making a website to serve as a hub for all my creative content. I am doing this for a project and I have been following random tutorials to get to where I am. Currently, I am stumped as a collapsible section I am trying to implement is sort of working. In the sense, that when I click the + changes to a - showing the click is being registered. However, the content does not expand, it remains hidden.

HTML code in question:

```<code><section>

<button type="button" class="collapsible"><h5>Click Here to View Entire YouTube Library!</h5></button>
<div class="content">
  <p>Lorem ipsum...ALLLLLLLLLLLLLLLLLLL</p>
</div>
<script src="collapsible.js"></script>
</section>
</code>```

JavaScript being used:

```<code>var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
    } else {
      content.style.display = "block";
    }
  });
}

</code>```

Relates css in case it is required:

```<code>.collapsible {
  background-color: #000;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

.active, .collapsible:hover {
  background-color: #272727;
}
.content {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
}
.collapsible:after {
  content: '\02795'; /* Unicode character for "plus" sign (+) */
  font-size: 13px;
  color: white;
  float: right;
  margin-left: 5px;
}

.active:after {
  content: "\2796"; /* Unicode character for "minus" sign (-) */
}
</code>```

Please keep in mind, I am a newbie following tutorials so I won't have deep understanding of the topic yet. Any help is appreciated. Thank You!

答:
The problem here is wrong styling manipulation, the reason element doesn't appear is because of overflow and not display, display is either block or inline by default (depends on the element). Edit your Javascript code like below:

```<code>    if (content.style.overflow === "visible") {
      content.style.overflow = "hidden";
    } else {
      content.style.overflow = "visible";
    }
</code>```

You have explicitly set overflow: hidden, so that's why changing the display doesn't work.

Body:
I am making a website to serve as a hub for all my creative content. I am doing this for a project and I have been following random tutorials to get to where I am. Currently, I am stumped as a collapsible section I am trying to implement is sort of working. In the sense, that when I click the + changes to a - showing the click is being registered. However, the content does not expand, it remains hidden.

HTML code in question:

<button type="button" class="collapsible">
Click Here to View Entire YouTube Library!
</button>

Lorem ipsum...ALLLLLLLLLLLLLLLLLLL

JavaScript being used:

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
    } else {
      content.style.display = "block";
    }
  });
}

Relates css in case it is required:

.collapsible {
  background-color: #000;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

.active, .collapsible:hover {
  background-color: #272727;
}
.content {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
}
.collapsible:after {
  content: '\02795'; /* Unicode character for "plus" sign (+) */
  font-size: 13px;
  color: white;
  float: right;
  margin-left: 5px;
}

.active:after {
  content: "\2796"; /* Unicode character for "minus" sign (-) */
}

Please keep in mind, I am a newbie following tutorials so I won't have deep understanding of the topic yet. Any help is appreciated. Thank You!

Body:
The problem here is wrong styling manipulation, the reason element doesn't appear is because of overflow and not display, display is either block or inline by default (depends on the element). Edit your Javascript code like below:

    if (content.style.overflow === "visible") {
      content.style.overflow = "hidden";
    } else {
      content.style.overflow = "visible";
    }

You have explicitly set overflow: hidden, so that's why changing the display doesn't work.


问:
Twilio SMS is saying a "to" phone number is not provided even though it is
I have very simple code and I just can't figure out what's going wrong.

I have a Twilio trial account and a trial phone number and I am trying to send an SMS using it.

from os import environ
from twilio.rest import Client

client = Client(environ['ACCOUNT_SID'], environ['AUTH_TOKEN'])

message = client.messages.create(body = f'The verification code for Treal is {code}', from_ = "+1**********", to = "+91**********")
```
<p>The one in the from is my Twilio trial number and the one in the "to" is a number I want to send to. I am getting an error:</p>
<pre class="lang-none prettyprint-override"><code>twilio.base.exceptions.TwilioRestException:
HTTP Error Your request was:

POST /Accounts/AC*******1830e0****a3403dfd16d****/Messages.json

Twilio returned the following information:

Unable to create record: A 'To' phone number is required.

More information may be available here:

https://www.twilio.com/docs/errors/21604
</code>```

答: Check for hidden control characters using a site like https://www.soscisurvey.de/tools/view-chars.php, and simply using a regular string, and see if it works or not and then work to failure.</p>

Body:
I have very simple code and I just can't figure out what's going wrong.

I have a Twilio trial account and a trial phone number and I am trying to send an SMS using it.

from os import environ
from twilio.rest import Client

client = Client(environ['ACCOUNT_SID'], environ['AUTH_TOKEN'])

message = client.messages.create(body = f'The verification code for Treal is {code}', from_ = "+1**********", to = "+91**********")

The one in the from is my Twilio trial number and the one in the "to" is a number I want to send to. I am getting an error:

twilio.base.exceptions.TwilioRestException:
HTTP Error Your request was:

POST /Accounts/AC*******1830e0****a3403dfd16d****/Messages.json

Twilio returned the following information:

Unable to create record: A 'To' phone number is required.

More information may be available here:

https://www.twilio.com/docs/errors/21604


问:
Calculate the Maximum Path Sum in a 2D array
In preparation for a coding interview, I found this question but am struggling to solve it. I'm very sure recursion needs to be used, but I can't seem to get it right.

A 2D array represents a map of cities, where the value at the index represents the number of treasures in that city. Some values in the array are zeros (indicating that they can't be crossed)

Goal: Given a 2D array, return an integer representing the maximum amount of treasures you can collect by travelling from city to city.

Rules:

Can start anywhere in the array

Avoid zeroes (ie. can't be crossed)

You can travel up, down, left, right at 1 index at a time

Possible for different paths to yield same amount of treasures

An empty map should return 0

If the map contains anything other than positive integers, the function should return -1

Eg. Map 1:

[[ 3, 0, 0, 1, 2],

[ 0, 1, 4, 0, 0],

[ 5, 0, 0, 3, 3]]

The maximum reward would be 6 items (3,3)

What I've tried:

I tried creating two for loops to access each index:
First, I check that the current Index is not zero or -1.
If not, then I add value at the current index to an empty array where each path indicated a different position. ie. left = arr[0], right = arr[1], etc.
Then found the possible paths and repeat the same processes
until my array index value is zero (for all paths).

If someone could provide a solution in python, it would be very much appreciated.

答:
The following is a naive approach that uses simple recursion to solve this problem. However, I wouldn't be surprised if there was a smarter solution to the task, preferably without recursion.

import numpy as np

reward_map = np.array(
    [[ 3, 0, 0, 1, 2],
     [ 0, 1, 4, 0, 0],
     [ 5, 0, 0, 3, 3]])

print("Reward map:")
print(reward_map)

# This function checks if [i,j] are valid indices for the matrix "mat"
def are_valid_idcs(mat, i, j):
    return i >= 0 and j >= 0 and i < mat.shape[0] and j < mat.shape[1]

# This is the recursive function that computes the value given a starting point
def get_cell_value(reward_map, i, j):
    if ( not are_valid_idcs(reward_map, i, j) ) or reward_map[i,j] == 0.:
        return 0.
    else:
        # If we are in a "city", we want to check the connected squares.
        # However, from there, we do not want to walk back.
        # That's why I copy the whole map and set [i,j] = 0, meaning this coordinate has already been handled.
        # This is important. If we do not do this, the recursion will not stop.
        submap = np.array(reward_map)
        submap[i,j] = 0.

        # Now we compute the value of our neighbors
        value_left = get_cell_value(submap, i-1, j)
        value_right = get_cell_value(submap, i+1, j)
        value_top = get_cell_value(submap, i, j-1)
        value_bottom = get_cell_value(submap, i, j+1)

        # And add everything together
        return value_left + value_right + value_top + value_bottom + reward_map[i,j]

# Here, we will remember the value and the coordinates where we started
values_per_idcs = []

# Loop over all cells and compute which value we can get if we start at that point
for i in range(reward_map.shape[0]):
    for j in range(reward_map.shape[1]):
        values_per_idcs += [ [ get_cell_value(reward_map, i, j), i, j] ]

# Now we build a numpy [n,3]-array over the results, where n is the total amount of elements in the map
# The 3 components in the 1-axis correspond to [value, i, j].
values_per_idcs = np.array(values_per_idcs, dtype=np.int64)

# Check if there are negative values in the map
if np.any(reward_map < 0):
    print(f" Value is -1 (due to negative values in reward map)")
# Check if all values are integer
elif not issubclass(reward_map.dtype.type, np.integer):
    print(f" Value is -1 (due to non-integer values in reward map)")
# If the input is OK, we can output the actual results
else:
    # in the [n,3]-result-array, find the n which has the maximum value (i.e. at position 0 on axis 1)
    best = np.argmax( values_per_idcs[...,0], axis=0 )

    # Print the best coordinate
    print(f"Maximum value is {values_per_idcs[best,0]} at indices {values_per_idcs[best,1], values_per_idcs[best,2]}")

    # Plot the suggested starting point which is easier for humans to read than the coordinates
    print("Suggested start-point:")
    starter = np.zeros_like(reward_map, dtype=np.int8)
    starter[values_per_idcs[best,1], values_per_idcs[best,2]] = 1
    print(starter)
```
<p>Output:</p>
```Reward map:
[[3 0 0 1 2]
 [0 1 4 0 0]
 [5 0 0 3 3]]
Maximum value is 6 at indices (2, 3)
Suggested start-point:
[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 1 0]]
```

Good practice task for you:

Note that this approach is sub-optimal, since it recomputes the value of a cluster of cities for every city in that cluster. Thus, if our reward_map is a [n,m] matrix of only 1's, it would start the full recursion for all n*m coordinates, which is pretty bad. A good practice for you would be to fix this problem by updating the reward_map inside the recursion, such that reward_map[i,j]=0. for every [i,j] that was ever processed in the recursion.

If you are happy with this answer, please do not forget to accept it.

Body:
The following is a naive approach that uses simple recursion to solve this problem. However, I wouldn't be surprised if there was a smarter solution to the task, preferably without recursion.

import numpy as np

reward_map = np.array(
    [[ 3, 0, 0, 1, 2],
     [ 0, 1, 4, 0, 0],
     [ 5, 0, 0, 3, 3]])

print("Reward map:")
print(reward_map)

# This function checks if [i,j] are valid indices for the matrix "mat"
def are_valid_idcs(mat, i, j):
    return i >= 0 and j >= 0 and i < mat.shape[0] and j < mat.shape[1]

# This is the recursive function that computes the value given a starting point
def get_cell_value(reward_map, i, j):
    if ( not are_valid_idcs(reward_map, i, j) ) or reward_map[i,j] == 0.:
        return 0.
    else:
        # If we are in a "city", we want to check the connected squares.
        # However, from there, we do not want to walk back.
        # That's why I copy the whole map and set [i,j] = 0, meaning this coordinate has already been handled.
        # This is important. If we do not do this, the recursion will not stop.
        submap = np.array(reward_map)
        submap[i,j] = 0.

        # Now we compute the value of our neighbors
        value_left = get_cell_value(submap, i-1, j)
        value_right = get_cell_value(submap, i+1, j)
        value_top = get_cell_value(submap, i, j-1)
        value_bottom = get_cell_value(submap, i, j+1)

        # And add everything together
        return value_left + value_right + value_top + value_bottom + reward_map[i,j]

# Here, we will remember the value and the coordinates where we started
values_per_idcs = []

# Loop over all cells and compute which value we can get if we start at that point
for i in range(reward_map.shape[0]):
    for j in range(reward_map.shape[1]):
        values_per_idcs += [ [ get_cell_value(reward_map, i, j), i, j] ]

# Now we build a numpy [n,3]-array over the results, where n is the total amount of elements in the map
# The 3 components in the 1-axis correspond to [value, i, j].
values_per_idcs = np.array(values_per_idcs, dtype=np.int64)

# Check if there are negative values in the map
if np.any(reward_map < 0):
    print(f" Value is -1 (due to negative values in reward map)")
# Check if all values are integer
elif not issubclass(reward_map.dtype.type, np.integer):
    print(f" Value is -1 (due to non-integer values in reward map)")
# If the input is OK, we can output the actual results
else:
    # in the [n,3]-result-array, find the n which has the maximum value (i.e. at position 0 on axis 1)
    best = np.argmax( values_per_idcs[...,0], axis=0 )

    # Print the best coordinate
    print(f"Maximum value is {values_per_idcs[best,0]} at indices {values_per_idcs[best,1], values_per_idcs[best,2]}")

    # Plot the suggested starting point which is easier for humans to read than the coordinates
    print("Suggested start-point:")
    starter = np.zeros_like(reward_map, dtype=np.int8)
    starter[values_per_idcs[best,1], values_per_idcs[best,2]] = 1
    print(starter)

Output:

Reward map:
[[3 0 0 1 2]
 [0 1 4 0 0]
 [5 0 0 3 3]]
Maximum value is 6 at indices (2, 3)
Suggested start-point:
[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 1 0]]

Good practice task for you:

Note that this approach is sub-optimal, since it recomputes the value of a cluster of cities for every city in that cluster. Thus, if our reward_map is a [n,m] matrix of only 1's, it would start the full recursion for all n*m coordinates, which is pretty bad. A good practice for you would be to fix this problem by updating the reward_map inside the recursion, such that reward_map[i,j]=0. for every [i,j] that was ever processed in the recursion.

If you are happy with this answer, please do not forget to accept it.


问:
Restrict external users to access bot from Channels like Teams
I have created a custom MS Teams Message extension app in Teams and successfully published that in Azure, but i have noticed that Azure web app bot where i have added Teams as a Channel, i can access the app out side the organization also.
So is there a way i can restrict it to my AD users and in AD also i need to provide access with specific AD groups.
If I copy the URL and try to open with user not in AD still i can access it.

答: In this case, you can implement the authentication for you bot/Messaging Extension and make sure your bot/ME is configured for single tenant only.you can not restrict uses to access it for AD Groups</p>


问:
How to check if value exists in PosrgreSQL enum custom type?
At my PostgreSQL database I have custom enum type called vegetables_type. It contains ('carrot', 'potato', 'tomato') values. My task is to add new value to this type. I am looking for an SQL statement to check if this new value already exists in this type and if not - add this value, if it exists - do nothing.

I've find SELECT unnest(enum_range(NULL::vegetables_type)); statement. But I can't find how to operate on this result - it is not possible to apply WHERE, IN, ANY operations.

答:
Move the call to unnest() to the FROM clause, then you can use the output like any other table:

```<code>SELECT *
FROM unnest(enum_range(NULL::vegetables_type)) as t(name)
WHERE name::text = 'carrot'
</code>```

To test if a value exist, you can use e.g.:

```<code>select exists (select *
               FROM unnest(enum_range(NULL::vegetables_type)) as t(name)
               WHERE t.name::text = 'new_item')
</code>```

The above will return true if new_item is already a member of the enum.

But you don't need such a complicated statement to begin with. You can simply use if not exists as part of the ALTER statement:

```<code>alter type vegetables_type add value if not exists 'new_item';
</code>```

Body:
Move the call to unnest() to the FROM clause, then you can use the output like any other table:

SELECT *
FROM unnest(enum_range(NULL::vegetables_type)) as t(name)
WHERE name::text = 'carrot'

To test if a value exist, you can use e.g.:

select exists (select *
               FROM unnest(enum_range(NULL::vegetables_type)) as t(name)
               WHERE t.name::text = 'new_item')

The above will return true if new_item is already a member of the enum.

But you don't need such a complicated statement to begin with. You can simply use if not exists as part of the ALTER statement:

alter type vegetables_type add value if not exists 'new_item';


问:
C# ASP.NET and MySql: How to wait until File.Exists?
I have an website C# ASP.NET, for create for the *.csv file from convert *.xls file in a chosen folder.

The app responsible for making that file takes following steps:

Make a *.csv file

Import the *.csv file in an dedicate table using LOAD DATA from MySQL

But there is a problem.

The LOAD DATA not find the *.csv file on the folder

ERROR [HY000] [MySQL][ODBC 5.1 Driver][mysqld-5.1.51-community]File
'D:\inetpub\wwwroot\public\target_D8BD592B2F99_08-02-2022.csv' not
found (Errcode: 2)

But the  *.csv file exists on the folder

'D:\inetpub\wwwroot\public\target_D8BD592B2F99_08-02-2022.csv'

I have tried without success waiting until File.Exists

Maybe the call of DATA LOAD is too fast?

Any suggestion?

```<code>var timeout = DateTime.Now.Add(TimeSpan.FromMinutes(1));

while (!File.Exists(output))
{
    if (DateTime.Now > timeout)
    {
        Response.Write("Application timeout; app_boxed could not be created; try again");
        Environment.Exit(0);
    }
    Thread.Sleep(TimeSpan.FromSeconds(1));

    //LOAD DATA
}
</code>```

答:
It looks like the real problem is how to import Excel files into MySQL. This can be done without converting the files to CSV or calling LOAD DATA explicitly.

Bulk loading data into MySql can be done using the MySqlBulkCopy class from the open source MySqlConnector.NET library.

MySqlConnector can send any data stored in a DataTable or available through an IDbDataReader interface to MySQL, using LOAD DATA underneath. This means all we need is a way to get an IDbDataReader from an Excel file.

```<code>using var excelReader = GetReaderFromExcel(somePath);

// open the connection
using var connection = new MySqlConnection("...;AllowLoadLocalInfile=True");
await connection.OpenAsync();

// bulk copy the data
var bulkCopy = new MySqlBulkCopy(connection);
bulkCopy.DestinationTableName = "some_table_name";
var result = await bulkCopy.WriteToServerAsync(dataTable);

// check for problems
if (result.Warnings.Count != 0) { /* handle potential data loss warnings */ }
</code>```

The popular ExcelDataReader can read data from xlsx or the obsolete xls format and return an IDbDataReader, without having to install OLEDB drivers. Reading data from an Excel file can be done with 2 lines.

```<code>using var reader = ExcelReaderFactory.CreateReader(stream);
...
</code>```

Putting it all together :

```<code>using var stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
using var excelReader = ExcelReaderFactory.CreateReader(stream);

using var connection = new MySqlConnection("...;AllowLoadLocalInfile=True");
await connection.OpenAsync();

var bulkCopy = new MySqlBulkCopy(connection);
bulkCopy.DestinationTableName = "some_table_name";
var result = await bulkCopy.WriteToServerAsync(dataTable);

if (result.Warnings.Count != 0) { /* handle potential data loss warnings */ }
</code>```

Body:
I have an website C# ASP.NET, for create for the *.csv file from convert *.xls file in a chosen folder.

The app responsible for making that file takes following steps:

Make a *.csv file

Import the *.csv file in an dedicate table using LOAD DATA from MySQL

But there is a problem.

The LOAD DATA not find the *.csv file on the folder

ERROR [HY000] [MySQL][ODBC 5.1 Driver][mysqld-5.1.51-community]File
'D:\inetpub\wwwroot\public\target_D8BD592B2F99_08-02-2022.csv' not
found (Errcode: 2)

But the  *.csv file exists on the folder

'D:\inetpub\wwwroot\public\target_D8BD592B2F99_08-02-2022.csv'

I have tried without success waiting until File.Exists

Maybe the call of DATA LOAD is too fast?

Any suggestion?

var timeout = DateTime.Now.Add(TimeSpan.FromMinutes(1));

while (!File.Exists(output))
{
    if (DateTime.Now > timeout)
    {
        Response.Write("Application timeout; app_boxed could not be created; try again");
        Environment.Exit(0);
    }
    Thread.Sleep(TimeSpan.FromSeconds(1));

    //LOAD DATA
}

Body:
It looks like the real problem is how to import Excel files into MySQL. This can be done without converting the files to CSV or calling LOAD DATA explicitly.

Bulk loading data into MySql can be done using the MySqlBulkCopy class from the open source MySqlConnector.NET library.

MySqlConnector can send any data stored in a DataTable or available through an IDbDataReader interface to MySQL, using LOAD DATA underneath. This means all we need is a way to get an IDbDataReader from an Excel file.

using var excelReader = GetReaderFromExcel(somePath);

// open the connection
using var connection = new MySqlConnection("...;AllowLoadLocalInfile=True");
await connection.OpenAsync();

// bulk copy the data
var bulkCopy = new MySqlBulkCopy(connection);
bulkCopy.DestinationTableName = "some_table_name";
var result = await bulkCopy.WriteToServerAsync(dataTable);

// check for problems
if (result.Warnings.Count != 0) { /* handle potential data loss warnings */ }

The popular ExcelDataReader can read data from xlsx or the obsolete xls format and return an IDbDataReader, without having to install OLEDB drivers. Reading data from an Excel file can be done with 2 lines.

using var reader = ExcelReaderFactory.CreateReader(stream);
...

Putting it all together :

using var stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
using var excelReader = ExcelReaderFactory.CreateReader(stream);

using var connection = new MySqlConnection("...;AllowLoadLocalInfile=True");
await connection.OpenAsync();

var bulkCopy = new MySqlBulkCopy(connection);
bulkCopy.DestinationTableName = "some_table_name";
var result = await bulkCopy.WriteToServerAsync(dataTable);

if (result.Warnings.Count != 0) { /* handle potential data loss warnings */ }


问:
Unable to connect to MongoDB client and insert data when using promises
I am experimenting nodeJS and I'm getting an error while trying to establish a connection to the MongDB Client. I have used promises for better readability and now I'm unable to connect. The code consist of connecting to the database, inserting a document, retrieving the entries and then clean the database by dropping the collection I had added, but the connection fails. Not sure what I'm doing wrong. Here is my code:

const MongoClient = require("mongodb").MongoClient;
const assert = require("assert");
const dboper = require("./operations");

const url = "mongodb://localhost:27017/";
const dbname = "conFusion";

MongoClient.connect(url).then((err, client) => {
    assert.strictEqual(err, null);
    console.log("Connected correctly to server");
    const db = client.db(dbname);
    dboper
      .insertDocument(db, {
        name: "Vadonut",
        description: "Test"
      }, "dishes")
      .then((result) => {
        console.log("Insert Document:\n", result.ops);

        return dboper
          .findDocuments(db, "dishes")

          .then((docs) => {
            console.log("Found documents:\n", docs);

            return dboper.updateDocument(
              db, {
                name: "Vadonut"
              }, {
                description: "Updated Test"
              },
              "dishes"
            );
          })
          .then((result) => {
            console.log("Updated document:\n", result.result);

            return dboper.findDocuments(db, "dishes");
          })
          .then((docs) => {
            return db.dropCollection("dishes");
          })
          .then((result) => {
            console.log("Dropped collection: ", result);

            client.close();
          })
          .catch((err) => console.log(err));
      });
  })
  .catch((err) => {
    console.log(err);
  });```
</div>
</div>
</p>
<p>this is the error I'm getting once I try connecting to the server</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected ... Lines skipped

+ MongoClient {
+   [Symbol(kCapture)]: false,
+   _events: [Object: null prototype] {},
+   _eventsCount: 0,
+   _maxListeners: undefined,
+   s: {
+     dbCache: {},
+     options: {
+       connectTimeoutMS: 30000,
+       dbName: 'admin',
+       db_options: {
+         readPreference: 'primary',
+         read_preference_tags: null
+       },
+       mongos_options: {
+         socketOptions: {}
+       },
+       promiseLibrary: [Function: Promise],
+       readPreference: ReadPreference {
+         mode: 'primary',
+         options: undefined,
+         tags: undefined
+       },
+       read_preference_tags: null,
+       rs_options: {
+         socketOptions: {}
+       },
+       server_options: {
+         socketOptions: {}
+       },
+       servers: [
+         {
+           host: 'localhost',
+           port: 27017
+         }
+       ],
+       socketOptions: {},
+       socketTimeoutMS: 360000
+     },
+     promiseLibrary: [Function: Promise],
+     sessions: [],
+     url: 'mongodb://localhost:27017/'
+   },
+   topology: <ref *1> Server {
+     [Symbol(kCapture)]: false,
+     _events: [Object: null prototype] {
+       all: [Function: bound onceWrapper] {
+         listener: [Function (anonymous)]
+       },
+       authenticated: [Function (anonymous)],
...
- null
...
    at /Users/thierrymwamba/Desktop/code/NodeJS/node-mongo/index.js:9:12
    at processTicksAndRejections (internal/process/task_queues.js:95:5) {
  generatedMessage: true,
  code: 'ERR_ASSERTION',
  actual: [MongoClient],
  expected: null,
  operator: 'strictEqual'
}</code>```

the expected output is as follow
enter image description here

答:
I encountered the same issue and I was able to fix it by just swapping (err, client) together in the first .then method

Wrong Code:
MongoClient.connect(url).then((err, client)

Correct Code:
MongoClient.connect(url).then((client, err)

Body:
I am experimenting nodeJS and I'm getting an error while trying to establish a connection to the MongDB Client. I have used promises for better readability and now I'm unable to connect. The code consist of connecting to the database, inserting a document, retrieving the entries and then clean the database by dropping the collection I had added, but the connection fails. Not sure what I'm doing wrong. Here is my code:

const MongoClient = require("mongodb").MongoClient;
const assert = require("assert");
const dboper = require("./operations");

const url = "mongodb://localhost:27017/";
const dbname = "conFusion";

MongoClient.connect(url).then((err, client) => {
    assert.strictEqual(err, null);
    console.log("Connected correctly to server");
    const db = client.db(dbname);
    dboper
      .insertDocument(db, {
        name: "Vadonut",
        description: "Test"
      }, "dishes")
      .then((result) => {
        console.log("Insert Document:\n", result.ops);

        return dboper
          .findDocuments(db, "dishes")

          .then((docs) => {
            console.log("Found documents:\n", docs);

            return dboper.updateDocument(
              db, {
                name: "Vadonut"
              }, {
                description: "Updated Test"
              },
              "dishes"
            );
          })
          .then((result) => {
            console.log("Updated document:\n", result.result);

            return dboper.findDocuments(db, "dishes");
          })
          .then((docs) => {
            return db.dropCollection("dishes");
          })
          .then((result) => {
            console.log("Dropped collection: ", result);

            client.close();
          })
          .catch((err) => console.log(err));
      });
  })
  .catch((err) => {
    console.log(err);
  });

this is the error I'm getting once I try connecting to the server

AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected ... Lines skipped

+ MongoClient {
+   [Symbol(kCapture)]: false,
+   _events: [Object: null prototype] {},
+   _eventsCount: 0,
+   _maxListeners: undefined,
+   s: {
+     dbCache: {},
+     options: {
+       connectTimeoutMS: 30000,
+       dbName: 'admin',
+       db_options: {
+         readPreference: 'primary',
+         read_preference_tags: null
+       },
+       mongos_options: {
+         socketOptions: {}
+       },
+       promiseLibrary: [Function: Promise],
+       readPreference: ReadPreference {
+         mode: 'primary',
+         options: undefined,
+         tags: undefined
+       },
+       read_preference_tags: null,
+       rs_options: {
+         socketOptions: {}
+       },
+       server_options: {
+         socketOptions: {}
+       },
+       servers: [
+         {
+           host: 'localhost',
+           port: 27017
+         }
+       ],
+       socketOptions: {},
+       socketTimeoutMS: 360000
+     },
+     promiseLibrary: [Function: Promise],
+     sessions: [],
+     url: 'mongodb://localhost:27017/'
+   },
+   topology: <ref *1> Server {
+     [Symbol(kCapture)]: false,
+     _events: [Object: null prototype] {
+       all: [Function: bound onceWrapper] {
+         listener: [Function (anonymous)]
+       },
+       authenticated: [Function (anonymous)],
...
- null
...
    at /Users/thierrymwamba/Desktop/code/NodeJS/node-mongo/index.js:9:12
    at processTicksAndRejections (internal/process/task_queues.js:95:5) {
  generatedMessage: true,
  code: 'ERR_ASSERTION',
  actual: [MongoClient],
  expected: null,
  operator: 'strictEqual'
}

the expected output is as follow
enter image description here


问:
Custom Arrows react-slick
I am using react-slick to create a carousel in my project.
I've read through the documents and tried different things but could not find a way to customize it exactly the way I need... Does anyone knows if there a way to have the nextArrow show on/in front of the image and not on its right?
See image below for desired result:
image

Thanks for your help!

答:
Remember that it is required to add onClick prop to your buttons:</p>
```<code>const SlickArrow = ({onClick}: props) => (
  <button onClick={onClick}><Icon.Arrow /></button>
);
</code>```

Title: Custom Arrows react-slick

Body:
Remember that it is required to add onClick prop to your buttons:

const SlickArrow = ({onClick}: props) => (
  <button onClick={onClick}><Icon.Arrow /></button>
);


问:
How can i deal with an error that shows 'lateinit property binding has not been initialized' while trying to display a list in a RecyclerView
I'm new to Android development and I'm trying to display a list of todo on my RecyclerView but it is throwing an error that says 'lateinit property binding has not been initialized' I think the error is from here :

 override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {

        holder.itemView.apply {
            binding.txtTitle.text = todos[position].title
            binding.cbTodo.isChecked = todos[position].isChecked
        }
```
<p>Because that's the line of code in my Adapter the logcat is highlighting while I checked for error.  Please I need help in solving this error , my app crashes whenever I tried entering this Activity.</p>
<p><strong>my Adapter</strong></p>
<pre class="lang-kotlin prettyprint-override"><code>class TodoAdapter(var todos : List<Todo>) : RecyclerView.Adapter<TodoAdapter.TodoViewHolder>()
{
    inner class TodoViewHolder(itemView:View) : RecyclerView.ViewHolder(itemView)
    private lateinit var binding:ItemTodoBinding

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_todo,parent,false)
        return TodoViewHolder(view)
    }

    override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
        holder.itemView.apply {
            binding.txtTitle.text = todos[position].title
            binding.cbTodo.isChecked = todos[position].isChecked
        }
    }

    override fun getItemCount(): Int {
        return  todos.size
    }
}
</code>```

My Class

data class Todo (
    val title :String,
    var  isChecked : Boolean
        )
```
<p><strong>My Activity.kt</strong></p>
<pre class="lang-kotlin prettyprint-override"><code>class NextAftertoolbar : AppCompatActivity() {
        binding = ActivityNextAftertoolbarBinding.inflate(layoutInflater)
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        supportActionBar?.hide()

        var todolist = mutableListOf(
            Todo("Follow Android devs",false),
            Todo(" Learn ",false),
            Todo("Build",false),
            Todo("Land a role",false),
        )

        val adapter = TodoAdapter(todolist)
        binding.rvTodo.adapter = adapter
        binding.rvTodo.layoutManager=LinearLayoutManager(this)

        binding.btnTodo.setOnClickListener {
            val title  = binding.etTodo.text.toString()
            val todo = Todo(title,false)
            todolist.add(todo)
            adapter.notifyItemInserted(todolist.size-1)
        }
    }
}
</code>```

答:
Please add following code into your onCreateViewHolder method.</p>
```<code>override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {

binding =
            ItemTodoBinding.inflate(LayoutInflater.from(context), parent, false)

return TodoViewHolder(binding)
}
</code>```

Body:
I'm new to Android development and I'm trying to display a list of todo on my RecyclerView but it is throwing an error that says 'lateinit property binding has not been initialized' I think the error is from here :

 override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {

        holder.itemView.apply {
            binding.txtTitle.text = todos[position].title
            binding.cbTodo.isChecked = todos[position].isChecked
        }

Because that's the line of code in my Adapter the logcat is highlighting while I checked for error.  Please I need help in solving this error , my app crashes whenever I tried entering this Activity.

my Adapter

class TodoAdapter(var todos : List<Todo>) : RecyclerView.Adapter<TodoAdapter.TodoViewHolder>()
{
    inner class TodoViewHolder(itemView:View) : RecyclerView.ViewHolder(itemView)
    private lateinit var binding:ItemTodoBinding

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_todo,parent,false)
        return TodoViewHolder(view)
    }

    override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
        holder.itemView.apply {
            binding.txtTitle.text = todos[position].title
            binding.cbTodo.isChecked = todos[position].isChecked
        }
    }

    override fun getItemCount(): Int {
        return  todos.size
    }
}

My Class

data class Todo (
    val title :String,
    var  isChecked : Boolean
        )

My Activity.kt

class NextAftertoolbar : AppCompatActivity() {
        binding = ActivityNextAftertoolbarBinding.inflate(layoutInflater)
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        supportActionBar?.hide()

        var todolist = mutableListOf(
            Todo("Follow Android devs",false),
            Todo(" Learn ",false),
            Todo("Build",false),
            Todo("Land a role",false),
        )

        val adapter = TodoAdapter(todolist)
        binding.rvTodo.adapter = adapter
        binding.rvTodo.layoutManager=LinearLayoutManager(this)

        binding.btnTodo.setOnClickListener {
            val title  = binding.etTodo.text.toString()
            val todo = Todo(title,false)
            todolist.add(todo)
            adapter.notifyItemInserted(todolist.size-1)
        }
    }
}

Body:
Please add following code into your onCreateViewHolder method.

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {

binding =
            ItemTodoBinding.inflate(LayoutInflater.from(context), parent, false)

return TodoViewHolder(binding)
}


问:
How to apply gradient blur to one side of an image?
The goal is to blur the right side of the image like this with css only
The example:

so as you can see they applied a blurry side on top of the image. i tried the backdrop filter but didn't work, also i didn't know how to work with the mask and the clip path...

答:
Actually, it is possible to get a fairly similar result with CSS.
More detailed: codepen

.effet {
  width: 400px;
  height: 300px;
  margin: 0 auto 50px auto;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.5);
}
.effet img {
  position: absolute;
}
.filtre--r {
  -webkit-mask: -webkit-radial-gradient(
    center,
    closest-side,
    transparent 30%,
    black 80%
  );
  -webkit-mask: radial-gradient(
    closest-side at center,
    transparent 50%,
    black 110%
  );
  -webkit-filter: blur(5px);
  mask: url("#mask-radial");
  filter: url("#filtre1");
}
.filtre:hover {
  -webkit-mask: none;
  -webkit-filter: none;
  mask: none;
  filter: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="effet">
  <img src="http://css3create.com/squelettes/images/articles/flou-localise-1.jpg" alt="" />
  <img class="filtre filtre--r" src="http://css3create.com/squelettes/images/articles/flou-localise-1.jpg" alt="" />
</div>

<svg height="0">
  <filter id="filtre1">
    <feGaussianBlur in="SourceGraphic" stdDeviation="5" />
  </filter>
</svg></code>```

Body:
Actually, it is possible to get a fairly similar result with CSS.
More detailed: codepen

.effet {
  width: 400px;
  height: 300px;
  margin: 0 auto 50px auto;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.5);
}
.effet img {
  position: absolute;
}
.filtre--r {
  -webkit-mask: -webkit-radial-gradient(
    center,
    closest-side,
    transparent 30%,
    black 80%
  );
  -webkit-mask: radial-gradient(
    closest-side at center,
    transparent 50%,
    black 110%
  );
  -webkit-filter: blur(5px);
  mask: url("#mask-radial");
  filter: url("#filtre1");
}
.filtre:hover {
  -webkit-mask: none;
  -webkit-filter: none;
  mask: none;
  filter: none;
}

<div class="effet">
  <img src="http://css3create.com/squelettes/images/articles/flou-localise-1.jpg" alt="" />
  <img class="filtre filtre--r" src="http://css3create.com/squelettes/images/articles/flou-localise-1.jpg" alt="" />
</div>

<svg height="0">
  <filter id="filtre1">
    <feGaussianBlur in="SourceGraphic" stdDeviation="5" />
  </filter>
</svg>


问:
How to specify color of extension triangle when using ListedColormap
This answer provides an example of how to use ListedColormap to create a colormap.

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap

tab20c = cm.get_cmap('tab20c', 256)
newcolors = tab20c(np.linspace(0, 1, 256))
newcmp = ListedColormap(newcolors)
</code>```

I know I could just use the tab20c color map and not ListedColormap in this particular case shown here, but the more complicated example discussed in that answer requires ListedColormap. I avoid that complication because it is not the focus of this question. Use newcmp to plot a function:

```<code>mock=\
np.array([[0.1,0.2,0.3],
          [0.2,0.3,0.4],
          [0.3,0.4,0.5],
          [0.4,0.5,0.6],
          [0.5,0.6,0.7],
          [0.6,0.7,0.8],
          [0.7,0.8,0.9]])

plt.figure(figsize=(6,6))
im = plt.imshow(mock,cmap = newcmp, vmin=0.0, vmax=1)
plt.colorbar(im,extend='min')
</code>```

I could use the extend='min' kwarg in the colorbar call to extend the colorbar downwards.

I would like to modify the color of this triangle at the bottom of color bar. To make it, let's say, yellow, I tried the above code with tab20c = cm.get_cmap('tab20c', 256).with_extremes(under='yellow'), but the triangle remains blue. I have read about .with_extremes() here.

Question

Without changing the rest, how can set the color of the triangle below the colorbar?

I hope there is a solution involving these 3 lines:

```<code>tab20c = cm.get_cmap('tab20c', 256)
newcolors = tab20c(np.linspace(0, 1, 256))
newcmp = ListedColormap(newcolors)
</code>```

as they are important in customizing the colorbar for more complicated cases then presented here.

答:
you are looking for the .set_under() method. For example:

tab20c = cm.get_cmap('tab20c', 256)
newcolors = tab20c(np.linspace(0, 1, 256))
newcmp = ListedColormap(newcolors)
newcmp.set_under('k')
```

would lead to this image:

Body:
This answer provides an example of how to use ListedColormap to create a colormap.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap

tab20c = cm.get_cmap('tab20c', 256)
newcolors = tab20c(np.linspace(0, 1, 256))
newcmp = ListedColormap(newcolors)

I know I could just use the tab20c color map and not ListedColormap in this particular case shown here, but the more complicated example discussed in that answer requires ListedColormap. I avoid that complication because it is not the focus of this question. Use newcmp to plot a function:

mock=\
np.array([[0.1,0.2,0.3],
          [0.2,0.3,0.4],
          [0.3,0.4,0.5],
          [0.4,0.5,0.6],
          [0.5,0.6,0.7],
          [0.6,0.7,0.8],
          [0.7,0.8,0.9]])

plt.figure(figsize=(6,6))
im = plt.imshow(mock,cmap = newcmp, vmin=0.0, vmax=1)
plt.colorbar(im,extend='min')

I could use the extend='min' kwarg in the colorbar call to extend the colorbar downwards.

I would like to modify the color of this triangle at the bottom of color bar. To make it, let's say, yellow, I tried the above code with tab20c = cm.get_cmap('tab20c', 256).with_extremes(under='yellow'), but the triangle remains blue. I have read about .with_extremes() here.

Question

Without changing the rest, how can set the color of the triangle below the colorbar?

I hope there is a solution involving these 3 lines:

tab20c = cm.get_cmap('tab20c', 256)
newcolors = tab20c(np.linspace(0, 1, 256))
newcmp = ListedColormap(newcolors)

as they are important in customizing the colorbar for more complicated cases then presented here.

Body:
you are looking for the .set_under() method. For example:

tab20c = cm.get_cmap('tab20c', 256)
newcolors = tab20c(np.linspace(0, 1, 256))
newcmp = ListedColormap(newcolors)
newcmp.set_under('k')

would lead to this image:


问:
Is it possible to tell if a java ResultSet is empty without affecting the record?
I do not want to use next() since if the ResultSet is not empty, I do not want the cursor to be advanced. Is there some sort of peek() method or equivalent that will return false if the ResultSet is empty and true otherwise without affecting the record?

Edit:

I cannot call beforeFirst because I get the following

Operation requires a scrollable ResultSet, but this ResultSet is
  FORWARD_ONLY

I need FORWARD_ONLY because I'm using postgreSQL cursors

答: You can invoke the first() method to check if you have results in the ResultSet. If first() returns true, you can then call beforeFirst() to reset the ResultSet cursor position.


问:
HTML - change pattern of date input field
I need to change the pattern of the input date field to Day.Month.Year, is it possible?

```<code><input type="date" name="datum" value="datum"/>
</code>```

Currently it looks like this:

but if I submit the form and catch the value in PHP then the value is stored like this "2022-02-17"

I found this section in the firefox documentation, but it does not provide any example.

答:
You could correct the date once you catch the value with your PHP handler.

```<code>$date = $_POST['datum'];
$date = date("Y-m-d",strtotime($date));
</code>```

To show date in d.m.Y format in HTML page, again convert it into

```<code>$date = date("d.m.Y",strtotime($date));
</code>```

Body:
I need to change the pattern of the input date field to Day.Month.Year, is it possible?

<input type="date" name="datum" value="datum"/>

Currently it looks like this:

but if I submit the form and catch the value in PHP then the value is stored like this "2022-02-17"

I found this section in the firefox documentation, but it does not provide any example.

Body:
You could correct the date once you catch the value with your PHP handler.

$date = $_POST['datum'];
$date = date("Y-m-d",strtotime($date));

To show date in d.m.Y format in HTML page, again convert it into

$date = date("d.m.Y",strtotime($date));


问:
.NET Core 6.0 COM interoperability issues with Python/Octave
I am currently trying to create a COM object in .NET Core 6. To achieve this I have made a class library and edited the project like this:

C#:

Project file (*.csproj):

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <EnableComHosting>true</EnableComHosting>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>

</Project>
</code>```

COM object (*.cs):

```<code>using System;
using System.Runtime.InteropServices;

namespace COMNetCore6
{
    [ComVisible(true)]
    [Guid("64D6F9F6-6163-401A-82E6-C941CAF01399")]
    [ProgId("HelloWorldCOMObject")]
    public class ComObject
    {
        public string SayHello() => "Hello world from .NET Core";
    }
}
</code>```

After building the project I get a *.comhost.dll file which I can add to the registry by using the command 'regsvr32 *.comhost.dll'. The comhost.dll gets registered successfully and it is working for Visual Basic in Excel as intended.

When I try using this COM object in another programming language though it will not work. I have tried using Octave and Python. While Octave only tells me that it wasn't able to create a server, Python gives me this error at least:

Python:

```<code>>>> import win32com.client
>>> comobj = win32com.client.Dispatch("HelloWorldCOMObject")
Traceback (most recent call last):
  File "C:\*\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 86, in _GetGoodDispatch
    IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221021, 'Operation unavailable', None, None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\*\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\__init__.py", line 117, in Dispatch
    dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, userName, clsctx)
  File "C:\*\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 106, in _GetGoodDispatchAndUserName
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "C:\*\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 88, in _GetGoodDispatch
    IDispatch = pythoncom.CoCreateInstance(
pywintypes.com_error: (-2147467262, 'No such interface supported', None, None)
</code>```

I have tried to solve this problem by following the steps described in these links (especially the first one) and adapting them to what I needed:

Can I connect a .NET 5 COM interop object with VB6?
https://github.com/GregReddick/ComTestLibrary/tree/master/ComTestLibrary1
https://learn.microsoft.com/en-us/dotnet/core/native-interop/expose-components-to-com

Unfortunately none of the approaches I tried worked. I have tried to create an interface for the COM object and use the correct interoperability annotations in C# but the error was still there. As I have said though the basic approach with no interface and barely any annotation from above worked for Visual Basic.

In this case I am trying to use late binding without a TLB (type library) because I need this to work for both late binding (without TLB) and early binding (with TLB) and I decided to start with late binding.

There has been a similar question regarding the late binding approach which wasn't answered as of now: 'No such interface supported' when using .NET 6.0 COM object in python 3.9.

Since the COM object works fine for Visual Basic but doesn't work for other programming languages I am not sure what exactly causes this issue.

答:
The .NET Core wrapper doesn't support this type of call where you ask for IDispatch at the same time you create the COM object:

C / C++:

```<code>IDispatch* disp;
CoCreateInstance(YourCLSID, NULL, CLSCTX_ALL, IID_IDispatch, &disp); // fails
</code>```

Python:

```<code>disp = pythoncom.CoCreateInstance(YourCLSID, None, pythoncom.CLSCTX_ALL, pythoncom.IID_IDispatch) // fails
</code>```

You must first get an IUnknown reference and QI for IDispatch on it, like this in python (which is what Excel/VBA does):

```<code>import pythoncom
import pywintypes
from win32com.client import Dispatch

unk = pythoncom.CoCreateInstance(pywintypes.IID('{64D6F9F6-6163-401A-82E6-C941CAF01399}'), None, pythoncom.CLSCTX_ALL, pythoncom.IID_IUnknown)
disp = Dispatch(unk.QueryInterface(pythoncom.IID_IDispatch))
print disp.SayHello
</code>```

IMHO, python COM support should be modified to do this always...

Body:
I am currently trying to create a COM object in .NET Core 6. To achieve this I have made a class library and edited the project like this:

C#:

Project file (*.csproj):

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <EnableComHosting>true</EnableComHosting>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>

</Project>

COM object (*.cs):

using System;
using System.Runtime.InteropServices;

namespace COMNetCore6
{
    [ComVisible(true)]
    [Guid("64D6F9F6-6163-401A-82E6-C941CAF01399")]
    [ProgId("HelloWorldCOMObject")]
    public class ComObject
    {
        public string SayHello() => "Hello world from .NET Core";
    }
}

After building the project I get a *.comhost.dll file which I can add to the registry by using the command 'regsvr32 *.comhost.dll'. The comhost.dll gets registered successfully and it is working for Visual Basic in Excel as intended.

When I try using this COM object in another programming language though it will not work. I have tried using Octave and Python. While Octave only tells me that it wasn't able to create a server, Python gives me this error at least:

Python:

>>> import win32com.client
>>> comobj = win32com.client.Dispatch("HelloWorldCOMObject")
Traceback (most recent call last):
  File "C:\*\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 86, in _GetGoodDispatch
    IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221021, 'Operation unavailable', None, None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\*\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\__init__.py", line 117, in Dispatch
    dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, userName, clsctx)
  File "C:\*\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 106, in _GetGoodDispatchAndUserName
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "C:\*\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 88, in _GetGoodDispatch
    IDispatch = pythoncom.CoCreateInstance(
pywintypes.com_error: (-2147467262, 'No such interface supported', None, None)

I have tried to solve this problem by following the steps described in these links (especially the first one) and adapting them to what I needed:

Can I connect a .NET 5 COM interop object with VB6?
https://github.com/GregReddick/ComTestLibrary/tree/master/ComTestLibrary1
https://learn.microsoft.com/en-us/dotnet/core/native-interop/expose-components-to-com

Unfortunately none of the approaches I tried worked. I have tried to create an interface for the COM object and use the correct interoperability annotations in C# but the error was still there. As I have said though the basic approach with no interface and barely any annotation from above worked for Visual Basic.

In this case I am trying to use late binding without a TLB (type library) because I need this to work for both late binding (without TLB) and early binding (with TLB) and I decided to start with late binding.

There has been a similar question regarding the late binding approach which wasn't answered as of now: 'No such interface supported' when using .NET 6.0 COM object in python 3.9.

Since the COM object works fine for Visual Basic but doesn't work for other programming languages I am not sure what exactly causes this issue.

Body:
The .NET Core wrapper doesn't support this type of call where you ask for IDispatch at the same time you create the COM object:

C / C++:

IDispatch* disp;
CoCreateInstance(YourCLSID, NULL, CLSCTX_ALL, IID_IDispatch, &disp); // fails

Python:

disp = pythoncom.CoCreateInstance(YourCLSID, None, pythoncom.CLSCTX_ALL, pythoncom.IID_IDispatch) // fails

You must first get an IUnknown reference and QI for IDispatch on it, like this in python (which is what Excel/VBA does):

import pythoncom
import pywintypes
from win32com.client import Dispatch

unk = pythoncom.CoCreateInstance(pywintypes.IID('{64D6F9F6-6163-401A-82E6-C941CAF01399}'), None, pythoncom.CLSCTX_ALL, pythoncom.IID_IUnknown)
disp = Dispatch(unk.QueryInterface(pythoncom.IID_IDispatch))
print disp.SayHello

IMHO, python COM support should be modified to do this always...