问:
gspread is not imported when running python3 script
Python: Python 3.4.3
OS: Ubuntu 14.04.6 LTS

Hello, I am getting the following error when I try to run my script under Ubuntu. Under Windows, the gspread module was imported without problems. Can you suggest what could be the problem?

Imported modules:

```<code>#!/usr/bin/python3
from simplejson import JSONDecodeError
import gspread
import os
</code>```

Error while running the script:

```<code>Traceback (most recent call last):
  File "./poverka_python.py", line 5, in <module>
    import gspread
  File "/usr/local/lib/python3.4/dist-packages/gspread/__init__.py", line 16, in <module>
    from .auth import (
  File "/usr/local/lib/python3.4/dist-packages/gspread/auth.py", line 16, in <module>
    from google_auth_oauthlib.flow import InstalledAppFlow
  File "/usr/local/lib/python3.4/dist-packages/google_auth_oauthlib/__init__.py", line 21, in <module>
    from .interactive import get_user_credentials
  File "/usr/local/lib/python3.4/dist-packages/google_auth_oauthlib/interactive.py", line 27, in <module>
    import google_auth_oauthlib.flow
  File "/usr/local/lib/python3.4/dist-packages/google_auth_oauthlib/flow.py", line 66, in <module>
    import google.auth.transport.requests
  File "/usr/local/lib/python3.4/dist-packages/google/auth/transport/requests.py", line 26, in <module>
    import requests
  File "/usr/local/lib/python3.4/dist-packages/requests/__init__.py", line 48, in <module>
    from charset_normalizer import __version__ as charset_normalizer_version
  File "/usr/local/lib/python3.4/dist-packages/charset_normalizer/__init__.py", line 24, in <module>
    from .api import from_bytes, from_fp, from_path, normalize
  File "/usr/local/lib/python3.4/dist-packages/charset_normalizer/api.py", line 71
    previous_logger_level: int = logger.level
</code>```

if you enter "pip3 install gspread"

```<code>Requirement already satisfied (use --upgrade to upgrade): gspread in /usr/local/lib/python3.4/dist-packages
Cleaning up...
</code>```

I have tried installing and reinstalling gspread. Also under Windows everything starts without problems.

Body:
Python: Python 3.4.3
OS: Ubuntu 14.04.6 LTS

Hello, I am getting the following error when I try to run my script under Ubuntu. Under Windows, the gspread module was imported without problems. Can you suggest what could be the problem?

Imported modules:

#!/usr/bin/python3
from simplejson import JSONDecodeError
import gspread
import os

Error while running the script:

Traceback (most recent call last):
  File "./poverka_python.py", line 5, in <module>
    import gspread
  File "/usr/local/lib/python3.4/dist-packages/gspread/__init__.py", line 16, in <module>
    from .auth import (
  File "/usr/local/lib/python3.4/dist-packages/gspread/auth.py", line 16, in <module>
    from google_auth_oauthlib.flow import InstalledAppFlow
  File "/usr/local/lib/python3.4/dist-packages/google_auth_oauthlib/__init__.py", line 21, in <module>
    from .interactive import get_user_credentials
  File "/usr/local/lib/python3.4/dist-packages/google_auth_oauthlib/interactive.py", line 27, in <module>
    import google_auth_oauthlib.flow
  File "/usr/local/lib/python3.4/dist-packages/google_auth_oauthlib/flow.py", line 66, in <module>
    import google.auth.transport.requests
  File "/usr/local/lib/python3.4/dist-packages/google/auth/transport/requests.py", line 26, in <module>
    import requests
  File "/usr/local/lib/python3.4/dist-packages/requests/__init__.py", line 48, in <module>
    from charset_normalizer import __version__ as charset_normalizer_version
  File "/usr/local/lib/python3.4/dist-packages/charset_normalizer/__init__.py", line 24, in <module>
    from .api import from_bytes, from_fp, from_path, normalize
  File "/usr/local/lib/python3.4/dist-packages/charset_normalizer/api.py", line 71
    previous_logger_level: int = logger.level

if you enter "pip3 install gspread"

Requirement already satisfied (use --upgrade to upgrade): gspread in /usr/local/lib/python3.4/dist-packages
Cleaning up...

I have tried installing and reinstalling gspread. Also under Windows everything starts without problems.


来源: stackexchange

问:
I want to set the Custom_ID in the format of 'ITM-00001', but currently, I am getting a Custom_ID of 'ITM-00None'
In Model.py

```<code>class Item(models.Model):
    item_id = models.AutoField(primary_key=True)
    item_description = models.CharField(max_length=500)
    quantity = models.IntegerField(default=0)
    avg_rate = models.IntegerField(default=0)
    category_id = models.ForeignKey(category, on_delete=models.CASCADE)
    last_purchase_rate = models.IntegerField(default=0)
    added_date = models.DateTimeField(auto_now=True)
    custom_id = models.CharField(max_length=11, unique=True, blank=True)

    def save(self, *args, **kwargs):
        self.custom_id = f"ITM-{str(self.item_id).zfill(5)}"
        super().save(*args, **kwargs)
</code>```

In Serializer.py

```<code>class ItemSerializer(serializers.ModelSerializer):
class Meta:
    model = Item
    fields = '__all__'

def create(self, validated_data):
    item = Item.objects.create(**validated_data)
    item.custom_id = f"ITM-{str(item.item_id).zfill(5)}"
    item.save()
    return item
</code>```

In view.py

```<code>@api_view(['GET', 'POST'])
def ItemsViewSet(request, format=None):
    # GET.
    if request.method == 'GET':
        itemsdata = Item.objects.all()
        serializer = ItemsSerializer(itemsdata, many=True)
        return Response(serializer.data)
    # POST.
    if request.method == 'POST':
        serializer = ItemsSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

SELECTED ITEM GET, PUT(UPDATE) & DELETE.

@api_view(['GET', 'PUT', 'DELETE'])
def items_detail(request, id):
    # ID PICK POINT.
    try:
        itms = Item.objects.get(pk=id)
    except itms.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    GET.
    if request.method == 'GET':
        serializer = ItemsSerializer(itms)
        return Response(serializer.data)
    # PUT.
    elif request.method == 'PUT':
        serializer = ItemsSerializer(itms, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    # DELETE.
   ` elif request.method == 'DELETE':
        itms.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
</code>```

I want to set the Custom_ID in the format of 'ITM-00001', but currently, I am getting a Custom_ID of 'ITM-00None'. Additionally, this code also performs CRUD operations. I need the category_name to be displayed on the frontend instead of the category_ID.
NOTE: Using Python and Django rest framework current version. Database: MySQL

ContentLicense: CC BY-SA 4.0

Body:
In Model.py

class Item(models.Model):
    item_id = models.AutoField(primary_key=True)
    item_description = models.CharField(max_length=500)
    quantity = models.IntegerField(default=0)
    avg_rate = models.IntegerField(default=0)
    category_id = models.ForeignKey(category, on_delete=models.CASCADE)
    last_purchase_rate = models.IntegerField(default=0)
    added_date = models.DateTimeField(auto_now=True)
    custom_id = models.CharField(max_length=11, unique=True, blank=True)

    def save(self, *args, **kwargs):
        self.custom_id = f"ITM-{str(self.item_id).zfill(5)}"
        super().save(*args, **kwargs)

In Serializer.py

class ItemSerializer(serializers.ModelSerializer):
class Meta:
    model = Item
    fields = '__all__'

def create(self, validated_data):
    item = Item.objects.create(**validated_data)
    item.custom_id = f"ITM-{str(item.item_id).zfill(5)}"
    item.save()
    return item

In view.py

@api_view(['GET', 'POST'])
def ItemsViewSet(request, format=None):
    # GET.
    if request.method == 'GET':
        itemsdata = Item.objects.all()
        serializer = ItemsSerializer(itemsdata, many=True)
        return Response(serializer.data)
    # POST.
    if request.method == 'POST':
        serializer = ItemsSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

SELECTED ITEM GET, PUT(UPDATE) & DELETE.

@api_view(['GET', 'PUT', 'DELETE'])
def items_detail(request, id):
    # ID PICK POINT.
    try:
        itms = Item.objects.get(pk=id)
    except itms.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    GET.
    if request.method == 'GET':
        serializer = ItemsSerializer(itms)
        return Response(serializer.data)
    # PUT.
    elif request.method == 'PUT':
        serializer = ItemsSerializer(itms, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    # DELETE.
   ` elif request.method == 'DELETE':
        itms.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

I want to set the Custom_ID in the format of 'ITM-00001', but currently, I am getting a Custom_ID of 'ITM-00None'. Additionally, this code also performs CRUD operations. I need the category_name to be displayed on the frontend instead of the category_ID.
NOTE: Using Python and Django rest framework current version. Database: MySQL


问:
Unexpected database locking in symfony
I have a recurring database lock that I'm trying to understand.

I have a cron that is adding jobs to a queue. These jobs are then processed by various workers on different instances of production. All of them are importing data from a resource, and then adding/updating a table. Theoretically, there would never be two jobs writing to the same row, as the data is partitioned in such a way that this won't happen (jobs are created per provider, which means the id used in this table is unique).

This is what msyql is logging for the lock:

```<code>2023-01-12T10:49:41.876818Z 610974 [Note] InnoDB:
*** (1) TRANSACTION:
TRANSACTION 41621347924, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 3 lock struct(s), heap size 1136, 2 row lock(s), undo log entries 1
MySQL thread id 610972, OS thread handle 22890357896960, query id 17518666 {instance} {app} updating
UPDATE offer SET timestamp = '2023-01-12 10:49:41' WHERE id = 17479128

2023-01-12T10:49:41.876850Z 610974 [Note] InnoDB: *** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 3037 page no 11514 n bits 96 index PRIMARY of table `{app}_production`.`offer` trx id 41621347924 lock_mode X locks rec but not gap waiting
Record lock, heap no 16 PHYSICAL RECORD: n_fields 10; compact format; info bits 0
 0: len 4; hex 810ab5d8; asc     ;;
 1: len 6; hex 0009b0d35e55; asc     ^U;;
 2: len 7; hex 230002401d04c1; asc #  @   ;;
 3: len 4; hex 8000e54d; asc    M;;
 4: len 17; hex 3330313032393431313035333030323630; asc 30102941105300260;;
 5: len 3; hex 8fce3c; asc   <;;
 6: len 3; hex 8fce41; asc   A;;
 7: len 30; hex 3c7265736f75726365207265736f7572636569643d223330313032393431; asc <resource resourceid="30102941; (total 326 bytes);
 8: len 1; hex 81; asc  ;;
 9: len 5; hex 99af18ac69; asc     i;;

2023-01-12T10:49:41.877237Z 610974 [Note] InnoDB: *** (2) TRANSACTION:
TRANSACTION 41621347925, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
3 lock struct(s), heap size 1136, 2 row lock(s), undo log entries 1
MySQL thread id 610974, OS thread handle 22894496118528, query id 17518667 {instance} {app} updating
UPDATE offer SET timestamp = '2023-01-12 10:49:41' WHERE id = 17821328

2023-01-12T10:49:41.877262Z 610974 [Note] InnoDB: *** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 3037 page no 11514 n bits 96 index PRIMARY of table `{app}_production`.`offer` trx id 41621347925 lock_mode X locks rec but not gap
Record lock, heap no 16 PHYSICAL RECORD: n_fields 10; compact format; info bits 0
 0: len 4; hex 810ab5d8; asc     ;;
 1: len 6; hex 0009b0d35e55; asc     ^U;;
 2: len 7; hex 230002401d04c1; asc #  @   ;;
 3: len 4; hex 8000e54d; asc    M;;
 4: len 17; hex 3330313032393431313035333030323630; asc 30102941105300260;;
 5: len 3; hex 8fce3c; asc   <;;
 6: len 3; hex 8fce41; asc   A;;
 7: len 30; hex 3c7265736f75726365207265736f7572636569643d223330313032393431; asc <resource resourceid="30102941; (total 326 bytes);
 8: len 1; hex 81; asc  ;;
 9: len 5; hex 99af18ac69; asc     i;;

2023-01-12T10:49:41.877643Z 610974 [Note] InnoDB: *** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 3037 page no 10300 n bits 104 index PRIMARY of table `{app}_production`.`offer` trx id 41621347925 lock_mode X locks rec but not gap waiting
Record lock, heap no 4 PHYSICAL RECORD: n_fields 10; compact format; info bits 0
 0: len 4; hex 810fee90; asc     ;;
 1: len 6; hex 0009b0d35e54; asc     ^T;;
 2: len 7; hex 22000240070d5b; asc "  @  [;;
 3: len 4; hex 8000e54d; asc    M;;
 4: len 17; hex 3330313032393431313035333030323630; asc 30102941105300260;;
 5: len 3; hex 8fce38; asc   8;;
 6: len 3; hex 8fce3c; asc   <;;
 7: len 30; hex 3c7265736f75726365207265736f7572636569643d223330313032393431; asc <resource resourceid="30102941; (total 326 bytes);
 8: len 1; hex 81; asc  ;;
 9: len 5; hex 99af18ac69; asc     i;;

2023-01-12T10:49:41.878014Z 610974 [Note] InnoDB: *** WE ROLL BACK TRANSACTION (2)
</code>```

I have always sucked at sorting out deadlocking issues so looking for a bit of guidance.

Is this a table or a row lock? I'm using symfony 2.8 (don't ask) and it's doctrine packages.

