问:
Ordering of related models by a field
I'm stuck in the ordering of a queryset and looking here for inputs

I have two models such as -

```<code>class Groups(models.Model):
    participants = models.ManyToManyField(User, related_name='group_member')
    def __str__(self):
        return str(self.id)
</code>```

and the second one as -

```<code>class GroupViews(models.Model):
    group = models.ForeignKey(Groups, related_name="abc", on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now=True)
</code>```

I have to sort Groups in the reverse order of timestamp - (latest first)

My approach till now -

First way -

```<code> grps = Groups.objects.filter(participants__id = userId)
 orderedGrp = grps.order_by("-abc__timestamp").distinct()
</code>```

.distinct() doesn't work here and I get multiple instances because Groups is used as one-to-many in GroupVIews

Second way -

```<code>grps = Groups.objects.filter(participants__id = userId)

da = []   //get the last element because timsestamp depends on last
for each in grps:
    da.append(GroupViews.objects.values_list("id", flat=True).filter(group = each).last())

//get the orderer values of Group from here
orderedValues = GroupViews.objects.values_list("group", flat=True).filter(id__in = da).order_by('-timestamp')

// here I have ordered Id of Groups, How can I run a query to get Groups in the same order ( values of OrderValues)
</code>```

I have ordered Id of Groups, How can I run a query to get Groups in the same order ( values of OrderValues).
Anyone ?

Thanks!!

Title: Ordering of related models by a field

Body:
I'm stuck in the ordering of a queryset and looking here for inputs

I have two models such as -

class Groups(models.Model):
    participants = models.ManyToManyField(User, related_name='group_member')
    def __str__(self):
        return str(self.id)

and the second one as -

class GroupViews(models.Model):
    group = models.ForeignKey(Groups, related_name="abc", on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now=True)

I have to sort Groups in the reverse order of timestamp - (latest first)

My approach till now -

First way -

 grps = Groups.objects.filter(participants__id = userId)
 orderedGrp = grps.order_by("-abc__timestamp").distinct()

.distinct() doesn't work here and I get multiple instances because Groups is used as one-to-many in GroupVIews

Second way -

grps = Groups.objects.filter(participants__id = userId)

da = []   //get the last element because timsestamp depends on last
for each in grps:
    da.append(GroupViews.objects.values_list("id", flat=True).filter(group = each).last())

//get the orderer values of Group from here
orderedValues = GroupViews.objects.values_list("group", flat=True).filter(id__in = da).order_by('-timestamp')

// here I have ordered Id of Groups, How can I run a query to get Groups in the same order ( values of OrderValues)

I have ordered Id of Groups, How can I run a query to get Groups in the same order ( values of OrderValues).
Anyone ?

Thanks!!


来源: stackexchange

问:
How to get django session data with javascript?
i save session data in django with key 'theme' :

```<code>request.session['theme'] = 'light'
</code>```

Then i want to get 'theme' session data in javascript with this code:

```<code>sessionStorage.getItem("theme");
</code>```

but i can't get theme data.

How can I do this?

ContentLicense: CC BY-SA 4.0

Body:
i save session data in django with key 'theme' :

request.session['theme'] = 'light'

Then i want to get 'theme' session data in javascript with this code:

sessionStorage.getItem("theme");

but i can't get theme data.

How can I do this?


问:
Homebrew/homebrew-core (no Git repository)
To install I have used this
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

```<code>devansh@Devansh:~$ brew --version
Homebrew 3.6.16
Homebrew/homebrew-core (no Git repository)
</code>```

but after checking the version it shows (no git repository).

How could I solve and fix it?

Body:
To install I have used this
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

devansh@Devansh:~$ brew --version
Homebrew 3.6.16
Homebrew/homebrew-core (no Git repository)

but after checking the version it shows (no git repository).

How could I solve and fix it?


问:
Prysm.sh beacon-chain stopped synchronization - How to fix?
I try to sync my Geth, but it stuck.

I see next errors in Prysm

```<code>[2022-12-30 08:24:56]  INFO p2p: Peer summary activePeers=42 inbound=0 outbound=42
[2022-12-30 08:24:59]  WARN initial-sync: Skip processing batched blocks error=could not process block in batch: could not set node to invalid: invalid nil or unknown node
[2022-12-30 08:24:59]  INFO initial-sync: Processing block batch of size 64 starting from  0x87ca0daa... 5192464/5463723 - estimated time remaining 7h50m56s blocksPerSecond=9.6 peers=41
[2022-12-30 08:24:59]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0x1a0877b34ccd9e92bdfe7859dbd3478d1c785fd6e970d8b8b637d5c457efec83 (in processBatchedBlocks, slot=5192464)
[2022-12-30 08:24:59]  INFO initial-sync: Processing block batch of size 64 starting from  0xa48361f2... 5192528/5463723 - estimated time remaining 5h53m7s blocksPerSecond=12.8 peers=41
[2022-12-30 08:24:59]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0xc569dd3f4241031b835bd7dd528d2337cca5b0c8315ae55f56b810d1b0a1aa40 (in processBatchedBlocks, slot=5192528)
[2022-12-30 08:24:59]  INFO initial-sync: Processing block batch of size 61 starting from  0x06de2537... 5192592/5463723 - estimated time remaining 4h45m6s blocksPerSecond=15.8 peers=41
[2022-12-30 08:24:59]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0xf9a776157c86f918aa82c39a69a2a880b0eb42a692bc6e1a97b3fe2fce73c916 (in processBatchedBlocks, slot=5192592)
[2022-12-30 08:24:59]  INFO initial-sync: Processing block batch of size 62 starting from  0x865d9e60... 5192656/5463723 - estimated time remaining 3h58m24s blocksPerSecond=18.9 peers=41
[2022-12-30 08:24:59]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0x03140ee59185dc417bf95c370ed4070458855da01b54d0b2186d9e11fd328314 (in processBatchedBlocks, slot=5192656)
[2022-12-30 08:25:09]  INFO initial-sync: Processing block batch of size 64 starting from  0x33e52bbd... 5192336/5463723 - estimated time remaining 3h58m41s blocksPerSecond=18.9 peers=44
[2022-12-30 08:25:16]  WARN initial-sync: Skip processing batched blocks error=could not process block in batch: could not set node to invalid: invalid nil or unknown node
[2022-12-30 08:25:20]  INFO initial-sync: Processing block batch of size 62 starting from  0x0ed9c790... 5192400/5463724 - estimated time remaining 11h57m47s blocksPerSecond=6.3 peers=44
[2022-12-30 08:25:20]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0x4f227a74a20bebe01369ac220aedacd7e4c986e8f569694f3c643da0cc9cfe83 (in processBatchedBlocks, slot=5192400)
[2022-12-30 08:25:20]  INFO initial-sync: Processing block batch of size 64 starting from  0x87ca0daa... 5192464/5463724 - estimated time remaining 7h55m53s blocksPerSecond=9.5 peers=44
[2022-12-30 08:25:20]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0x1a0877b34ccd9e92bdfe7859dbd3478d1c785fd6e970d8b8b637d5c457efec83 (in processBatchedBlocks, slot=5192464)
[2022-12-30 08:25:20]  INFO initial-sync: Processing block batch of size 64 starting from  0xa48361f2... 5192528/5463724 - estimated time remaining 5h55m54s blocksPerSecond=12.7 peers=44
[2022-12-30 08:25:20]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0xc569dd3f4241031b835bd7dd528d2337cca5b0c8315ae55f56b810d1b0a1aa40 (in processBatchedBlocks, slot=5192528)
[2022-12-30 08:25:20]  INFO initial-sync: Processing block batch of size 61 starting from  0x06de2537... 5192592/5463724 - estimated time remaining 4h46m54s blocksPerSecond=15.8 peers=44
[2022-12-30 08:25:20]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0xf9a776157c86f918aa82c39a69a2a880b0eb42a692bc6e1a97b3fe2fce73c916 (in processBatchedBlocks, slot=5192592)
[2022-12-30 08:25:20]  INFO initial-sync: Processing block batch of size 62 starting from  0x865d9e60... 5192656/5463724 - estimated time remaining 3h59m40s blocksPerSecond=18.9 peers=44
[2022-12-30 08:25:20]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0x03140ee59185dc417bf95c370ed4070458855da01b54d0b2186d9e11fd328314 (in processBatchedBlocks, slot=5192656)
[2022-12-30 08:25:20]  INFO initial-sync: Processing block batch of size 64 starting from  0x74b66233... 5192720/5463724 - estimated time remaining 3h24m50s blocksPerSecond=22.1 peers=44
[2022-12-30 08:25:20]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0xed2e36835d677750e41fecc7a16c7d8669fd8a8ff629c9480b575d6d27c26085 (in processBatchedBlocks, slot=5192720)
[2022-12-30 08:25:27]  INFO initial-sync: Processing block batch of size 64 starting from  0x33e52bbd... 5192336/5463725 - estimated time remaining 2h59m8s blocksPerSecond=25.2 peers=45
[2022-12-30 08:25:33]  WARN initial-sync: Skip processing batched blocks error=could not process block in batch: could not set node to invalid: invalid nil or unknown node
</code>```

And next I see in Geth

ERROR[12-30|08:30:48.985] Error in block freeze operation          err="block receipts missing, can't freeze block 15850304"
WARN [12-30|08:30:55.145] Previously seen beacon client is offline. Please ensure it is operational to follow the chain!
WARN [12-30|08:30:56.688] Ignoring already known beacon payload    number=16,026,540 hash=145907..4f081f age=1mo1w16h
WARN [12-30|08:30:56.696] Ignoring already known beacon payload    number=16,026,541 hash=6acd62..e3bac2 age=1mo1w16h
WARN [12-30|08:30:56.701] Ignoring already known beacon payload    number=16,026,542 hash=1da1d8..c55a69 age=1mo1w16h
WARN [12-30|08:30:56.708] Ignoring already known beacon payload    number=16,026,543 hash=762b24..f56957 age=1mo1w16h
WARN [12-30|08:30:56.719] Ignoring already known beacon payload    number=16,026,544 hash=ff1aef..389471 age=1mo1w16h
WARN [12-30|08:30:56.725] Ignoring already known beacon payload    number=16,026,545 hash=6767aa..85bf1d age=1mo1w16h
WARN [12-30|08:30:56.730] Ignoring already known beacon payload    number=16,026,546 hash=95b736..dc2456 age=1mo1w16h
WARN [12-30|08:30:56.732] Ignoring already known beacon payload    number=16,026,547 hash=34e43f..777810 age=1mo1w16h
WARN [12-30|08:30:56.742] Ignoring already known beacon payload    number=16,026,548 hash=1c67b8..cbc356 age=1mo1w16h
WARN [12-30|08:30:56.750] Ignoring already known beacon payload    number=16,026,549 hash=fe9e47..ed347e age=1mo1w16h
WARN [12-30|08:30:56.754] Ignoring already known beacon payload    number=16,026,550 hash=c98bf1..40560a age=1mo1w16h
WARN [12-30|08:30:56.772] Ignoring already known beacon payload    number=16,026,551 hash=f55377..a1582e age=1mo1w16h
WARN [12-30|08:30:56.780] Ignoring already known beacon payload    number=16,026,552 hash=0bf769..af0ed8 age=1mo1w16h
WARN [12-30|08:30:56.784] Ignoring already known beacon payload    number=16,026,553 hash=382866..a5a4f8 age=1mo1w16h
WARN [12-30|08:30:56.907] Ignoring already known beacon payload    number=16,026,554 hash=65d2ff..6ebef5 age=1mo1w16h
WARN [12-30|08:30:56.918] Ignoring already known beacon payload    number=16,026,555 hash=f04209..4779e9 age=1mo1w16h
WARN [12-30|08:30:56.935] Ignoring already known beacon payload    number=16,026,556 hash=f2b1ab..373dc0 age=1mo1w16h
WARN [12-30|08:30:56.943] Ignoring already known beacon payload    number=16,026,557 hash=979712..00891d age=1mo1w16h
WARN [12-30|08:30:56.956] Ignoring already known beacon payload    number=16,026,558 hash=b53705..8483a1 age=1mo1w16h
WARN [12-30|08:30:56.979] Ignoring already known beacon payload    number=16,026,559 hash=61e689..7e7c79 age=1mo1w16h
WARN [12-30|08:30:56.994] Ignoring already known beacon payload    number=16,026,560 hash=a0f45b..802daf age=1mo1w16h
WARN [12-30|08:30:57.004] Ignoring already known beacon payload    number=16,026,561 hash=037435..474e8d age=1mo1w16h
WARN [12-30|08:30:57.009] Ignoring already known beacon payload    number=16,026,562 hash=565f15..bf9980 age=1mo1w16h
WARN [12-30|08:30:57.031] Ignoring already known beacon payload    number=16,026,563 hash=c7f6ef..cc5ddf age=1mo1w16h
WARN [12-30|08:30:57.033] Ignoring already known beacon payload    number=16,026,564 hash=c87d53..223987 age=1mo1w16h
WARN [12-30|08:30:57.068] Ignoring already known beacon payload    number=16,026,565 hash=51f821..fc1a26 age=1mo1w16h

