问:
Can you configure Camel Saga compensation retries?
Given this saga definition:

```<code>from("direct:bookTrip")
  .saga(
    .setHeader("id", header(Exchange.TIMER_COUNTER))
    .setHeader(Exchange.HTTP_METHOD, constant("POST"))
    .log("Executing saga #${header.id}")
    .to("http4://camel-saga-train-service:8080/api/train/buy/seat")
    .to("http4://camel-saga-flight-service:8080/api/flight/buy");
</code>```
```<code>rest().post("/train/buy/seat")
  .param().type(RestParamType.header).name("id").required(true).endParam()
  .route()
  .saga()
     .propagation(SagaPropagation.MANDATORY)
       .option("id", header("id"))
       .compensation("http4://camel-saga-payment-service:8080/api/cancel&type=train")
       .log("Buying flight #${header.id}")
     .to("http4://camel-saga-payment-service:8080/api/pay?bridgeEndpoint=true&type=train")
     .log("Payment for train #${header.id} done");
</code>```
```<code>rest().post("/flight/buy")
  .param().type(RestParamType.header).name("id").required(true).endParam()
  .route()
  .saga()
     .propagation(SagaPropagation.MANDATORY)
       .option("id", header("id"))
       .compensation("http4://camel-saga-payment-service:8080/api/cancel&type=flight")
       .log("Buying flight #${header.id}")
     .to("http4://camel-saga-payment-service:8080/api/pay?bridgeEndpoint=true&type=flight")
     .log("Payment for flight #${header.id} done");
</code>```

Imagine the /flight/buy call failed, then the train compensation would be executed -> .compensation("http4://camel-saga-payment-service:8080/api/cancel&type=train")

Given that this is an HTTP call, the compensation invocation could fail. Is there a way to configure the number of retries and backoff period of the compensation process?

Currently it tries to compensate 5 times:

```<code> Exception thrown during compensation at xxx. Attempt 1 of 5
</code>```

Body:
Given this saga definition:

from("direct:bookTrip")
  .saga(
    .setHeader("id", header(Exchange.TIMER_COUNTER))
    .setHeader(Exchange.HTTP_METHOD, constant("POST"))
    .log("Executing saga #${header.id}")
    .to("http4://camel-saga-train-service:8080/api/train/buy/seat")
    .to("http4://camel-saga-flight-service:8080/api/flight/buy");

rest().post("/train/buy/seat")
  .param().type(RestParamType.header).name("id").required(true).endParam()
  .route()
  .saga()
     .propagation(SagaPropagation.MANDATORY)
       .option("id", header("id"))
       .compensation("http4://camel-saga-payment-service:8080/api/cancel&type=train")
       .log("Buying flight #${header.id}")
     .to("http4://camel-saga-payment-service:8080/api/pay?bridgeEndpoint=true&type=train")
     .log("Payment for train #${header.id} done");

rest().post("/flight/buy")
  .param().type(RestParamType.header).name("id").required(true).endParam()
  .route()
  .saga()
     .propagation(SagaPropagation.MANDATORY)
       .option("id", header("id"))
       .compensation("http4://camel-saga-payment-service:8080/api/cancel&type=flight")
       .log("Buying flight #${header.id}")
     .to("http4://camel-saga-payment-service:8080/api/pay?bridgeEndpoint=true&type=flight")
     .log("Payment for flight #${header.id} done");

Imagine the /flight/buy call failed, then the train compensation would be executed -> .compensation("http4://camel-saga-payment-service:8080/api/cancel&type=train")

Given that this is an HTTP call, the compensation invocation could fail. Is there a way to configure the number of retries and backoff period of the compensation process?

Currently it tries to compensate 5 times:

 Exception thrown during compensation at xxx. Attempt 1 of 5


来源: stackexchange

问:
concat a transposed dataframe to another dataframe and write it to a spreadsheet
I have a data frame looks like this:

```<code>Date    Demand  Forecast Error [Error]  Error%  Error^2
1       47
2       70
3       95
4       122     61       51    51       54     23
5       142     86       34    51       54     23
6       155     110      34    51       45     36
7       189     130      54    51       45     86
8       208     152
9       160     174
10    142       176
11      160
12      160
13      160
</code>```

and the df2 that looks like:

```<code>    Bias      MAPE      MAE        RMSE_rel
0   0.143709  0.273529  42.285714  43.198692
1  22.952381  0.273529   0.264758   0.270475

</code>```

the df2 would be transposed with new columns absulote,scaled to look like this:

```<code> df2.set_index('Bias').T
 df2.columns= ["Absulote", "Scaled"]
</code>```

```<code>           Absulote    Scaled
MAPE       0.273529  0.273529
MAE       42.285714  0.264758
RMSE_rel  43.198692  0.270475
</code>```

and there is no Bias

to Concatenate both I do this :

complete_df = pd.concat([df1, df2],axis=0, ignore_index=True)```
</div>
</div>
</p>
<p>I get this result:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    Demand    Forecast      Error   Absulote    Scaled
0     47.0         NaN        NaN        NaN       NaN
1     70.0         NaN        NaN        NaN       NaN
2     95.0         NaN        NaN        NaN       NaN
3    122.0   70.666667  51.333333        NaN       NaN
4    142.0   95.666667  46.333333        NaN       NaN
5    155.0  119.666667  35.333333        NaN       NaN
6    189.0  139.666667  49.333333        NaN       NaN
7    208.0  162.000000  46.000000        NaN       NaN
8    160.0  184.000000 -24.000000        NaN       NaN
9    142.0  185.666667 -43.666667        NaN       NaN
10     NaN  170.000000        NaN        NaN       NaN
11     NaN         NaN        NaN        NaN       NaN
12     NaN         NaN        NaN        NaN       NaN
13     NaN         NaN        NaN        NaN       NaN
14     NaN         NaN        NaN   0.273529  0.273529
15     NaN         NaN        NaN  42.285714  0.264758
16     NaN         NaN        NaN  43.198692  0.270475</code>```

there is no Bias MAPE MAE RMSE_rel

I want the result to imitate the following :

is there anyway to achieve that?

ContentLicense: CC BY-SA 4.0

Body:
I have a data frame looks like this:

Date    Demand  Forecast Error [Error]  Error%  Error^2
1       47
2       70
3       95
4       122     61       51    51       54     23
5       142     86       34    51       54     23
6       155     110      34    51       45     36
7       189     130      54    51       45     86
8       208     152
9       160     174
10    142       176
11      160
12      160
13      160

and the df2 that looks like:

    Bias      MAPE      MAE        RMSE_rel
0   0.143709  0.273529  42.285714  43.198692
1  22.952381  0.273529   0.264758   0.270475

the df2 would be transposed with new columns absulote,scaled to look like this:

 df2.set_index('Bias').T
 df2.columns= ["Absulote", "Scaled"]

           Absulote    Scaled
MAPE       0.273529  0.273529
MAE       42.285714  0.264758
RMSE_rel  43.198692  0.270475

and there is no Bias

to Concatenate both I do this :

complete_df = pd.concat([df1, df2],axis=0, ignore_index=True)

I get this result:

    Demand    Forecast      Error   Absulote    Scaled
0     47.0         NaN        NaN        NaN       NaN
1     70.0         NaN        NaN        NaN       NaN
2     95.0         NaN        NaN        NaN       NaN
3    122.0   70.666667  51.333333        NaN       NaN
4    142.0   95.666667  46.333333        NaN       NaN
5    155.0  119.666667  35.333333        NaN       NaN
6    189.0  139.666667  49.333333        NaN       NaN
7    208.0  162.000000  46.000000        NaN       NaN
8    160.0  184.000000 -24.000000        NaN       NaN
9    142.0  185.666667 -43.666667        NaN       NaN
10     NaN  170.000000        NaN        NaN       NaN
11     NaN         NaN        NaN        NaN       NaN
12     NaN         NaN        NaN        NaN       NaN
13     NaN         NaN        NaN        NaN       NaN
14     NaN         NaN        NaN   0.273529  0.273529
15     NaN         NaN        NaN  42.285714  0.264758
16     NaN         NaN        NaN  43.198692  0.270475

there is no Bias MAPE MAE RMSE_rel

I want the result to imitate the following :

is there anyway to achieve that?


问:
Unexpected format when using fieldresolver from type-graphql with typegoose
The structure of my user object returned from typegoose is unexpected.

@Resolver((of) => User)
export class UserResolver {
  @FieldResolver(() => String, { nullable: true })
  email(@Root() user: User, @Ctx() { req }: MyContext) {
    console.log(user); // This returns an object that is not expected

    // user.id is not defined here. It is defined as user._doc._id
    if (req.session.userId && req.session.userId === user.id) {
      // This is the current user and it is okay to show them their own email
      return user.email;
    }

    // Current user wants to see someone elses email
    return null;
  }
}
```
<p>The user is returned in the following format.</p>
```User {
  '$__': InternalCache {
    activePaths: StateMachine { paths: [Object], states: [Object] },
    skipId: true
  },
  '$isNew': false,
  _doc: {
    _id: new ObjectId("6390c30fedf888da24803ee2"),
    email: 'test@test.com',
    username: 'test_username',
    emailConfirmed: false,
    password: '$argon2id$v=19$m=65536,t=3,p=4$ulYnFAqZVg3RGgFOVZHjMQ$sYIHnbxmIP710T3CcEZm2mToM+XsjzqCBI1Lr71+apI',
    lastPasswordReset: 2022-12-07T21:11:54.957Z,
    createdAt: 2022-12-07T16:45:03.827Z,
    updatedAt: 2022-12-07T21:11:54.961Z,
    __v: 0
  }
}
```
<p>I want it to return a mongoose model where I can access the id in such a manner as user.id</p>
<p>Does anyone have an idéa what I am doing wrong?</p>
<p>Edit:</p>
<p>The expected format of user</p>
```{
  id: "6390c30fedf888da24803ee2",
  email: "test@test.com",
  username: "test_username",
  emailConfirmed: false
}
```

Body:
The structure of my user object returned from typegoose is unexpected.

@Resolver((of) => User)
export class UserResolver {
  @FieldResolver(() => String, { nullable: true })
  email(@Root() user: User, @Ctx() { req }: MyContext) {
    console.log(user); // This returns an object that is not expected

    // user.id is not defined here. It is defined as user._doc._id
    if (req.session.userId && req.session.userId === user.id) {
      // This is the current user and it is okay to show them their own email
      return user.email;
    }

    // Current user wants to see someone elses email
    return null;
  }
}

The user is returned in the following format.

User {
  '$__': InternalCache {
    activePaths: StateMachine { paths: [Object], states: [Object] },
    skipId: true
  },
  '$isNew': false,
  _doc: {
    _id: new ObjectId("6390c30fedf888da24803ee2"),
    email: 'test@test.com',
    username: 'test_username',
    emailConfirmed: false,
    password: '$argon2id$v=19$m=65536,t=3,p=4$ulYnFAqZVg3RGgFOVZHjMQ$sYIHnbxmIP710T3CcEZm2mToM+XsjzqCBI1Lr71+apI',
    lastPasswordReset: 2022-12-07T21:11:54.957Z,
    createdAt: 2022-12-07T16:45:03.827Z,
    updatedAt: 2022-12-07T21:11:54.961Z,
    __v: 0
  }
}

I want it to return a mongoose model where I can access the id in such a manner as user.id

Does anyone have an idéa what I am doing wrong?

Edit:

The expected format of user

{
  id: "6390c30fedf888da24803ee2",
  email: "test@test.com",
  username: "test_username",
  emailConfirmed: false
}


问:
On appear doesn't trigger every time
I have problem because on appear modifier doesn't call every time when I enter the screen and it calls randomly (when on appear is applied to navigation view). When I put it on some view inside navigation view it never calls. What is the problem, I can't solve it, this is very strange behaviour. This is the view:

```<code>struct CheckListView: View {

@EnvironmentObject var appState: AppState
@StateObject var checkListViewModel = CheckListViewModel()
//@State var didSelectCreateNewList = false
@State var didSelectShareList = false

var body: some View {
    NavigationView {
        GeometryReader { reader in
            VStack {
                Spacer()
                    .frame(height: 30)

                Text("\(appState.hikingTypeModel.name)/\(appState.lengthOfStayType.name)")
                    .foregroundColor(Color("rectBackground"))
                    .multilineTextAlignment(.center)
                    .font(.largeTitle)

                Spacer()
                    .frame(height: 40)

                List {
                    ForEach(checkListViewModel.checkListModel.sections) { section in
                        CheckListSection(model: section)
                            .listRowBackground(Color("background"))
                    }
                }
                .listStyle(.plain)
                .clearListBackground()
                .clipped()

                Spacer()
                    .frame(height: 40)

                HStack {
                    FilledRectangleBorderButtonView(titleLabel: "Share", backgroundColor: Color("rectBackground"),foregroundColor: .white, height: 55, didActionOnButtonHappened: $didSelectShareList)

                    Spacer()

                    FilledRectangleBorderButtonView(titleLabel: "Create new list", backgroundColor: .clear, foregroundColor: Color("rectBackground"), height: 55, didActionOnButtonHappened: $checkListViewModel.didSelectNewList)
                        .onChange(of: checkListViewModel.didSelectNewList) { _ in
                            UserDefaultsHelper().emptyUserDefaults()
                            appState.moveToRootView = .createNewList
                        }
                }
                .padding([.leading, .trailing], 20)
                .frame(width: reader.size.width)

                Spacer()

            }
            .frame(width: reader.size.width, height: reader.size.height)
            .background(Color("background"))
            .navigationBarStyle()
        }
    }
    .onAppear {
        self.checkListViewModel.loadJSON(hikingTypeId: appState.hikingTypeModel.id, lengthStayId: appState.lengthOfStayType.id)
    }
}
</code>```

}

Title: On appear doesn't trigger every time

Body:
I have problem because on appear modifier doesn't call every time when I enter the screen and it calls randomly (when on appear is applied to navigation view). When I put it on some view inside navigation view it never calls. What is the problem, I can't solve it, this is very strange behaviour. This is the view:

struct CheckListView: View {

@EnvironmentObject var appState: AppState
@StateObject var checkListViewModel = CheckListViewModel()
//@State var didSelectCreateNewList = false
@State var didSelectShareList = false

var body: some View {
    NavigationView {
        GeometryReader { reader in
            VStack {
                Spacer()
                    .frame(height: 30)

                Text("\(appState.hikingTypeModel.name)/\(appState.lengthOfStayType.name)")
                    .foregroundColor(Color("rectBackground"))
                    .multilineTextAlignment(.center)
                    .font(.largeTitle)

                Spacer()
                    .frame(height: 40)

                List {
                    ForEach(checkListViewModel.checkListModel.sections) { section in
                        CheckListSection(model: section)
                            .listRowBackground(Color("background"))
                    }
                }
                .listStyle(.plain)
                .clearListBackground()
                .clipped()

                Spacer()
                    .frame(height: 40)

                HStack {
                    FilledRectangleBorderButtonView(titleLabel: "Share", backgroundColor: Color("rectBackground"),foregroundColor: .white, height: 55, didActionOnButtonHappened: $didSelectShareList)

                    Spacer()

                    FilledRectangleBorderButtonView(titleLabel: "Create new list", backgroundColor: .clear, foregroundColor: Color("rectBackground"), height: 55, didActionOnButtonHappened: $checkListViewModel.didSelectNewList)
                        .onChange(of: checkListViewModel.didSelectNewList) { _ in
                            UserDefaultsHelper().emptyUserDefaults()
                            appState.moveToRootView = .createNewList
                        }
                }
                .padding([.leading, .trailing], 20)
                .frame(width: reader.size.width)

                Spacer()

            }
            .frame(width: reader.size.width, height: reader.size.height)
            .background(Color("background"))
            .navigationBarStyle()
        }
    }
    .onAppear {
        self.checkListViewModel.loadJSON(hikingTypeId: appState.hikingTypeModel.id, lengthStayId: appState.lengthOfStayType.id)
    }
}

}


问:
Overseer sending a blank message on discord when new movie / Tv has been added to plex
I have overseerr set up to send a message on discord when a movie / Tv show is available on plex. A few months back it stopped working, just had not had time to look into it. This is the default json in overseerr

```<code>{
"notification_type": "{{notification_type}}",
"event": "{{event}}",
"subject": "{{subject}}",
"message": "{{message}}",
"image": "{{image}}",
"{{media}}": {
    "media_type": "{{media_type}}",
    "tmdbId": "{{media_tmdbid}}",
    "tvdbId": "{{media_tvdbid}}",
    "status": "{{media_status}}",
    "status4k": "{{media_status4k}}"
},
"{{request}}": {
    "request_id": "{{request_id}}",
    "requestedBy_email": "{{requestedBy_email}}",
    "requestedBy_username": "{{requestedBy_username}}",
    "requestedBy_avatar": "{{requestedBy_avatar}}"
},
"{{issue}}": {
    "issue_id": "{{issue_id}}",
    "issue_type": "{{issue_type}}",
    "issue_status": "{{issue_status}}",
    "reportedBy_email": "{{reportedBy_email}}",
    "reportedBy_username": "{{reportedBy_username}}",
    "reportedBy_avatar": "{{reportedBy_avatar}}"
},
"{{comment}}": {
    "comment_message": "{{comment_message}}",
    "commentedBy_email": "{{commentedBy_email}}",
    "commentedBy_username": "{{commentedBy_username}}",
    "commentedBy_avatar": "{{commentedBy_avatar}}"
},
"{{extra}}": []
</code>```

}

In the logs, I see this error code 400 and 50006

Can anyone advise on how to fix the code? Many thanks

Body:
I have overseerr set up to send a message on discord when a movie / Tv show is available on plex. A few months back it stopped working, just had not had time to look into it. This is the default json in overseerr

{
"notification_type": "{{notification_type}}",
"event": "{{event}}",
"subject": "{{subject}}",
"message": "{{message}}",
"image": "{{image}}",
"{{media}}": {
    "media_type": "{{media_type}}",
    "tmdbId": "{{media_tmdbid}}",
    "tvdbId": "{{media_tvdbid}}",
    "status": "{{media_status}}",
    "status4k": "{{media_status4k}}"
},
"{{request}}": {
    "request_id": "{{request_id}}",
    "requestedBy_email": "{{requestedBy_email}}",
    "requestedBy_username": "{{requestedBy_username}}",
    "requestedBy_avatar": "{{requestedBy_avatar}}"
},
"{{issue}}": {
    "issue_id": "{{issue_id}}",
    "issue_type": "{{issue_type}}",
    "issue_status": "{{issue_status}}",
    "reportedBy_email": "{{reportedBy_email}}",
    "reportedBy_username": "{{reportedBy_username}}",
    "reportedBy_avatar": "{{reportedBy_avatar}}"
},
"{{comment}}": {
    "comment_message": "{{comment_message}}",
    "commentedBy_email": "{{commentedBy_email}}",
    "commentedBy_username": "{{commentedBy_username}}",
    "commentedBy_avatar": "{{commentedBy_avatar}}"
},
"{{extra}}": []

}

In the logs, I see this error code 400 and 50006

Can anyone advise on how to fix the code? Many thanks


问:
Django - Keep data filtered trough the duration of the session using django-filters
I have a view that lists all data from a model with a form that enables filtering using the django-filters library. The view also stores the filtered data in the session, inside the form_data variable. The view:

```<code>def list_accsplan(request):
    accsplan = AccountsPlan.objects.all().order_by('code')
    accsplanfilter = AccountsPlanFilter(request.GET, queryset=accsplan)

    request.session['form_data'] = accsplanfilter.data
    form_data = request.session.get('form_data')

    paginator = Paginator(accsplanfilter.qs, 30)
    page = request.GET.get('page')

    try:
        dataqs = paginator.page(page)
    except PageNotAnInteger:
        dataqs = paginator.page(1)
    except EmptyPage:
        dataqs = paginator.page(paginator.num_pages)

    return render(request, 'confi/pages/accounts_plan/list_accsplan.html', context={
        'accsplan': accsplan,
        'accsplanfilter': accsplanfilter,
        'dataqs': dataqs,
    })
</code>```

The filter form is this:

```<code>class AccountsPlanFilter(django_filters.FilterSet):

    accplantype = ChoiceFilter(choices=AccountsPlan.AccPlanType.choices, field_name='accplantype',)
    code = CharFilter(field_name='code', lookup_expr='icontains',)
    name = CharFilter(field_name='name', lookup_expr='icontains',)
    active = BooleanFilter(field_name='active', widget=CustomBooleanWidget,)

    class Meta:
        model = AccountsPlan
        fields = '__all__'
</code>```

What I want is to keep this list filtered as long as the session is active, even if the user changes pages and then get back to this one, but I'm stuck in how to do this.

I tried to add an if statement in the view like this:

```<code>if form_data:
    accsplan = AccountsPlan.objects.filter(**form_data)
    accsplanfilter = AccountsPlanFilter(request.GET, queryset=accsplan)
</code>```

But I receive this ValidationError in the list:

ValidationError at /list_accsplan/
["the value “['true']”  must be True ou False."]

I was thinking that this was because I didn't filter the active field, but even selecting one gives me this error. How can I pass these parameters to the view and keep the filters applied as long as the session is active? Thanks!

Body:
I have a view that lists all data from a model with a form that enables filtering using the django-filters library. The view also stores the filtered data in the session, inside the form_data variable. The view:

def list_accsplan(request):
    accsplan = AccountsPlan.objects.all().order_by('code')
    accsplanfilter = AccountsPlanFilter(request.GET, queryset=accsplan)

    request.session['form_data'] = accsplanfilter.data
    form_data = request.session.get('form_data')

    paginator = Paginator(accsplanfilter.qs, 30)
    page = request.GET.get('page')

    try:
        dataqs = paginator.page(page)
    except PageNotAnInteger:
        dataqs = paginator.page(1)
    except EmptyPage:
        dataqs = paginator.page(paginator.num_pages)

    return render(request, 'confi/pages/accounts_plan/list_accsplan.html', context={
        'accsplan': accsplan,
        'accsplanfilter': accsplanfilter,
        'dataqs': dataqs,
    })

The filter form is this:

class AccountsPlanFilter(django_filters.FilterSet):

    accplantype = ChoiceFilter(choices=AccountsPlan.AccPlanType.choices, field_name='accplantype',)
    code = CharFilter(field_name='code', lookup_expr='icontains',)
    name = CharFilter(field_name='name', lookup_expr='icontains',)
    active = BooleanFilter(field_name='active', widget=CustomBooleanWidget,)

    class Meta:
        model = AccountsPlan
        fields = '__all__'

What I want is to keep this list filtered as long as the session is active, even if the user changes pages and then get back to this one, but I'm stuck in how to do this.

I tried to add an if statement in the view like this:

if form_data:
    accsplan = AccountsPlan.objects.filter(**form_data)
    accsplanfilter = AccountsPlanFilter(request.GET, queryset=accsplan)

But I receive this ValidationError in the list:

ValidationError at /list_accsplan/
["the value “['true']”  must be True ou False."]

I was thinking that this was because I didn't filter the active field, but even selecting one gives me this error. How can I pass these parameters to the view and keep the filters applied as long as the session is active? Thanks!


问:
NASM Assembler, comparing two 1-char strings with EAX dword compare doesn't jump
I'm just trying to compare 2 values and I think the syntax is correct but it doesn't work, same goes with integer.

```<code>%include "asm_io.inc"

segment .data
    msg_fail        db  "wrong", 0
    msg_success     db  "right", 0
    value1          db  "A", 0
    value2          db  "z", 0

segment .bss

segment .text
    global  asm_main

asm_main:

    enter   0,0
    pusha

    mov eax, [value1]

    cmp eax, [value2]
    je next

next:
    mov eax, msg_fail
    call print_string

    popa
    mov     eax, 0
    leave
    ret
</code>```

I expect that the program does nothing, since A and z are not equal but it always prints the message. I'm starting to get desperate

Body:
I'm just trying to compare 2 values and I think the syntax is correct but it doesn't work, same goes with integer.

%include "asm_io.inc"

segment .data
    msg_fail        db  "wrong", 0
    msg_success     db  "right", 0
    value1          db  "A", 0
    value2          db  "z", 0

segment .bss

segment .text
    global  asm_main

asm_main:

    enter   0,0
    pusha

    mov eax, [value1]

    cmp eax, [value2]
    je next

next:
    mov eax, msg_fail
    call print_string

    popa
    mov     eax, 0
    leave
    ret

I expect that the program does nothing, since A and z are not equal but it always prints the message. I'm starting to get desperate


问:
Use Tailwindcss classes in Ruby Gems
I am working on externalizing some of an app's functionality, so that we can use it across multiple apps. The functionality in question contains several ViewComponent's that use TailwindCSS for CSS. These CSS classes work as expected when the files are contained internal to the app, but fail to be loaded when the files are externally contained in the gem. Likely due to them now being external to the TailwindCSS config's content.

The methods I have tried are:

Including CSS through an Engine in the gem as mentioned in this blog

Safelisting classes which works, but requires that the end user add all required classes into the main app. I am hoping for a more dynamic approach to avoid hard coding classes.

Following the Third-Party library instructions to attempt to hack together a Gem way of dynamically adding the files to content. (Can be linked to via Github if that is an option)

Most promising to me seems to be the third-party options, which unfortunately caters to NPM packages, while I am trying to do the same with a Ruby gem. Any pointers on including via a link for dynamically loading the classes would be appreciated!

Title: Use Tailwindcss classes in Ruby Gems


问:
SwiftUI Line Graphs in iOS 15
How can I make a graph like this with SwiftUI in iOS 15, I know the Charts library is a great way but those are only available in iOS 16+. Is there a native way to make a chart like this? (no third party libraries)

The dots + labels should adjust with a slider value.

Title: SwiftUI Line Graphs in iOS 15


问:
How to merge queryset multiple dictionaries with common date value(not key) in django?
I have result queryset dictionaries like this.

```<code><QuerySet [
    {'tags__name': 'Mobile', 'month': datetime.datetime(2022, 11, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>), 'tags_count': 5, 'price_avg': Decimal('120.400000'), 'price_sum': Decimal('602.00'), 'fee_sum': Decimal('17.01')},
    {'tags__name': 'Device', 'month': datetime.datetime(2022, 11, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>), 'tags_count': 5, 'price_avg': Decimal('120.400000'), 'price_sum': Decimal('602.00'), 'fee_sum': Decimal('17.01')},
    {'tags__name': 'Device', 'month': datetime.datetime(2022, 12, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>), 'tags_count': 3, 'price_avg': Decimal('311.000000'), 'price_sum': Decimal('933.00'), 'fee_sum': Decimal('27.99')},
    {'tags__name': 'Mobile', 'month': datetime.datetime(2022, 12, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>), 'tags_count': 3, 'price_avg': Decimal('311.000000'), 'price_sum': Decimal('933.00'), 'fee_sum': Decimal('27.99')}
]>
</code>```

I want result like this

```<code>{'Mobile': 1,'Device': 1, 'month': datetime.datetime(2022, 11, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>), 'price_avg': Decimal('120.400000'), 'price_sum': Decimal('602.00'), 'fee_sum': Decimal('17.01')}
{'Mobile': 1,'Device': 1, 'month': datetime.datetime(2022, 12, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>), 'price_avg': Decimal('311.000000'), 'price_sum': Decimal('933.00'), 'fee_sum': Decimal('27.99')}
</code>```

Any help will be appreciated.

Body:
I have result queryset dictionaries like this.

<QuerySet [
    {'tags__name': 'Mobile', 'month': datetime.datetime(2022, 11, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>), 'tags_count': 5, 'price_avg': Decimal('120.400000'), 'price_sum': Decimal('602.00'), 'fee_sum': Decimal('17.01')},
    {'tags__name': 'Device', 'month': datetime.datetime(2022, 11, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>), 'tags_count': 5, 'price_avg': Decimal('120.400000'), 'price_sum': Decimal('602.00'), 'fee_sum': Decimal('17.01')},
    {'tags__name': 'Device', 'month': datetime.datetime(2022, 12, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>), 'tags_count': 3, 'price_avg': Decimal('311.000000'), 'price_sum': Decimal('933.00'), 'fee_sum': Decimal('27.99')},
    {'tags__name': 'Mobile', 'month': datetime.datetime(2022, 12, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>), 'tags_count': 3, 'price_avg': Decimal('311.000000'), 'price_sum': Decimal('933.00'), 'fee_sum': Decimal('27.99')}
]>

I want result like this

{'Mobile': 1,'Device': 1, 'month': datetime.datetime(2022, 11, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>), 'price_avg': Decimal('120.400000'), 'price_sum': Decimal('602.00'), 'fee_sum': Decimal('17.01')}
{'Mobile': 1,'Device': 1, 'month': datetime.datetime(2022, 12, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>), 'price_avg': Decimal('311.000000'), 'price_sum': Decimal('933.00'), 'fee_sum': Decimal('27.99')}

Any help will be appreciated.


问:
Angular dynamically change assets location
I am creating an Angular application that is used in Electron, and it has access to the users filesystem. The user will create a project within the app which will load files through http. When the project changes, so does the static files location, so is there a way to tell angular where the static files for the project are located as the user switches between projects? I don't think this is supported in Angular's angular.json file.

Is there a way to do this without having to write my own http server?

Note: The request are made from threejs which doesn't use the HttpClient service.


问:
Is there a performance hit by running OpenJDK 17 in debug mode in a container before a debugger is attached?
We are consolidating and updating our Java deployments, and in that process we would like to be prepared for having to find non-reproducible problems with a running JVM in a container, by having the JVM start in server debug mode (and with Flight Recorder active so we currently do not want J9), where the JVM runs the application while awaiting a debugger connecting.

I believe I have read years back that JVM debug performance had been improved, but I have not been able to located information about how things are now, and whether this might be distribution specific.

Would this perform as well as a JVM not running in debug mode for OpenJDK 17?


问:
Git Gui on Windows: couldn't open ".git/PREPARE_COMMIT_MSG": permission denied
Been using Git Gui on Windows on a work computer for over two years now. Last night the repo was working fine, but this morning after a reboot, Git Gui pops up a message about "permission denied".

No idea what changed, although we did get an email saying that a corporate antivirus update had been pushed out which required a reboot. Also, a Windows update for December 2022 was installed on my machine which also required a reboot.

The full error message is:

```<code>couldn't open ".git/PREPARE_COMMIT_MSG": permission denied
couldn't open ".git/PREPARE_COMMIT_MSG": permission denied
    while executing
"open [gitdir PREPARE_COMMIT_MSG] a"
    (procedure "run_prepare_commit_msg_hook" line 8)
    invoked from within
"run_prepare_commit_msg_hook"
    (procedure "rescan" line 27)
    invoked from within
"rescan ui_ready"
    (procedure "do_rescan" line 2)
    invoked from within
"do_rescan"
    ("after" script)
</code>```

Things I have tried:

Based on suggestions in threads with similar "permission denied" errors, I ran the follow from a command prompt:

icacls "path\to\Work.git" /grant MyUserName:(OI)(CI)F /T

The command executed without errors, but no change to the repo.

Ran Git Bash (MINGW64) which runs without any immediate errors but only git status works. git add gives the error fatal: Unable to create '/path/to/Work/.git/index.lock': Permission denied

Tried a separate, personal, repo on the same work computer for a repo hosted on github.com. That worked fine (can commit, pull, etc.).

Any thoughts? My user account is part of the Administrators group, but it looks like the Windows and "corporate anti-virus" updates have modified or blocked something to do with my user account.

UPDATE 1

Rebooted Windows into Safe Mode. Now I can git add and git commit, though git push fails due to a failure to resolve dev.azure.com (something to do with the network not loaded in Safe Mode). Rebooted back into normal Windows and the problem returns: git add and other commands fail immediately and git push finds dev.azure.com but I get a permission denied error.

UPDATE 2

Based on the comments from @LeGEC, I checked the repo .git folder. There is no PREPRE_COMMIT_MESSAGE or index.lock file. The permissions haven't been touched by me, but after explicitly allowing my user "Full Control" over the folder, its still not working - still "permission denied" errors.

A colleague does not use Git for Windows, and was not having issues after the recent update. He suggested I try Visual Studio (which is tied directly into dev.azure.com)...and git works from Visual Studio 2019!

So we think that recent anti-virus or group policy changes has revoked, blocked or broken authentication of my user (presumably) connecting to the corporate network's and/or dev.azure.com. Somehow Visual Studio is able to authenticate me (through the Mcicrosoft Azure account?) which fails when using my Windows account....does that make sense?

Will update this question as and when I find out more details.

If anyone has seen this type of thing before (suddenly one application stops working with git with "permission denied" errors, while another works), your input would be appreciated!

Body:
Been using Git Gui on Windows on a work computer for over two years now. Last night the repo was working fine, but this morning after a reboot, Git Gui pops up a message about "permission denied".

No idea what changed, although we did get an email saying that a corporate antivirus update had been pushed out which required a reboot. Also, a Windows update for December 2022 was installed on my machine which also required a reboot.

The full error message is:

couldn't open ".git/PREPARE_COMMIT_MSG": permission denied
couldn't open ".git/PREPARE_COMMIT_MSG": permission denied
    while executing
"open [gitdir PREPARE_COMMIT_MSG] a"
    (procedure "run_prepare_commit_msg_hook" line 8)
    invoked from within
"run_prepare_commit_msg_hook"
    (procedure "rescan" line 27)
    invoked from within
"rescan ui_ready"
    (procedure "do_rescan" line 2)
    invoked from within
"do_rescan"
    ("after" script)

Things I have tried:

Based on suggestions in threads with similar "permission denied" errors, I ran the follow from a command prompt:

icacls "path\to\Work.git" /grant MyUserName:(OI)(CI)F /T

The command executed without errors, but no change to the repo.

Ran Git Bash (MINGW64) which runs without any immediate errors but only git status works. git add gives the error fatal: Unable to create '/path/to/Work/.git/index.lock': Permission denied

Tried a separate, personal, repo on the same work computer for a repo hosted on github.com. That worked fine (can commit, pull, etc.).

Any thoughts? My user account is part of the Administrators group, but it looks like the Windows and "corporate anti-virus" updates have modified or blocked something to do with my user account.

UPDATE 1

Rebooted Windows into Safe Mode. Now I can git add and git commit, though git push fails due to a failure to resolve dev.azure.com (something to do with the network not loaded in Safe Mode). Rebooted back into normal Windows and the problem returns: git add and other commands fail immediately and git push finds dev.azure.com but I get a permission denied error.

UPDATE 2

Based on the comments from @LeGEC, I checked the repo .git folder. There is no PREPRE_COMMIT_MESSAGE or index.lock file. The permissions haven't been touched by me, but after explicitly allowing my user "Full Control" over the folder, its still not working - still "permission denied" errors.

A colleague does not use Git for Windows, and was not having issues after the recent update. He suggested I try Visual Studio (which is tied directly into dev.azure.com)...and git works from Visual Studio 2019!

So we think that recent anti-virus or group policy changes has revoked, blocked or broken authentication of my user (presumably) connecting to the corporate network's and/or dev.azure.com. Somehow Visual Studio is able to authenticate me (through the Mcicrosoft Azure account?) which fails when using my Windows account....does that make sense?

Will update this question as and when I find out more details.

If anyone has seen this type of thing before (suddenly one application stops working with git with "permission denied" errors, while another works), your input would be appreciated!


问:
NFC Tag emulated by Android phone triggers Apple Wallet
I am working on an android app that emulates NFC Tag (HCE Host-Card Emulation), so other devices can read NDEF messages. Whenever if I approach the android device to iPhone, it sometimes shows the Apple Wallet app automatically. Basic NFC tags do not trigger Apple Wallet. Is there any way to prevent showing Apple Wallet by HCE? How can I change this behavior?

Update:

Any NFC available android phone can trigger Apple Wallet if NFC functionality is enabled and approach to iPhone (without emulation of HCE, just an android phone itself).


问:
What happens when my go.mod version is newer than the golang version of the container image im using?
I've got a pipeline that runs "go build" in one of the jobs. The go.mod file in our project contains "go 1.18" but the container the "go build" is being executed in is using a golang 1.17 image. I'm curious what happens in this scenario? The build works fine but I'm curious if it's actually compiling to go 1.18 or is it only compiling to 1.17 and just not giving a warning or making it obvious there's a mismatch between go.mod and the container image version? What, if any, problems would be caused by mismatching the container image version and the go.mod version?

I'm not even sure what to try or what to be looking for here. Several developer peers didn't know the answer but were interested in what i find out, and google didn't help either.


问:
Bypassing skip restrictions
So I've been watching a course on a site(gov site)... and I already know everything about the stuff mentioned in it, I want to skip the video timings and jump to any part, as I have to submit the certificate to my teacher tomorrow, but its giving me restrictionsPutting an image for the same

I tried inspecting it, but couldnt find anything related to that block/restriction

Title: Bypassing skip restrictions


问:
Express App, diagnosing latency spikes in EC2 instances in Beanstalk
We have a medium-sized Express API that performs well as long as incoming traffic is relatively stable, but when there is a quick uptick in requests, the latency has a tendency to briefly shoot through the roof.

You can see in this image 3 latency spikes that clearly correlate to incoming traffic spikes.

enter image description here

The app is perfectly capable of handling a larger sum of requests with low latency, it is just when  there is a spike that this happens.

Also of note, the DB does not struggle or show any correlating spikes at all, and the CPU usage is only moderately affected, rarely going much above 50%-60% even at peak times.

Load-testing shows same issues, whether on local machine or against another AWS QA environment, so probably not related to network.

Given that the DB and CPU are rarely chugging to process requests, and given that the app performs well under higher traffic amounts (reqs fulfilled in <100ms), how would you go about diagnosing the root cause specific issue we have here with traffic spikes?

We have tried pinpointing poorly performing code bottlenecks, but the savings have been negligible. We have engaged with our devops folks to see if there were some options to smooth this out with config changes, but efforts to give us larger instances and adjust auto-scaling haven't really helped this particular problem.

Here's hoping seasoned eyes can give us some clues, assumption is still that there is some code improvements that will help, maybe this is a typical issue in node/express apps. Happy to give additional details, thx in advance.


问:
How check two tables content in two instance are same or not?

The Problem Description

I have two similar databases (MySQL) on two machines with a table with exactly the same structure. The order of  data insertion can be different, but the final table contents must be the same except for the order of rows.

Table structur

#
Column
Type
Info

1
old_id
int(11)
unsigned, primary key, not null

2
new_id
int(11)
unsigned, primary key, not null

The unsuccessful solution

I tried this query to get the MD5 checksum of all records to be able to compare the result of each database:

SELECT
    MD5(GROUP_CONCAT(CONCAT(`new_id`,':', `old_id`)))
FROM `maptable`
ORDER BY `new_id`,`old_id`

```
<p>But there is a problem here. The checksum does not change even when I filter some rows. For example:</p>
<pre class="lang-sql prettyprint-override"><code>
SELECT
    MD5(GROUP_CONCAT(CONCAT(`new_id`, `old_id`)))
FROM `maptable`
WHERE mod(`new_id`, 2) = 0
ORDER BY `new_id`,`old_id`

</code>```

Questions

Why does it not work? Is that because of the size of the GROUP_CONCAT() result? (the tables have about one million rows)

Do you have any simple query to get a checksum of the table content to check if the table content is the same? (I do not want to use Python, PHP, or any other programs to fetch the rows and make checksum.)

Body:
The Problem Description

I have two similar databases (MySQL) on two machines with a table with exactly the same structure. The order of  data insertion can be different, but the final table contents must be the same except for the order of rows.

Table structur

#
Column
Type
Info

1
old_id
int(11)
unsigned, primary key, not null

2
new_id
int(11)
unsigned, primary key, not null

The unsuccessful solution

I tried this query to get the MD5 checksum of all records to be able to compare the result of each database:

SELECT
    MD5(GROUP_CONCAT(CONCAT(`new_id`,':', `old_id`)))
FROM `maptable`
ORDER BY `new_id`,`old_id`

But there is a problem here. The checksum does not change even when I filter some rows. For example:

SELECT
    MD5(GROUP_CONCAT(CONCAT(`new_id`, `old_id`)))
FROM `maptable`
WHERE mod(`new_id`, 2) = 0
ORDER BY `new_id`,`old_id`

Questions

Why does it not work? Is that because of the size of the GROUP_CONCAT() result? (the tables have about one million rows)

Do you have any simple query to get a checksum of the table content to check if the table content is the same? (I do not want to use Python, PHP, or any other programs to fetch the rows and make checksum.)


问:
Error 1004 when trying to sort on key, sort reference not valid
When I run this sort, I am receiving the following error:

"Run-time Error '1004':

The Sort reference is not valid. Make sure that it's within the data you want to sort, and the first Sort BY box isn't the same or blank"

I had it running just find earlier, and have been testing a sub on the same data, I haven't changed anything but adding the xlheader option to yes. I have tried removing the header option to get the range working with no result.

I have tried defining the range specifically ("A:AL"), yet it still does not work for sht3 as it does for sht2

```<code>'Dim sht2 as worksheet, sht3 as worksheet

Set sht2 = thiswb.Sheets("Tracking Report")
Set sht3 = thiswb.Sheets("New Extract")

    'sorting block
        With sht3.Range("A1").CurrentRegion
            'secondary here
            .Sort Key1:=Range("A1"), Key2:=Range("C1"), Header:=xlYes
            'priority here
            .Sort Key1:=Range("M1"), Key2:=Range("D1"), Key3:=Range("I1"), Header:=xlYes
        End With
        With sht2.Range("A1").CurrentRegion
        'Errors on next line
            .Sort Key1:=Range("A1"), Key2:=Range("C1"), Header:=xlYes
            .Sort Key1:=Range("M1"), Key2:=Range("D1"), Key3:=Range("I1"), Header:=xlYes
        End With
</code>```

Body:
When I run this sort, I am receiving the following error:

"Run-time Error '1004':

The Sort reference is not valid. Make sure that it's within the data you want to sort, and the first Sort BY box isn't the same or blank"

I had it running just find earlier, and have been testing a sub on the same data, I haven't changed anything but adding the xlheader option to yes. I have tried removing the header option to get the range working with no result.

I have tried defining the range specifically ("A:AL"), yet it still does not work for sht3 as it does for sht2

'Dim sht2 as worksheet, sht3 as worksheet

Set sht2 = thiswb.Sheets("Tracking Report")
Set sht3 = thiswb.Sheets("New Extract")

    'sorting block
        With sht3.Range("A1").CurrentRegion
            'secondary here
            .Sort Key1:=Range("A1"), Key2:=Range("C1"), Header:=xlYes
            'priority here
            .Sort Key1:=Range("M1"), Key2:=Range("D1"), Key3:=Range("I1"), Header:=xlYes
        End With
        With sht2.Range("A1").CurrentRegion
        'Errors on next line
            .Sort Key1:=Range("A1"), Key2:=Range("C1"), Header:=xlYes
            .Sort Key1:=Range("M1"), Key2:=Range("D1"), Key3:=Range("I1"), Header:=xlYes
        End With


问:
Android ZoomControl layout
I'm testing my android app with espresso and want to test the ZoomControls like this:

```<code>onView(withId(R.id.zoomIn)).perform(click());
</code>```

But I don't get the zoomIn/zoomOut id, from the Zoom_Controls. In the Layout Component Tree, the zoomIn and zoomOut are visible.

Can someone help me?
Thanks in advance.

```<code>Resources res = Resources.getSystem();
int id = res.getIdentifier("btn_zoom_down", "drawable", "android");
</code>```

Didn't work.

Got it working with:

Resources res = Resources.getSystem();
int id = res.getIdentifier("@id/zoomOut", "drawable", "android");
onView(withId(id)).perform(click());
```

Title: Android ZoomControl layout

Body:
I'm testing my android app with espresso and want to test the ZoomControls like this:

onView(withId(R.id.zoomIn)).perform(click());

But I don't get the zoomIn/zoomOut id, from the Zoom_Controls. In the Layout Component Tree, the zoomIn and zoomOut are visible.

Can someone help me?
Thanks in advance.

Resources res = Resources.getSystem();
int id = res.getIdentifier("btn_zoom_down", "drawable", "android");

Didn't work.

Got it working with:

Resources res = Resources.getSystem();
int id = res.getIdentifier("@id/zoomOut", "drawable", "android");
onView(withId(id)).perform(click());


问:
Why is "log_source" field blank in logs sent to Splunk by fluentd?
Dashboards show zero log Volume in the Jfrog App for Splunk.  Looking at the query in Search pane, they contain "log_source" field which is consistently blank.  What field should be used and when will the JFrog app for Splunk be updated?

If this is the wrong place to ask question, please direct me to proper source. Thanks!

We're expecting the JFrog App for Splunk to show logs, we've installed it and aren't getting the metrics displayed that are otherwise available.


问:
Pynput keyboard listener not working on Macbook air M2
I have recently purchased a Macbook air M2. One python code that I have been successfully been using on my older Macbook air, doesn't longer work for some reason.

I receive this error message when trying to run the code in Spyder 5.3.3 through Anaconda, despite adding accessibility to Anaconda via System preferences:

This process is not trusted! Input event monitoring will not be possible until it is added to accessibility clients.

When trying to run the code via terminal I receive the following error:

zsh: segmentation fault ...

OS: MacOS Ventura 13.0.1

There shouldn't be problems with the code, but it seems there is some problem adding the correct accessibility? Does pynput not work on the latest Macbooks or is there some other reason to it not working?

The code:

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pyperclip
import os
import os.path
from pynput.keyboard import Key, Listener
from striprtf import striprtf
import re

def replace_words(string, dictionary):
    # sort keys by length, in reverse order
    for item in sorted(dictionary.keys(), key = len, reverse = True):
        string = re.sub(item, dictionary[item], string)
    return string

SAVE_FILE = input("Name of clipboard file: ")

save_path = "/Users/username/Clipboard"
FileName = os.path.join(save_path, SAVE_FILE+".txt")
f= open(FileName, "w")

def on_release(key):

    print("f")
    if str(key) == "'c'":
        print('Copying the slected')
        text = pyperclip.paste()  # text will have the content of clipboard
        print(text)
        text = striprtf(text)
        text = text.replace('\n\n', '\n')
        print(text)
        f.write(text+"\n")

    print('{0} release'.format(
        key))
    if key == Key.esc:
        print("End")
        return False

# Collect events until released
with Listener(
        on_release=on_release) as listener:
    listener.join()

f.close()
</code>```

Body:
I have recently purchased a Macbook air M2. One python code that I have been successfully been using on my older Macbook air, doesn't longer work for some reason.

I receive this error message when trying to run the code in Spyder 5.3.3 through Anaconda, despite adding accessibility to Anaconda via System preferences:

This process is not trusted! Input event monitoring will not be possible until it is added to accessibility clients.

When trying to run the code via terminal I receive the following error:

zsh: segmentation fault ...

OS: MacOS Ventura 13.0.1

There shouldn't be problems with the code, but it seems there is some problem adding the correct accessibility? Does pynput not work on the latest Macbooks or is there some other reason to it not working?

The code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pyperclip
import os
import os.path
from pynput.keyboard import Key, Listener
from striprtf import striprtf
import re

def replace_words(string, dictionary):
    # sort keys by length, in reverse order
    for item in sorted(dictionary.keys(), key = len, reverse = True):
        string = re.sub(item, dictionary[item], string)
    return string

SAVE_FILE = input("Name of clipboard file: ")

save_path = "/Users/username/Clipboard"
FileName = os.path.join(save_path, SAVE_FILE+".txt")
f= open(FileName, "w")

def on_release(key):

    print("f")
    if str(key) == "'c'":
        print('Copying the slected')
        text = pyperclip.paste()  # text will have the content of clipboard
        print(text)
        text = striprtf(text)
        text = text.replace('\n\n', '\n')
        print(text)
        f.write(text+"\n")

    print('{0} release'.format(
        key))
    if key == Key.esc:
        print("End")
        return False

# Collect events until released
with Listener(
        on_release=on_release) as listener:
    listener.join()

f.close()


问:
TailwindCSS Nesting not including media queries
I'm using tailwind CSS and would like to nest the entire tailwind CSS base/components/utilities code in a nested CSS class so that the code will be applied when used in children of the HTML elements inside that class

I know it's possible to use a prefix system instead, but I don't want to have to modify all html class attributes, so it's not an option for me.

main.css

```<code>.webapp {
   @tailwind base;
   @tailwind components;
   @tailwind utilities;
}
</code>```

I'm using the configuration from the official documentation https://tailwindcss.com/docs/using-with-preprocessors#nesting

postcss.config.js

```<code>module.exports = {
  plugins: {
    'postcss-import': {},
    'tailwindcss/nesting': {},
    tailwindcss: {},
    autoprefixer: {},
  }
}
</code>```

tailwind.config.js

```<code>module.exports = {
  content: [
    "../default/pages/*.html"
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
</code>```

cmd

```<code>tailwindcss --postcss -i  ./main.scss -o ./output.css --watch
</code>```

The problem is that, in output.css, the nesting of the node responsive css class is handled properly but not the media queries

output.css sample

```<code>.webapp button,
.webapp input,
.webapp optgroup,
.webapp select,
.webapp textarea {
    font-family: inherit;
    /* 1 */
    font-size: 100%;
    /* 1 */
    font-weight: inherit;
    /* 1 */
    line-height: inherit;
    /* 1 */
    color: inherit;
    /* 1 */
    margin: 0;
    /* 2 */
    padding: 0;
    /* 3 */
  }

@media (min-width: 1024px) {
  .lg\:static {
    position: static;
  }

  .lg\:bottom-0 {
    bottom: 0px;
  }
}
</code>```

The nesting of .webapp class is only working outside the @media. It's the same for .hover/ and .focus/ . I would need it to include everything to make it work.

Thanks for your help !

Body:
I'm using tailwind CSS and would like to nest the entire tailwind CSS base/components/utilities code in a nested CSS class so that the code will be applied when used in children of the HTML elements inside that class

I know it's possible to use a prefix system instead, but I don't want to have to modify all html class attributes, so it's not an option for me.

main.css

.webapp {
   @tailwind base;
   @tailwind components;
   @tailwind utilities;
}

I'm using the configuration from the official documentation https://tailwindcss.com/docs/using-with-preprocessors#nesting

postcss.config.js

module.exports = {
  plugins: {
    'postcss-import': {},
    'tailwindcss/nesting': {},
    tailwindcss: {},
    autoprefixer: {},
  }
}

tailwind.config.js

module.exports = {
  content: [
    "../default/pages/*.html"
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

cmd

tailwindcss --postcss -i  ./main.scss -o ./output.css --watch

The problem is that, in output.css, the nesting of the node responsive css class is handled properly but not the media queries

output.css sample

.webapp button,
.webapp input,
.webapp optgroup,
.webapp select,
.webapp textarea {
    font-family: inherit;
    /* 1 */
    font-size: 100%;
    /* 1 */
    font-weight: inherit;
    /* 1 */
    line-height: inherit;
    /* 1 */
    color: inherit;
    /* 1 */
    margin: 0;
    /* 2 */
    padding: 0;
    /* 3 */
  }

@media (min-width: 1024px) {
  .lg\:static {
    position: static;
  }

  .lg\:bottom-0 {
    bottom: 0px;
  }
}

The nesting of .webapp class is only working outside the @media. It's the same for .hover/ and .focus/ . I would need it to include everything to make it work.

Thanks for your help !


问:
ModuleNotFound Error on installed package in Jupyter Notebook environment
Using Python Jupyter notebooks to work in an environment I've created. Everything went fine until I decided to add another package to the environment. After setting up the environment, I was unable to import additional packages I installed in the environment. I was only able to import packages I installed on set-up.

Here are the commands I used to create the environment initially:

```<code>python -m venv test
. test/bin/activate

pip install pyodbc
deactivate

python3 -m ipykernel install --user --name test

</code>```

This all worked fine. I started a notebook using the new environment and was able to import pyodbc without error!
Then I decided I wanted to add another package, geopandas.

```<code>. test/bin/activate

pip install geopandas

deactivate

</code>```

I opened a notebook in the kernel and tried

```<code>import geopandas
</code>```
```<code>
ModuleNotFoundError                       Traceback (most recent call last)
/tmp/ipykernel_47903/1529612126.py in <module>
----> 1 import geopandas

ModuleNotFoundError: No module named 'geopandas'

</code>```

I then attempted linking it to ipykernel again

```<code>python3 -m ipykernel install --user --name test

</code>```

But I still received the same error in the notebook and was unable to import the package. How can I add more packages to an environment after already establishing it? I'm not sure what I'm doing wrong. Thank you!

Body:
Using Python Jupyter notebooks to work in an environment I've created. Everything went fine until I decided to add another package to the environment. After setting up the environment, I was unable to import additional packages I installed in the environment. I was only able to import packages I installed on set-up.

Here are the commands I used to create the environment initially:

python -m venv test
. test/bin/activate

pip install pyodbc
deactivate

python3 -m ipykernel install --user --name test

This all worked fine. I started a notebook using the new environment and was able to import pyodbc without error!
Then I decided I wanted to add another package, geopandas.

. test/bin/activate

pip install geopandas

deactivate

I opened a notebook in the kernel and tried

import geopandas

ModuleNotFoundError                       Traceback (most recent call last)
/tmp/ipykernel_47903/1529612126.py in <module>
----> 1 import geopandas

ModuleNotFoundError: No module named 'geopandas'

I then attempted linking it to ipykernel again

python3 -m ipykernel install --user --name test

But I still received the same error in the notebook and was unable to import the package. How can I add more packages to an environment after already establishing it? I'm not sure what I'm doing wrong. Thank you!


问:
OpenSeaDragon IIIF Viewer does not work with Manifest json in a NextJS application
Can we make OpenSeaDragon IIIF Viewer work with manifests json? Is Mirador the only option or can we use something else and make OpenSeaDragon work?

I have a manifest.json https://api.bl.uk/metadata/iiif/ark:/81055/vdc_00000004216E/manifest.json and I am trying to use OpenSeaDragon to view it, but it gives me error "No TileSource was able to open".

```<code>const source = new TileSource({
url: imageUrl1
})

source && source.addHandler('ready', (event) => {
const viewer = new Viewer({
element: imageElementRef.current,
prefixUrl: '//openseadragon.github.io/openseadragon/images/',
tileSources: [event.tileSource],
showRotationControl: false
})
})
</code>```

Body:
Can we make OpenSeaDragon IIIF Viewer work with manifests json? Is Mirador the only option or can we use something else and make OpenSeaDragon work?

I have a manifest.json https://api.bl.uk/metadata/iiif/ark:/81055/vdc_00000004216E/manifest.json and I am trying to use OpenSeaDragon to view it, but it gives me error "No TileSource was able to open".

const source = new TileSource({
url: imageUrl1
})

source && source.addHandler('ready', (event) => {
const viewer = new Viewer({
element: imageElementRef.current,
prefixUrl: '//openseadragon.github.io/openseadragon/images/',
tileSources: [event.tileSource],
showRotationControl: false
})
})


问:
Vitest -Unable to access the DOM inside a test
I am new to front-end testing, and I am trying to get a good grasp on it.

In the process, inside one project, I am creating a test for a Vue component. I want to test that the behaviour of the code is correct (The component has code inside the mounted() hook that has to perform basically some checks and an API call).

I want to check that the code reaches one method. Previously to that, the code creates a click event listener to one element in the DOM.

My test emulates a click event (triggers it), but it cannot assert that the proper method has been called after the click event.

This is due to it not finding the element in the DOM to which it has to add the event listener. It seems that the code cannot find anything inside the document (using .getElementById()).

I wonder why, and how I would resolve this, since I have been stuck here for hours and I haven't found any solution that could work here, even when I have learned some interesting things in the process. I will leave a code example with the code structure I have built:

Inside the component:

```<code><template>
   // ...
   <button id = "myButton">Add</button>
</template>
<script>
import { classInExternalScriptsFile } from "@/scripts/externalScriptsFile ";

let classIESF = new classInExternalScriptsFile();

export default {
  methods: {
    setup: function () {
      classIESF.setupMethod();
    },
  },
  mounted() {
    this.setupMethod();
  },
};
</script>
</code>```

Inside the scriptsFile

```<code>export class classInExternalScriptsFile {
  setupMethod() {
     let myButton = document.getElementById("myButton") // <-- getElementById() returns a null here

    if (typeof myButton !== "undefined" && myButton !== null) {
       myButton.onclick = () => { // <-- The test code complains because it cannot enter here
        // Some lines...
        this.mySuperMethod()
      }
    }
  }

  mySuperMethod() {
     // API call etc.
  }
}
</code>```

Inside the .spec.js test file:

```<code>// imports...

import { classInExternalScriptsFile } from "@/scripts/externalScriptsFile.js";

describe("description...", () => {

    const mySuperMethodMock = vi
      .spyOn(classInExternalScriptsFile.prototype, "mySuperMethod")
      .mockImplementation(() => {});

  test("That the button performs x when clicked", () => {
    let wrapper = mount(myComponent, {
        props: ...,
      });

      let myButton = wrapper.find('[test-id="my-button"]');
      myButton.trigger("click");

      expect(mySuperMethodMock).toHaveBeenCalled(); // <-- The test fails here
  }
}
</code>```

Body:
I am new to front-end testing, and I am trying to get a good grasp on it.

In the process, inside one project, I am creating a test for a Vue component. I want to test that the behaviour of the code is correct (The component has code inside the mounted() hook that has to perform basically some checks and an API call).

I want to check that the code reaches one method. Previously to that, the code creates a click event listener to one element in the DOM.

My test emulates a click event (triggers it), but it cannot assert that the proper method has been called after the click event.

This is due to it not finding the element in the DOM to which it has to add the event listener. It seems that the code cannot find anything inside the document (using .getElementById()).

I wonder why, and how I would resolve this, since I have been stuck here for hours and I haven't found any solution that could work here, even when I have learned some interesting things in the process. I will leave a code example with the code structure I have built:

Inside the component:

<template>
   // ...
   <button id = "myButton">Add</button>
</template>

Inside the scriptsFile

export class classInExternalScriptsFile {
  setupMethod() {
     let myButton = document.getElementById("myButton") // <-- getElementById() returns a null here

    if (typeof myButton !== "undefined" && myButton !== null) {
       myButton.onclick = () => { // <-- The test code complains because it cannot enter here
        // Some lines...
        this.mySuperMethod()
      }
    }
  }

  mySuperMethod() {
     // API call etc.
  }
}

Inside the .spec.js test file:

// imports...

import { classInExternalScriptsFile } from "@/scripts/externalScriptsFile.js";

describe("description...", () => {

    const mySuperMethodMock = vi
      .spyOn(classInExternalScriptsFile.prototype, "mySuperMethod")
      .mockImplementation(() => {});

  test("That the button performs x when clicked", () => {
    let wrapper = mount(myComponent, {
        props: ...,
      });

      let myButton = wrapper.find('[test-id="my-button"]');
      myButton.trigger("click");

      expect(mySuperMethodMock).toHaveBeenCalled(); // <-- The test fails here
  }
}


问:
How to know if the cache is loaded on databricks
I'm using Databricks cache with Reactjs in order to improve the performance when the app request something. But, how do I know when the cache is ready? Because when I run the SQL sentence, e.g CACHE SELECT * FROM table, doesn't return anything. There is any way to know if the cache is loaded correctly?

Thanks!


问:
Why I cannot compute stress terms correctly?
I am new to mathematica and I am trying to write a simple code to compute the stress and strains.
I can compute the strain.
I am trying to calculate stress, using the Hooke's Law:

```<code>disp = {{u1[x, y, z], u2 [x, y, z], u3[x, y, z]}, {x, y, z}};

\[CurlyEpsilon] =
 1/2 (Grad @@ disp + Transpose[Grad @@ disp]) // MatrixForm

\[Sigma] = Table[\[Lambda]*Tr[\[CurlyEpsilon]]*IdentityMatrix[3] + 2*\[Mu]*\[CurlyEpsilon]*KroneckerDelta[i,j],{i,3},{j,3}]//MatrixForm
</code>```

But the output is not correct for the stress terms. Can you help me in understanding the error here?
Thanks in advance,

Body:
I am new to mathematica and I am trying to write a simple code to compute the stress and strains.
I can compute the strain.
I am trying to calculate stress, using the Hooke's Law:

disp = {{u1[x, y, z], u2 [x, y, z], u3[x, y, z]}, {x, y, z}};

\[CurlyEpsilon] =
 1/2 (Grad @@ disp + Transpose[Grad @@ disp]) // MatrixForm

\[Sigma] = Table[\[Lambda]*Tr[\[CurlyEpsilon]]*IdentityMatrix[3] + 2*\[Mu]*\[CurlyEpsilon]*KroneckerDelta[i,j],{i,3},{j,3}]//MatrixForm

But the output is not correct for the stress terms. Can you help me in understanding the error here?
Thanks in advance,


问:
ValueError: at least one array or dtype is required
Here is my df.info()

```<code><class 'pandas.core.frame.DataFrame'>
RangeIndex: 1162 entries, 0 to 1161
Data columns (total 61 columns):
 #   Column                                        Non-Null Count  Dtype
---  ------                                        --------------  -----
 0   Algorithms&DataStructures                     428 non-null    float64
 1   C/C++Programming                              688 non-null    float64
 2   Calculus1                                     835 non-null    float64
 3   Calculus2                                     752 non-null    float64
 4   Calculus3                                     366 non-null    float64
 5   ChemistryLaboratory                           497 non-null    float64
 6   ChemistryforEngineers                         823 non-null    float64
 7   ComputerArchitecture                          433 non-null    float64
</code>```

And this is the function used to impute the NaN value:

```<code>from sklearn.neighbors import KNeighborsRegressor

# function that imputes a dataframe
def impute_knn(df):

    ''' inputs: pandas df containing feature matrix '''
    ''' outputs: dataframe with NaN imputed '''
    # imputation with KNN unsupervised method
    # separate dataframe into numerical/categorical
    ldf = df.select_dtypes(include=[np.number])           # select numerical columns in df
    ldf_putaside = df.select_dtypes(exclude=[np.number])  # select categorical columns in df
    # define columns w/ and w/o missing data
    cols_nan = ldf.columns[ldf.isna().any()].tolist()         # columns w/ nan
    cols_no_nan = ldf.columns.difference(cols_nan).values     # columns w/o nan

    for col in cols_nan:
        imp_test = ldf[ldf[col].isna()]   # indicies which have missing data will become our test set
        imp_train = ldf.dropna()          # all indicies which which have no missing data
        model = KNeighborsRegressor(n_neighbors=5)  # KNR Unsupervised Approach
        knr = model.fit(imp_train[cols_no_nan], imp_train[col])
        ldf.loc[df[col].isna(), col] = knr.predict(imp_test[cols_no_nan])

    return pd.concat([ldf,ldf_putaside],axis=1)
</code>```

I got it from: Bayesian Regression | House Price Prediction

However, when I apply it to my dataframe, it reports an error:

Full error:

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-284-b13fac408835> in <module>
----> 1 df2 = impute_knn(df)
      2 # looks like we have a full feature matrix
      3 df2.info()

5 frames
/usr/local/lib/python3.8/dist-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator)
    663
    664         if all(isinstance(dtype, np.dtype) for dtype in dtypes_orig):
--> 665             dtype_orig = np.result_type(*dtypes_orig)
    666
    667     if dtype_numeric:

<__array_function__ internals> in result_type(*args, **kwargs)

ValueError: at least one array or dtype is required
</code>```

I'd love to hear your comment! Thank you!

Body:
Here is my df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1162 entries, 0 to 1161
Data columns (total 61 columns):
 #   Column                                        Non-Null Count  Dtype
---  ------                                        --------------  -----
 0   Algorithms&DataStructures                     428 non-null    float64
 1   C/C++Programming                              688 non-null    float64
 2   Calculus1                                     835 non-null    float64
 3   Calculus2                                     752 non-null    float64
 4   Calculus3                                     366 non-null    float64
 5   ChemistryLaboratory                           497 non-null    float64
 6   ChemistryforEngineers                         823 non-null    float64
 7   ComputerArchitecture                          433 non-null    float64

And this is the function used to impute the NaN value:

from sklearn.neighbors import KNeighborsRegressor

# function that imputes a dataframe
def impute_knn(df):

    ''' inputs: pandas df containing feature matrix '''
    ''' outputs: dataframe with NaN imputed '''
    # imputation with KNN unsupervised method
    # separate dataframe into numerical/categorical
    ldf = df.select_dtypes(include=[np.number])           # select numerical columns in df
    ldf_putaside = df.select_dtypes(exclude=[np.number])  # select categorical columns in df
    # define columns w/ and w/o missing data
    cols_nan = ldf.columns[ldf.isna().any()].tolist()         # columns w/ nan
    cols_no_nan = ldf.columns.difference(cols_nan).values     # columns w/o nan

    for col in cols_nan:
        imp_test = ldf[ldf[col].isna()]   # indicies which have missing data will become our test set
        imp_train = ldf.dropna()          # all indicies which which have no missing data
        model = KNeighborsRegressor(n_neighbors=5)  # KNR Unsupervised Approach
        knr = model.fit(imp_train[cols_no_nan], imp_train[col])
        ldf.loc[df[col].isna(), col] = knr.predict(imp_test[cols_no_nan])

    return pd.concat([ldf,ldf_putaside],axis=1)

I got it from: Bayesian Regression | House Price Prediction

However, when I apply it to my dataframe, it reports an error:

Full error:

ValueError                                Traceback (most recent call last)
<ipython-input-284-b13fac408835> in <module>
----> 1 df2 = impute_knn(df)
      2 # looks like we have a full feature matrix
      3 df2.info()

5 frames
/usr/local/lib/python3.8/dist-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator)
    663
    664         if all(isinstance(dtype, np.dtype) for dtype in dtypes_orig):
--> 665             dtype_orig = np.result_type(*dtypes_orig)
    666
    667     if dtype_numeric:

<__array_function__ internals> in result_type(*args, **kwargs)

ValueError: at least one array or dtype is required

I'd love to hear your comment! Thank you!


问:
Power Apps Code Component - How to dynamically add HTMLInputElement to a PCF Control?
I have a requirement to create a Multi Search PCF Control. The requirement is to have a Select Option (dropdown list) of numbers 1 to 10. Depending on the selected number in dropdown, I need to be able to add that many Search Text Boxes (HTMLInputElements) and when clicked to search, component needs to search each search box value against D365 Contact entity.

My code as follows shows the dropdown list numbers and triggers the onchange event but does not display the dynamically added number of searchboxes.

enter image description here

My code is as follows

ControlManifest.Input.xml

`

```<code><?xml version="1.0" encoding="utf-8" ?>
<manifest>
  <control namespace="MyNS" constructor="SearchContactPCF" version="1.0.0" display-name-key="SearchRegistrantPCF" description-key="SearchContactPCF description" control-type="standard" >
    <external-service-usage enabled="false">
    </external-service-usage>
    <property name="propNumberOfSearchBoxOption" display-name-key="NumberOfSearchBoxOptionProperty_Display_Key" description-key="NumberOfSearchBoxOptionProperty_Desc_Key" of-type="OptionSet" usage="bound" required="true" />
    <resources>
      <code path="index.ts" order="1"/>
      <css path="css/SearchContactPCF.css" order="1" />
      <!-- UNCOMMENT TO ADD MORE RESOURCES
      <resx path="strings/SearchContactPCF.1033.resx" version="1.0.0" />
      -->
    </resources>
  </control>
</manifest>
</code>```

`

index.ts

`

```<code>import {IInputs, IOutputs} from "./generated/ManifestTypes";

export class SearchRegistrantPCF implements ComponentFramework.StandardControl<IInputs, IOutputs> {

    private contextObj: ComponentFramework.Context<IInputs>;
    private _notifyOutputChanged: () => void;
    //Div element
    private mainContainer: HTMLDivElement;

    private searchBoxContainer: HTMLDivElement;
    private _value: number;
    //Button to add number of search boxes
    private loadNumberOfSearchBoxesButton: HTMLButtonElement;
    private numberOfSearchBoxSelection: HTMLSelectElement;
    private numberOfSearchBoxSelectionLabel : HTMLLabelElement;
    private labelNumber : HTMLLabelElement;

    private numberOfSearchBoxes: [];

    /**
     * Empty constructor.
     */
    constructor()
    {

    }

    /*eslint no-unused-vars: "error"*/
    public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container:HTMLDivElement): void
    {
        this.contextObj = context;
        this._notifyOutputChanged = notifyOutputChanged;

        // Add control initialization code
        context.mode.trackContainerResize(true);
        this.mainContainer = document.createElement("div");
        this.searchBoxContainer = document.createElement("div");
        this.mainContainer.setAttribute("class","form-group");
        this.searchBoxContainer.setAttribute("class","form-group");

        this.numberOfSearchBoxSelection = document.createElement("select");
        this.numberOfSearchBoxSelection.setAttribute("name", "numberOfSearchBoxSelection");
        this.numberOfSearchBoxSelection.setAttribute("id", "numberOfSearchBoxSelection");

        this.numberOfSearchBoxSelectionLabel = document.createElement("label");
        this.numberOfSearchBoxSelectionLabel.innerHTML = "Select no of registrants to search";
        this.numberOfSearchBoxSelectionLabel.setAttribute("for", "numberOfSearchBoxSelection");
        this.numberOfSearchBoxSelectionLabel.setAttribute("id", "numberOfSearchBoxSelectionLabel");
        this.mainContainer.appendChild(this.numberOfSearchBoxSelectionLabel);

        this.labelNumber = document.createElement("label");
        this.labelNumber.innerHTML = "Number: ";
        this.mainContainer.appendChild(this.labelNumber);

        this.numberOfSearchBoxSelection.addEventListener("change", this.onChangeNumberOfSearchBoxesOptionSelect.bind(this));

        for (let index = 0; index < 10; index++) {
            let optionSearchBox = document.createElement("option");
            optionSearchBox.value = index.toString();
            optionSearchBox.text = (index + 1).toString();
            this.numberOfSearchBoxSelection.appendChild(optionSearchBox);
        }

        //this.loadNumberOfSearchBoxesButton = document.createElement("button");
        //this.loadNumberOfSearchBoxesButton.addEventListener("click", this.onLoadNumberOfSearchBoxesButtonClick.bind(this));
        this.mainContainer.appendChild(this.numberOfSearchBoxSelection);
        container.appendChild(this.mainContainer);
    }

    /**
     * Called when any value in the property bag has changed. This includes field values, data-sets, global values such as container height and width, offline status, control metadata values such as label, visible, etc.
     * @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to names defined in the manifest, as well as utility functions
     */
    public updateView(context: ComponentFramework.Context<IInputs>): void
    {
        // Add code to update control view
        this.contextObj = context;
    }

    private onChangeNumberOfSearchBoxesOptionSelect(evt: Event): void {
        // eslint-disable-line no-unused-vars
        let x = Number((evt.currentTarget as HTMLSelectElement).value) + 1;

        this.labelNumber.innerHTML += x.toString();

        this._value = parseInt(this.numberOfSearchBoxSelection.selectedOptions[0].value);

        if (x) {
            let selectedOptionValueInt = x;

            this.labelNumber.innerHTML += " second number is: " + selectedOptionValueInt;

            for(let optionInt = 0; optionInt < selectedOptionValueInt; optionInt++)
            {
                let searchTextBox = document.createElement("input");
                searchTextBox.setAttribute("type", "text");
                searchTextBox.setAttribute("name", "searchTextBox" + optionInt.toString());
                searchTextBox.setAttribute("id", "searchTextBox" + optionInt.toString());
                this.searchBoxContainer.appendChild(searchTextBox);
            }
        }
        this._notifyOutputChanged();
    }

    /**
     * It is called by the framework prior to a control receiving new data.
     * @returns an object based on nomenclature defined in manifest, expecting object[s] for property marked as “bound” or “output”
     */
    public getOutputs(): IOutputs
    {
        return {};
    }

    /**
     * Called when the control is to be removed from the DOM tree. Controls should use this call for cleanup.
     * i.e. cancelling any pending remote calls, removing listeners, etc.
     */
    public destroy(): void
    {
        // Add code to cleanup control if necessary
    }
}

</code>```

`

Tried all my best but I am still new to PCF Code Components. Any help is very much appreciated.

Body:
I have a requirement to create a Multi Search PCF Control. The requirement is to have a Select Option (dropdown list) of numbers 1 to 10. Depending on the selected number in dropdown, I need to be able to add that many Search Text Boxes (HTMLInputElements) and when clicked to search, component needs to search each search box value against D365 Contact entity.

My code as follows shows the dropdown list numbers and triggers the onchange event but does not display the dynamically added number of searchboxes.

enter image description here

My code is as follows

ControlManifest.Input.xml

`

<?xml version="1.0" encoding="utf-8" ?>
<manifest>
  <control namespace="MyNS" constructor="SearchContactPCF" version="1.0.0" display-name-key="SearchRegistrantPCF" description-key="SearchContactPCF description" control-type="standard" >
    <external-service-usage enabled="false">
    </external-service-usage>
    <property name="propNumberOfSearchBoxOption" display-name-key="NumberOfSearchBoxOptionProperty_Display_Key" description-key="NumberOfSearchBoxOptionProperty_Desc_Key" of-type="OptionSet" usage="bound" required="true" />
    <resources>

      <css path="css/SearchContactPCF.css" order="1" />

    </resources>
  </control>
</manifest>

`

index.ts

`

import {IInputs, IOutputs} from "./generated/ManifestTypes";

export class SearchRegistrantPCF implements ComponentFramework.StandardControl<IInputs, IOutputs> {

    private contextObj: ComponentFramework.Context<IInputs>;
    private _notifyOutputChanged: () => void;
    //Div element
    private mainContainer: HTMLDivElement;

    private searchBoxContainer: HTMLDivElement;
    private _value: number;
    //Button to add number of search boxes
    private loadNumberOfSearchBoxesButton: HTMLButtonElement;
    private numberOfSearchBoxSelection: HTMLSelectElement;
    private numberOfSearchBoxSelectionLabel : HTMLLabelElement;
    private labelNumber : HTMLLabelElement;

    private numberOfSearchBoxes: [];

    /**
     * Empty constructor.
     */
    constructor()
    {

    }

    /*eslint no-unused-vars: "error"*/
    public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container:HTMLDivElement): void
    {
        this.contextObj = context;
        this._notifyOutputChanged = notifyOutputChanged;

        // Add control initialization code
        context.mode.trackContainerResize(true);
        this.mainContainer = document.createElement("div");
        this.searchBoxContainer = document.createElement("div");
        this.mainContainer.setAttribute("class","form-group");
        this.searchBoxContainer.setAttribute("class","form-group");

        this.numberOfSearchBoxSelection = document.createElement("select");
        this.numberOfSearchBoxSelection.setAttribute("name", "numberOfSearchBoxSelection");
        this.numberOfSearchBoxSelection.setAttribute("id", "numberOfSearchBoxSelection");

        this.numberOfSearchBoxSelectionLabel = document.createElement("label");
        this.numberOfSearchBoxSelectionLabel.innerHTML = "Select no of registrants to search";
        this.numberOfSearchBoxSelectionLabel.setAttribute("for", "numberOfSearchBoxSelection");
        this.numberOfSearchBoxSelectionLabel.setAttribute("id", "numberOfSearchBoxSelectionLabel");
        this.mainContainer.appendChild(this.numberOfSearchBoxSelectionLabel);

        this.labelNumber = document.createElement("label");
        this.labelNumber.innerHTML = "Number: ";
        this.mainContainer.appendChild(this.labelNumber);

        this.numberOfSearchBoxSelection.addEventListener("change", this.onChangeNumberOfSearchBoxesOptionSelect.bind(this));

        for (let index = 0; index < 10; index++) {
            let optionSearchBox = document.createElement("option");
            optionSearchBox.value = index.toString();
            optionSearchBox.text = (index + 1).toString();
            this.numberOfSearchBoxSelection.appendChild(optionSearchBox);
        }

        //this.loadNumberOfSearchBoxesButton = document.createElement("button");
        //this.loadNumberOfSearchBoxesButton.addEventListener("click", this.onLoadNumberOfSearchBoxesButtonClick.bind(this));
        this.mainContainer.appendChild(this.numberOfSearchBoxSelection);
        container.appendChild(this.mainContainer);
    }

    /**
     * Called when any value in the property bag has changed. This includes field values, data-sets, global values such as container height and width, offline status, control metadata values such as label, visible, etc.
     * @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to names defined in the manifest, as well as utility functions
     */
    public updateView(context: ComponentFramework.Context<IInputs>): void
    {
        // Add code to update control view
        this.contextObj = context;
    }

    private onChangeNumberOfSearchBoxesOptionSelect(evt: Event): void {
        // eslint-disable-line no-unused-vars
        let x = Number((evt.currentTarget as HTMLSelectElement).value) + 1;

        this.labelNumber.innerHTML += x.toString();

        this._value = parseInt(this.numberOfSearchBoxSelection.selectedOptions[0].value);

        if (x) {
            let selectedOptionValueInt = x;

            this.labelNumber.innerHTML += " second number is: " + selectedOptionValueInt;

            for(let optionInt = 0; optionInt < selectedOptionValueInt; optionInt++)
            {
                let searchTextBox = document.createElement("input");
                searchTextBox.setAttribute("type", "text");
                searchTextBox.setAttribute("name", "searchTextBox" + optionInt.toString());
                searchTextBox.setAttribute("id", "searchTextBox" + optionInt.toString());
                this.searchBoxContainer.appendChild(searchTextBox);
            }
        }
        this._notifyOutputChanged();
    }

    /**
     * It is called by the framework prior to a control receiving new data.
     * @returns an object based on nomenclature defined in manifest, expecting object[s] for property marked as “bound” or “output”
     */
    public getOutputs(): IOutputs
    {
        return {};
    }

    /**
     * Called when the control is to be removed from the DOM tree. Controls should use this call for cleanup.
     * i.e. cancelling any pending remote calls, removing listeners, etc.
     */
    public destroy(): void
    {
        // Add code to cleanup control if necessary
    }
}

`

Tried all my best but I am still new to PCF Code Components. Any help is very much appreciated.


问:
How to get only one frame at a time from camera in a blocking loop in opencv-python?
I have a sensor that signals in the serial port and I want to capture the  frame of that very moment whenever I get this signal. The function for recieving the signal is blocking:

import serial

ser = serial.Serial(port=PORT_NAME, baudrate=9600)
while True:
    data = ser.readline()
    print("object detected; capture a frame.")`
```
<p>The code that I have right now (and works) is like bellow where I create a VideoCapture object at each iteration.</p>
<pre class="lang-py prettyprint-override"><code>import serial
import cv2

ser = serial.Serial(port=PORT_NAME, baudrate=9600)
while True:
    data = ser.readline()
    print("object detected.")
    cap = cv2.VideoCapture(0)
    ret, frame = cap.read()
    cap.release()
</code>```

Performance-wise, making an object each time is not a wise move, and the problem with standard code like bellow is that each time cap.read() is called it returns the "next" frame, not the current frame that the camera is capturing at that moment:

import serial
import cv2

cap = cv2.VideoCapture(0)
ser = serial.Serial(port=PORT_NAME, baudrate=9600)

while True:
    data = ser.readline()
    print("object detected.")
    ret, frame = cap.read()

cap.release()
```

please provide me with a performant solution. Thanks in advance.

I have tried the making VideoCapture object each time but I don't think this would be the right way.

Edit: I rather not use multi-threading if possible.

Body:
I have a sensor that signals in the serial port and I want to capture the  frame of that very moment whenever I get this signal. The function for recieving the signal is blocking:

import serial

ser = serial.Serial(port=PORT_NAME, baudrate=9600)
while True:
    data = ser.readline()
    print("object detected; capture a frame.")`

The code that I have right now (and works) is like bellow where I create a VideoCapture object at each iteration.

import serial
import cv2

ser = serial.Serial(port=PORT_NAME, baudrate=9600)
while True:
    data = ser.readline()
    print("object detected.")
    cap = cv2.VideoCapture(0)
    ret, frame = cap.read()
    cap.release()

Performance-wise, making an object each time is not a wise move, and the problem with standard code like bellow is that each time cap.read() is called it returns the "next" frame, not the current frame that the camera is capturing at that moment:

import serial
import cv2

cap = cv2.VideoCapture(0)
ser = serial.Serial(port=PORT_NAME, baudrate=9600)

while True:
    data = ser.readline()
    print("object detected.")
    ret, frame = cap.read()

cap.release()

please provide me with a performant solution. Thanks in advance.

I have tried the making VideoCapture object each time but I don't think this would be the right way.

Edit: I rather not use multi-threading if possible.


问:
Filepath as Makefile target
I'm trying to write a Makefile. I have two targets in the Makefile.

```<code>$(var1)_target : a.txt b.txt
         <recipes>
$(var2) : c.txt d.txt
         <recipes>
</code>```

Here var1 and var2 both are file paths of the form (./dir1/dir2/file)
When I'm trying to run this, although the first target gets created/updated as expected, the second target doesn't gets created.
But if I add "_target" to the second target as well, it functions as expected (i.e. file2 gets created)

I've been scratching my head around this, but I'm unable to understand this behavior.
It'll be helpful if someone takes this up and help me in understanding what's actually happening here.

Thanks in advance.

Title: Filepath as Makefile target

Body:
I'm trying to write a Makefile. I have two targets in the Makefile.

$(var1)_target : a.txt b.txt
         <recipes>
$(var2) : c.txt d.txt
         <recipes>

Here var1 and var2 both are file paths of the form (./dir1/dir2/file)
When I'm trying to run this, although the first target gets created/updated as expected, the second target doesn't gets created.
But if I add "_target" to the second target as well, it functions as expected (i.e. file2 gets created)

I've been scratching my head around this, but I'm unable to understand this behavior.
It'll be helpful if someone takes this up and help me in understanding what's actually happening here.

Thanks in advance.


问:
how to check if it's an old tab that was loaded before installing the chrome extension
Content scripts are loaded on the tabs opened after installing the extension, or the user needs to reload old tabs to make them work.

How can I programmatically check whether the currently opened tab is an old one when the user clicks on the extension popup so that I can inform them about reloading the page once?


问:
How to improve the launch of gitlab-runner?
I installed on my vps gitlab runner, but every time I use in gitlab-ci.yml

```<code>tags:
 - vps
</code>```

I have a hold of 5 minutes (minimum) each time.

I installed gitlab runner with

```<code>apt-get install gitlab-runner
</code>```

whereas if I use the gitlab-=runner from gitlab.com I don't get the hold

gitlab-runner info:

```<code>gitlab-runner status Runtime platform arch=amd64 os=linux pid=662441 revision=133d7e76 version=15.6.1

concurrent = 1
check_interval = 0
shutdown_timeout = 0

[session_server]
  session_timeout = 1800

[[runners]]
</code>```

runner 1:

```<code>[[runners]]
  name = "name1"
  url = "https://gitlab.com/"
  id = 123
  token = "ABC"
  token_obtained_at = 2022-11-26T20:24:16Z
  token_expires_at = 0001-01-01T00:00:00Z
  executor = "shell"
  [runners.custom_build_dir]
  [runners.cache]
    MaxUploadedArchiveSize = 0
    [runners.cache.s3]
    [runners.cache.gcs]
    [runners.cache.azure]
</code>```

runner2:

```<code>[[runners]]
  name = "runner2"
  url = "https://gitlab.com/"
  id = 456
  token = "ABC"
  token_obtained_at = 2022-11-26T20:34:45Z
  token_expires_at = 0001-01-01T00:00:00Z
  executor = "docker"
  [runners.custom_build_dir]
  [runners.cache]
    MaxUploadedArchiveSize = 0
    [runners.cache.s3]
    [runners.cache.gcs]
    [runners.cache.azure]
  [runners.docker]
    tls_verify = false
    image = "ruby:latest"
    privileged = false
    disable_entrypoint_overwrite = false
    oom_kill_disable = false
    disable_cache = false
    volumes = ["/cache"]
    shm_size = 0
</code>```

thank you

Body:
I installed on my vps gitlab runner, but every time I use in gitlab-ci.yml

tags:
 - vps

I have a hold of 5 minutes (minimum) each time.

I installed gitlab runner with

apt-get install gitlab-runner

whereas if I use the gitlab-=runner from gitlab.com I don't get the hold

gitlab-runner info:

gitlab-runner status Runtime platform arch=amd64 os=linux pid=662441 revision=133d7e76 version=15.6.1

concurrent = 1
check_interval = 0
shutdown_timeout = 0

[session_server]
  session_timeout = 1800

[[runners]]

runner 1:

[[runners]]
  name = "name1"
  url = "https://gitlab.com/"
  id = 123
  token = "ABC"
  token_obtained_at = 2022-11-26T20:24:16Z
  token_expires_at = 0001-01-01T00:00:00Z
  executor = "shell"
  [runners.custom_build_dir]
  [runners.cache]
    MaxUploadedArchiveSize = 0
    [runners.cache.s3]
    [runners.cache.gcs]
    [runners.cache.azure]

runner2:

[[runners]]
  name = "runner2"
  url = "https://gitlab.com/"
  id = 456
  token = "ABC"
  token_obtained_at = 2022-11-26T20:34:45Z
  token_expires_at = 0001-01-01T00:00:00Z
  executor = "docker"
  [runners.custom_build_dir]
  [runners.cache]
    MaxUploadedArchiveSize = 0
    [runners.cache.s3]
    [runners.cache.gcs]
    [runners.cache.azure]
  [runners.docker]
    tls_verify = false
    image = "ruby:latest"
    privileged = false
    disable_entrypoint_overwrite = false
    oom_kill_disable = false
    disable_cache = false
    volumes = ["/cache"]
    shm_size = 0

thank you


问:
Adding an empty line when inserting a new item in a QTableWidget
I'm looking to update the display of my QTableWidget when I add a new item. But when adding, an empty line is added. The element that has been added is only visible on the next addition.

Before the first add : (Only the bottom QTableWidget is affected)

After the first add : (Only the bottom QTableWidget is affected)

After the second add : (Only the bottom QTableWidget is affected)

My update method : The affected table is situationBudgetsTab

def majBudget(self, nomBudget: QLineEdit, montantMax: QLineEdit):
          self.budgetsTab.setRowCount(self.budgetsTab.rowCount() + 1)
          self.situationBudgetsTab.setRowCount(self.situationBudgetsTab.rowCount() + 1)

          # # ajout du budget dans le fichier Budget.txt
          self.budgets.addBudgetInFile(nomBudget, montantMax)

          # rangement des valeurs dans le tableau des situations
          for k in range(len(self.dicoBudgets)):

               nom = QTableWidgetItem(self.dicoBudgets[k][0])
               # rangement de la valeur à la position courante
               self.situationBudgetsTab.setItem(k, 0, nom)

               # rangement du montantMax dans une chaine de caractères
               s = str(self.dicoBudgets[k][1])

               # on veut savoir à combien nous sommes de la limite de budget fixée
               situation = QTableWidgetItem("0" + "/" + s[:-1].strip()) # stirp() supprime '\n' pour un affichage plus joli
               # rangement de la valeur à la position courante
               self.situationBudgetsTab.setItem(k, 1, situation)

          # on place k à la dernière position du dictionnaire
          k = len(self.dicoBudgets)-1

          # ajout du dernier élément en sans le '\n'
          nom = QTableWidgetItem(self.dicoBudgets[k][0])
          self.situationBudgetsTab.setItem(k, 0, nom)

          s = str(self.dicoBudgets[k][1])
          situation = QTableWidgetItem("0" + "/" + s)
          self.situationBudgetsTab.setItem(k, 1, situation)

          # # mise à jour de l'affichage
          self.printBudgetsTab()
```


问:
Does docker stats Block I/O include reads from the filesystem cache?
As the title suggests I would like to know whether the number shown under docker stats "block IO" includes the reads performed on the filesystem cache?

Tried to find a clear definition, but got a bit lost.


问:
Change the path where Flutter looks for android emulators
Android Studio used to store all the emulators in my SSD. But the SSD just ran out of space, and now the emulators started crashing. So, I figured I need to change their disk location.

To do that, I set an environment variable "ANDROID_SDK_HOME" to somewhere in my HDD. And now when I am creating a new emulator on Android Studio, it is being stored in the new location.

But when I open a flutter project on VS Code, I can not start the emulator using the extension, which used to work fine before changing the location. Now it just won't list the emulator which is stored in a new location, that is why I can't start it from VS Code.

Any help on how to change the path where Flutter extension in VS Code looks for android emulators?


问:
Lambda expression used inside Include is not valid if nullable column
```<code>        public t4? t4{ get; set; }
...

query = query
            .Include(x => x.t1)
            .Include(x => x.t2)
                .ThenInclude(x => x.tt)
            .Include(x => x.t3)
                .ThenInclude(x => x.ttt)
            .Include(x => x.t4);
</code>```

when I try to include the t4, which is a nullable property, the ef outputs the title error (Lambda expression used inside Include is not valid). Is this really the reason, or is this a coincidence?

Body:
        public t4? t4{ get; set; }
...

query = query
            .Include(x => x.t1)
            .Include(x => x.t2)
                .ThenInclude(x => x.tt)
            .Include(x => x.t3)
                .ThenInclude(x => x.ttt)
            .Include(x => x.t4);

when I try to include the t4, which is a nullable property, the ef outputs the title error (Lambda expression used inside Include is not valid). Is this really the reason, or is this a coincidence?