Is there some way to disable the locking completely?

What can I read to better understand these logs?

Title: Unexpected database locking in symfony

Body:
I have a recurring database lock that I'm trying to understand.

I have a cron that is adding jobs to a queue. These jobs are then processed by various workers on different instances of production. All of them are importing data from a resource, and then adding/updating a table. Theoretically, there would never be two jobs writing to the same row, as the data is partitioned in such a way that this won't happen (jobs are created per provider, which means the id used in this table is unique).

This is what msyql is logging for the lock:

2023-01-12T10:49:41.876818Z 610974 [Note] InnoDB:
*** (1) TRANSACTION:
TRANSACTION 41621347924, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 3 lock struct(s), heap size 1136, 2 row lock(s), undo log entries 1
MySQL thread id 610972, OS thread handle 22890357896960, query id 17518666 {instance} {app} updating
UPDATE offer SET timestamp = '2023-01-12 10:49:41' WHERE id = 17479128

2023-01-12T10:49:41.876850Z 610974 [Note] InnoDB: *** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 3037 page no 11514 n bits 96 index PRIMARY of table `{app}_production`.`offer` trx id 41621347924 lock_mode X locks rec but not gap waiting
Record lock, heap no 16 PHYSICAL RECORD: n_fields 10; compact format; info bits 0
 0: len 4; hex 810ab5d8; asc     ;;
 1: len 6; hex 0009b0d35e55; asc     ^U;;
 2: len 7; hex 230002401d04c1; asc #  @   ;;
 3: len 4; hex 8000e54d; asc    M;;
 4: len 17; hex 3330313032393431313035333030323630; asc 30102941105300260;;
 5: len 3; hex 8fce3c; asc   <;;
 6: len 3; hex 8fce41; asc   A;;
 7: len 30; hex 3c7265736f75726365207265736f7572636569643d223330313032393431; asc <resource resourceid="30102941; (total 326 bytes);
 8: len 1; hex 81; asc  ;;
 9: len 5; hex 99af18ac69; asc     i;;

2023-01-12T10:49:41.877237Z 610974 [Note] InnoDB: *** (2) TRANSACTION:
TRANSACTION 41621347925, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
3 lock struct(s), heap size 1136, 2 row lock(s), undo log entries 1
MySQL thread id 610974, OS thread handle 22894496118528, query id 17518667 {instance} {app} updating
UPDATE offer SET timestamp = '2023-01-12 10:49:41' WHERE id = 17821328

2023-01-12T10:49:41.877262Z 610974 [Note] InnoDB: *** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 3037 page no 11514 n bits 96 index PRIMARY of table `{app}_production`.`offer` trx id 41621347925 lock_mode X locks rec but not gap
Record lock, heap no 16 PHYSICAL RECORD: n_fields 10; compact format; info bits 0
 0: len 4; hex 810ab5d8; asc     ;;
 1: len 6; hex 0009b0d35e55; asc     ^U;;
 2: len 7; hex 230002401d04c1; asc #  @   ;;
 3: len 4; hex 8000e54d; asc    M;;
 4: len 17; hex 3330313032393431313035333030323630; asc 30102941105300260;;
 5: len 3; hex 8fce3c; asc   <;;
 6: len 3; hex 8fce41; asc   A;;
 7: len 30; hex 3c7265736f75726365207265736f7572636569643d223330313032393431; asc <resource resourceid="30102941; (total 326 bytes);
 8: len 1; hex 81; asc  ;;
 9: len 5; hex 99af18ac69; asc     i;;

2023-01-12T10:49:41.877643Z 610974 [Note] InnoDB: *** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 3037 page no 10300 n bits 104 index PRIMARY of table `{app}_production`.`offer` trx id 41621347925 lock_mode X locks rec but not gap waiting
Record lock, heap no 4 PHYSICAL RECORD: n_fields 10; compact format; info bits 0
 0: len 4; hex 810fee90; asc     ;;
 1: len 6; hex 0009b0d35e54; asc     ^T;;
 2: len 7; hex 22000240070d5b; asc "  @  [;;
 3: len 4; hex 8000e54d; asc    M;;
 4: len 17; hex 3330313032393431313035333030323630; asc 30102941105300260;;
 5: len 3; hex 8fce38; asc   8;;
 6: len 3; hex 8fce3c; asc   <;;
 7: len 30; hex 3c7265736f75726365207265736f7572636569643d223330313032393431; asc <resource resourceid="30102941; (total 326 bytes);
 8: len 1; hex 81; asc  ;;
 9: len 5; hex 99af18ac69; asc     i;;

2023-01-12T10:49:41.878014Z 610974 [Note] InnoDB: *** WE ROLL BACK TRANSACTION (2)

I have always sucked at sorting out deadlocking issues so looking for a bit of guidance.

Is this a table or a row lock? I'm using symfony 2.8 (don't ask) and it's doctrine packages.

Is there some way to disable the locking completely?

What can I read to better understand these logs?


问:
Baggage field not getting added in same span in spring-cloud-sleuth with open-telemetry collector
I have integrated open-telemetry collector with spring-cloud-sleuth.
I have created a spring aspect where I am trying to add a custom baggage field serviceName to the current trace using following line of code (Reference)

```<code>tracer.createBaggage( "serviceName", "spring-cloud-sleuth-otel-slf4j" );
</code>```

This works but the baggage is added from the next span onwards. I found the following solution (here) which is supposed to solve this but it works with brave only

```<code> @Bean
 ScopeDecorator mdcScopeDecorator() {
 return MDCScopeDecorator.newBuilder().clear().add( SingleCorrelationField.newBuilder( countryCodeField() ).flushOnUpdate().build() ).build();
 }
</code>```

However, I could not find anything similar when not using brave. Can somebody suggest how it can be achieved?

Body:
I have integrated open-telemetry collector with spring-cloud-sleuth.
I have created a spring aspect where I am trying to add a custom baggage field serviceName to the current trace using following line of code (Reference)

tracer.createBaggage( "serviceName", "spring-cloud-sleuth-otel-slf4j" );

This works but the baggage is added from the next span onwards. I found the following solution (here) which is supposed to solve this but it works with brave only

 @Bean
 ScopeDecorator mdcScopeDecorator() {
 return MDCScopeDecorator.newBuilder().clear().add( SingleCorrelationField.newBuilder( countryCodeField() ).flushOnUpdate().build() ).build();
 }

However, I could not find anything similar when not using brave. Can somebody suggest how it can be achieved?


问:
Flutter SSO (Single Sign On) through SAML
I want to add authentication through SAML in flutter app.But I didn't find any helpful doc or package for integration with flutter.

So any suggestion will be of great help.


问:
Legato-AF platform [ Unable to sync leaf profile ]
```<code>OS=Linux Mint 20.1
Sierra Wireless Lef version=2.4.0
</code>```

I’m setting up a leaf workspace and I'm unable to sync my additional profile completely.

```<code> leaf profile sync
</code>```

command has no error output, but I can’t find wp77stable files at all. All files for the wp76stable profile are there according to the manual.

Is there a way to do a force update or similar action?

Body:
OS=Linux Mint 20.1
Sierra Wireless Lef version=2.4.0

I’m setting up a leaf workspace and I'm unable to sync my additional profile completely.

 leaf profile sync

command has no error output, but I can’t find wp77stable files at all. All files for the wp76stable profile are there according to the manual.

Is there a way to do a force update or similar action?


问:
Why I'm not able to pass a string to a custom layer?
I'm building a NER model with a custom pre-processing layer. This layer converts the input string into a sequence of ints (each int mapped to a word of the vocabulary), so that I could then deploy the model on a server and call the predict method through APIs.

However I'm having some problems when running model.predict:

by running predict right after compile, it works only if run_eagerly=True was passed  to the compile.

if the model is exported (model.save) and then loaded, the predict method raises an error even if run_eagerly=True was used in the compilation of the model.

Full code below; colab notebook here.

Sample data