Has anyone encountered similar problems before?

I already tried to sync again. It didn`t help.

Body:
I try to sync my Geth, but it stuck.

I see next errors in Prysm

[2022-12-30 08:24:56]  INFO p2p: Peer summary activePeers=42 inbound=0 outbound=42
[2022-12-30 08:24:59]  WARN initial-sync: Skip processing batched blocks error=could not process block in batch: could not set node to invalid: invalid nil or unknown node
[2022-12-30 08:24:59]  INFO initial-sync: Processing block batch of size 64 starting from  0x87ca0daa... 5192464/5463723 - estimated time remaining 7h50m56s blocksPerSecond=9.6 peers=41
[2022-12-30 08:24:59]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0x1a0877b34ccd9e92bdfe7859dbd3478d1c785fd6e970d8b8b637d5c457efec83 (in processBatchedBlocks, slot=5192464)
[2022-12-30 08:24:59]  INFO initial-sync: Processing block batch of size 64 starting from  0xa48361f2... 5192528/5463723 - estimated time remaining 5h53m7s blocksPerSecond=12.8 peers=41
[2022-12-30 08:24:59]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0xc569dd3f4241031b835bd7dd528d2337cca5b0c8315ae55f56b810d1b0a1aa40 (in processBatchedBlocks, slot=5192528)
[2022-12-30 08:24:59]  INFO initial-sync: Processing block batch of size 61 starting from  0x06de2537... 5192592/5463723 - estimated time remaining 4h45m6s blocksPerSecond=15.8 peers=41
[2022-12-30 08:24:59]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0xf9a776157c86f918aa82c39a69a2a880b0eb42a692bc6e1a97b3fe2fce73c916 (in processBatchedBlocks, slot=5192592)
[2022-12-30 08:24:59]  INFO initial-sync: Processing block batch of size 62 starting from  0x865d9e60... 5192656/5463723 - estimated time remaining 3h58m24s blocksPerSecond=18.9 peers=41
[2022-12-30 08:24:59]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0x03140ee59185dc417bf95c370ed4070458855da01b54d0b2186d9e11fd328314 (in processBatchedBlocks, slot=5192656)
[2022-12-30 08:25:09]  INFO initial-sync: Processing block batch of size 64 starting from  0x33e52bbd... 5192336/5463723 - estimated time remaining 3h58m41s blocksPerSecond=18.9 peers=44
[2022-12-30 08:25:16]  WARN initial-sync: Skip processing batched blocks error=could not process block in batch: could not set node to invalid: invalid nil or unknown node
[2022-12-30 08:25:20]  INFO initial-sync: Processing block batch of size 62 starting from  0x0ed9c790... 5192400/5463724 - estimated time remaining 11h57m47s blocksPerSecond=6.3 peers=44
[2022-12-30 08:25:20]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0x4f227a74a20bebe01369ac220aedacd7e4c986e8f569694f3c643da0cc9cfe83 (in processBatchedBlocks, slot=5192400)
[2022-12-30 08:25:20]  INFO initial-sync: Processing block batch of size 64 starting from  0x87ca0daa... 5192464/5463724 - estimated time remaining 7h55m53s blocksPerSecond=9.5 peers=44
[2022-12-30 08:25:20]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0x1a0877b34ccd9e92bdfe7859dbd3478d1c785fd6e970d8b8b637d5c457efec83 (in processBatchedBlocks, slot=5192464)
[2022-12-30 08:25:20]  INFO initial-sync: Processing block batch of size 64 starting from  0xa48361f2... 5192528/5463724 - estimated time remaining 5h55m54s blocksPerSecond=12.7 peers=44
[2022-12-30 08:25:20]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0xc569dd3f4241031b835bd7dd528d2337cca5b0c8315ae55f56b810d1b0a1aa40 (in processBatchedBlocks, slot=5192528)
[2022-12-30 08:25:20]  INFO initial-sync: Processing block batch of size 61 starting from  0x06de2537... 5192592/5463724 - estimated time remaining 4h46m54s blocksPerSecond=15.8 peers=44
[2022-12-30 08:25:20]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0xf9a776157c86f918aa82c39a69a2a880b0eb42a692bc6e1a97b3fe2fce73c916 (in processBatchedBlocks, slot=5192592)
[2022-12-30 08:25:20]  INFO initial-sync: Processing block batch of size 62 starting from  0x865d9e60... 5192656/5463724 - estimated time remaining 3h59m40s blocksPerSecond=18.9 peers=44
[2022-12-30 08:25:20]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0x03140ee59185dc417bf95c370ed4070458855da01b54d0b2186d9e11fd328314 (in processBatchedBlocks, slot=5192656)
[2022-12-30 08:25:20]  INFO initial-sync: Processing block batch of size 64 starting from  0x74b66233... 5192720/5463724 - estimated time remaining 3h24m50s blocksPerSecond=22.1 peers=44
[2022-12-30 08:25:20]  WARN initial-sync: Skip processing batched blocks error=beacon node doesn't have a parent in db with root: 0xed2e36835d677750e41fecc7a16c7d8669fd8a8ff629c9480b575d6d27c26085 (in processBatchedBlocks, slot=5192720)
[2022-12-30 08:25:27]  INFO initial-sync: Processing block batch of size 64 starting from  0x33e52bbd... 5192336/5463725 - estimated time remaining 2h59m8s blocksPerSecond=25.2 peers=45
[2022-12-30 08:25:33]  WARN initial-sync: Skip processing batched blocks error=could not process block in batch: could not set node to invalid: invalid nil or unknown node

And next I see in Geth

ERROR[12-30|08:30:48.985] Error in block freeze operation          err="block receipts missing, can't freeze block 15850304"
WARN [12-30|08:30:55.145] Previously seen beacon client is offline. Please ensure it is operational to follow the chain!
WARN [12-30|08:30:56.688] Ignoring already known beacon payload    number=16,026,540 hash=145907..4f081f age=1mo1w16h
WARN [12-30|08:30:56.696] Ignoring already known beacon payload    number=16,026,541 hash=6acd62..e3bac2 age=1mo1w16h
WARN [12-30|08:30:56.701] Ignoring already known beacon payload    number=16,026,542 hash=1da1d8..c55a69 age=1mo1w16h
WARN [12-30|08:30:56.708] Ignoring already known beacon payload    number=16,026,543 hash=762b24..f56957 age=1mo1w16h
WARN [12-30|08:30:56.719] Ignoring already known beacon payload    number=16,026,544 hash=ff1aef..389471 age=1mo1w16h
WARN [12-30|08:30:56.725] Ignoring already known beacon payload    number=16,026,545 hash=6767aa..85bf1d age=1mo1w16h
WARN [12-30|08:30:56.730] Ignoring already known beacon payload    number=16,026,546 hash=95b736..dc2456 age=1mo1w16h
WARN [12-30|08:30:56.732] Ignoring already known beacon payload    number=16,026,547 hash=34e43f..777810 age=1mo1w16h
WARN [12-30|08:30:56.742] Ignoring already known beacon payload    number=16,026,548 hash=1c67b8..cbc356 age=1mo1w16h
WARN [12-30|08:30:56.750] Ignoring already known beacon payload    number=16,026,549 hash=fe9e47..ed347e age=1mo1w16h
WARN [12-30|08:30:56.754] Ignoring already known beacon payload    number=16,026,550 hash=c98bf1..40560a age=1mo1w16h
WARN [12-30|08:30:56.772] Ignoring already known beacon payload    number=16,026,551 hash=f55377..a1582e age=1mo1w16h
WARN [12-30|08:30:56.780] Ignoring already known beacon payload    number=16,026,552 hash=0bf769..af0ed8 age=1mo1w16h
WARN [12-30|08:30:56.784] Ignoring already known beacon payload    number=16,026,553 hash=382866..a5a4f8 age=1mo1w16h
WARN [12-30|08:30:56.907] Ignoring already known beacon payload    number=16,026,554 hash=65d2ff..6ebef5 age=1mo1w16h
WARN [12-30|08:30:56.918] Ignoring already known beacon payload    number=16,026,555 hash=f04209..4779e9 age=1mo1w16h
WARN [12-30|08:30:56.935] Ignoring already known beacon payload    number=16,026,556 hash=f2b1ab..373dc0 age=1mo1w16h
WARN [12-30|08:30:56.943] Ignoring already known beacon payload    number=16,026,557 hash=979712..00891d age=1mo1w16h
WARN [12-30|08:30:56.956] Ignoring already known beacon payload    number=16,026,558 hash=b53705..8483a1 age=1mo1w16h
WARN [12-30|08:30:56.979] Ignoring already known beacon payload    number=16,026,559 hash=61e689..7e7c79 age=1mo1w16h
WARN [12-30|08:30:56.994] Ignoring already known beacon payload    number=16,026,560 hash=a0f45b..802daf age=1mo1w16h
WARN [12-30|08:30:57.004] Ignoring already known beacon payload    number=16,026,561 hash=037435..474e8d age=1mo1w16h
WARN [12-30|08:30:57.009] Ignoring already known beacon payload    number=16,026,562 hash=565f15..bf9980 age=1mo1w16h
WARN [12-30|08:30:57.031] Ignoring already known beacon payload    number=16,026,563 hash=c7f6ef..cc5ddf age=1mo1w16h
WARN [12-30|08:30:57.033] Ignoring already known beacon payload    number=16,026,564 hash=c87d53..223987 age=1mo1w16h
WARN [12-30|08:30:57.068] Ignoring already known beacon payload    number=16,026,565 hash=51f821..fc1a26 age=1mo1w16h

Has anyone encountered similar problems before?

I already tried to sync again. It didn`t help.