```<code>import pandas as pd
import numpy as np
import io, os, traceback

data = '''Sentence #,Word,Tag
Sentence: 0,It,O
Sentence: 0,was,O
Sentence: 0,23/10/1991,B-dat
Sentence: 0,when,O
Sentence: 0,the,O
Sentence: 0,life,O
Sentence: 0,of,O
Sentence: 0,James,B-nam
Sentence: 0,Parker,I-nam
Sentence: 0,suddenly,O
Sentence: 0,changed,O
Sentence: 1,George,B-nam
Sentence: 1,is,O
Sentence: 1,going,O
Sentence: 1,to,O
Sentence: 1,buy,O
Sentence: 1,a,O
Sentence: 1,gift,O
Sentence: 1,for,O
Sentence: 1,his,O
Sentence: 1,dad,O
Sentence: 1,Jim,B-nam
Sentence: 1,since,O
Sentence: 1,on,O
Sentence: 1,11/11/2021,B-dat
Sentence: 1,its,O
Sentence: 1,his,O
Sentence: 1,birthday,O
Sentence: 2,There,O
Sentence: 2,is,O
Sentence: 2,no,O
Sentence: 2,evidence,O
Sentence: 2,that,O
Sentence: 2,Alice,B-nam
Sentence: 2,Jackson,I-nam
Sentence: 2,was,O
Sentence: 2,at,O
Sentence: 2,home,O
Sentence: 2,the,O
Sentence: 2,night,O
Sentence: 2,of,O
Sentence: 2,10/10/2010,B-dat'''

data = pd.read_csv(io.StringIO(data), sep=',')
</code>```

Create vocabulary

```<code>padding_value = ""
vocab_token = list(set(data['Word'])) + [padding_value]
idx2token = {idx:tok for idx, tok in enumerate(vocab_token)}
token2idx = {tok:idx for idx, tok in enumerate(vocab_token)}

vocab_tag = list(set(data['Tag']))
idx2tag = {idx:tok for idx, tok in enumerate(vocab_tag)}
tag2idx = {tok:idx for idx, tok in enumerate(vocab_tag)}

data['Word_idx'] = data['Word'].map(token2idx)
data['Tag_idx']  = data['Tag'].map(tag2idx)

n_words = len(vocab_token)
n_tags  = len(vocab_tag)
n_sentences = len(data['Sentence #'].unique())
max_len = max(data['Sentence #'].value_counts())
</code>```

Padding

```<code>from sklearn.model_selection import train_test_split
from keras_preprocessing.sequence import pad_sequences
import tensorflow as tf

data_group = data.groupby(['Sentence #'], as_index=False)[['Word', 'Tag', 'Word_idx', 'Tag_idx']].agg(lambda x: list(x))

tokens = data_group['Word_idx'].tolist()
pad_tokens = pad_sequences(tokens, maxlen=max_len, dtype='int32', padding='post', value=token2idx[padding_value])

tags = data_group['Tag_idx'].tolist()
pad_tags = pad_sequences(tags, maxlen=max_len, dtype='int32', padding='post', value=tag2idx["O"])
pad_tags = [tf.keras.utils.to_categorical(i, num_classes=n_tags) for i in pad_tags]
</code>```

Model definition and fit

```<code>import tensorflow as tf
from tensorflow.keras import Sequential, Input
from tensorflow.keras.layers import LSTM, Embedding, Dense, TimeDistributed, Bidirectional

output_dim = 32

model = Sequential()
model.add(Embedding(input_dim=n_words + 1, output_dim=output_dim, input_length=max_len))
model.add(Bidirectional(LSTM(units=output_dim, return_sequences=True, dropout=0.2, recurrent_dropout=0.2), merge_mode = 'concat'))
model.add(TimeDistributed(Dense(n_tags, activation="softmax")))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(pad_tokens, np.array(pad_tags), batch_size=16, epochs=1)
</code>```

Pre-processing layer

```<code>@tf.keras.utils.register_keras_serializable(name='pre_processing_layer')
class InputProcessingLayer(tf.keras.layers.Layer):
    def __init__(self, vocab, **kwargs):
        super(InputProcessingLayer, self).__init__(**kwargs)
        self.vocab = vocab

    def call(self, input_str, training=False):
        # a print useful for debugging
        print('-->', input_str, type(input_str))
        # from tf.Tensor([b'...']) to tf.Tensor(b'...')
        input_str = input_str[0]
        try:
            # lowers the input string, splits it on whitespaces and map each
            tokens = self.vocab(tf.strings.split(tf.strings.lower(input_str)))
            left = 0
            right = max(0, max_len - len(tokens))
            paddings = tf.constant([[left, right]])
            # pad the list so that its length will be equal to max_len
            padded_list = tf.pad(tokens, paddings, mode="CONSTANT", constant_values=token2idx[padding_value])
            input_words = tf.reshape(padded_list, [1,max_len])
        except:
            print('\n- - - - ERROR MSG - - - -\n')
            traceback.print_exc()
            print('\n- - - - END MSG - - - -\n')
            padded_list = [0]*max_len
            # a dummy list but necessary because the output's shape of InputProcessingLayer must be compatible with the embedding layer's shape of the model
            input_words = np.array(padded_list, dtype='int32').reshape(1,max_len)
        return input_words

    def get_config(self):
        config = super().get_config()
        config['vocab'] = self.vocab
        return config
</code>```

Add the custom layer to the model

```<code>vocab = tf.keras.layers.StringLookup(vocabulary=[x for x in token2idx.keys()])

temp_model = Sequential([
    Input(shape=(max_len,), dtype=tf.string, name='description'),
    InputProcessingLayer(vocab),
    model
])
temp_model.compile('adam', loss=None, run_eagerly=False)
</code>```

Test the final model

```<code>sample_input = "James birthday is on 11/11/2021"
pred = temp_model.predict([sample_input])
print(pred)
</code>```

With run_eagerly=False I get (notice that 17 is the max_len)

```<code>WARNING:tensorflow:Model was constructed with shape (None, 17) for input KerasTensor(type_spec=TensorSpec(shape=(None, 17), dtype=tf.string, name='description'), name='description', description="created by layer 'description'"), but it was called on an input with incompatible shape (None,).
--> Tensor("IteratorGetNext:0", shape=(None,), dtype=string) <class 'tensorflow.python.framework.ops.Tensor'>
</code>```

Notice that what follows the --> is a print from inside the InputProcessingLayer, and in this case it says that the string received by the layer is "IteratorGetNext:0" instead of "James birthday is on 11/11/2021".

By using run_eagerly=True then string received by the layer is correct

```<code>--> tf.Tensor([b'James birthday is on 11/11/2021'], shape=(1,), dtype=string) <class 'tensorflow.python.framework.ops.EagerTensor'>
</code>```

However, if I save the model, i.e. temp_model.save(EXPORT_PATH, overwrite=True), and then load it for a prediction

```<code>import tensorflow as tf

loaded_model = tf.keras.models.load_model(EXPORT_PATH)

sample_input = "James birthday is on 11/11/2021"
pred = loaded_model.predict([sample_input])
print(pred)
</code>```

then it raises this error

```<code>padding_value = ""
vocab_token = list(set(data['Word'])) + [padding_value]
idx2token = {idx:tok for idx, tok in enumerate(vocab_token)}
token2idx = {tok:idx for idx, tok in enumerate(vocab_token)}

vocab_tag = list(set(data['Tag']))
idx2tag = {idx:tok for idx, tok in enumerate(vocab_tag)}
tag2idx = {tok:idx for idx, tok in enumerate(vocab_tag)}

data['Word_idx'] = data['Word'].map(token2idx)
data['Tag_idx']  = data['Tag'].map(tag2idx)

n_words = len(vocab_token)
n_tags  = len(vocab_tag)
n_sentences = len(data['Sentence #'].unique())
max_len = max(data['Sentence #'].value_counts())
</code>```0

From the error we see that the string received by the layer is "input_str:0", instead of the one passed to the predict method. What's going on here?

p.s. I know the problem can be solved using the TextVectorization layer, but I would like to understand why this custom layer doesn't work

Body:
I'm building a NER model with a custom pre-processing layer. This layer converts the input string into a sequence of ints (each int mapped to a word of the vocabulary), so that I could then deploy the model on a server and call the predict method through APIs.

However I'm having some problems when running model.predict:

by running predict right after compile, it works only if run_eagerly=True was passed  to the compile.

if the model is exported (model.save) and then loaded, the predict method raises an error even if run_eagerly=True was used in the compilation of the model.

Full code below; colab notebook here.

Sample data

import pandas as pd
import numpy as np
import io, os, traceback

data = '''Sentence #,Word,Tag
Sentence: 0,It,O
Sentence: 0,was,O
Sentence: 0,23/10/1991,B-dat
Sentence: 0,when,O
Sentence: 0,the,O
Sentence: 0,life,O
Sentence: 0,of,O
Sentence: 0,James,B-nam
Sentence: 0,Parker,I-nam
Sentence: 0,suddenly,O
Sentence: 0,changed,O
Sentence: 1,George,B-nam
Sentence: 1,is,O
Sentence: 1,going,O
Sentence: 1,to,O
Sentence: 1,buy,O
Sentence: 1,a,O
Sentence: 1,gift,O
Sentence: 1,for,O
Sentence: 1,his,O
Sentence: 1,dad,O
Sentence: 1,Jim,B-nam
Sentence: 1,since,O
Sentence: 1,on,O
Sentence: 1,11/11/2021,B-dat
Sentence: 1,its,O
Sentence: 1,his,O
Sentence: 1,birthday,O
Sentence: 2,There,O
Sentence: 2,is,O
Sentence: 2,no,O
Sentence: 2,evidence,O
Sentence: 2,that,O
Sentence: 2,Alice,B-nam
Sentence: 2,Jackson,I-nam
Sentence: 2,was,O
Sentence: 2,at,O
Sentence: 2,home,O
Sentence: 2,the,O
Sentence: 2,night,O
Sentence: 2,of,O
Sentence: 2,10/10/2010,B-dat'''

data = pd.read_csv(io.StringIO(data), sep=',')

Create vocabulary

padding_value = ""
vocab_token = list(set(data['Word'])) + [padding_value]
idx2token = {idx:tok for idx, tok in enumerate(vocab_token)}
token2idx = {tok:idx for idx, tok in enumerate(vocab_token)}

vocab_tag = list(set(data['Tag']))
idx2tag = {idx:tok for idx, tok in enumerate(vocab_tag)}
tag2idx = {tok:idx for idx, tok in enumerate(vocab_tag)}

data['Word_idx'] = data['Word'].map(token2idx)
data['Tag_idx']  = data['Tag'].map(tag2idx)

n_words = len(vocab_token)
n_tags  = len(vocab_tag)
n_sentences = len(data['Sentence #'].unique())
max_len = max(data['Sentence #'].value_counts())

Padding

from sklearn.model_selection import train_test_split
from keras_preprocessing.sequence import pad_sequences
import tensorflow as tf

data_group = data.groupby(['Sentence #'], as_index=False)[['Word', 'Tag', 'Word_idx', 'Tag_idx']].agg(lambda x: list(x))

tokens = data_group['Word_idx'].tolist()
pad_tokens = pad_sequences(tokens, maxlen=max_len, dtype='int32', padding='post', value=token2idx[padding_value])

tags = data_group['Tag_idx'].tolist()
pad_tags = pad_sequences(tags, maxlen=max_len, dtype='int32', padding='post', value=tag2idx["O"])
pad_tags = [tf.keras.utils.to_categorical(i, num_classes=n_tags) for i in pad_tags]

Model definition and fit

import tensorflow as tf
from tensorflow.keras import Sequential, Input
from tensorflow.keras.layers import LSTM, Embedding, Dense, TimeDistributed, Bidirectional

output_dim = 32

model = Sequential()
model.add(Embedding(input_dim=n_words + 1, output_dim=output_dim, input_length=max_len))
model.add(Bidirectional(LSTM(units=output_dim, return_sequences=True, dropout=0.2, recurrent_dropout=0.2), merge_mode = 'concat'))
model.add(TimeDistributed(Dense(n_tags, activation="softmax")))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(pad_tokens, np.array(pad_tags), batch_size=16, epochs=1)

Pre-processing layer

@tf.keras.utils.register_keras_serializable(name='pre_processing_layer')
class InputProcessingLayer(tf.keras.layers.Layer):
    def __init__(self, vocab, **kwargs):
        super(InputProcessingLayer, self).__init__(**kwargs)
        self.vocab = vocab

    def call(self, input_str, training=False):
        # a print useful for debugging
        print('-->', input_str, type(input_str))
        # from tf.Tensor([b'...']) to tf.Tensor(b'...')
        input_str = input_str[0]
        try:
            # lowers the input string, splits it on whitespaces and map each
            tokens = self.vocab(tf.strings.split(tf.strings.lower(input_str)))
            left = 0
            right = max(0, max_len - len(tokens))
            paddings = tf.constant([[left, right]])
            # pad the list so that its length will be equal to max_len
            padded_list = tf.pad(tokens, paddings, mode="CONSTANT", constant_values=token2idx[padding_value])
            input_words = tf.reshape(padded_list, [1,max_len])
        except:
            print('\n- - - - ERROR MSG - - - -\n')
            traceback.print_exc()
            print('\n- - - - END MSG - - - -\n')
            padded_list = [0]*max_len
            # a dummy list but necessary because the output's shape of InputProcessingLayer must be compatible with the embedding layer's shape of the model
            input_words = np.array(padded_list, dtype='int32').reshape(1,max_len)
        return input_words

    def get_config(self):
        config = super().get_config()
        config['vocab'] = self.vocab
        return config

Add the custom layer to the model

vocab = tf.keras.layers.StringLookup(vocabulary=[x for x in token2idx.keys()])

temp_model = Sequential([
    Input(shape=(max_len,), dtype=tf.string, name='description'),
    InputProcessingLayer(vocab),
    model
])
temp_model.compile('adam', loss=None, run_eagerly=False)

Test the final model

sample_input = "James birthday is on 11/11/2021"
pred = temp_model.predict([sample_input])
print(pred)

With run_eagerly=False I get (notice that 17 is the max_len)

WARNING:tensorflow:Model was constructed with shape (None, 17) for input KerasTensor(type_spec=TensorSpec(shape=(None, 17), dtype=tf.string, name='description'), name='description', description="created by layer 'description'"), but it was called on an input with incompatible shape (None,).
--> Tensor("IteratorGetNext:0", shape=(None,), dtype=string) <class 'tensorflow.python.framework.ops.Tensor'>

Notice that what follows the --> is a print from inside the InputProcessingLayer, and in this case it says that the string received by the layer is "IteratorGetNext:0" instead of "James birthday is on 11/11/2021".

By using run_eagerly=True then string received by the layer is correct

--> tf.Tensor([b'James birthday is on 11/11/2021'], shape=(1,), dtype=string) <class 'tensorflow.python.framework.ops.EagerTensor'>

However, if I save the model, i.e. temp_model.save(EXPORT_PATH, overwrite=True), and then load it for a prediction

import tensorflow as tf

loaded_model = tf.keras.models.load_model(EXPORT_PATH)

sample_input = "James birthday is on 11/11/2021"
pred = loaded_model.predict([sample_input])
print(pred)

then it raises this error

WARNING:tensorflow:Model was constructed with shape (None, 17) for input KerasTensor(type_spec=TensorSpec(shape=(None, 17), dtype=tf.string, name='description'), name='description', description="created by layer 'description'"), but it was called on an input with incompatible shape (None,).
Traceback (most recent call last):
  File "C:\Users\gtu\Desktop\test_signature_inp.py", line 12, in <module>
    pred = loaded_model.predict([sample_input])
  File "C:\Users\gtu\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\gtu\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\framework\func_graph.py", line 1147, in autograph_handler
    raise e.ag_error_metadata.to_exception(e)
ValueError: in user code:

    File "C:\Users\gtu\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\engine\training.py", line 1801, in predict_function  *
        return step_function(self, iterator)
    File "C:\Users\gtu\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\engine\training.py", line 1790, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\gtu\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\engine\training.py", line 1783, in run_step  **
        outputs = model.predict_step(data)
    File "C:\Users\gtu\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\engine\training.py", line 1751, in predict_step
        return self(x, training=False)
    File "C:\Users\gtu\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None

    ValueError: Exception encountered when calling layer "input_processing_layer" (type Custom>pre_processing_layer).

    Could not find matching concrete function to call loaded from the SavedModel. Got:
      Positional arguments (2 total):
        * Tensor("input_str:0", shape=(None,), dtype=string)
        * False
      Keyword arguments: {}

     Expected these arguments to match one of the following 2 option(s):

    Option 1:
      Positional arguments (2 total):
        * TensorSpec(shape=(None, 17), dtype=tf.string, name='input_str')
        * False
      Keyword arguments: {}

    Option 2:
      Positional arguments (2 total):
        * TensorSpec(shape=(None, 17), dtype=tf.string, name='input_str')
        * True
      Keyword arguments: {}

    Call arguments received:
      • args=('tf.Tensor(shape=(None,), dtype=string)',)
      • kwargs={'training': 'False'}

From the error we see that the string received by the layer is "input_str:0", instead of the one passed to the predict method. What's going on here?

p.s. I know the problem can be solved using the TextVectorization layer, but I would like to understand why this custom layer doesn't work


问:
RDS blue green switch failing with replication status
I have a database cluster A in AWS RDS mysql aurora.

I create a blue green deployment that generates a database A-green. I choose "Switch" in the AWS UI. The switch fails and it shows in the logs:

Switchover from DB cluster A to A-green was canceled due to external replication on A. Stop replication from an external database to A before you switch over.

Where can I find this replication that the error talks about? I don't see anything in the console.

Also, show slave status returns empty

Cheers


问:
For some reason, join() and toString() not working on created array. Array created from JSON object
I have created an array like this. When I try to turn it into string so I can use it, the result in the console log is blank.

const measureList = Object.entries(objectMeasure)
var ingredList = []
for (i=0; i<20;i++) {
  ingredList.push(measureList[29+i][1])
  ingredList.push(measureList[9+i][1])
}
```
<p>This is what the array looks like in the console.</p>
<pre class="lang-js prettyprint-override"><code>0 :  "1 tbsp"
1 :  "Olive Oil"
2 :  "1 chopped"
3 :  "Onion"
4 :  "200g"
5 :  "Chicken Breast"
6 :  "pinch"
7 :  "Ginger"
8 :  "2 tblsp "
9 :  "Harissa Spice"
10 :  "10"
11 :  "Dried Apricots"
12 :  "220g"
13 :  "Chickpeas"
14 :  "200g"
15 :  "Couscous"
16 :  "200ml"
17 :  "Chicken Stock"
18 :  "Handful"
19 :  "Coriander"
20 :  ""
21 :  ""
22 :  ""
23 :  ""
24 :  ""
25 :  ""
26 :  ""
27 :  ""
28 :  ""
29 :  ""
30 :  ""
31 :  ""
32 :  ""
33 :  ""
34 :  ""
35 :  ""
36 :  ""
37 :  ""
38 :  ""
39 :  ""
</code>```

I want that as a string. This is the first time I have tried this so I am not sure what I am doing.

Line 92 in the image is the result of:

console.log(ingredList.join(" "))
```
```$.ajax({
  method: 'GET',
  url: buildApiUrl({
    query: 'lookup',
    value: 52850,
  }),
}).then(response => {
  console.log(response);

  const objectMeasure = response.meals[0];
  const measureList = Object.values(objectMeasure);

  const ingredList = [];

  for (let i = 1; i <= 3; i++) {
    let key = '.strMeasure' + i;
    // ingredList.push(objectMeasure[key]);
    // console.log(ingredList);
    console.log(measureList);
  }
  for (i = 0; i < 20; i++) {
    // console.log(measureList[29+i][1]);
    // console.log(measureList[9+i][1]);
    ingredList.push(measureList[29 + i]);
    ingredList.push(measureList[9 + i]);
    // console.log(ingredList);
  }

  console.log(ingredList.join(" "));
});

```

Body:
I have created an array like this. When I try to turn it into string so I can use it, the result in the console log is blank.

const measureList = Object.entries(objectMeasure)
var ingredList = []
for (i=0; i<20;i++) {
  ingredList.push(measureList[29+i][1])
  ingredList.push(measureList[9+i][1])
}

This is what the array looks like in the console.

0 :  "1 tbsp"
1 :  "Olive Oil"
2 :  "1 chopped"
3 :  "Onion"
4 :  "200g"
5 :  "Chicken Breast"
6 :  "pinch"
7 :  "Ginger"
8 :  "2 tblsp "
9 :  "Harissa Spice"
10 :  "10"
11 :  "Dried Apricots"
12 :  "220g"
13 :  "Chickpeas"
14 :  "200g"
15 :  "Couscous"
16 :  "200ml"
17 :  "Chicken Stock"
18 :  "Handful"
19 :  "Coriander"
20 :  ""
21 :  ""
22 :  ""
23 :  ""
24 :  ""
25 :  ""
26 :  ""
27 :  ""
28 :  ""
29 :  ""
30 :  ""
31 :  ""
32 :  ""
33 :  ""
34 :  ""
35 :  ""
36 :  ""
37 :  ""
38 :  ""
39 :  ""

I want that as a string. This is the first time I have tried this so I am not sure what I am doing.

Line 92 in the image is the result of:

console.log(ingredList.join(" "))

$.ajax({
  method: 'GET',
  url: buildApiUrl({
    query: 'lookup',
    value: 52850,
  }),
}).then(response => {
  console.log(response);

  const objectMeasure = response.meals[0];
  const measureList = Object.values(objectMeasure);

  const ingredList = [];

  for (let i = 1; i <= 3; i++) {
    let key = '.strMeasure' + i;
    // ingredList.push(objectMeasure[key]);
    // console.log(ingredList);
    console.log(measureList);
  }
  for (i = 0; i < 20; i++) {
    // console.log(measureList[29+i][1]);
    // console.log(measureList[9+i][1]);
    ingredList.push(measureList[29 + i]);
    ingredList.push(measureList[9 + i]);
    // console.log(ingredList);
  }

  console.log(ingredList.join(" "));
});


问:
How to run a laravel app using a php interpreter in a local folder
I want to make my Laravel app portable so that I can run it on other Windows machines. So, I want to include the PHP interpreter with the project so that I don't have to worry about the PHP version installed on the other machines.

I have the following folder structure:

```<code>.
|- server-runner.bat
|- php\
|- src\
</code>```

where src\ contains a Laravel project, and php\ is the php interpreter folder copied from C:\xampp\. I renamed the original C:\xampp\ folder for testing purposes (as if Xampp is not installed).

I want to write a batch script server-runner.bat to start the Laravel app server using the local php interpreter. This is the code I write:

```<code>@echo off
php\php.exe src\artisan serve
pause
</code>```

but I get many errors like this one

```<code>PHP Warning:  PHP Startup: Unable to load dynamic library 'bz2'
(tried: C:\xampp\php\ext\bz2 (The specified module could not be found),
 C:\xampp\php\ext\php_bz2.dll (The specified module could not be found))