问:
EF 7 + Oracle DB - InvalidCastException: Specified cast is not valid
I am trying to query an Oracle database from .NET7.

I used database first approach to generate my model context. When querying, I get the following exception:

InvalidCastException: Specified cast is not valid.
Oracle.ManagedDataAccess.Client.OracleDataReader.GetInt16(int i)...

That's my (truncated) object class, and the property causing the exception (when I comment the property, select query is working):

```<code>public partial class Car
{
    public string? Owner { get; set; }
    [...]
}
</code>```

Database looks like this:

```<code>CREATE TABLE "Car"
(   "Owner" VARCHAR2(6 BYTE)
    [...]
</code>```

Generated context:

```<code>modelBuilder.Entity<Car>(entity =>
        {
            entity.Property(e => e.Owner)
            .HasMaxLength(6)
            .IsUnicode(false)
            .HasColumnName("Owner")
         [...]
        }
</code>```

Packages:

Oracle.EntityFrameworkCore 7.21.8

Microsoft.EntityFrameworkCore.Design 7.0.1

What's the problem? Is it because the column is nullable? I have no idea.

EDIT:
Seems like the problem is the stored data. Some rows must be corrupted / not like the column definition.

EDIT2:
That's the LINQ query:

```<code>return await _context.Cars.Take(10).ToListAsync();
</code>```

Stacktrace:

```<code>System.InvalidCastException: Specified cast is not valid.
   at Oracle.ManagedDataAccess.Client.OracleDataReader.GetInt16(Int32 i)
   at lambda_method19(Closure, QueryContext, DbDataReader, ResultContext, SingleQueryResultCoordinator)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at CarService.Controllers.CarController.GetCars(Int32 plate) in C:\GIT\webservices\car-service-dotnet\CarService\Controllers\CarController.cs:line 45
   at lambda_method5(Closure, Object)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
</code>```

Body:
I am trying to query an Oracle database from .NET7.

I used database first approach to generate my model context. When querying, I get the following exception:

InvalidCastException: Specified cast is not valid.
Oracle.ManagedDataAccess.Client.OracleDataReader.GetInt16(int i)...

That's my (truncated) object class, and the property causing the exception (when I comment the property, select query is working):

public partial class Car
{
    public string? Owner { get; set; }
    [...]
}

Database looks like this:

CREATE TABLE "Car"
(   "Owner" VARCHAR2(6 BYTE)
    [...]

Generated context:

modelBuilder.Entity<Car>(entity =>
        {
            entity.Property(e => e.Owner)
            .HasMaxLength(6)
            .IsUnicode(false)
            .HasColumnName("Owner")
         [...]
        }

Packages:

Oracle.EntityFrameworkCore 7.21.8

Microsoft.EntityFrameworkCore.Design 7.0.1

What's the problem? Is it because the column is nullable? I have no idea.

EDIT:
Seems like the problem is the stored data. Some rows must be corrupted / not like the column definition.

EDIT2:
That's the LINQ query:

return await _context.Cars.Take(10).ToListAsync();

Stacktrace:

System.InvalidCastException: Specified cast is not valid.
   at Oracle.ManagedDataAccess.Client.OracleDataReader.GetInt16(Int32 i)
   at lambda_method19(Closure, QueryContext, DbDataReader, ResultContext, SingleQueryResultCoordinator)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at CarService.Controllers.CarController.GetCars(Int32 plate) in C:\GIT\webservices\car-service-dotnet\CarService\Controllers\CarController.cs:line 45
   at lambda_method5(Closure, Object)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)


问:
Create and save a GSheet file with list of dictionaries
Have dict1 {subdict1,subdict2}, dict2 {subdict1,subdict2} and dict3 (doesnt have subdicts) into a list 'insights', need to create a gsheet file for each dict of 'insights' list but a sheet for each subdict, this is what its inside 'insights':

```<code>[{'city': {'name': 'follower_demographics',
   'period': 'lifetime',
   'title': 'Follower demographics',
   'type': 'city',
   'description': 'The demographic characteristics of followers, including countries, cities and gender distribution.',
   'df': ''},
  'gender': {'name': 'follower_demographics',
   'period': 'lifetime',
   'title': 'Follower demographics',
   'type': 'gender',
   'description': 'The demographic characteristics of followers, including countries, cities and gender distribution.',
   'df': ''},
  'country': {'name': 'follower_demographics',
   'period': 'lifetime',
   'title': 'Follower demographics',
   'type': 'country',
   'description': 'The demographic characteristics of followers, including countries, cities and gender distribution.',
   'df': ''},
  'age': {'name': 'follower_demographics',
   'period': 'lifetime',
   'title': 'Follower demographics',
   'type': 'age',
   'description': 'The demographic characteristics of followers, including countries, cities and gender distribution.',
   'df': ''}},
 {'city': {'name': 'reached_audience_demographics',
   'period': 'lifetime',
   'title': 'Reached audience demographics',
   'type': 'city',
   'description': 'The demographic characteristics of the reached audience, including countries, cities and gender distribution.',
   'df': ''},
  'gender': {'name': 'reached_audience_demographics',
   'period': 'lifetime',
   'title': 'Reached audience demographics',
   'type': 'gender',
   'description': 'The demographic characteristics of the reached audience, including countries, cities and gender distribution.',
   'df': ''},
  'country': {'name': 'reached_audience_demographics',
   'period': 'lifetime',
   'title': 'Reached audience demographics',
   'type': 'country',
   'description': 'The demographic characteristics of the reached audience, including countries, cities and gender distribution.',
   'df': ''},
  'age': {'name': 'reached_audience_demographics',
   'period': 'lifetime',
   'title': 'Reached audience demographics',
   'type': 'age',
   'description': 'The demographic characteristics of the reached audience, including countries, cities and gender distribution.',
   'df': ''}},
 {'name': 'follower_count',
  'period': 'day',
  'title': 'Follower Count',
  'description': 'Total number of unique accounts following this profile',
  'df': ''}]
</code>```

As you can see in summary the list is the following:

```<code>insights = [
    follower_demographics,
    reached_demographics,
    followers_count
]
</code>```

And this is what each dictionary of the list have, in the case of 'follower_demographics' it breaks in a dictionary of ['city', 'gender', 'country', 'age'] where inside each one is this:

```<code>demographics = {
        'name': '',
        'period': '',
        'title': '',
        'type': '',
        'description': '',
        'df': ''
    }
</code>```

So I did the function below to create a file for the 3 dictionaries of 'insights', the problem is that it creates 4 files of 'follower_demographics' and each one with one respective dataframe.

```<code>def create_gsheet(insights, folder_id):
    try:
        # create a list to store the created files
        files = []

        # iterate over the items in the insights dictionary
        for idx, (key, value) in enumerate(insights.items()):
            # check if the value is a dictionary
            if isinstance(value, dict):
                # Create a new file with the name taken from the 'title' key
                file = gc.create(value['title'], folder=folder_id)

                print(f"Creating {value['title']} - {idx}/{len(insights)}")

                # add the file to the list
                files.append(file)

                # Create a new sheet within the file with the name taken from the 'name' key
                sheet = file.add_worksheet(value['type'] + '_' + value['name'])

                # Set the sheet data to the df provided in the dictionary
                sheet.set_dataframe(value['df'], (1,1), encoding='utf-8', fit=True)

                sheet.frozen_rows = 1

        # delete the default sheet1 from all the created files
        for file in files:
            file.del_worksheet(file.sheet1)

    except Exception as error:
        print(F'An error occurred: {error}')
        sheet = None
</code>```

And the result I want is that for example create 'follower_demographics' file and as sub_sheets 'city_follower_demographics', 'gender_follower_demographics' with their respective dataframes.

Body:
Have dict1 {subdict1,subdict2}, dict2 {subdict1,subdict2} and dict3 (doesnt have subdicts) into a list 'insights', need to create a gsheet file for each dict of 'insights' list but a sheet for each subdict, this is what its inside 'insights':

[{'city': {'name': 'follower_demographics',
   'period': 'lifetime',
   'title': 'Follower demographics',
   'type': 'city',
   'description': 'The demographic characteristics of followers, including countries, cities and gender distribution.',
   'df': ''},
  'gender': {'name': 'follower_demographics',
   'period': 'lifetime',
   'title': 'Follower demographics',
   'type': 'gender',
   'description': 'The demographic characteristics of followers, including countries, cities and gender distribution.',
   'df': ''},
  'country': {'name': 'follower_demographics',
   'period': 'lifetime',
   'title': 'Follower demographics',
   'type': 'country',
   'description': 'The demographic characteristics of followers, including countries, cities and gender distribution.',
   'df': ''},
  'age': {'name': 'follower_demographics',
   'period': 'lifetime',
   'title': 'Follower demographics',
   'type': 'age',
   'description': 'The demographic characteristics of followers, including countries, cities and gender distribution.',
   'df': ''}},
 {'city': {'name': 'reached_audience_demographics',
   'period': 'lifetime',
   'title': 'Reached audience demographics',
   'type': 'city',
   'description': 'The demographic characteristics of the reached audience, including countries, cities and gender distribution.',
   'df': ''},
  'gender': {'name': 'reached_audience_demographics',
   'period': 'lifetime',
   'title': 'Reached audience demographics',
   'type': 'gender',
   'description': 'The demographic characteristics of the reached audience, including countries, cities and gender distribution.',
   'df': ''},
  'country': {'name': 'reached_audience_demographics',
   'period': 'lifetime',
   'title': 'Reached audience demographics',
   'type': 'country',
   'description': 'The demographic characteristics of the reached audience, including countries, cities and gender distribution.',
   'df': ''},
  'age': {'name': 'reached_audience_demographics',
   'period': 'lifetime',
   'title': 'Reached audience demographics',
   'type': 'age',
   'description': 'The demographic characteristics of the reached audience, including countries, cities and gender distribution.',
   'df': ''}},
 {'name': 'follower_count',
  'period': 'day',
  'title': 'Follower Count',
  'description': 'Total number of unique accounts following this profile',
  'df': ''}]

As you can see in summary the list is the following:

insights = [
    follower_demographics,
    reached_demographics,
    followers_count
]

And this is what each dictionary of the list have, in the case of 'follower_demographics' it breaks in a dictionary of ['city', 'gender', 'country', 'age'] where inside each one is this:

demographics = {
        'name': '',
        'period': '',
        'title': '',
        'type': '',
        'description': '',
        'df': ''
    }

So I did the function below to create a file for the 3 dictionaries of 'insights', the problem is that it creates 4 files of 'follower_demographics' and each one with one respective dataframe.

def create_gsheet(insights, folder_id):
    try:
        # create a list to store the created files
        files = []

        # iterate over the items in the insights dictionary
        for idx, (key, value) in enumerate(insights.items()):
            # check if the value is a dictionary
            if isinstance(value, dict):
                # Create a new file with the name taken from the 'title' key
                file = gc.create(value['title'], folder=folder_id)

                print(f"Creating {value['title']} - {idx}/{len(insights)}")

                # add the file to the list
                files.append(file)

                # Create a new sheet within the file with the name taken from the 'name' key
                sheet = file.add_worksheet(value['type'] + '_' + value['name'])

                # Set the sheet data to the df provided in the dictionary
                sheet.set_dataframe(value['df'], (1,1), encoding='utf-8', fit=True)

                sheet.frozen_rows = 1

        # delete the default sheet1 from all the created files
        for file in files:
            file.del_worksheet(file.sheet1)

    except Exception as error:
        print(F'An error occurred: {error}')
        sheet = None

And the result I want is that for example create 'follower_demographics' file and as sub_sheets 'city_follower_demographics', 'gender_follower_demographics' with their respective dataframes.


问:
Selecting multiple values from another table on SQL (phpMyAdmin)
I've been trying to select multiple values from another table (i.e. texts in multiple rows) and display it on main table so that multiple values can be on one cell.

(also, I don't speak English, so some terms might sound different, sorry)

Example:

1st table:

ID
Name
Value1

1
Cell 2
A; B

2
Cell 4
B;C;D

2nd table (column Value1 is connected to the previous table's Value1 column):

ID
Value1

1
A

2
B

3
C

4
D

5
E

So in the first table I want to put both values in one cell from the 2nd table

Thank you!

At the moment, I am able to select only one value for Value1 column in the first table that is referenced to the second table.

On phpMyAdmin, I tried to add several columns on one constraint, but error occurred.


问:
Outer merge 3 or more datasets based on an id and calculate the cosine similarity between them using another column?
Let's say we have three datasets with three different years:

ID
Text
Year

101
abc
1990

102
abd
1990

103
a
1990

And the second dataset that could (or not) contain the IDs from the first year:

ID
Text
Year

104
bc
1991

101
abc
1991

102
abe
1991

And the third dataset:

ID
Text
Year

104
bc
1992

105
a
1992

I want somehow to merge these three dataframes + add a new column to calculate the text similarity (using TF-IDF+cosine similarity) between the common IDs (and uncommon IDs) from those consecutive years + also update the year + the text if we notice there's similarity > 0.8 between text from Year1 and Year2.

Here is the result I want:

ID
Text
Year
Similarity

101
abc
1991
1

102
abe
1991
Cosine(TF-IDF('abd'), TF-IDF('abe'))

103
a
1990
0

104
bc
1992
1

105
a
1992
0

So I also want to include those new IDs corresponding to the new years, but also to keep the IDs of the previous year, but without having a match in terms of ID + that similarity column.
The merge should not be inner (because we also want to integrate those IDs that are not present in the second/third dataframe) and the year should be updated if the similarity score is above a threshold (let's say if text from ID 104, year 1991 has > 0.8 similarity with the text from ID 104, year 1992).

Thanks


问:
How to access old .mdb file using python pyodbc
I have an older mdb file that I need to open and convert the tables into csv. My client doesn't have a way to turn the mdb file into a csv or update the format to be accessable by newer MS Access. So I am stuck trying to open this old mdb file. I can open it in MDBViewr plus but I want a programatic way to open and grab the tables data. I tried pyodbc but got the same error I got when trying to open with MS Access

```<code>Cannot open a database created with a previous version of your application.
</code>```

I'm on windows 11 and would like to not have to use linux to convert this. But if I must I will. Let me know if anyone out there has a solution, thanks in advanced.

I tried pyodbc but got the same error I got from MS Access. That it cannont open db file created on a previous version.

Body:
I have an older mdb file that I need to open and convert the tables into csv. My client doesn't have a way to turn the mdb file into a csv or update the format to be accessable by newer MS Access. So I am stuck trying to open this old mdb file. I can open it in MDBViewr plus but I want a programatic way to open and grab the tables data. I tried pyodbc but got the same error I got when trying to open with MS Access

Cannot open a database created with a previous version of your application.

I'm on windows 11 and would like to not have to use linux to convert this. But if I must I will. Let me know if anyone out there has a solution, thanks in advanced.

I tried pyodbc but got the same error I got from MS Access. That it cannont open db file created on a previous version.


问:
Cast works fine, but Convert not
I tried to Convert.ToInt16 in Contains() but it didnt work

This line of code doesnt work:

filter.OrgUnits = _context.OrgUnit.Where(x => dropdownFilterDto.ViewAllOrgUnits ? true :
staffOrgUnitsAsRegionalManager.Contains(Convert.ToInt16(x.OrgUnitParentId))

But this works just fine :

```<code>filter.OrgUnits = _context.OrgUnit.Where(x => dropdownFilterDto.ViewAllOrgUnits ? true :
                  staffOrgUnitsAsRegionalManager.Contains((short)x.OrgUnitParentId)
</code>```

Can u tell what is the difference between cast and convert?

Title: Cast works fine, but Convert not

Body:
I tried to Convert.ToInt16 in Contains() but it didnt work

This line of code doesnt work:

filter.OrgUnits = _context.OrgUnit.Where(x => dropdownFilterDto.ViewAllOrgUnits ? true :
staffOrgUnitsAsRegionalManager.Contains(Convert.ToInt16(x.OrgUnitParentId))

But this works just fine :

filter.OrgUnits = _context.OrgUnit.Where(x => dropdownFilterDto.ViewAllOrgUnits ? true :
                  staffOrgUnitsAsRegionalManager.Contains((short)x.OrgUnitParentId)

Can u tell what is the difference between cast and convert?


问:
C# how to get rotation matrix that align column vector1 to column vector2?
my code is from How to Calculate a Rotation Matrix to Align Vector A to Vector B in 3D

```<code>public static Matrix<double> RotateAlign(Vector<double> vector1, Vector<double> vector2)
{
    var v1 = Vector3D.OfVector(vector1);
    var v2 = Vector3D.OfVector(vector2);
    var axis = v1.CrossProduct(v2);

    double cosA = v1.DotProduct(v2);
    double k = 1.0 / (1.0 + cosA);

    return M.DenseOfRowArrays(
        new [] {
            (axis.X * axis.X * k) + cosA,
            (axis.Y * axis.X * k) - axis.Z,
            (axis.Z * axis.X * k) + axis.Y,
        },
        new [] {
            (axis.X * axis.Y * k) + axis.Z,
                (axis.Y * axis.Y * k) + cosA,
                (axis.Z * axis.Y * k) - axis.X,
        },
        new [] {
                (axis.X * axis.Z * k) - axis.Y,
                (axis.Y * axis.Z * k) + axis.X,
                (axis.Z * axis.Z * k) + cosA
        }
    );
}
</code>```

however, I found sometimes it's not working...

Body:
my code is from How to Calculate a Rotation Matrix to Align Vector A to Vector B in 3D

public static Matrix<double> RotateAlign(Vector<double> vector1, Vector<double> vector2)
{
    var v1 = Vector3D.OfVector(vector1);
    var v2 = Vector3D.OfVector(vector2);
    var axis = v1.CrossProduct(v2);

    double cosA = v1.DotProduct(v2);
    double k = 1.0 / (1.0 + cosA);

    return M.DenseOfRowArrays(
        new [] {
            (axis.X * axis.X * k) + cosA,
            (axis.Y * axis.X * k) - axis.Z,
            (axis.Z * axis.X * k) + axis.Y,
        },
        new [] {
            (axis.X * axis.Y * k) + axis.Z,
                (axis.Y * axis.Y * k) + cosA,
                (axis.Z * axis.Y * k) - axis.X,
        },
        new [] {
                (axis.X * axis.Z * k) - axis.Y,
                (axis.Y * axis.Z * k) + axis.X,
                (axis.Z * axis.Z * k) + cosA
        }
    );
}

however, I found sometimes it's not working...


问:
Custom validation function with AJV
We are using AJV to validate data.

Here's the schema

```<code>const mySchema = {
  $schema: "https://json-schema.org/draft/2020-12/schema",
  $id: "some_schema_id",
  title: "My list",
  type: "array",
  items: {
    type: "object",
    properties: {
      my_list_key: {
        type: "string",
        maxLength: 20,
        title: "My List",
        readOnly: false,
        isRequired: true,
        disabled: true,
      },
      my_list_itm: {
        type: "array",
        items: {
          type: "object",
          uniqueItems: true,
          properties: {
            date_fr: {
              type: "string",
              format: "date",
              title: "Date From",
              description: "Date From",
              tooltip: "Individual Date or the Start of a Range of Dates",
              readOnly: false,
              disabled: false,
            },
            date_to: {
              type: "string",
              format: "date",
              title: "Date To",
              description: "Date To",
              tooltip: "Optional End of a Range of Dates",
              readOnly: false,
              disabled: false,
            },
          },
        },
      },
    },
  },
};
</code>```

Our requirement is to check for each record that date_fr is always less that date_to. I don't want to add any extra keyword.

TLDR: How to add custom validation function to ajv schema.

Title: Custom validation function with AJV

Body:
We are using AJV to validate data.

Here's the schema

const mySchema = {
  $schema: "https://json-schema.org/draft/2020-12/schema",
  $id: "some_schema_id",
  title: "My list",
  type: "array",
  items: {
    type: "object",
    properties: {
      my_list_key: {
        type: "string",
        maxLength: 20,
        title: "My List",
        readOnly: false,
        isRequired: true,
        disabled: true,
      },
      my_list_itm: {
        type: "array",
        items: {
          type: "object",
          uniqueItems: true,
          properties: {
            date_fr: {
              type: "string",
              format: "date",
              title: "Date From",
              description: "Date From",
              tooltip: "Individual Date or the Start of a Range of Dates",
              readOnly: false,
              disabled: false,
            },
            date_to: {
              type: "string",
              format: "date",
              title: "Date To",
              description: "Date To",
              tooltip: "Optional End of a Range of Dates",
              readOnly: false,
              disabled: false,
            },
          },
        },
      },
    },
  },
};

Our requirement is to check for each record that date_fr is always less that date_to. I don't want to add any extra keyword.

TLDR: How to add custom validation function to ajv schema.


问:
Freezes at accessing Mouser.com using Urllib
I want to access mouser.com using urllib. When I try to fetch the data from the URL, it hangs indefinitely.

Here is code:

import urllib.error
import urllib.request
try:
    htmls = urllib.request.urlopen("https://www.mouser.com/")
except urllib.error.HTTPError as e:
        print("HTTP ERROR")
except urllib.error.URLError as e:
        print("URL ERROR")
else :
    print(htmls.read().decode("utf-8"))
```

This piece of code works fine for most URLs, but for some URLs it doesn't like Mouser or element14.

Body:
I want to access mouser.com using urllib. When I try to fetch the data from the URL, it hangs indefinitely.

Here is code:

import urllib.error
import urllib.request
try:
    htmls = urllib.request.urlopen("https://www.mouser.com/")
except urllib.error.HTTPError as e:
        print("HTTP ERROR")
except urllib.error.URLError as e:
        print("URL ERROR")
else :
    print(htmls.read().decode("utf-8"))

This piece of code works fine for most URLs, but for some URLs it doesn't like Mouser or element14.


问:
request spring boot ,add rating
i have to add rating to product by user,actually,i the user have the right to do the rating of product many times,now i will try to add rating to product once by user,if he haven't a rating to the product x,he can rate it,if he rated it in the past the value of rating will be updated:

my old request:
@Override
public RatingDto addRating(RatingDto rating) {

```<code>    Optional<User> optionalUser = userRepo.findById(rating.getUser().getId());
    Optional<Product> optionalProduct = productRepo.findById(rating.getProduct().getId());
    rating.setUser(optionalUser.isPresent() ? optionalUser.get() : null);
    rating.setProduct(optionalProduct.isPresent() ? optionalProduct.get() : null);

    return ModelMapperConverter.map(ratingRepo.save(ModelMapperConverter.map(rating, Rating.class)), RatingDto.class);

}
</code>```

my class rating:
public class Rating {

```<code>@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private double value;
@ManyToOne (cascade = CascadeType.MERGE)
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "userId")
private User user;
@ManyToOne (cascade = CascadeType.MERGE)
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "productId")
private Product product;

public Rating(double value, User user, Product product) {

    this.setValue(value);
    this.user = user;
    this.product = product;
}
</code>```

}

my class dto rating:
public class RatingDto {

```<code>private Long id;
private double value;
private User user;
private Product product;

public RatingDto(double value, User user, Product product) {
    super();
    this.setValue(value);
    this.user = user;
    this.product = product;
}
</code>```

}

my table actual table in the database:

i need to have a table that contain rating of product by user and ,when he need to add a rating value,just the value will be updated

Title: request spring boot ,add rating

Body:
i have to add rating to product by user,actually,i the user have the right to do the rating of product many times,now i will try to add rating to product once by user,if he haven't a rating to the product x,he can rate it,if he rated it in the past the value of rating will be updated:

my old request:
@Override
public RatingDto addRating(RatingDto rating) {

    Optional<User> optionalUser = userRepo.findById(rating.getUser().getId());
    Optional<Product> optionalProduct = productRepo.findById(rating.getProduct().getId());
    rating.setUser(optionalUser.isPresent() ? optionalUser.get() : null);
    rating.setProduct(optionalProduct.isPresent() ? optionalProduct.get() : null);

    return ModelMapperConverter.map(ratingRepo.save(ModelMapperConverter.map(rating, Rating.class)), RatingDto.class);

}

my class rating:
public class Rating {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private double value;
@ManyToOne (cascade = CascadeType.MERGE)
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "userId")
private User user;
@ManyToOne (cascade = CascadeType.MERGE)
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "productId")
private Product product;

public Rating(double value, User user, Product product) {

    this.setValue(value);
    this.user = user;
    this.product = product;
}

}

my class dto rating:
public class RatingDto {

private Long id;
private double value;
private User user;
private Product product;

public RatingDto(double value, User user, Product product) {
    super();
    this.setValue(value);
    this.user = user;
    this.product = product;
}

}

my table actual table in the database:

i need to have a table that contain rating of product by user and ,when he need to add a rating value,just the value will be updated


问:
Can I use Gino[starlette] with SQLite?
I'm trying to make the Gino mock, but I keep seeing the error

```<code>gino.exceptions.UninitializedError: Gino engine is not initialized.
</code>```

My code is formed like this:

# __init__.py
@functools.lru_cache
def get_db_service():
    db = Gino(dsn=settings.get_settings().postgresql_conn_url)

    return db
```
<pre class="lang-py prettyprint-override"><code># model

_db = get_db_service()

class EdaTableInstance(_db.Model):
    __tablename__ = "eda_table_instance"
#...

   @classmethod
    async def get_all(cls) -> List['EdaTableInstance']:
        async with _db.acquire():
              return await EdaTableInstance.query.gino.all()
</code>```

How I'm writing the tests (various attempts):

# conftest.py
@pytest.fixture(autouse=True)
def mock_get_db_service(mocker):
    db = Gino(dsn="sqlite//:memory:")
    async_mock = AsyncMock(db)
    mocker.patch("gateway_api.services.get_db_service", return_value=async_mock)
    yield
```
<p>or</p>
<pre class="lang-py prettyprint-override"><code># conftest.py

@pytest.fixture
async def db_initialize():
   await db.set_bind('sqlite:///:memory:')
   await db.gino.create_all()
   await EdaTableInstance.create_eda_table_instance(
       EdaTableInstanceInputOnCreate({"name":"table_server1", "host":"123.123.123.123"})
   )
   yield
</code>```

or

# test_models.py
@pytest.fixture
def mock_gino_get_all(mocker):
    mocker.patch("gino.api.GinoExecutor.all", return_value=[])

@pytest.mark.asyncio
@pytest.mark.parametrize("id, expected", [(None, None)])
async def test_01_table_instance_get_all(id, expected):
    mock_cursor = MagicMock()
    mock_cursor.configure_mock(
        **{
            "get_one.return_value":[id]
        }
    )
    res = await EdaTableInstance().get_one(mock_cursor)
    assert res == expected

```

I would like to use SQLite in memory, so I don't have to connect from a database, if you know better methods to mock the database, it would help me so much.

Title: Can I use Gino[starlette] with SQLite?

Body:
I'm trying to make the Gino mock, but I keep seeing the error

gino.exceptions.UninitializedError: Gino engine is not initialized.

My code is formed like this:

# __init__.py
@functools.lru_cache
def get_db_service():
    db = Gino(dsn=settings.get_settings().postgresql_conn_url)

    return db

# model

_db = get_db_service()

class EdaTableInstance(_db.Model):
    __tablename__ = "eda_table_instance"
#...

   @classmethod
    async def get_all(cls) -> List['EdaTableInstance']:
        async with _db.acquire():
              return await EdaTableInstance.query.gino.all()

How I'm writing the tests (various attempts):

# conftest.py
@pytest.fixture(autouse=True)
def mock_get_db_service(mocker):
    db = Gino(dsn="sqlite//:memory:")
    async_mock = AsyncMock(db)
    mocker.patch("gateway_api.services.get_db_service", return_value=async_mock)
    yield

or

# conftest.py

@pytest.fixture
async def db_initialize():
   await db.set_bind('sqlite:///:memory:')
   await db.gino.create_all()
   await EdaTableInstance.create_eda_table_instance(
       EdaTableInstanceInputOnCreate({"name":"table_server1", "host":"123.123.123.123"})
   )
   yield

or

# test_models.py
@pytest.fixture
def mock_gino_get_all(mocker):
    mocker.patch("gino.api.GinoExecutor.all", return_value=[])

@pytest.mark.asyncio
@pytest.mark.parametrize("id, expected", [(None, None)])
async def test_01_table_instance_get_all(id, expected):
    mock_cursor = MagicMock()
    mock_cursor.configure_mock(
        **{
            "get_one.return_value":[id]
        }
    )
    res = await EdaTableInstance().get_one(mock_cursor)
    assert res == expected

I would like to use SQLite in memory, so I don't have to connect from a database, if you know better methods to mock the database, it would help me so much.


问:
is there any options to change bundle identifier while generating the build using terminal
i) is it possible to change the Bundle identifier and Provisional Profiles in Codebase while generating the Archive File and IPA file.

ii) is it possible to change the Application name while generating IPA file in Command line Tools.

```<code>I am following these two syntax while generating the Archive and IPA.

xcodebuild -workspace ".workspace" -scheme "SchemeName"  -archivePath "archivePath/appName.xcarchive" archive

xcodebuild -exportArchive -archivePath "archivePath/appName.xcarchive" \
  -exportOptionsPlist "ecportOptionsPlist" \
   -exportPath "ExportPath"

</code>```

Body:
i) is it possible to change the Bundle identifier and Provisional Profiles in Codebase while generating the Archive File and IPA file.

ii) is it possible to change the Application name while generating IPA file in Command line Tools.