in Unknown on line 0
</code>```

It still uses the C:\xampp\php path although it's not currently in this location.

How to solve this problem?

Body:
I want to make my Laravel app portable so that I can run it on other Windows machines. So, I want to include the PHP interpreter with the project so that I don't have to worry about the PHP version installed on the other machines.

I have the following folder structure:

.
|- server-runner.bat
|- php\
|- src\

where src\ contains a Laravel project, and php\ is the php interpreter folder copied from C:\xampp\. I renamed the original C:\xampp\ folder for testing purposes (as if Xampp is not installed).

I want to write a batch script server-runner.bat to start the Laravel app server using the local php interpreter. This is the code I write:

@echo off
php\php.exe src\artisan serve
pause

but I get many errors like this one

PHP Warning:  PHP Startup: Unable to load dynamic library 'bz2'
(tried: C:\xampp\php\ext\bz2 (The specified module could not be found),
 C:\xampp\php\ext\php_bz2.dll (The specified module could not be found))
in Unknown on line 0

It still uses the C:\xampp\php path although it's not currently in this location.

How to solve this problem?


问:
Want to create 2 column metrics in Pandas based on some condition

Snapshot of the referenced data given below:
reference data

I want to create two new columns from this data set.

I need to create a scatter plot to display how each firm performed in the year 2017 based on their average score (x-axis) per their market penetration (y-axis)  [# of unique respondents that rated the company / total unique respondents] based on the data (a portion of data is in snapshot)

New column ‘mtkp’. 'mktp' is the #unique respondents per company per year / total unique respondents in 2017

New column 'mean'. mean is the average score given to a company that year.

How do I do it? Any suggestion? I am using Pandas and python 3


问:
How to force a .NET tests project to use System.Net.Http.dll from bin folder instead of from the shared folder?
I have a .NET tests project that uses HttpClient from System.Net.Http.dll that is loaded from shared folder:
C:\Program Files\dotnet\shared\Microsoft.NETCore.App\System.Net.Http.dll (example for netcoreapp3.1 tests project target framework).

I need the tests project to use a modified version of System.Net.Http.dll from the bin folder instead of from the shared folder or instead of from the GAC.
Is it possible by configuring the tests project?

Another option could be to modify tests project dll via dnlib library. I loaded a list of references via dnlib but could not change reference for System.Net.Http.
Is there a way to force project dll to use System.Net.Http.dll from the bin folder by modifying project dll via dnlib library or by any other similar library?

Thanks for your time and your help.


问:
SMTP server for developers
Hi hope you're doing great! I'm looking a portable SMTP server (Windows), basically with RFC compliance for ETLs testing purposes. Right now I'm using Fake SMTP Server but it permits email addresses with invalid characters and oversized attachments so I need something close to real situations.

Please must be a portable app.

Best regards

Francisco

Search in Google for alternatives, not found.

Title: SMTP server for developers


问:
Capabilities and detecting capability conflicts with Maven
Gradle has a concept called capabilities. In a nutshell, libraries can declare the capabilities they provide (e.g. logging). Gradle will then detect when a project's dependencies contain conflicting dependencies and attempt to resolve them or fail the build.
One use case for this is to mediate between libraries whose coordinates changed (e.g. Java EE 8 vs. Jakarta EE 8). Gradle even offers a plugin for dealing with the the whole EE situation.

Now I wonder how I can get similar functionality for my Maven builds:

does Maven offer something comparable out of the box?

is there a plugin or extension for Maven providing such functionality?

is there a way to integrate Gradle with Maven without having to migrate fully?


问:
Spotfire multiple threads | workers | parallelization
I have the following code snippet below which is composed of multiple subtasks that are not related to each other. I would like to execute them either in a worker thread or asynchronously. All the subtasks make use of Document, Spotfire.Dxp or Filtering etc objects in some fashion:

#suppose all the necessary imports are here
ps = Application.GetService[ProgressService]()
def execute():
    try:
        # subtask 1
        ps.CurrentProgress.ExecuteSubtask("STEP 1");
        Document.Data.Tables["someTable"].ReloadAllData()
        ps.CurrentProgress.CheckCancel()
        # subtask 2
        #...
        #subtask 3
        #...
    except: # user canceled
        print("ERROR")
        pass
ps.ExecuteWithProgress("MyScript", "Loading", execute)
```
<h2>How can I make the subtasks parallel ? Here is what I have tried, but failed (in all the trials below, suppose necessary imports are there if not explicitly indicated):</h2>
<p><em>Trial 1: wrap the subtask in a function and repeat the imports. Throws <code>SystemError: Object reference not set to an instance of an object.</code></em></p>
<pre class="lang-py prettyprint-override"><code>#from X import Y
#...
ps = Application.GetService[ProgressService]()
# subtask 1
def subtask1 ():
    #from X import Y
    #...
    ps.CurrentProgress.ExecuteSubtask("STEP 1")
    Document.Data.Tables["someTable"].ReloadAllData()
    ps.CurrentProgress.CheckCancel()
# subtask 2
def subtask2 ():
    ...
def execute():
    try:
        if __name__ == "__builtin__":
            thread1 = Thread(target = subtask1, args = ())
            thread1.start()
            thread2 = Thread(target = subtask2, args = ())
            thread2.start()
        thread1.join()
        thread2.join()
    except: # user canceled
        print("ERROR")
        pass
ps.ExecuteWithProgress("MyScript", "Loading", execute)
</code>```

Trial 2: Make a monkey patch for the function to prevent references from being garbage collected. Throws SystemError: Object reference not set to an instance of an object.

#...
# subtask 1
def subtask1Outer (Document, someTableRef, ScriptDefinition, clr, DataTableDataSource, ps):
    def subtask1Inner ():
        ps.CurrentProgress.ExecuteSubtask("STEP 1");
        someTableRef.ReloadAllData()
        ps.CurrentProgress.CheckCancel()
    return subtask1Inner
#...
def execute():
    try:
        if __name__ == "__builtin__":
            thread1 = Thread(target = subtask1Outer(Document,
                Document.Data.Tables["someTable"],
                ScriptDefinition,
                clr,
                DataTableDataSource,
                ps
            ), args = ())
            thread1.start()
        thread1.join()
    except Exception as e: # user canceled
        print("ERROR")
        print(e)
        pass
...
```
<p>An alternative to above is to store the objects within a generic object <code>{}</code> and pass it to the <code>subtask1</code> rather than using a function generator. The result is the same, <code>SystemError:...</code></p>
<p><em>Trial 3: Write a new script <code>subtask1</code> with all the dependencies inlined. Use the <code>Script Manager</code> to call <code>subtask1</code>. Throws <code>SystemError: Object reference not set to an instance of an object.</code></em></p>
<pre class="lang-py prettyprint-override"><code>#...
def callScript(scriptName):
    from System.Collections.Generic import Dictionary
    from Spotfire.Dxp.Application.Scripting import ScriptDefinition
    import clr
    scriptDef = clr.Reference[ScriptDefinition]()
    Document.ScriptManager.TryGetScript(scriptName, scriptDef)
    paramDict = {"MyParam":"Value1"}
    params = Dictionary[str, object](paramDict)
    Document.ScriptManager.ExecuteScript(scriptDef.Value, params)

if __name__ == "__builtin__":
    thread1 = Thread(target = callScript, args = ("subtask1",))
    thread1.start()
thread1.join()
</code>```

Trial 4: Write a new script subtask1 with all the dependencies inlined. Use the Script Manager to call subtask1 with scriptDef as argument to prevent garbage collection. Throws SystemError: Attempt to perform an operation on an incorrect thread. Use ApplicationThread.Invoke() to invoke into the application thread.

#...
def callScript(scriptDef):
    paramDict = {"MyParam":"Value1"}
    params = Dictionary[str, object](paramDict)
    Document.ScriptManager.ExecuteScript(scriptDef.Value, params)
if __name__ == "__builtin__":
    scriptDef = clr.Reference[ScriptDefinition]()
    Document.ScriptManager.TryGetScript("subtask1", scriptDef)
    thread1 = Thread(target = callScript, args = (scriptDef,))
    thread1.start()
thread1.join()
```
<p><em>Trial 5: Pass all the references to the inner function <code>callScript</code> to prevent garbage collection. Throws <code>SystemError: Object reference not set to an instance of an object.</code></em></p>
<pre class="lang-py prettyprint-override"><code>#all the imports like ScriptDefinition, clr etc.
def outer(Dictionary, ScriptDefinition, clr, Document, Application,):
    def callScript(scriptName):
        scriptDef = clr.Reference[ScriptDefinition]()
        Document.ScriptManager.TryGetScript(scriptName, scriptDef)
        paramDict = {"MyParam":"Value1"}
        params = Dictionary[str, object](paramDict)
        Document.ScriptManager.ExecuteScript(scriptDef.Value, params)
    return callScript

if __name__ == "__builtin__":
    thread1 = Thread(target = outer(Dictionary, ScriptDefinition, clr, Document, Application), args = ("subtask1",))
    thread1.start()
thread1.join()
</code>```

Trial 6: Use ApplicationThread.InvokeAsynchronously method to call the script. Does not throw any errors, but outputs nothing.

#suppose all the necessary imports...
# test object to see if the thread is doing something
obj = {}
def outer(Document, Dictionary, scriptDef, obj):
    def callScript():
        #print might not work due to absence of tty, so maybe we can set a property on the object
        print("Inner Started!")
        obj['innerStart'] = 1;
        paramDict = {"MyParam":"Value1"}
        params = Dictionary[str, object](paramDict)
        Document.ScriptManager.ExecuteScript(scriptDef.Value, params)
        print("Inner Done!")
        obj['innerEnd'] = 1;
    return callScript

scriptDef = clr.Reference[ScriptDefinition]()
Document.ScriptManager.TryGetScript("subtask1", scriptDef)
Application.GetService[ApplicationThread]().InvokeAsynchronously(outer(Document, Dictionary, scriptDef, obj))
print(obj) #prints {}
print("Done outer!")
```
<p>I must point out that if I substitute <code>InvokeAsynchronously</code> with <code>Invoke</code>, the scripts works as expected, calls the other script and outputs:</p>
```Inner Started!
Inner Done!
{'innerStart': 1, 'innerEnd': 1}
Done outer!
```

So how can I execute tasks in parallel in Spotfire? I've looked to the docs, searched for keywords but did not find much, other then the Worker package that does not include a single usage snippet.

Body:
I have the following code snippet below which is composed of multiple subtasks that are not related to each other. I would like to execute them either in a worker thread or asynchronously. All the subtasks make use of Document, Spotfire.Dxp or Filtering etc objects in some fashion:

#suppose all the necessary imports are here
ps = Application.GetService[ProgressService]()
def execute():
    try:
        # subtask 1
        ps.CurrentProgress.ExecuteSubtask("STEP 1");
        Document.Data.Tables["someTable"].ReloadAllData()
        ps.CurrentProgress.CheckCancel()
        # subtask 2
        #...
        #subtask 3
        #...
    except: # user canceled
        print("ERROR")
        pass
ps.ExecuteWithProgress("MyScript", "Loading", execute)

How can I make the subtasks parallel ? Here is what I have tried, but failed (in all the trials below, suppose necessary imports are there if not explicitly indicated):

Trial 1: wrap the subtask in a function and repeat the imports. Throws SystemError: Object reference not set to an instance of an object.

#from X import Y
#...
ps = Application.GetService[ProgressService]()
# subtask 1
def subtask1 ():
    #from X import Y
    #...
    ps.CurrentProgress.ExecuteSubtask("STEP 1")
    Document.Data.Tables["someTable"].ReloadAllData()
    ps.CurrentProgress.CheckCancel()
# subtask 2
def subtask2 ():
    ...
def execute():
    try:
        if __name__ == "__builtin__":
            thread1 = Thread(target = subtask1, args = ())
            thread1.start()
            thread2 = Thread(target = subtask2, args = ())
            thread2.start()
        thread1.join()
        thread2.join()
    except: # user canceled
        print("ERROR")
        pass
ps.ExecuteWithProgress("MyScript", "Loading", execute)

Trial 2: Make a monkey patch for the function to prevent references from being garbage collected. Throws SystemError: Object reference not set to an instance of an object.

#...
# subtask 1
def subtask1Outer (Document, someTableRef, ScriptDefinition, clr, DataTableDataSource, ps):
    def subtask1Inner ():
        ps.CurrentProgress.ExecuteSubtask("STEP 1");
        someTableRef.ReloadAllData()
        ps.CurrentProgress.CheckCancel()
    return subtask1Inner
#...
def execute():
    try:
        if __name__ == "__builtin__":
            thread1 = Thread(target = subtask1Outer(Document,
                Document.Data.Tables["someTable"],
                ScriptDefinition,
                clr,
                DataTableDataSource,
                ps
            ), args = ())
            thread1.start()
        thread1.join()
    except Exception as e: # user canceled
        print("ERROR")
        print(e)
        pass
...

An alternative to above is to store the objects within a generic object {} and pass it to the subtask1 rather than using a function generator. The result is the same, SystemError:...

Trial 3: Write a new script subtask1 with all the dependencies inlined. Use the Script Manager to call subtask1. Throws SystemError: Object reference not set to an instance of an object.

#...
def callScript(scriptName):
    from System.Collections.Generic import Dictionary
    from Spotfire.Dxp.Application.Scripting import ScriptDefinition
    import clr
    scriptDef = clr.Reference[ScriptDefinition]()
    Document.ScriptManager.TryGetScript(scriptName, scriptDef)
    paramDict = {"MyParam":"Value1"}
    params = Dictionary[str, object](paramDict)
    Document.ScriptManager.ExecuteScript(scriptDef.Value, params)

if __name__ == "__builtin__":
    thread1 = Thread(target = callScript, args = ("subtask1",))
    thread1.start()
thread1.join()

Trial 4: Write a new script subtask1 with all the dependencies inlined. Use the Script Manager to call subtask1 with scriptDef as argument to prevent garbage collection. Throws SystemError: Attempt to perform an operation on an incorrect thread. Use ApplicationThread.Invoke() to invoke into the application thread.

#...
def callScript(scriptDef):
    paramDict = {"MyParam":"Value1"}
    params = Dictionary[str, object](paramDict)
    Document.ScriptManager.ExecuteScript(scriptDef.Value, params)
if __name__ == "__builtin__":
    scriptDef = clr.Reference[ScriptDefinition]()
    Document.ScriptManager.TryGetScript("subtask1", scriptDef)
    thread1 = Thread(target = callScript, args = (scriptDef,))
    thread1.start()
thread1.join()

Trial 5: Pass all the references to the inner function callScript to prevent garbage collection. Throws SystemError: Object reference not set to an instance of an object.

#all the imports like ScriptDefinition, clr etc.
def outer(Dictionary, ScriptDefinition, clr, Document, Application,):
    def callScript(scriptName):
        scriptDef = clr.Reference[ScriptDefinition]()
        Document.ScriptManager.TryGetScript(scriptName, scriptDef)
        paramDict = {"MyParam":"Value1"}
        params = Dictionary[str, object](paramDict)
        Document.ScriptManager.ExecuteScript(scriptDef.Value, params)
    return callScript

if __name__ == "__builtin__":
    thread1 = Thread(target = outer(Dictionary, ScriptDefinition, clr, Document, Application), args = ("subtask1",))
    thread1.start()
thread1.join()

Trial 6: Use ApplicationThread.InvokeAsynchronously method to call the script. Does not throw any errors, but outputs nothing.

#suppose all the necessary imports...
# test object to see if the thread is doing something
obj = {}
def outer(Document, Dictionary, scriptDef, obj):
    def callScript():
        #print might not work due to absence of tty, so maybe we can set a property on the object
        print("Inner Started!")
        obj['innerStart'] = 1;
        paramDict = {"MyParam":"Value1"}
        params = Dictionary[str, object](paramDict)
        Document.ScriptManager.ExecuteScript(scriptDef.Value, params)
        print("Inner Done!")
        obj['innerEnd'] = 1;
    return callScript

scriptDef = clr.Reference[ScriptDefinition]()
Document.ScriptManager.TryGetScript("subtask1", scriptDef)
Application.GetService[ApplicationThread]().InvokeAsynchronously(outer(Document, Dictionary, scriptDef, obj))
print(obj) #prints {}
print("Done outer!")

I must point out that if I substitute InvokeAsynchronously with Invoke, the scripts works as expected, calls the other script and outputs:

Inner Started!
Inner Done!
{'innerStart': 1, 'innerEnd': 1}
Done outer!

So how can I execute tasks in parallel in Spotfire? I've looked to the docs, searched for keywords but did not find much, other then the Worker package that does not include a single usage snippet.


问:
I've gotten a count of strings from a dataframe column, now i want the strings themselves
So this code returns the value counts, but I also want the names, how do i get that?
```spotify_df.artist_names.value_counts().head(10)</p>


问:
RUN dotnet restore is failing on docker-compose
I am following Udemy:Microservie.

I have created DockerFile for the WebAPI and added Mongo image as database.

when I run the docker-compose -f .\docker-compose.yml -f .\docker-compose.override.yml up -d command, I am getting the following error:

docker-compose.yml file:

```<code>version: '3.4'

services:
  catalogdb:
    image: mongo

  catalog.api:
    image: ${DOCKER_REGISTRY-}catalogapi
    build:
      context: .
      dockerfile: Services/Catalog/Catalog.API/Dockerfile

volumes:
  mongo_data:
</code>```

docker-compose.override.yml file:

```<code>version: '3.4'

services:
  catalogdb:
    container_name: catalogdb
    restart: always
    ports:
      - "27017:27017"
    volumes:
      - mongo_data:/data/db

  catalog.api:
    container_name: catalog.api
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - "DatabaseSettings_ConnectionString=mongodb://catalogdb:27017"
    depends_on:
      - catalogdb
    ports:
      - "8000:80"
version: '3.4'

services:
  catalogdb:
    container_name: catalogdb
    restart: always
    ports:
      - "27017:27017"
    volumes:
      - mongo_data:/data/db

  catalog.api:
    container_name: catalog.api
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - "DatabaseSettings_ConnectionString=mongodb://catalogdb:27017"
    depends_on:
      - catalogdb
    ports:
      - "8000:80"
</code>```

before posting I have spent some time in stack overflow for resolution and tried

Restarting Docker and VS2022

Connected to Internet when running the command

deleted nuget.config in appdata/Roaming.

Added 'DisabledByDefault' and set to 0 in 'Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.3\Client'

but nothing worked.

Can someone Please help on the above issue.

Body:
I am following Udemy:Microservie.

I have created DockerFile for the WebAPI and added Mongo image as database.

when I run the docker-compose -f .\docker-compose.yml -f .\docker-compose.override.yml up -d command, I am getting the following error:

docker-compose.yml file:

version: '3.4'

services:
  catalogdb:
    image: mongo

  catalog.api:
    image: ${DOCKER_REGISTRY-}catalogapi
    build:
      context: .
      dockerfile: Services/Catalog/Catalog.API/Dockerfile

volumes:
  mongo_data:

docker-compose.override.yml file:

version: '3.4'

services:
  catalogdb:
    container_name: catalogdb
    restart: always
    ports:
      - "27017:27017"
    volumes:
      - mongo_data:/data/db

  catalog.api:
    container_name: catalog.api
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - "DatabaseSettings_ConnectionString=mongodb://catalogdb:27017"
    depends_on:
      - catalogdb
    ports:
      - "8000:80"
version: '3.4'

services:
  catalogdb:
    container_name: catalogdb
    restart: always
    ports:
      - "27017:27017"
    volumes:
      - mongo_data:/data/db

  catalog.api:
    container_name: catalog.api
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - "DatabaseSettings_ConnectionString=mongodb://catalogdb:27017"
    depends_on:
      - catalogdb
    ports:
      - "8000:80"

before posting I have spent some time in stack overflow for resolution and tried

Restarting Docker and VS2022

Connected to Internet when running the command

deleted nuget.config in appdata/Roaming.

Added 'DisabledByDefault' and set to 0 in 'Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.3\Client'

but nothing worked.

Can someone Please help on the above issue.


问:
Why is Spring Security 6 not hitting the validate method of my OAuth2TokenValidator?
I have the following code...

public class AudienceValidator implements OAuth2TokenValidator<Jwt> {

    private final String audience;

    public AudienceValidator(String audience) {
        this.audience = audience;
    }

    @Override
    public OAuth2TokenValidatorResult validate(Jwt jwt) {
        if (jwt.getAudience().contains(audience)) {
            return OAuth2TokenValidatorResult.success();
        } else {
            return OAuth2TokenValidatorResult.failure(error);
        }
    }
}

@EnableWebSecurity
public class SecurityConfig{

    @Value("${auth0.audience}")
    private String audience;

    @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
    private String issuer;
    @Bean
    public JwtDecoder jwtDecoder() {
        NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
                JwtDecoders.fromOidcIssuerLocation(issuer);

        OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(audience);
        OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
        OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);

        jwtDecoder.setJwtValidator(withAudience);

        return jwtDecoder;
    }
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        .anyRequest().authenticated()
                )
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        return http.build();
    }
}
```
<p>I have confirmed it stops inside the <code>jwtDecode</code> method using the debugger but when I send a message with an Access Token, I don't see it hitting the validation function and it doesn't seem to confirm that the audience is correct. Am I missing something? Why is the validate function not getting called as expected?</p>
<p>I also tried to manually add the JWTDecoder...</p>
```public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        .anyRequest().authenticated()
                )
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt(jwt -> jwt
                                .decoder(jwtDecoder())
                        )
                );
        return http.build();
    }
```
<p>And I still don't hit the debug breakpoint at</p>
<p><code>if (jwt.getAudience().contains(audience)) {</code></p>
<p>I also tried using the Reactive Decoder like...</p>
```    @Bean
    ReactiveJwtDecoder jwtDecoder() {
        NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder)
                ReactiveJwtDecoders.fromIssuerLocation(issuer);

        OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(audience);
        OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
        OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);

        jwtDecoder.setJwtValidator(withAudience);

        return jwtDecoder;
    }
```

This still didn't hit the debugger.

Body:
I have the following code...

public class AudienceValidator implements OAuth2TokenValidator<Jwt> {

    private final String audience;

    public AudienceValidator(String audience) {
        this.audience = audience;
    }

    @Override
    public OAuth2TokenValidatorResult validate(Jwt jwt) {
        if (jwt.getAudience().contains(audience)) {
            return OAuth2TokenValidatorResult.success();
        } else {
            return OAuth2TokenValidatorResult.failure(error);
        }
    }
}

@EnableWebSecurity
public class SecurityConfig{

    @Value("${auth0.audience}")
    private String audience;

    @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
    private String issuer;
    @Bean
    public JwtDecoder jwtDecoder() {
        NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
                JwtDecoders.fromOidcIssuerLocation(issuer);

        OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(audience);
        OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
        OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);

        jwtDecoder.setJwtValidator(withAudience);

        return jwtDecoder;
    }
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        .anyRequest().authenticated()
                )
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        return http.build();
    }
}

I have confirmed it stops inside the jwtDecode method using the debugger but when I send a message with an Access Token, I don't see it hitting the validation function and it doesn't seem to confirm that the audience is correct. Am I missing something? Why is the validate function not getting called as expected?

I also tried to manually add the JWTDecoder...

public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        .anyRequest().authenticated()
                )
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt(jwt -> jwt
                                .decoder(jwtDecoder())
                        )
                );
        return http.build();
    }

And I still don't hit the debug breakpoint at

if (jwt.getAudience().contains(audience)) {

I also tried using the Reactive Decoder like...

    @Bean
    ReactiveJwtDecoder jwtDecoder() {
        NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder)
                ReactiveJwtDecoders.fromIssuerLocation(issuer);

        OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(audience);
        OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
        OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);

        jwtDecoder.setJwtValidator(withAudience);

        return jwtDecoder;
    }

This still didn't hit the debugger.


问:
Conditional Statement Continues After Attempting to Exit in PySide6 GUI
I am using PySide6 to create a GUI and wanting to add a button that when pressed aborts the program but does not close the main window just stops the current code that is running. I have done my best to strip down the GUI to be as simple as possible, but still illustrates the point at hand.

Here is the code:

import sys
import time

from PySide6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QGridLayout,
    QTableView, QHeaderView, QPushButton, QMessageBox,
)
from PySide6.QtGui import QCursor, QBrush
from PySide6.QtCore import QSize, Qt

from table_model import TableModel

class MainWindow(QMainWindow):
    '''
    Main Window GUI
    '''
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setWindowTitle("Start and Abort Question")
        self.setFixedSize(QSize(900, 525))

        self.create_table()

        self.start_button = QPushButton("Start Test", self)
        self.start_button.clicked.connect(self.click_start)
        self.start_button.setCursor(QCursor(Qt.PointingHandCursor))

        layout = QGridLayout()
        layout.addWidget(self.table, 0, 0)
        layout.addWidget(self.start_button, 1, 0)

        widget = QWidget()
        widget.setLayout(layout)
        self.setCentralWidget(widget)

    def create_table(self):
        '''
        Creates table
        '''

        self.table = QTableView()
        h_header = self.table.horizontalHeader()
        h_header.setVisible(False)
        h_header.setSectionResizeMode(QHeaderView.Stretch)
        v_header = self.table.verticalHeader()
        v_header.setVisible(False)

        data = [
            ["Task 1"],
            ["Task 2"],
            ["Task 3"],
            ["Task 4"],
            ["Task 5"],
            ["Task 6"],
            ["Task 7"],
            ["Task 8"]
        ]

        self.model = TableModel(data)
        self.table.setModel(self.model)

    def click_start(self):
        '''
        When start button is clicked program runs
        '''

        keep_running = True

        while keep_running == True:
            # Test 1
            if self.start_button.text() == "Start Test":
                self.start_button.setText("Abort Test")
                QApplication.processEvents()
                for i in range(8):
                    self.model.setData(self.model.index(i, 0), QBrush(Qt.green), Qt.BackgroundRole)
                    QApplication.processEvents()
                    time.sleep(0.5)
                keep_running = False

            elif self.start_button.text() == "Abort Test":

                msg = QMessageBox()
                msg.setIcon(msg.Warning)
                msg.setText("Test Aborted!")
                msg.addButton(msg.Ok)
                msg.setDefaultButton(msg.Ok)
                msg.exec()
                keep_running = False

        # Button Changes back
        self.start_button.setText("Start Test")

# Needed per applicaiton
app = QApplication(sys.argv)
app.setStyle('Fusion')
# Displays main windows
window = MainWindow()
window.show()
# Starts the loop
app.exec()
```
<p>Right now, the GUI is just a window with a button. When the start button is pressed the text changes to say, "Abort Test". When start is pressed the code will run and change the color of the rows of the table. When I press "Abort Test" the QMessageBox will pop up. <strong>The problem occurs</strong> when I close the QMessageBox the program that was running when I first clicked start will continue to color rows of the table instead of stopping. I have tried putting the code in the <code>click_start</code> function inside a while loop and using the <code>break</code> statement but get the same results.</p>
<p>This section of code is the Table Model that I created as a separate python file table_model.py and import into the code above.</p>
<pre class="lang-py prettyprint-override"><code>'''
Table Model
'''

from PySide6.QtCore import (
    Qt, QAbstractTableModel
)
from PySide6.QtGui import QFont

class TableModel(QAbstractTableModel):
    '''
    Table Model
    '''

    def __init__(self, data):
        super().__init__()
        self._data = data
        rows = len(data)
        cols = len(data[0])
        self._backgrounds = [[None] * cols for _ in range(rows)]

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid():
            return

        elif role in (Qt.DisplayRole, Qt.EditRole):
            return self._data[index.row()][index.column()]

        elif role == Qt.BackgroundRole:
            return self._backgrounds[index.row()][index.column()]

        elif role == Qt.TextAlignmentRole:
            return Qt.AlignCenter

        elif role == Qt.FontRole:
            font = QFont("72 Black")
            return font

    def setData(self, index, value, role=Qt.EditRole):
        if (
            not index.isValid()
            or index.row() >= len(self._data)
            or index.column() >= len(self._data[0])
        ):
            return False

        if role == Qt.EditRole:
            self._data[index.row()][index.column()] = value
        elif role == Qt.BackgroundRole:
            self._backgrounds[index.row()][index.column()] = value
        else:
            return False

        self.dataChanged.emit(index, index, [role])
        return True

    def rowCount(self, index):
        # The length of the outer list.
        return len(self._data)

    def columnCount(self, index):
        # The following takes the first sub-list, and returns
        # the length (only works if all rows are an equal length)
        return len(self._data[0])

</code>```

I am convinced this is a very trivial task, but nothing that I do seems actually stop the program.

Body:
I am using PySide6 to create a GUI and wanting to add a button that when pressed aborts the program but does not close the main window just stops the current code that is running. I have done my best to strip down the GUI to be as simple as possible, but still illustrates the point at hand.

Here is the code:

import sys
import time

from PySide6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QGridLayout,
    QTableView, QHeaderView, QPushButton, QMessageBox,
)
from PySide6.QtGui import QCursor, QBrush
from PySide6.QtCore import QSize, Qt

from table_model import TableModel

class MainWindow(QMainWindow):
    '''
    Main Window GUI
    '''
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setWindowTitle("Start and Abort Question")
        self.setFixedSize(QSize(900, 525))

        self.create_table()

        self.start_button = QPushButton("Start Test", self)
        self.start_button.clicked.connect(self.click_start)
        self.start_button.setCursor(QCursor(Qt.PointingHandCursor))

        layout = QGridLayout()
        layout.addWidget(self.table, 0, 0)
        layout.addWidget(self.start_button, 1, 0)

        widget = QWidget()
        widget.setLayout(layout)
        self.setCentralWidget(widget)

    def create_table(self):
        '''
        Creates table
        '''

        self.table = QTableView()
        h_header = self.table.horizontalHeader()
        h_header.setVisible(False)
        h_header.setSectionResizeMode(QHeaderView.Stretch)
        v_header = self.table.verticalHeader()
        v_header.setVisible(False)

        data = [
            ["Task 1"],
            ["Task 2"],
            ["Task 3"],
            ["Task 4"],
            ["Task 5"],
            ["Task 6"],
            ["Task 7"],
            ["Task 8"]
        ]

        self.model = TableModel(data)
        self.table.setModel(self.model)

    def click_start(self):
        '''
        When start button is clicked program runs
        '''

        keep_running = True

        while keep_running == True:
            # Test 1
            if self.start_button.text() == "Start Test":
                self.start_button.setText("Abort Test")
                QApplication.processEvents()
                for i in range(8):
                    self.model.setData(self.model.index(i, 0), QBrush(Qt.green), Qt.BackgroundRole)
                    QApplication.processEvents()
                    time.sleep(0.5)
                keep_running = False

            elif self.start_button.text() == "Abort Test":

                msg = QMessageBox()
                msg.setIcon(msg.Warning)
                msg.setText("Test Aborted!")
                msg.addButton(msg.Ok)
                msg.setDefaultButton(msg.Ok)
                msg.exec()
                keep_running = False

        # Button Changes back
        self.start_button.setText("Start Test")

# Needed per applicaiton
app = QApplication(sys.argv)
app.setStyle('Fusion')
# Displays main windows
window = MainWindow()
window.show()
# Starts the loop
app.exec()

Right now, the GUI is just a window with a button. When the start button is pressed the text changes to say, "Abort Test". When start is pressed the code will run and change the color of the rows of the table. When I press "Abort Test" the QMessageBox will pop up. The problem occurs when I close the QMessageBox the program that was running when I first clicked start will continue to color rows of the table instead of stopping. I have tried putting the code in the click_start function inside a while loop and using the break statement but get the same results.

This section of code is the Table Model that I created as a separate python file table_model.py and import into the code above.

'''
Table Model
'''

from PySide6.QtCore import (
    Qt, QAbstractTableModel
)
from PySide6.QtGui import QFont