I am following these two syntax while generating the Archive and IPA.

xcodebuild -workspace ".workspace" -scheme "SchemeName"  -archivePath "archivePath/appName.xcarchive" archive

xcodebuild -exportArchive -archivePath "archivePath/appName.xcarchive" \
  -exportOptionsPlist "ecportOptionsPlist" \
   -exportPath "ExportPath"


问:
ODBC SQL - ROUND in HAVING clause is invalid
I have the following command that I use to extract data through ODBC:

```<code>SELECT SALES_LEDGER.ACCOUNT_REF, SALES_LEDGER.BALANCE
FROM SALES_LEDGER
INNER JOIN AUDIT_SPLIT ON SALES_LEDGER.ACCOUNT_REF = AUDIT_SPLIT.ACCOUNT_REF
GROUP BY
SALES_LEDGER.ACCOUNT_REF, SALES_LEDGER.BALANCE
HAVING
ROUND(SUM(AUDIT_SPLIT.GROSS_AMOUNT), 2) <> SALES_LEDGER.BALANCE;
</code>```

Running this in Excel without the ROUND is fine but I need the ROUND because otherwise the values of the SUM are not equal to BALANCE and I get false results.

The error in Excel is:
"ODBC: ERROR [42000] Syntax error: Invalid filter in HAVING clause"

Why can't I have the ROUND command there? I try with CAST as well but it is the ROUND that I really need there.

Body:
I have the following command that I use to extract data through ODBC:

SELECT SALES_LEDGER.ACCOUNT_REF, SALES_LEDGER.BALANCE
FROM SALES_LEDGER
INNER JOIN AUDIT_SPLIT ON SALES_LEDGER.ACCOUNT_REF = AUDIT_SPLIT.ACCOUNT_REF
GROUP BY
SALES_LEDGER.ACCOUNT_REF, SALES_LEDGER.BALANCE
HAVING
ROUND(SUM(AUDIT_SPLIT.GROSS_AMOUNT), 2) <> SALES_LEDGER.BALANCE;

Running this in Excel without the ROUND is fine but I need the ROUND because otherwise the values of the SUM are not equal to BALANCE and I get false results.

The error in Excel is:
"ODBC: ERROR [42000] Syntax error: Invalid filter in HAVING clause"

Why can't I have the ROUND command there? I try with CAST as well but it is the ROUND that I really need there.


问:
Android in-app billing for non-digital goods?
I want to make a small app in which I sell some non-digital products. I was wondering if there is some sort of payment system with which the users can pay directly within the app?
I only found the in-app billing for Android but this is only working for digital content. PayPal also has an app but this is more or less something on its own as far as I saw.

Thanks for hints.

ContentLicense: CC BY-SA 3.0


问:
Problems running Quarkus sample application from a GraalVM image-based Docker container
Working on Windows 10, I downloaded the simple Quarkus sample prototype.

I run it normally and be able to access http://localhost:8118/hello, except if I try to run it from the native image executable for GraalVM.

I have to say that I don't have GraalVM installed, but I'm trying to do it from a Docker container (called contenedor-graalvm-1) based on the following GraalVM image:
container-registry.oracle.com/graalvm/community:ol8-java17-22.3.0-b1

The sequence I follow is:

```<code>docker start contenedor-graalvm-1

docker exec -it contenedor-graalvm-1 bash

cd code-with-quarkus-one/target
</code>```

And then, successive launch attempts:

```<code>A)
./code-with-quarkus-one-1.0.0-SNAPSHOT-runner -Dquarkus.http.host=0.0.0.0 -Dquarkus.http.port=8118

B)
./code-with-quarkus-one-1.0.0-SNAPSHOT-runner -Dquarkus.http.host=192.168.49.147 -Dquarkus.http.port=8118

C)
./code-with-quarkus-one-1.0.0-SNAPSHOT-runner -Dquarkus.http.host=127.0.0.1 -Dquarkus.http.port=8118

D)
./code-with-quarkus-one-1.0.0-SNAPSHOT-runner -Dquarkus.http.host=localhost -Dquarkus.http.port=8118
</code>```

That seems to start properly (except -B- option):

But none of them allow me to access to the desired endpoint:

Any help will be appreciatted.

Body:
Working on Windows 10, I downloaded the simple Quarkus sample prototype.

I run it normally and be able to access http://localhost:8118/hello, except if I try to run it from the native image executable for GraalVM.

I have to say that I don't have GraalVM installed, but I'm trying to do it from a Docker container (called contenedor-graalvm-1) based on the following GraalVM image:
container-registry.oracle.com/graalvm/community:ol8-java17-22.3.0-b1

The sequence I follow is:

docker start contenedor-graalvm-1

docker exec -it contenedor-graalvm-1 bash

cd code-with-quarkus-one/target

And then, successive launch attempts:

A)
./code-with-quarkus-one-1.0.0-SNAPSHOT-runner -Dquarkus.http.host=0.0.0.0 -Dquarkus.http.port=8118

B)
./code-with-quarkus-one-1.0.0-SNAPSHOT-runner -Dquarkus.http.host=192.168.49.147 -Dquarkus.http.port=8118

C)
./code-with-quarkus-one-1.0.0-SNAPSHOT-runner -Dquarkus.http.host=127.0.0.1 -Dquarkus.http.port=8118

D)
./code-with-quarkus-one-1.0.0-SNAPSHOT-runner -Dquarkus.http.host=localhost -Dquarkus.http.port=8118

That seems to start properly (except -B- option):

But none of them allow me to access to the desired endpoint:

Any help will be appreciatted.


问:
Can I use the Scipy simulated annealing library to solve the traveling salesman problem?
To solve the traveling salesman problem with simulated annealing, we need to start with an initial solution, a random permutation of the cities. This is the order in which the salesman is supposed to visit them. Then, we switch to a "neighboring solution" by swapping two cities. And then there are details around when to switch to the neighboring solution, etc.

I could implement all of this from scratch. But I wanted to see if I could use the inbuilt Scipy annealing solver. Looking at the documentation, looks like the old anneal method has been deprecated. The new methods that is supposed to have replaced it is basinhopping. But looking through the documentation and source code, it seems these are more towards optimizing a function of some array where any float values of that array are permissible (and then there are local and global optima). That's what all the examples in the documentation or code comments are geared towards. I can't imagine how I would use any of these inbuilt routines to solve the famous traveling salesman problem itself since the array there is a permutation array. If you just perturb its values by some floating point numbers, you won't get a valid solution.

So, the conclusion seems to be that those standard routines are inapplicable on a combinatorial optimization problem like the traveling salesman? Or am I missing something?


问:
VS Code manual folding ranges disappear randomly
I think the main cause of manual folding ranges disappearing for me is when I open the file that is on my OneDrive on my laptop after I created folding ranges on my desktop PC and vice versa. Also they disappear for no reason even when I only edit on desktop PC on some days.
So I would assume that these ranges are not actually defined in the file you're working on but in some settings file that's in .vscode folder maybe?

So my question is how to make VS Code manual folding ranges constant for a file no matter where/how you open it (different machines or maybe even web version of vscode).
Does anyone know where these ranges are defined?


问:
php mysql - how query the database with multiple ids
I am looking for the result of the queries contained in this table:
`

```<code>$queries = array_map(static function ($odd_task) use ($id_oeuvre): string{
    return <<<SQL
    SELECT
        PK_ASSOC_OVRUSRTCH,
        FK_OUT_REF_USR
    FROM sc_t_assoc_ovr_usr_tch
    WHERE
        FK_OUT_REF_TCH = {$odd_task}
    AND FK_OUT_REF_OVR = {$id_oeuvre};
    SQL;
    }, $odd_tasks);
</code>```

Basically, we should be able to make an array of these loops and get the results:

```<code>$oRecordset = mysqli_query($queries[0], $oConnexion);
while($fetch = mysqli_fetch_object($oRecordset)){
    $pk_usr_tch_missing1 = $fetch->PK_ASSOC_OVRUSRTCH;
    $user_missing1 = $fetch->FK_OUT_REF_USR;
}
$oRecordset = mysqli_query($queries[1], $oConnexion);
while($fetch = mysqli_fetch_object($oRecordset)){
    $pk_usr_tch_missing2 = $fetch->PK_ASSOC_OVRUSRTCH;
    $user_missing2 = $fetch->FK_OUT_REF_USR;
}
</code>```

`

I would like to iterate over that future table and get the results of the requests that are contained within it as strings.

Body:
I am looking for the result of the queries contained in this table:
`

$queries = array_map(static function ($odd_task) use ($id_oeuvre): string{
    return <<<SQL
    SELECT
        PK_ASSOC_OVRUSRTCH,
        FK_OUT_REF_USR
    FROM sc_t_assoc_ovr_usr_tch
    WHERE
        FK_OUT_REF_TCH = {$odd_task}
    AND FK_OUT_REF_OVR = {$id_oeuvre};
    SQL;
    }, $odd_tasks);

Basically, we should be able to make an array of these loops and get the results:

$oRecordset = mysqli_query($queries[0], $oConnexion);
while($fetch = mysqli_fetch_object($oRecordset)){
    $pk_usr_tch_missing1 = $fetch->PK_ASSOC_OVRUSRTCH;
    $user_missing1 = $fetch->FK_OUT_REF_USR;
}
$oRecordset = mysqli_query($queries[1], $oConnexion);
while($fetch = mysqli_fetch_object($oRecordset)){
    $pk_usr_tch_missing2 = $fetch->PK_ASSOC_OVRUSRTCH;
    $user_missing2 = $fetch->FK_OUT_REF_USR;
}

`

I would like to iterate over that future table and get the results of the requests that are contained within it as strings.


问:
How to get the session expiration event in express using ioredis?
I am using ioRedis coupled with express-session in my NodeJS app and I'd like to fire an event when a session expires. I wrote this:

```<code>let Redis = require('ioredis');
let clientRedis = new Redis();
let RedisStore = require('connect-redis')(session);

const sessionMiddleware = session({
  store: new RedisStore({
    client: clientRedis,
  }),
  secret: SESSIONSECRET,
  resave: true,
  saveUninitialized: true,
  cookie: {
    maxAge: 5000,
    secure: false,
    httpOnly: true,
    domain: config.get('app.domainecookie')
   }
});

app.use(sessionMiddleware);
</code>```

I read the doc and I have no clue on how capture the "expire" event... There must be a ioredis function, but I don't see which one.
I read a lot of questions talking about key expiration but this is not a particular key I want to get the notifications of, I want the session of the user to get a notification (I'm handling the messages with a socket which works like a charm, I just don't know how to capture the event).

For the moment I created an express middleware firing timed out functions in a custom "activeSessions" object, but this is using memory of my NodeJS.app, there must be a better way to do this.

Thanks in advance :)

Body:
I am using ioRedis coupled with express-session in my NodeJS app and I'd like to fire an event when a session expires. I wrote this:

let Redis = require('ioredis');
let clientRedis = new Redis();
let RedisStore = require('connect-redis')(session);

const sessionMiddleware = session({
  store: new RedisStore({
    client: clientRedis,
  }),
  secret: SESSIONSECRET,
  resave: true,
  saveUninitialized: true,
  cookie: {
    maxAge: 5000,
    secure: false,
    httpOnly: true,
    domain: config.get('app.domainecookie')
   }
});

app.use(sessionMiddleware);

I read the doc and I have no clue on how capture the "expire" event... There must be a ioredis function, but I don't see which one.
I read a lot of questions talking about key expiration but this is not a particular key I want to get the notifications of, I want the session of the user to get a notification (I'm handling the messages with a socket which works like a charm, I just don't know how to capture the event).

For the moment I created an express middleware firing timed out functions in a custom "activeSessions" object, but this is using memory of my NodeJS.app, there must be a better way to do this.

Thanks in advance :)


问:
ModuleNotFoundError: No module named 'gevent.signal'

# test.py
# a minimum reproducible demo

import gevent
from gevent import monkey
monkey.patch_all(thread=False)
```
<p>compile with <code>nuitka</code>, cmd: <code>python -m nuitka --standalone  --output-dir=out test.py</code></p>
<p>running the output test.exe</p>
```Traceback (most recent call last):
  File "D:\GetMailExtension\out\test.dist\test.py", line 3, in <module>
  File "D:\GetMailExtension\out\test.dist\gevent\monkey.py", line 1285, in patch_all
  File "D:\GetMailExtension\out\test.dist\gevent\monkey.py", line 200, in ignores
  File "D:\GetMailExtension\out\test.dist\gevent\monkey.py", line 1165, in patch_signal
  File "D:\GetMailExtension\out\test.dist\gevent\monkey.py", line 462, in _patch_module
  File "D:\GetMailExtension\out\test.dist\gevent\monkey.py", line 448, in _check_availability
ModuleNotFoundError: No module named 'gevent.signal'
```
<p>no such module as 'gevent.signal'?</p>
<p>I've tried <code>python -m nuitka --standalone  --output-dir=out --plugin-enable=gevent test.py</code>, but in vain.</p>
<p>sys environment:</p>
```python 3.7.3 (32bit)
nuitka 1.3.4
gevent 22.10.2
```

Body:
# test.py
# a minimum reproducible demo

import gevent
from gevent import monkey
monkey.patch_all(thread=False)

compile with nuitka, cmd: python -m nuitka --standalone  --output-dir=out test.py

running the output test.exe

Traceback (most recent call last):
  File "D:\GetMailExtension\out\test.dist\test.py", line 3, in <module>
  File "D:\GetMailExtension\out\test.dist\gevent\monkey.py", line 1285, in patch_all
  File "D:\GetMailExtension\out\test.dist\gevent\monkey.py", line 200, in ignores
  File "D:\GetMailExtension\out\test.dist\gevent\monkey.py", line 1165, in patch_signal
  File "D:\GetMailExtension\out\test.dist\gevent\monkey.py", line 462, in _patch_module
  File "D:\GetMailExtension\out\test.dist\gevent\monkey.py", line 448, in _check_availability
ModuleNotFoundError: No module named 'gevent.signal'

no such module as 'gevent.signal'?

I've tried python -m nuitka --standalone  --output-dir=out --plugin-enable=gevent test.py, but in vain.

sys environment:

python 3.7.3 (32bit)
nuitka 1.3.4
gevent 22.10.2


问:
Bash script is waiting to open second file in gedit until I close the first one
I wrote a simple bash script to create and open two files

```<code>#!/bin/bash

mynewdate="$(date '+%d-%m-%Y')"
cd /my/path/
echo "praparing files..."

pilot="pilot-mode-"${mynewdate}
echo $pilot
touch $pilot
cat pilot-mode-schema >> $pilot
gedit $pilot

cd distractions
distratcions="distractions-"${mynewdate}
echo $distratcions
touch $distratcions
cat distractions-schema >> $distratcions