class TableModel(QAbstractTableModel):
    '''
    Table Model
    '''

    def __init__(self, data):
        super().__init__()
        self._data = data
        rows = len(data)
        cols = len(data[0])
        self._backgrounds = [[None] * cols for _ in range(rows)]

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid():
            return

        elif role in (Qt.DisplayRole, Qt.EditRole):
            return self._data[index.row()][index.column()]

        elif role == Qt.BackgroundRole:
            return self._backgrounds[index.row()][index.column()]

        elif role == Qt.TextAlignmentRole:
            return Qt.AlignCenter

        elif role == Qt.FontRole:
            font = QFont("72 Black")
            return font

    def setData(self, index, value, role=Qt.EditRole):
        if (
            not index.isValid()
            or index.row() >= len(self._data)
            or index.column() >= len(self._data[0])
        ):
            return False

        if role == Qt.EditRole:
            self._data[index.row()][index.column()] = value
        elif role == Qt.BackgroundRole:
            self._backgrounds[index.row()][index.column()] = value
        else:
            return False

        self.dataChanged.emit(index, index, [role])
        return True

    def rowCount(self, index):
        # The length of the outer list.
        return len(self._data)

    def columnCount(self, index):
        # The following takes the first sub-list, and returns
        # the length (only works if all rows are an equal length)
        return len(self._data[0])

I am convinced this is a very trivial task, but nothing that I do seems actually stop the program.


问:
DFU lib to do firmware update via software
My use case is I am trying to do the firmware update of a stm32 uC, using the DFU protocol via an application written in C++.

Can someone recommend a DFU library that i could use in order to do this?


问:
Owl carousel click on slide to show description DIV uniquely
i'm using owl carousel, when i click on slide there is a description div open outside of owl carousel hierarchy.

Please help me out.

Thanks a lot

I'm trying click function but its toggle the all description div's at once

$(document).ready(function() {
  $(".owl-item").click(function() {
    $(".carousel-item-desc1,.carousel-item-desc2,.carousel-item-desc3,.carousel-item-desc4").slideToggle();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div> need more here </div></code>```

Before

After

Body:
i'm using owl carousel, when i click on slide there is a description div open outside of owl carousel hierarchy.

Please help me out.

Thanks a lot

I'm trying click function but its toggle the all description div's at once

$(document).ready(function() {
  $(".owl-item").click(function() {
    $(".carousel-item-desc1,.carousel-item-desc2,.carousel-item-desc3,.carousel-item-desc4").slideToggle();
  });
});

 need more here

Before

After


问:
Odoo Popup button not working (JS, xml, Controller and manifest to troubleshoot)
I have the following code:

```<code>odoo.define('ebs_portal_attendance.mn_tasks', function (require) {
    "use strict";

    $(document).ready(function () {
        // Show create timesheet popup
        $('#create_timesheet_button').on('click', function () {
            var $modal = $('#create_timesheet_popup');
            var task_id = $(this).data('task-id');
            $modal.modal('show');
        });

        // Create timesheet
        $('#create_timesheet_popup #create_timesheet_button').on('click', function () {
            var $modal = $('#create_timesheet_popup');
            var task_id = $modal.find('#task_id').val();
            var name = $modal.find('#name').val();
            var unit_amount = $modal.find('#unit_amount').val();
            var date = $modal.find('#date').val();

            ajax.jsonRpc("/my/tasks/create_timesheet", 'call', {
                'values': {
                    'name': name,
                    'task_id': task_id,
                    'unit_amount': unit_amount,
                    'date': date,
                }
            }).then(function (result) {
                if (result.success) {
                    $modal.modal('hide');
                    alert("Timesheet created successfully!");
                } else {
                    alert("An error occurred while creating the timesheet.");
                }
            });
        });
    });
});

        <template id="mn_tasks_list" inherit_id="project.portal_tasks_list">
            <xpath expr="//t//t//t//tbody//t//tr//td[last()]" position="after">
                <td>
                    <div class="o_download_pdf btn-toolbar flex-sm-nowrap">
                        <div>
                            <a role="button" class="btn btn-secondary flex-grow-1 mb-1 create_timesheet_button"
                               data-toggle="modal"
                               id='create_timesheet_button' data-target="#create_timesheet_popup" href="#">
                                <t>Create Timesheet</t>
                            </a>
                        </div>
                    </div>
                </td>
            </xpath>
        </template>
    </data>

    <template id="create_timesheet_popup" name="Create Timesheet Popup">
        <div id="create_timesheet_popup" class="modal fade">
            <div class="modal-dialog modal-content"
                 style="border:solid 2px white; min-height:200px;max-width:800px;margin-top:10px">
                <div class="modal-body" id="pop_html">
                    <a href="#" class="o_popup_btn_close o_not_editable o_default_snippet_text pull-right"
                       data-dismiss="modal" aria-hidden="true">X</a>
                    <div class="row">
                        <div class="col-md-12">
                            <form class="o_form_sheet">
                                <div class="o_form_sheet_name">
                                    <h4>Create Timesheet</h4>
                                </div>
                                <div class="form-group">
                                    <label for="name">Name:</label>
                                    <input type="text" class="form-control" id="name" name="name" required="required"/>
                                </div>
                                <div class="form-group">
                                    <label for="task_id">Task:</label>
                                    <select class="form-control" id="task_id" name="task_id" required="required">
                                        <t t-foreach="tasks" t-as="task">
                                            <option value="{{ task.id }}">{{ task.name }}</option>
                                        </t>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="unit_amount">Hours:</label>
                                    <input type="number" class="form-control" id="unit_amount" name="unit_amount"
                                           required="required"/>
                                </div>
                                <div class="form-group">
                                    <label for="date">Date:</label>
                                    <input type="date" class="form-control" id="date" name="date" required="required"/>
                                </div>
                                <div class="form-group">
                                    <button type="button" class="btn btn-primary" id="create_timesheet_button" data-task-id="{{ task.id }}">Create Timesheet</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>

    @http.route('/my/tasks/create_timesheet', type='json', auth='user')
    def create_timesheet(self, values):
        task_id = values.get('task_id')
        name = values.get('name')
        unit_amount = values.get('unit_amount')
        date = values.get('date')

        try:
            # Create new timesheet record
            new_timesheet = http.request.env['account.analytic.line'].sudo().create({
                'name': name,
                'task_id': task_id,
                'unit_amount': unit_amount,
                'date': date,
            })
            # Return success message
            return {'success': True, 'message': 'Timesheet created successfully'}
        except Exception as e:
            # Return error message
            return {'success': False, 'message': 'An error occurred while creating the timesheet: %s' % e}
</code>```

with the manifest is as follows:

```<code>`    # always loaded
    'data': [
        'security/security.xml',
        'security/ir.model.access.csv',
        'views/views.xml',
        'views/templates.xml',
        'views/inherited_templates.xml',
    ],
    'assets': {
        'web.assets_backend': [
            'model_folder/static/src/js/portal_timesheets.js',
        ],
    },`
</code>```

My Problem is that button on the portal in the list of tasks where the button is located it's there but now it's not doing anything i tried checking the js via adding console.log("test") to see if anything would appear under the web browser's console but there's nothing... what i am doing wring here please do help me.

Thank you!!

I'm looking to have it work where when the user clicks on create timesheet, a popup would appear and it'll take the task's ID and task.analytical_account_id.id and other inputs to which it'll create at the end a record for that model and appears under his timesheets.

Body:
I have the following code:

odoo.define('ebs_portal_attendance.mn_tasks', function (require) {
    "use strict";

    $(document).ready(function () {
        // Show create timesheet popup
        $('#create_timesheet_button').on('click', function () {
            var $modal = $('#create_timesheet_popup');
            var task_id = $(this).data('task-id');
            $modal.modal('show');
        });

        // Create timesheet
        $('#create_timesheet_popup #create_timesheet_button').on('click', function () {
            var $modal = $('#create_timesheet_popup');
            var task_id = $modal.find('#task_id').val();
            var name = $modal.find('#name').val();
            var unit_amount = $modal.find('#unit_amount').val();
            var date = $modal.find('#date').val();

            ajax.jsonRpc("/my/tasks/create_timesheet", 'call', {
                'values': {
                    'name': name,
                    'task_id': task_id,
                    'unit_amount': unit_amount,
                    'date': date,
                }
            }).then(function (result) {
                if (result.success) {
                    $modal.modal('hide');
                    alert("Timesheet created successfully!");
                } else {
                    alert("An error occurred while creating the timesheet.");
                }
            });
        });
    });
});

        <template id="mn_tasks_list" inherit_id="project.portal_tasks_list">
            <xpath expr="//t//t//t//tbody//t//tr//td[last()]" position="after">

                                <t>Create Timesheet</t>

            </xpath>
        </template>
    </data>

    <template id="create_timesheet_popup" name="Create Timesheet Popup">

                    X

                            <form class="o_form_sheet">

Create Timesheet

                                    Name:
                                    <input type="text" class="form-control" id="name" name="name" required="required"/>

                                    Task:
                                    <select class="form-control" id="task_id" name="task_id" required="required">
                                        <t t-foreach="tasks" t-as="task">
                                            <option value="{{ task.id }}">{{ task.name }}</option>
                                        </t>
                                    </select>

                                    Hours:
                                    <input type="number" class="form-control" id="unit_amount" name="unit_amount"
                                           required="required"/>

                                    Date:
                                    <input type="date" class="form-control" id="date" name="date" required="required"/>

                                    <button type="button" class="btn btn-primary" id="create_timesheet_button" data-task-id="{{ task.id }}">Create Timesheet</button>

                            </form>

    </template>

    @http.route('/my/tasks/create_timesheet', type='json', auth='user')
    def create_timesheet(self, values):
        task_id = values.get('task_id')
        name = values.get('name')
        unit_amount = values.get('unit_amount')
        date = values.get('date')

        try:
            # Create new timesheet record
            new_timesheet = http.request.env['account.analytic.line'].sudo().create({
                'name': name,
                'task_id': task_id,
                'unit_amount': unit_amount,
                'date': date,
            })
            # Return success message
            return {'success': True, 'message': 'Timesheet created successfully'}
        except Exception as e:
            # Return error message
            return {'success': False, 'message': 'An error occurred while creating the timesheet: %s' % e}

with the manifest is as follows:

`    # always loaded
    'data': [
        'security/security.xml',
        'security/ir.model.access.csv',
        'views/views.xml',
        'views/templates.xml',
        'views/inherited_templates.xml',
    ],
    'assets': {
        'web.assets_backend': [
            'model_folder/static/src/js/portal_timesheets.js',
        ],
    },`

My Problem is that button on the portal in the list of tasks where the button is located it's there but now it's not doing anything i tried checking the js via adding console.log("test") to see if anything would appear under the web browser's console but there's nothing... what i am doing wring here please do help me.

Thank you!!

I'm looking to have it work where when the user clicks on create timesheet, a popup would appear and it'll take the task's ID and task.analytical_account_id.id and other inputs to which it'll create at the end a record for that model and appears under his timesheets.


问:
Could not determine the dependencies of task ':kotlinNodeJsSetup' - Kotlin Multiplatform

Build was configured to prefer settings repositories over project repositories but repository 'Node Distributions at https://nodejs.org/dist' was added by unknown code

Could not determine the dependencies of task ':kotlinYarnSetup'.

Build was configured to prefer settings repositories over project repositories but repository 'Yarn Distributions at https://github.com/yarnpkg/yarn/releases/download' was added by unknown code