gedit $distratcions
</code>```

but when I open the first one

```<code>gedit $pilot
</code>```

it opens and the second one opens only after I close the first one.

How can I change the script to open two files at once?

I was trying to look for similar answers on askubuntu and other places but with no luck

and also tried adding ; sign at the end of line, still the same.

Body:
I wrote a simple bash script to create and open two files

#!/bin/bash

mynewdate="$(date '+%d-%m-%Y')"
cd /my/path/
echo "praparing files..."

pilot="pilot-mode-"${mynewdate}
echo $pilot
touch $pilot
cat pilot-mode-schema >> $pilot
gedit $pilot

cd distractions
distratcions="distractions-"${mynewdate}
echo $distratcions
touch $distratcions
cat distractions-schema >> $distratcions

gedit $distratcions

but when I open the first one

gedit $pilot

it opens and the second one opens only after I close the first one.

How can I change the script to open two files at once?

I was trying to look for similar answers on askubuntu and other places but with no luck

and also tried adding ; sign at the end of line, still the same.


问:
How to get C char * string value in swift?
```<code>char*   iperf_get_test_json_output_string ( struct iperf_test* ipt );    // .h file
</code>```

I am using iperf SDK .c file in iOS project in swift. Above function return (char *) pointer reference. I am getting pointer reference. Anyone Can help to get the string in swift using this above function?

```<code>var result =  iperf_get_test_json_output_string(test)
let temp = withUnsafePointer(to: result) {
          $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: $0) ) {
               String(cString: $0)
           }
</code>```

Body:
char*   iperf_get_test_json_output_string ( struct iperf_test* ipt );    // .h file

I am using iperf SDK .c file in iOS project in swift. Above function return (char *) pointer reference. I am getting pointer reference. Anyone Can help to get the string in swift using this above function?

var result =  iperf_get_test_json_output_string(test)
let temp = withUnsafePointer(to: result) {
          $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: $0) ) {
               String(cString: $0)
           }


问:
Paging adapter unable to receive updated data
I am currently building a fragment, and within the fragment contains 2 paging adapter sharing the same data. When I update the data, only one of the paging adapter receives the updated data while the other does not.

On first start up. for reference (backdrop - top adapter/viewpager, poster - bottom adapter/viewpager)

first item =

second item =

third item =

when I change the movie category, only the bottom paging adapter receive the updated data

updated first item =

updated second item =

updated third item =

as seen in the image, the bottom paging adapter have successfully updated its image while the top paging adapter does not

additional information:
I am using Remote Mediator to store network data to ROOM Database.
Both top and bottom list is displayed using viewpager2, page transformer is applied to both viewpager. To add on, top viewpager scroll is dependent on the bottom viewpager (i.e. top viewpager will only scroll if bottom view pager scrolls).

depending on which paging adapter's submitData function is called first, its data will be updated, while the paging adapter after it won't update its data.
for the case below, the bottom viewPager(poster) will be updated while the top viewPager(backdrop) won't be updated.

```<code>collectLatestLifecycleFlow(viewModel.movieList) { pagingData ->
    posterPagingAdapter.submitData(pagingData)
    backdropPagingAdapter.submitData(pagingData)
}
</code>```

I expect both paging adapter to be updated when I update the movie category.

so far as a temporary solution I created two flow collectors to collect the data so that both viewpager can update their data, however this is inefficient as it will do another Api Call which is redundant.

```<code>collectLatestLifecycleFlow(viewModel.movieList) { pagingData ->
    backdropPagingAdapter.submitData(pagingData)
}
collectLatestLifecycleFlow(viewModel.movieList) { pagingData ->
    posterPagingAdapter.submitData(pagingData)
}
</code>```

below is the code I use to in ViewModel to get the data

```<code>val movieList = selectedMovieCategory.flatMapLatest {
    Timber.i("selected category: $it")
    when (it) {
        MoviePagingCategory.NOW_PLAYING.categoryName -> {
            moviesUseCase.getNowPlayingPagingData(loadSinglePage = true)
        }
        MoviePagingCategory.POPULAR.categoryName -> {
            moviesUseCase.getPopularMoviesPagingData(loadSinglePage = true)
        }
        MoviePagingCategory.TRENDING.categoryName -> {
            moviesUseCase.getTrendingMoviesPagingData(loadSinglePage = true)
        }
        else -> throw Exception("No listed category")
    }.cachedIn(viewModelScope)
}
</code>```

for PagingAdapter's diff util. do note that id here is a manually generated id instead of movieId provided by the Api. the reason for this is to store multiple movie types in single room table.

```<code>companion object DiffUtilCallback : DiffUtil.ItemCallback<Result>() {
    override fun areItemsTheSame(oldItem: Result, newItem: Result): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: Result, newItem: Result): Boolean {
        return oldItem == newItem
    }
}
</code>```

Body:
I am currently building a fragment, and within the fragment contains 2 paging adapter sharing the same data. When I update the data, only one of the paging adapter receives the updated data while the other does not.

On first start up. for reference (backdrop - top adapter/viewpager, poster - bottom adapter/viewpager)

first item =

second item =

third item =

when I change the movie category, only the bottom paging adapter receive the updated data

updated first item =

updated second item =

updated third item =

as seen in the image, the bottom paging adapter have successfully updated its image while the top paging adapter does not

additional information:
I am using Remote Mediator to store network data to ROOM Database.
Both top and bottom list is displayed using viewpager2, page transformer is applied to both viewpager. To add on, top viewpager scroll is dependent on the bottom viewpager (i.e. top viewpager will only scroll if bottom view pager scrolls).

depending on which paging adapter's submitData function is called first, its data will be updated, while the paging adapter after it won't update its data.
for the case below, the bottom viewPager(poster) will be updated while the top viewPager(backdrop) won't be updated.

collectLatestLifecycleFlow(viewModel.movieList) { pagingData ->
    posterPagingAdapter.submitData(pagingData)
    backdropPagingAdapter.submitData(pagingData)
}

I expect both paging adapter to be updated when I update the movie category.

so far as a temporary solution I created two flow collectors to collect the data so that both viewpager can update their data, however this is inefficient as it will do another Api Call which is redundant.

collectLatestLifecycleFlow(viewModel.movieList) { pagingData ->
    backdropPagingAdapter.submitData(pagingData)
}
collectLatestLifecycleFlow(viewModel.movieList) { pagingData ->
    posterPagingAdapter.submitData(pagingData)
}

below is the code I use to in ViewModel to get the data

val movieList = selectedMovieCategory.flatMapLatest {
    Timber.i("selected category: $it")
    when (it) {
        MoviePagingCategory.NOW_PLAYING.categoryName -> {
            moviesUseCase.getNowPlayingPagingData(loadSinglePage = true)
        }
        MoviePagingCategory.POPULAR.categoryName -> {
            moviesUseCase.getPopularMoviesPagingData(loadSinglePage = true)
        }
        MoviePagingCategory.TRENDING.categoryName -> {
            moviesUseCase.getTrendingMoviesPagingData(loadSinglePage = true)
        }
        else -> throw Exception("No listed category")
    }.cachedIn(viewModelScope)
}

for PagingAdapter's diff util. do note that id here is a manually generated id instead of movieId provided by the Api. the reason for this is to store multiple movie types in single room table.

companion object DiffUtilCallback : DiffUtil.ItemCallback<Result>() {
    override fun areItemsTheSame(oldItem: Result, newItem: Result): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: Result, newItem: Result): Boolean {
        return oldItem == newItem
    }
}


问:
Slate - set multiple variables via javascript?
How can i set multiple variables via JavaScript in Slate?
So, can i set a slate variable also via JavaScript, by running a JavaScript if a button event was done?
I want to avoid 10 events for each variable...</p>


问:
Logout is not working correctly in iOS for Spring Authorization Server with React-Native
This is my code for http security

```<code>  @Bean
    SecurityFilterChain defaultSecurityFilterChain(final HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorizeRequests ->
                        authorizeRequests.anyRequest().authenticated()
                )
                .formLogin(Customizer.withDefaults())
                .formLogin(form -> form.loginPage("/login").failureUrl("/login-error").permitAll())
                .csrf().disable()
                .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer
                        .deleteCookies("JSESSIONID")
                        .clearAuthentication(true)
                        .permitAll()
                        .logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> httpServletResponse.sendRedirect("myUrl://Signup")));

        return http.build();
    }
</code>```

But in iOS when i call /logout in a browser it doesn't work well , and the session never close, so when the user try to login , it connects from its own

Body:
This is my code for http security

  @Bean
    SecurityFilterChain defaultSecurityFilterChain(final HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorizeRequests ->
                        authorizeRequests.anyRequest().authenticated()
                )
                .formLogin(Customizer.withDefaults())
                .formLogin(form -> form.loginPage("/login").failureUrl("/login-error").permitAll())
                .csrf().disable()
                .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer
                        .deleteCookies("JSESSIONID")
                        .clearAuthentication(true)
                        .permitAll()
                        .logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> httpServletResponse.sendRedirect("myUrl://Signup")));

        return http.build();
    }

But in iOS when i call /logout in a browser it doesn't work well , and the session never close, so when the user try to login , it connects from its own


问:
When I'm scraping Angular app nothing happens when I change select options

When I'm trying to change options in select "event doesn't load like ((ngModelChange) or (ngchnage))"

I tried this for change selected option, but no event loaded
document.querySelectorAll("select")[1].value=2" and
document.querySelectorAll("select option")[2].selected=true;


问:
I am manually generating a form in django(3.1.2) framework, but the name and type field are empty while rendering form
```<code><div class="col-sm-9">
 <input type="{{ widget.type }}" class="form-control mt-3" id="{{form.Address.id_for_label}}" name="{{ widget.name }}" {% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %} {% include "django/forms/widgets/attrs.html" %} />
</div>
</code>```

name and type field are empty. so i cannot pass the form data to request.POST.

```<code><div class="col-sm-9">
 <input type="" class="form-control mt-3" id="id_Address" name=""   />
</div>
</code>```

Body:
 <input type="{{ widget.type }}" class="form-control mt-3" id="{{form.Address.id_for_label}}" name="{{ widget.name }}" {% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %} {% include "django/forms/widgets/attrs.html" %} />

name and type field are empty. so i cannot pass the form data to request.POST.

 <input type="" class="form-control mt-3" id="id_Address" name=""   />


问:
Error when import of node module 'windows' in electrons
I am updating the node module of an application made by somebody else. The module used is 'windows' and the version that was used was 0.0.8. I updated electronjs to 22 and the node module 'windows' to the latest version 0.1.2.

I am using the module, as it was used before :

const windows = require('windows');

var a = windows.registry('/RegistryPath/').SomeValueName.value;

And I am getting the error :
A JavaScript error occurred in the main process

Uncaught Exception:

TypeError: Cannot read properties of undefined (reading 'split')

at Object.
(/path/node_modules/windows/lib/runnable.js:9:29)
 at
Module._compile (node:internal/modules/cjs/loader:1141:14)
 at
Module._extensions..js (node:internal/modules/cjs/loader:1196:10)

at Module.load (node:internal/modules/cjs/loader:1011:32)
 at
Module._load (node:internal/modules/cjs/loader:846:12)
 at f._load
(node:electron/js2c/asar_bundle:2:13328)
 at Module.require
(node:internal/modules/cjs/loader:1035:19)
 at require
(node:internal/modules/cjs/helpers:102:18)
 at Object.
(/path/node_modules/windows/index.js:4:17)
 at
Module._compile (node:internal/modules/cjs/loader:1141:14)

The error location is at runnable.js:9 :

```<code>var path = require('path');
var fs = require('fs');

var exists = require('./utility').exists;
var resolve = require('./utility').resolve;

var PATH = process.env.Path.split(';').filter(function(s){ return ~s.indexOf('node') });
</code>```

I tried to read the environnemental variable in Linux and I found that if I modify the code of the module 'windows' to get process.env.PATH.split(';') instead of process.env.Path.split(';') I don't get the same error. The code move forward to the next conditional loop. But the filter of the line discussed here is looking for the string 'node'. In the case of an electron app when it is package there is no node_module folder. So I also hit the same next error when the app is package; which is :

```<code>//Bugfix taken from @schmittberger
if (!exists(PATH)) {
  if (process.env.NODE_PATH) {
    PATH = process.env.NODE_PATH
  } else {
    throw new Error('No bin-PATH found');
  }
}
</code>```

At this point I am receiving the Error('No bin-PATH found'). I don't have enough experience to know how to fix such an issue. Even if I add the path to my node bin in the environnemental variable of Linux I will hit the same error when the app is package for Windows as there are no folder "node_modules" in the packaged app.

Body:
I am updating the node module of an application made by somebody else. The module used is 'windows' and the version that was used was 0.0.8. I updated electronjs to 22 and the node module 'windows' to the latest version 0.1.2.

I am using the module, as it was used before :

const windows = require('windows');

var a = windows.registry('/RegistryPath/').SomeValueName.value;

And I am getting the error :
A JavaScript error occurred in the main process

Uncaught Exception:

TypeError: Cannot read properties of undefined (reading 'split')

at Object.
(/path/node_modules/windows/lib/runnable.js:9:29)
 at
Module._compile (node:internal/modules/cjs/loader:1141:14)
 at
Module._extensions..js (node:internal/modules/cjs/loader:1196:10)

at Module.load (node:internal/modules/cjs/loader:1011:32)
 at
Module._load (node:internal/modules/cjs/loader:846:12)
 at f._load
(node:electron/js2c/asar_bundle:2:13328)
 at Module.require
(node:internal/modules/cjs/loader:1035:19)
 at require
(node:internal/modules/cjs/helpers:102:18)
 at Object.
(/path/node_modules/windows/index.js:4:17)
 at
Module._compile (node:internal/modules/cjs/loader:1141:14)

The error location is at runnable.js:9 :

var path = require('path');
var fs = require('fs');

var exists = require('./utility').exists;
var resolve = require('./utility').resolve;

var PATH = process.env.Path.split(';').filter(function(s){ return ~s.indexOf('node') });

I tried to read the environnemental variable in Linux and I found that if I modify the code of the module 'windows' to get process.env.PATH.split(';') instead of process.env.Path.split(';') I don't get the same error. The code move forward to the next conditional loop. But the filter of the line discussed here is looking for the string 'node'. In the case of an electron app when it is package there is no node_module folder. So I also hit the same next error when the app is package; which is :

//Bugfix taken from @schmittberger
if (!exists(PATH)) {
  if (process.env.NODE_PATH) {
    PATH = process.env.NODE_PATH
  } else {
    throw new Error('No bin-PATH found');
  }
}

At this point I am receiving the Error('No bin-PATH found'). I don't have enough experience to know how to fix such an issue. Even if I add the path to my node bin in the environnemental variable of Linux I will hit the same error when the app is package for Windows as there are no folder "node_modules" in the packaged app.


问:
How to type Date types with Prisma and JSON blobs?
There seems to be an issue with prisma's serialization of JSON blobs wrt Date types.
I wonder if anyone else has seen this and has some guidance/workaround.
This is for a JSON field with Planetscale which is basically MySQL driver.

I have an object with a Date field, that I want to encode. This is a blob of data coming back from an external API

eg my object tp has a field defined typed a Date:

```<code>trained_at: Date;
</code>```

in my prisma schema for tunePrompt I have a JSON field:

```<code>model TunePrompt {
   apiData                 Json?   // from external API
</code>```

But when I try to write to that apiData JSON field:

```<code>      const data = {
        apiData: tp,
      }
      const newPrompt = await prisma.tunePrompt.create({ data })
</code>```
```<code>Property 'trained_at' is incompatible with index signature.
Type 'Date' is not assignable to type 'InputJsonValue | null | undefined'.",
</code>```

if I were to do JSON.stringify(tp) this works without error, but then I get double escaped JSON.

The generated types are something like:

```<code>  export type TunePromptCreateInput = {
    apiData?: NullableJsonNullValueInput | InputJsonValue
  }
</code>```

the only workaround i've found is to type the Date fields as a string, but I'm sure this is going to lead to other parsing problems later.

Maybe I can look into typing the JSON blob, but I don't think that would solve the issue as its the serialization I think that's the problem.

Body:
There seems to be an issue with prisma's serialization of JSON blobs wrt Date types.
I wonder if anyone else has seen this and has some guidance/workaround.
This is for a JSON field with Planetscale which is basically MySQL driver.

I have an object with a Date field, that I want to encode. This is a blob of data coming back from an external API

eg my object tp has a field defined typed a Date:

trained_at: Date;

in my prisma schema for tunePrompt I have a JSON field:

model TunePrompt {
   apiData                 Json?   // from external API

But when I try to write to that apiData JSON field:

      const data = {
        apiData: tp,
      }
      const newPrompt = await prisma.tunePrompt.create({ data })

Property 'trained_at' is incompatible with index signature.
Type 'Date' is not assignable to type 'InputJsonValue | null | undefined'.",

if I were to do JSON.stringify(tp) this works without error, but then I get double escaped JSON.

The generated types are something like:

  export type TunePromptCreateInput = {
    apiData?: NullableJsonNullValueInput | InputJsonValue
  }

the only workaround i've found is to type the Date fields as a string, but I'm sure this is going to lead to other parsing problems later.

Maybe I can look into typing the JSON blob, but I don't think that would solve the issue as its the serialization I think that's the problem.


问:
gnu ld: symbol remains undefined, even when it is defined
Trying to link a program which (for unknown reasons) generates a reference to "xmemdup".

I found the source code for xmemdup.c, and compiled it, and included the .o file in the link, but ld still claims it is undefined.

```<code>$ gcc -Wall -g -O2 -pipe -DBINDIR=\"/usr/bin\"   -c -o rsh.o rsh.c
</code>```

This worked, generating rsh.o

```<code>$ ll rsh.o ../publib-0.40/alloc/xmemdup.o
-rw-r--r-- 1 perryh perryh  2344 Dec 29 22:25 ../publib-0.40/alloc/xmemdup.o
-rw-r--r-- 1 perryh perryh 68656 Dec 30 00:47 rsh.o
</code>```

Proves that the .o files I am about to pass to the linker do exist.  BTW xmemdup.o is an object file, not a library, so it should get included unconditionally even if it were not needed to resolve a reference.

```<code>$ gcc -Wall -g -O2 -pipe -DBINDIR=\"/usr/bin\" -o rsh rsh.o ../publib-0.40/alloc/xmemdup.o
/usr/bin/ld: symbol lookup error: /usr/bin/ld: undefined symbol: xmemdup
collect2: error: ld returned 127 exit status
</code>```

and yet the linker can't see the definition of xmemdup in xmemdup.o

Body:
Trying to link a program which (for unknown reasons) generates a reference to "xmemdup".

I found the source code for xmemdup.c, and compiled it, and included the .o file in the link, but ld still claims it is undefined.

$ gcc -Wall -g -O2 -pipe -DBINDIR=\"/usr/bin\"   -c -o rsh.o rsh.c

This worked, generating rsh.o

$ ll rsh.o ../publib-0.40/alloc/xmemdup.o
-rw-r--r-- 1 perryh perryh  2344 Dec 29 22:25 ../publib-0.40/alloc/xmemdup.o
-rw-r--r-- 1 perryh perryh 68656 Dec 30 00:47 rsh.o

Proves that the .o files I am about to pass to the linker do exist.  BTW xmemdup.o is an object file, not a library, so it should get included unconditionally even if it were not needed to resolve a reference.

$ gcc -Wall -g -O2 -pipe -DBINDIR=\"/usr/bin\" -o rsh rsh.o ../publib-0.40/alloc/xmemdup.o
/usr/bin/ld: symbol lookup error: /usr/bin/ld: undefined symbol: xmemdup
collect2: error: ld returned 127 exit status

and yet the linker can't see the definition of xmemdup in xmemdup.o


问:
How to add appengine preview urls to Google OAuth Authorized domains
Is there a way to add appengine preview urls to authorized domain without specifying each preview url? Wildcards no longer work and I find it a chore to add every preview url dynamically generated for the app. Any ideas?


问:
Lefalet markes from MySQL database with PHP
I'm trying to add Lefalet Map that is JavaScript based to my HTML/PHP website.

Adding the MAP with HTML

```<code>echo "<div id='skijegern'></div>";
</code>```

Easy.

Runned by Javacript like this

```<code><script>
  var map = L.map('skijegern').setView([63.36601, 10.21204], 13);
  L.tileLayer('https://api.maptiler.com/maps/basic/256/{z}/{x}/{y}.png?key=dVhthbXQs3EHCi0XzzkL',{
    attribution:
    '<a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap contributors</a>'
  }).addTo(map);
  //var marker = L.marker([14.0940, 120.6890]).addTo(map);
  var city = L.markerClusterGroup();
  // var Points = $.getJSON("get_location.php", function(data) {
    var data = <?php echo json_encode($data); ?>;
    for (var i = 0; i < data.length; i++) {
      var new_location = new L.LatLng(data[i].lat, data[i].lon);
      var place = data[i].Details;
      var marker = new L.Marker(new_location, {
        title: place
      });
      var message = 'Demo: ' +place;
      marker.bindPopup(message);
      city.addLayer(marker);
    }

  map.addLayer(city);
</script>
</code>```

So far so good, but it does not add Markers.

My JSON encode looks like this:

```<code>$sqls=mysqli_query($dbSQLi,"SELECT * FROM poster");
$data=array();
while($roww= mysqli_fetch_array($sqls)){
    $data[] = array("lat"=>$roww["gps_lat"], "lon"=>$roww["gps_long"], "Details"=>$roww['nr']);
}
echo json_encode($data);
</code>```

It gives data like this:

```<code>[
    {"lat":"63.36601","lon":"10.21204","Details":"1"},
    {"lat":"63.38334","lon":"10.19244","Details":"2"},
    {"lat":"63.39169","lon":"10.21045","Details":"3"},
    {"lat":"63.40088","lon":"10.18628","Details":"4"}
</code>```

Can someone see what I'm doing wrong?

Body:
I'm trying to add Lefalet Map that is JavaScript based to my HTML/PHP website.

Adding the MAP with HTML

echo "

";

Easy.

Runned by Javacript like this

So far so good, but it does not add Markers.

My JSON encode looks like this:

$sqls=mysqli_query($dbSQLi,"SELECT * FROM poster");
$data=array();
while($roww= mysqli_fetch_array($sqls)){
    $data[] = array("lat"=>$roww["gps_lat"], "lon"=>$roww["gps_long"], "Details"=>$roww['nr']);
}
echo json_encode($data);

It gives data like this:

[
    {"lat":"63.36601","lon":"10.21204","Details":"1"},
    {"lat":"63.38334","lon":"10.19244","Details":"2"},
    {"lat":"63.39169","lon":"10.21045","Details":"3"},
    {"lat":"63.40088","lon":"10.18628","Details":"4"}

Can someone see what I'm doing wrong?