问:
Core Data is giving an error, even though I am not using Core Data in my project
Can someone explain why these errors keep coming up?
I have gotten rid of all traces of Core Data from the project, yet it keeps coming up.
These errors go away if I add the Assets folder to Development Assets, but I don’t want to do that for obvious reasons…

The error:

```<code>/Users/{user}/Documents/GitHub/ZoZo/CoreData error build:  API Misuse: Attempt to serialize store access on non-owning coordinator (PSC = 0x600000a0d8f0, store PSC = 0x0)
</code>```

The /ZoZo/CoreData/ folder does not even exist, which is even more confusing...

This error only shows up when Archiving the project, not when building it normally

Body:
Can someone explain why these errors keep coming up?
I have gotten rid of all traces of Core Data from the project, yet it keeps coming up.
These errors go away if I add the Assets folder to Development Assets, but I don’t want to do that for obvious reasons…

The error:

/Users/{user}/Documents/GitHub/ZoZo/CoreData error build:  API Misuse: Attempt to serialize store access on non-owning coordinator (PSC = 0x600000a0d8f0, store PSC = 0x0)

The /ZoZo/CoreData/ folder does not even exist, which is even more confusing...

This error only shows up when Archiving the project, not when building it normally


来源: stackexchange

问:
error Too large total max_bars_back 309517 max 300000 allowed in Pinescript
Have a nice day

I have problem with my max_bars_back in my pinescript code and I couldn't solve it

```<code>strategy('Test',shorttitle='Test' , overlay=true, pyramiding=10, commission_type=strategy.commission.percent, commission_value=0.01, initial_capital=1000, default_qty_type=strategy.cash, default_qty_value=500, currency=currency.USD, max_bars_back=3000)
</code>```

when I for example put 2900 in max_bars_back it's ok, but I can't put more than that and when I do it gets me this error : "Too large total max_bars_back 309517 max 300000 allowed".

however in Pinescript references says we can put maximum 5000 in max_bars_back

ContentLicense: CC BY-SA 4.0

Body:
Have a nice day

I have problem with my max_bars_back in my pinescript code and I couldn't solve it

strategy('Test',shorttitle='Test' , overlay=true, pyramiding=10, commission_type=strategy.commission.percent, commission_value=0.01, initial_capital=1000, default_qty_type=strategy.cash, default_qty_value=500, currency=currency.USD, max_bars_back=3000)

when I for example put 2900 in max_bars_back it's ok, but I can't put more than that and when I do it gets me this error : "Too large total max_bars_back 309517 max 300000 allowed".

however in Pinescript references says we can put maximum 5000 in max_bars_back


问:
Why i am unable to mock the activated route?
I am trying to mock my activated route but its throwing undefined error at get. I tried tweaking the code and stuffs but in vain. The error it shows is

TypeError: Cannot read properties of undefined (reading 'get')
at ViewEmployeesbyDeptComponent.call [as ngOnInit] (http://localhost:9877/karma_webpack/webpack:/src/app/components/departments/view-employeesby-dept/view-employeesby-dept.component.ts:19:51)

Here is my component.ts:

```<code>ngOnInit(): void {
    this.getId = Number(this.ar.snapshot.paramMap.get('id'));
    this.employeeService.getEmployeeById(this.getId).subscribe({
        next:(data) => {
          this.viewEmp = data;

        }

    })
  }
</code>```

Here is my service.ts:

```<code> getEmployeesByDepartment(id: number): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.baseApiUrl + "/department/" + id + "/employee");
  }
</code>```

Here is my spec.ts:

```<code>describe('ViewEmployeesbyDeptComponent', () => {
  let component: ViewEmployeesbyDeptComponent;
  let fixture: ComponentFixture<ViewEmployeesbyDeptComponent>;
  let mockEmpService: DepartmentsService;
  let httpController: HttpTestingController;
  let mockActivatedRoute;

  let mockEmp: any = [{
    //dummy data
  }];

  beforeEach(async () => {

    mockActivatedRoute = {
      snapshot: { paraMap: { get: () => { return '1' } } }
    };

    await TestBed.configureTestingModule({
      declarations: [ViewEmployeesbyDeptComponent],
      imports: [ReactiveFormsModule, HttpClientTestingModule, HttpClientModule],
      providers: [
        { provide: DepartmentsService, useValue: mockEmpService },
        { provide: ActivatedRoute, useValue: mockActivatedRoute },
        { provide: HttpTestingController, useValue: httpController }
      ]
    })
      .compileComponents();

    mockEmpService = TestBed.inject(DepartmentsService);
    httpController = TestBed.inject(HttpTestingController);

    fixture = TestBed.createComponent(ViewEmployeesbyDeptComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('Should Get Employees By Department ID', () => {
   spyOn(mockEmpService, 'getEmployeesByDepartment')
   .and
   .callThrough();
   component.ngOnInit();
   expect(mockEmpService.getEmployeesByDepartment).toHaveBeenCalledWith(1);
   expect(component.getId).toBe(1);
   expect(component.employees).toEqual(mockEmp);
  });
});
</code>```

Body:
I am trying to mock my activated route but its throwing undefined error at get. I tried tweaking the code and stuffs but in vain. The error it shows is

TypeError: Cannot read properties of undefined (reading 'get')
at ViewEmployeesbyDeptComponent.call [as ngOnInit] (http://localhost:9877/karma_webpack/webpack:/src/app/components/departments/view-employeesby-dept/view-employeesby-dept.component.ts:19:51)

Here is my component.ts:

ngOnInit(): void {
    this.getId = Number(this.ar.snapshot.paramMap.get('id'));
    this.employeeService.getEmployeeById(this.getId).subscribe({
        next:(data) => {
          this.viewEmp = data;

        }

    })
  }

Here is my service.ts:

 getEmployeesByDepartment(id: number): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.baseApiUrl + "/department/" + id + "/employee");
  }

Here is my spec.ts:

describe('ViewEmployeesbyDeptComponent', () => {
  let component: ViewEmployeesbyDeptComponent;
  let fixture: ComponentFixture<ViewEmployeesbyDeptComponent>;
  let mockEmpService: DepartmentsService;
  let httpController: HttpTestingController;
  let mockActivatedRoute;

  let mockEmp: any = [{
    //dummy data
  }];

  beforeEach(async () => {

    mockActivatedRoute = {
      snapshot: { paraMap: { get: () => { return '1' } } }
    };

    await TestBed.configureTestingModule({
      declarations: [ViewEmployeesbyDeptComponent],
      imports: [ReactiveFormsModule, HttpClientTestingModule, HttpClientModule],
      providers: [
        { provide: DepartmentsService, useValue: mockEmpService },
        { provide: ActivatedRoute, useValue: mockActivatedRoute },
        { provide: HttpTestingController, useValue: httpController }
      ]
    })
      .compileComponents();

    mockEmpService = TestBed.inject(DepartmentsService);
    httpController = TestBed.inject(HttpTestingController);

    fixture = TestBed.createComponent(ViewEmployeesbyDeptComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('Should Get Employees By Department ID', () => {
   spyOn(mockEmpService, 'getEmployeesByDepartment')
   .and
   .callThrough();
   component.ngOnInit();
   expect(mockEmpService.getEmployeesByDepartment).toHaveBeenCalledWith(1);
   expect(component.getId).toBe(1);
   expect(component.employees).toEqual(mockEmp);
  });
});


问:
Having an issue with user_business_profile_state while scrapping Twitter with TWINT
I am actually using TWINT to sort out some data on twitter and I am facing a problem.

Indeed, here is first the repo of TWINT : https://github.com/twintproject/twint

So the thing is for exemple for this two users :
https://twitter.com/hansvonrueden : Business category = Entrepreneur enter image description here
https://twitter.com/productbees : Business category = Professional services  enter image description here

Here is the results I am getting :  "'business_profile_state': 'none',

Here in this case it should be displaying "true" or "yes" idk but the problem is that it's displaying "none"enter image description here

If the user doeesn't have a professional category asigned, it's displaying "none" so in that case it is correct. But if the user assigned a professional category such as "Entrepreneur" "Profeessional service" , it's still returning "none", which is a pain in the *ss

If someone has an idea to fix this issue, I'd take it !

As I said, I was expecting it to return "true" or "yes" atleast. Actually it's returning "none" even if the user assigned a professional category to his account...


问:
In SwiftUI, How to educe size of Image BEFORE saving it in CoreData Attribute "Binary Data" using PhotosPicker
I have a CoreData Entity “GameSession” with an attribute “photo” which is of type “Binary Data” (and I clicked on “Allows External Storage”).

In a view, I save a photo in that attribute, like that:

```<code>PhotosPicker(selection: $selectedItem ,matching: .images) {
    Label("Select a photo", systemImage: "photo")
}
.onChange(of: selectedItem) { newItem in
    Task {
        if let data = try? await newItem?.loadTransferable(type: Data.self) {
            selectedPhotoData = data
        }
    }
}
</code>```

Then I save it in my CoreData Entity “GameSession” in the attribute “photo” which is of type “Binary Data”, like that

```<code>let newSession = GameSession(context: self.moc)
        newSession.date = self.date
        newSession.setValue(self.selectedPhotoData, forKeyPath: "photo")
self.moc.save()
</code>```

Everything works fine but I am wondering if I am not going to hit a memory issue when I will have a high number of “session” (and so a high number of photo).

Moreover, In my application, I only display the photo in a small square of 300 pixel by 300 pixels. So I don’t really need to store it in my coredata entity in high resolution.

How could I reduce the size of the photo BEFORE saving it?
I guess I have to apply a “reduce_size” function to “selectedItem” or “newItem” in my PhotosPicker, but I don’t know how.

I know there is UIImageJPEGRepresentation that I could use and apply a compression ratio, But how to use that method on $selectedItem ?

Thanks and regards

Body:
I have a CoreData Entity “GameSession” with an attribute “photo” which is of type “Binary Data” (and I clicked on “Allows External Storage”).

In a view, I save a photo in that attribute, like that:

PhotosPicker(selection: $selectedItem ,matching: .images) {
    Label("Select a photo", systemImage: "photo")
}
.onChange(of: selectedItem) { newItem in
    Task {
        if let data = try? await newItem?.loadTransferable(type: Data.self) {
            selectedPhotoData = data
        }
    }
}

Then I save it in my CoreData Entity “GameSession” in the attribute “photo” which is of type “Binary Data”, like that

let newSession = GameSession(context: self.moc)
        newSession.date = self.date
        newSession.setValue(self.selectedPhotoData, forKeyPath: "photo")
self.moc.save()

Everything works fine but I am wondering if I am not going to hit a memory issue when I will have a high number of “session” (and so a high number of photo).

Moreover, In my application, I only display the photo in a small square of 300 pixel by 300 pixels. So I don’t really need to store it in my coredata entity in high resolution.

How could I reduce the size of the photo BEFORE saving it?
I guess I have to apply a “reduce_size” function to “selectedItem” or “newItem” in my PhotosPicker, but I don’t know how.

I know there is UIImageJPEGRepresentation that I could use and apply a compression ratio, But how to use that method on $selectedItem ?

Thanks and regards


问:
How can I find the bug exactly when I use VScode to write a LaTex project?
enter image description here
like the picture,it just tell me the code has bug,but does not show me where the bug is and how the bug come about.

I want to make some changes on the vscode so that it can show me the bug exactly but I do not know how to do it.


问:
how to validate integer
My bot asks a user to enter an integer. There're two options for user to do this:

the integer must be > 0 and < 31

the integer must be > 0 and < 185

I wrote a code which validates user's input but my bot falls silent after the second attempt. How to fix it?

main function recieves input from user:

```<code>async def _save_data(user_data: str, state: FSMContext, type: str):
    data = await state.get_data()
    user_id = data['user']
    try:
        validate_date(user_data, type)
    except (InvalidDate, ValueError) as error:
        await bot.send_message(user_id, error)
    except Exception as e:
        await bot.send_message(user_id, messages.error_message.format(e))
    else:
       ### saves to the DB
</code>```

function which validates user's input:

```<code>def validate_date(user_date: str, record_type: str):
    match record_type:
        case 'month':
            try:
                if int(user_date) > 31 or int(user_date) <= 0:
                    raise InvalidDate(messages.invalid_month_message)
            except ValueError:
                raise InvalidDate(messages.invalid_digits_message)
        case 'every_few_days':
            if int(user_date) > 185:
                raise InvalidDate(messages.invalid_days_message)
        case 'once':
            if datetime.strptime(user_date, "%Y-%m-%d").date() < datetime.today().date():
                raise InvalidDate(messages.invalid_calendar_date)
</code>```

by the way it works correctly in the case 'once' and the bot sends the calendar to the user as many times as requiered for the user to choose the right date

function which sends the calendar:

```<code>async def receive_calendar_date(date: datetime, state: FSMContext, user_id: int):
    data = await state.get_data()
    date_to_save = ''
    try:
        validate_date(str(date), data['type'])
    except InvalidDate as e:
        await bot.send_message(user_id, e, reply_markup=await SimpleCalendar().start_calendar())
    else:
        ### saves user's data
</code>```

InvalidDate:

```<code>class InvalidDate(Exception):
    pass
</code>```

Title: how to validate integer

Body:
My bot asks a user to enter an integer. There're two options for user to do this:

the integer must be > 0 and < 31

the integer must be > 0 and < 185

I wrote a code which validates user's input but my bot falls silent after the second attempt. How to fix it?

main function recieves input from user:

async def _save_data(user_data: str, state: FSMContext, type: str):
    data = await state.get_data()
    user_id = data['user']
    try:
        validate_date(user_data, type)
    except (InvalidDate, ValueError) as error:
        await bot.send_message(user_id, error)
    except Exception as e:
        await bot.send_message(user_id, messages.error_message.format(e))
    else:
       ### saves to the DB

function which validates user's input:

def validate_date(user_date: str, record_type: str):
    match record_type:
        case 'month':
            try:
                if int(user_date) > 31 or int(user_date) <= 0:
                    raise InvalidDate(messages.invalid_month_message)
            except ValueError:
                raise InvalidDate(messages.invalid_digits_message)
        case 'every_few_days':
            if int(user_date) > 185:
                raise InvalidDate(messages.invalid_days_message)
        case 'once':
            if datetime.strptime(user_date, "%Y-%m-%d").date() < datetime.today().date():
                raise InvalidDate(messages.invalid_calendar_date)

by the way it works correctly in the case 'once' and the bot sends the calendar to the user as many times as requiered for the user to choose the right date

function which sends the calendar:

async def receive_calendar_date(date: datetime, state: FSMContext, user_id: int):
    data = await state.get_data()
    date_to_save = ''
    try:
        validate_date(str(date), data['type'])
    except InvalidDate as e:
        await bot.send_message(user_id, e, reply_markup=await SimpleCalendar().start_calendar())
    else:
        ### saves user's data

InvalidDate:

class InvalidDate(Exception):
    pass


问:
Oracle SQL: cannot specify rows separator for sqlldr when loading from a file
I have a table DimTime. Its schema is as follows:

```<code>CREATE TABLE DimTime ( SK_TimeID NUMBER(11,0) PRIMARY KEY,
                        TimeValue DATE Not NULL,
                        HourID NUMBER(2) Not NULL,
                        HourDesc CHAR(20) Not NULL,
                        MinuteID NUMBER(2) Not NULL,
                        MinuteDesc CHAR(20) Not NULL,
                        SecondID NUMBER(2) Not NULL,
                        SecondDesc CHAR(20) Not NULL,
                        MarketHoursFlag CHAR(5) NOT NULL check (MarketHoursFlag = 'false' or MarketHoursFlag = 'true'),
                        OfficeHoursFlag CHAR(5) NOT NULL check (OfficeHoursFlag = 'false' or OfficeHoursFlag = 'true')
);
</code>```

I am trying to load data from the source file Time.txt into it. This file was generated for TPC-DI benchmarking on Oracle Linux 8.6. Here are the first 3 rows:

```<code>000000|00:00:00|00|00|00|00:00|00|00:00:00|false|false
000001|00:00:01|00|00|00|00:00|01|00:00:01|false|false
000002|00:00:02|00|00|00|00:00|02|00:00:02|false|false
</code>```

I tried to load the data into the table using the following ctl file:

```<code>LOAD DATA
INFILE
TRUNCATE
INTO TABLE DimTime
FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"' TRAILING NULLCOLS
(
    SK_TimeID,
    TimeValue DATE "HH24:MI:SS",
    HourID,
    HourDesc,
    MinuteID,
    MinuteDesc,
    SecondID,
    SecondDesc,
    MarketHoursFlag,
    OfficeHoursFlag
)
</code>```

and running sqlldr userid=user/password@localhost/db_name control=DimTime.ctl data=path/to/Time.txt

But the log file states that the last column had an error:

```<code>Record 1: Rejected - Error on table DIMTIME, column OFFICEHOURSFLAG.
ORA-12899: value too large for column "SAYYUS"."DIMTIME"."OFFICEHOURSFLAG" (actual: 6, maximum: 5)
</code>```

even though it contains only values "true" or "false" (max 5 characters) as can be seen in the sample file.

I am sure, the problem is that as explained by TPC-DI documentation, "records have a terminator character appropriate for the System Under Test". So it has a character at the end of each line that is appended to the last column but I cannot discard this character. I tried to put INFILE "STR X'0A'" as explained by this webpage and tried to trim the column in the ctl file: OfficeHoursFlag "TRIM (:OfficeHoursFlag)" but it didn't work.

Does anybody know what character is in the end of the line? How is it possible to discard it?

Body:
I have a table DimTime. Its schema is as follows:

CREATE TABLE DimTime ( SK_TimeID NUMBER(11,0) PRIMARY KEY,
                        TimeValue DATE Not NULL,
                        HourID NUMBER(2) Not NULL,
                        HourDesc CHAR(20) Not NULL,
                        MinuteID NUMBER(2) Not NULL,
                        MinuteDesc CHAR(20) Not NULL,
                        SecondID NUMBER(2) Not NULL,
                        SecondDesc CHAR(20) Not NULL,
                        MarketHoursFlag CHAR(5) NOT NULL check (MarketHoursFlag = 'false' or MarketHoursFlag = 'true'),
                        OfficeHoursFlag CHAR(5) NOT NULL check (OfficeHoursFlag = 'false' or OfficeHoursFlag = 'true')
);

I am trying to load data from the source file Time.txt into it. This file was generated for TPC-DI benchmarking on Oracle Linux 8.6. Here are the first 3 rows:

000000|00:00:00|00|00|00|00:00|00|00:00:00|false|false
000001|00:00:01|00|00|00|00:00|01|00:00:01|false|false
000002|00:00:02|00|00|00|00:00|02|00:00:02|false|false

I tried to load the data into the table using the following ctl file:

LOAD DATA
INFILE
TRUNCATE
INTO TABLE DimTime
FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"' TRAILING NULLCOLS
(
    SK_TimeID,
    TimeValue DATE "HH24:MI:SS",
    HourID,
    HourDesc,
    MinuteID,
    MinuteDesc,
    SecondID,
    SecondDesc,
    MarketHoursFlag,
    OfficeHoursFlag
)

and running sqlldr userid=user/password@localhost/db_name control=DimTime.ctl data=path/to/Time.txt

But the log file states that the last column had an error:

Record 1: Rejected - Error on table DIMTIME, column OFFICEHOURSFLAG.
ORA-12899: value too large for column "SAYYUS"."DIMTIME"."OFFICEHOURSFLAG" (actual: 6, maximum: 5)

even though it contains only values "true" or "false" (max 5 characters) as can be seen in the sample file.

I am sure, the problem is that as explained by TPC-DI documentation, "records have a terminator character appropriate for the System Under Test". So it has a character at the end of each line that is appended to the last column but I cannot discard this character. I tried to put INFILE "STR X'0A'" as explained by this webpage and tried to trim the column in the ctl file: OfficeHoursFlag "TRIM (:OfficeHoursFlag)" but it didn't work.

Does anybody know what character is in the end of the line? How is it possible to discard it?


问:
WHENEVER SQLERROR of postgresql causes INTO assignment to fail
This is a piece of ecpg code. When using fetch to traverse the data, because of the use of WHENEVER SQLERROR DO sqlerr(), if an error occurs, it will be judged by the sqlerr method that it is a 22002 error, and the error will be ignored and the traversal will continue

```<code>int main(int argc, char *argv[]) {
    ....
    EXEC SQL DECLARE mt_cur CURSOR WITH HOLD FOR
            SELECT
                C1, C2, C3
            FROM MYTABLE,
            ORDER BY C1;
    EXEC SQL WHENEVER SQLERROR CONTINUE;
    EXEC SQL CLOSE mt_cur;
    EXEC SQL WHENEVER SQLERROR DO sqlerr();
    EXEC SQL OPEN mt_cur;
    EXEC SQL WHENEVER NOT FOUND DO break;

    while (1) {
        EXEC SQL FETCH mt_cur INTO :v1, :v2, :v3;
        if (v3 > 5 ) {
            continue;
        }
        printf("%d%d\n", v1, v3);
    }
    EXEC SQL CLOSE mt_cur;
    ....
    return (0);
}

void sqlerr() {
    if (strncmp(sqlca.sqlstate, "22002", 5) == 0) {
        return;
    }
    EXEC SQL WHENEVER SQLERROR CONTINUE;
    EXEC SQL ROLLBACK WORK;
    exit(1);
}

</code>```

If the data in the table is like this

```<code>C1   C2     C3
1    0      2
2    (NULL) 8
3    (NULL) 9
</code>```

The correct running result should be to print only one 12, but now it prints out 12, 22, 32

After analyzing the program, I think that when traversing the second row of data, the C2 column is NULL, which leads to entering the sqlerr method. After returning in sqlerr, INTO will not be executed to assign a value to v3, and it will enter the next traversal. At this time, the value of v3 is 2 assigned during the first traversal

Is my idea correct? If so, is there a way for postgresql to avoid this situation, I want the value of C3 to be INTO to v3 normally when C2 is NULL

Body:
This is a piece of ecpg code. When using fetch to traverse the data, because of the use of WHENEVER SQLERROR DO sqlerr(), if an error occurs, it will be judged by the sqlerr method that it is a 22002 error, and the error will be ignored and the traversal will continue

int main(int argc, char *argv[]) {
    ....
    EXEC SQL DECLARE mt_cur CURSOR WITH HOLD FOR
            SELECT
                C1, C2, C3
            FROM MYTABLE,
            ORDER BY C1;
    EXEC SQL WHENEVER SQLERROR CONTINUE;
    EXEC SQL CLOSE mt_cur;
    EXEC SQL WHENEVER SQLERROR DO sqlerr();
    EXEC SQL OPEN mt_cur;
    EXEC SQL WHENEVER NOT FOUND DO break;

    while (1) {
        EXEC SQL FETCH mt_cur INTO :v1, :v2, :v3;
        if (v3 > 5 ) {
            continue;
        }
        printf("%d%d\n", v1, v3);
    }
    EXEC SQL CLOSE mt_cur;
    ....
    return (0);
}

void sqlerr() {
    if (strncmp(sqlca.sqlstate, "22002", 5) == 0) {
        return;
    }
    EXEC SQL WHENEVER SQLERROR CONTINUE;
    EXEC SQL ROLLBACK WORK;
    exit(1);
}

If the data in the table is like this

C1   C2     C3
1    0      2
2    (NULL) 8
3    (NULL) 9

The correct running result should be to print only one 12, but now it prints out 12, 22, 32

After analyzing the program, I think that when traversing the second row of data, the C2 column is NULL, which leads to entering the sqlerr method. After returning in sqlerr, INTO will not be executed to assign a value to v3, and it will enter the next traversal. At this time, the value of v3 is 2 assigned during the first traversal

Is my idea correct? If so, is there a way for postgresql to avoid this situation, I want the value of C3 to be INTO to v3 normally when C2 is NULL


问:
{Widget: Product Filter – Filter by Attribute} Context-dependent product count
When the WooCommerce stock widget Filter by Attribute is set to show product count, it shows the number of products for each attribute term overall in the whole store.

However, I would like to change this behavior: Specifically, I would like the widget product count to be calculated based on the page on which the widget is appearing at any particular moment.

So, in essence, if the widget appears on X category page, it should show color red count as 5 (because category X has 5 red products)

but on category Y page, it should show color red count as 28 (because category Y has 28 red products), etc

The widget's class-wc-widget-layered-nav.php file has the following code:

```<code>/**
     * Count products within certain terms, taking the main WP query into consideration.
     *
     * This query allows counts to be generated based on the viewed products, not all products.
     *
     * @param  array  $term_ids Term IDs.
     * @param  string $taxonomy Taxonomy.
     * @param  string $query_type Query Type.
     * @return array
     */
    protected function get_filtered_term_product_counts( $term_ids, $taxonomy, $query_type ) {
        return wc_get_container()->get( Filterer::class )->get_filtered_term_product_counts( $term_ids, $taxonomy, $query_type );
    }
</code>```

but I'm not sure how to get it to work, since there's no UI for this.

Would appreciate any help.

Body:
When the WooCommerce stock widget Filter by Attribute is set to show product count, it shows the number of products for each attribute term overall in the whole store.

However, I would like to change this behavior: Specifically, I would like the widget product count to be calculated based on the page on which the widget is appearing at any particular moment.

So, in essence, if the widget appears on X category page, it should show color red count as 5 (because category X has 5 red products)

but on category Y page, it should show color red count as 28 (because category Y has 28 red products), etc

The widget's class-wc-widget-layered-nav.php file has the following code:

/**
     * Count products within certain terms, taking the main WP query into consideration.
     *
     * This query allows counts to be generated based on the viewed products, not all products.
     *
     * @param  array  $term_ids Term IDs.
     * @param  string $taxonomy Taxonomy.
     * @param  string $query_type Query Type.
     * @return array
     */
    protected function get_filtered_term_product_counts( $term_ids, $taxonomy, $query_type ) {
        return wc_get_container()->get( Filterer::class )->get_filtered_term_product_counts( $term_ids, $taxonomy, $query_type );
    }

but I'm not sure how to get it to work, since there's no UI for this.

Would appreciate any help.


问:
2 problems with binaryen.js
I tried writing some code based on binaryen.js 'https://www.npmjs.com/package/binaryen?activeTab=readme', but the following errors were given.

```<code>Compiled with problems:X

ERROR in ./node_modules/_binaryen@111.0.0@binaryen/index.js 5:1332-1348

Module not found: Error: Can't resolve 'module' in 'D:\web\pseudocode-ide\node_modules\_binaryen@111.0.0@binaryen'

ERROR in ./node_modules/_binaryen@111.0.0@binaryen/index.js

Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
Error: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
    at D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\dependencies\HarmonyDetectionParserPlugin.js:54:11
    at Hook.eval [as call] (eval at create (D:\web\pseudocode-ide\node_modules\_tapable@2.2.1@tapable\lib\HookCodeFactory.js:19:10), <anonymous>:7:16)
    at Hook.CALL_DELEGATE [as _call] (D:\web\pseudocode-ide\node_modules\_tapable@2.2.1@tapable\lib\Hook.js:14:14)
    at JavascriptParser.walkAwaitExpression (D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\javascript\JavascriptParser.js:2342:29)
    at JavascriptParser.walkExpression (D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\javascript\JavascriptParser.js:2272:10)
    at JavascriptParser.walkVariableDeclaration (D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\javascript\JavascriptParser.js:2126:33)
    at JavascriptParser.walkStatement (D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\javascript\JavascriptParser.js:1620:10)
    at JavascriptParser.walkStatements (D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\javascript\JavascriptParser.js:1481:9)
    at JavascriptParser.parse (D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\javascript\JavascriptParser.js:3375:9)
    at D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\NormalModule.js:1087:26
    at processResult (D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\NormalModule.js:800:11)
    at D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\NormalModule.js:860:5
    at D:\web\pseudocode-ide\node_modules\_loader-runner@4.3.0@loader-runner\lib\LoaderRunner.js:407:3
    at iterateNormalLoaders (D:\web\pseudocode-ide\node_modules\_loader-runner@4.3.0@loader-runner\lib\LoaderRunner.js:233:10)
    at iterateNormalLoaders (D:\web\pseudocode-ide\node_modules\_loader-runner@4.3.0@loader-runner\lib\LoaderRunner.js:240:10)
    at D:\web\pseudocode-ide\node_modules\_loader-runner@4.3.0@loader-runner\lib\LoaderRunner.js:255:3
    at context.callback (D:\web\pseudocode-ide\node_modules\_loader-runner@4.3.0@loader-runner\lib\LoaderRunner.js:124:13)
    at D:\web\pseudocode-ide\node_modules\babel-loader\lib\index.js:59:71

</code>```

I tried searching up solutions but none of them worked

Title: 2 problems with binaryen.js

Body:
I tried writing some code based on binaryen.js 'https://www.npmjs.com/package/binaryen?activeTab=readme', but the following errors were given.

Compiled with problems:X

ERROR in ./node_modules/_binaryen@111.0.0@binaryen/index.js 5:1332-1348

Module not found: Error: Can't resolve 'module' in 'D:\web\pseudocode-ide\node_modules\_binaryen@111.0.0@binaryen'

ERROR in ./node_modules/_binaryen@111.0.0@binaryen/index.js

Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
Error: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
    at D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\dependencies\HarmonyDetectionParserPlugin.js:54:11
    at Hook.eval [as call] (eval at create (D:\web\pseudocode-ide\node_modules\_tapable@2.2.1@tapable\lib\HookCodeFactory.js:19:10), <anonymous>:7:16)
    at Hook.CALL_DELEGATE [as _call] (D:\web\pseudocode-ide\node_modules\_tapable@2.2.1@tapable\lib\Hook.js:14:14)
    at JavascriptParser.walkAwaitExpression (D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\javascript\JavascriptParser.js:2342:29)
    at JavascriptParser.walkExpression (D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\javascript\JavascriptParser.js:2272:10)
    at JavascriptParser.walkVariableDeclaration (D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\javascript\JavascriptParser.js:2126:33)
    at JavascriptParser.walkStatement (D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\javascript\JavascriptParser.js:1620:10)
    at JavascriptParser.walkStatements (D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\javascript\JavascriptParser.js:1481:9)
    at JavascriptParser.parse (D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\javascript\JavascriptParser.js:3375:9)
    at D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\NormalModule.js:1087:26
    at processResult (D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\NormalModule.js:800:11)
    at D:\web\pseudocode-ide\node_modules\_webpack@5.75.0@webpack\lib\NormalModule.js:860:5
    at D:\web\pseudocode-ide\node_modules\_loader-runner@4.3.0@loader-runner\lib\LoaderRunner.js:407:3
    at iterateNormalLoaders (D:\web\pseudocode-ide\node_modules\_loader-runner@4.3.0@loader-runner\lib\LoaderRunner.js:233:10)
    at iterateNormalLoaders (D:\web\pseudocode-ide\node_modules\_loader-runner@4.3.0@loader-runner\lib\LoaderRunner.js:240:10)
    at D:\web\pseudocode-ide\node_modules\_loader-runner@4.3.0@loader-runner\lib\LoaderRunner.js:255:3
    at context.callback (D:\web\pseudocode-ide\node_modules\_loader-runner@4.3.0@loader-runner\lib\LoaderRunner.js:124:13)
    at D:\web\pseudocode-ide\node_modules\babel-loader\lib\index.js:59:71

I tried searching up solutions but none of them worked


问:
why the object literal doesn't have a length property throws error
I have a simple object as below

{"a" : 1}.length```
</div>
</div>
</p>
<p>This throws an error and makes sense that the object doesn't have a length property in its prototype ... but</p>
<p>why does assigning it a variable and accessing the props which are not there will return <code>undefined</code> ?</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>const obj = {"a" : 123};

console.log(obj.length)</code>```

sorry, what am I missing here , thanks for your suggestions ..

Body:
I have a simple object as below

{"a" : 1}.length

This throws an error and makes sense that the object doesn't have a length property in its prototype ... but

why does assigning it a variable and accessing the props which are not there will return undefined ?

const obj = {"a" : 123};

console.log(obj.length)

sorry, what am I missing here , thanks for your suggestions ..


问:
1 node(s) had taint, that the pod didn't tolerate, 4 Insufficient CPUs
I have a namespace HPA configuration as follows:-

NAME   REFERENCE        TARGETS   MINPODS   MAXPODS   REPLICAS   AGE

web    Deployment/web   0%/65%    3         5         3          385d

the namespace created 3 pods and then I invoked a deployment

for that new deployment, it started creating new pods but the pods are not able to be in a running state they

goes into CrashLoopBackOff state and the error is as follows

1 node(s) had taint, that the pod didn't tolerate, 4 Insufficient CPUs.

because it was a burning issue I deleted the deployment and started the new deployment from CI then it deleted the old pods and the new pods were recreated but it generated some downtime

I think there must be some other way to handle this or I have misconfigured the number of replicas and min/max pods


问:
How to get task id in tokio with tokio_unstable
I'm trying to compile the following code,

```<code>let id = tokio::task::id();
</code>```

I have enabled both "rt" feature and tokio_unstable. But it's giving me an error like the following

```<code>error[E0425]: cannot find function `id` in module `tokio::task`
--> xxxx\src\util\utils.rs:27:35
|
27 | let id = tokio::task::id();
| ^^ not found in `tokio::task`
|
help: consider importing this function
|
1 | use std::process::id;
|
help: if you import `id`, refer to it directly
|
27 - let id = tokio::task::id();
27 + let id = id();
|
</code>```

What should I do to fix this ?

Body:
I'm trying to compile the following code,

let id = tokio::task::id();

I have enabled both "rt" feature and tokio_unstable. But it's giving me an error like the following

error[E0425]: cannot find function `id` in module `tokio::task`
--> xxxx\src\util\utils.rs:27:35
|
27 | let id = tokio::task::id();
| ^^ not found in `tokio::task`
|
help: consider importing this function
|
1 | use std::process::id;
|
help: if you import `id`, refer to it directly
|
27 - let id = tokio::task::id();
27 + let id = id();
|

What should I do to fix this ?


问:
error when calling lua custom search function in telescope
I have telescope installed and functioning correctly. But when calling a custom telescope builtin I get the error:

```<code>E5108: Error executing lua [string ":lua"]:1: attempt to index a boolean value
stack traceback:
        [string ":lua"]:1: in main chunk
</code>```

I can type :Telescope live_grep and search file contents.  I have tried to create a couple of customizations to search in a specific directory etc.  I have even copied more than a couple of configs from the www.  I have put for example the following in a file  lua/config/telescope-custom.lua.

```<code>local M = {}

function M.dotfiles()
  require("telescope.builtin").find_files({
    prompt_title = "< config >",
    prompt_prefix = "",
    cwd = "$HOME/.config/",
  })

  function M.mandenkan()
    require("telescope.builtin").live_grep({
      cwd = "$HOME/Documents/Jula/search",
      prompt_title = "< mandenkan >",
      prompt_prefix = "",
      layout_strategy = "horizontal",
    })
  end

  function M.find_notes()
    require("telescope.builtin").find_files({
      prompt_title = " Find Notes",
      path_display = { "smart" },
      cwd = "~/notes/",
      layout_strategy = "horizontal",
      layout_config = { preview_width = 0.65, width = 0.75 },
    })
  end

  return M
end
</code>```

But if I try to run this by typing :lua require'c._telescope-custom'.find_notes(), I get

```<code>E5108: Error executing lua [string ":lua"]:1: attempt to index a boolean value
stack traceback:
        [string ":lua"]:1: in main chunk
</code>```

I have tried putting the custom builtin functions at the end of the telescope.lua file with the same result.

What do I need to do to make this work?

NB:  This was actually working a few months back.  No idea what has happened.

Body:
I have telescope installed and functioning correctly. But when calling a custom telescope builtin I get the error:

E5108: Error executing lua [string ":lua"]:1: attempt to index a boolean value
stack traceback:
        [string ":lua"]:1: in main chunk

I can type :Telescope live_grep and search file contents.  I have tried to create a couple of customizations to search in a specific directory etc.  I have even copied more than a couple of configs from the www.  I have put for example the following in a file  lua/config/telescope-custom.lua.

local M = {}

function M.dotfiles()
  require("telescope.builtin").find_files({
    prompt_title = "< config >",
    prompt_prefix = "",
    cwd = "$HOME/.config/",
  })

  function M.mandenkan()
    require("telescope.builtin").live_grep({
      cwd = "$HOME/Documents/Jula/search",
      prompt_title = "< mandenkan >",
      prompt_prefix = "",
      layout_strategy = "horizontal",
    })
  end

  function M.find_notes()
    require("telescope.builtin").find_files({
      prompt_title = " Find Notes",
      path_display = { "smart" },
      cwd = "~/notes/",
      layout_strategy = "horizontal",
      layout_config = { preview_width = 0.65, width = 0.75 },
    })
  end

  return M
end

But if I try to run this by typing :lua require'c._telescope-custom'.find_notes(), I get

E5108: Error executing lua [string ":lua"]:1: attempt to index a boolean value
stack traceback:
        [string ":lua"]:1: in main chunk

I have tried putting the custom builtin functions at the end of the telescope.lua file with the same result.

What do I need to do to make this work?

NB:  This was actually working a few months back.  No idea what has happened.


问:
TS: Mongoose Union Type of two Models: findOne Signatures incompatible
This is about a type error in Typescript.

I have two Mongoose Models with different types of documents. They share some properties and I want to be able to use findOne on the union type of both Models. I am told the two function signatures are incompatible by Typescript.

I am dealing with two collections. All documents that share a collection have the same fields. Between collections, the documents share some of their properties. General things like createdAt and _id but also more specific things. However, they also differ in a few key ways, which is why I separated them in the first place.

I now have two Mongoose Models for these two collections. Let's call them ModelA and ModelB. Inside a function, I have some code where it doesn't matter which of the two collections I am dealing with. The function could look like this:

```<code>async function foo(model: ModelA | ModelB, query: any) {
    const res = await model.findOne(query);
    console.log(res);
}
</code>```

The above code underlines findOne with the error:

```<code>Each member of the union type
'{ <ResultDoc = Document<unknown, any, InterfaceA> & InterfaceA & { _id: ObjectId; }>(filter?:
FilterQuery<InterfaceA>, projection?: ProjectionType<InterfaceA>, options?: QueryOptions<...>,
callback?: Callback<...>): Query<...>; <ResultDoc = Document<...> & ... 1 more ...
& { ...; }>(filter?: FilterQuery<...>, projection?: Projectio...'
has signatures, but none of those signatures are compatible with each other.
</code>```

Looking at the signature I see that, indeed,

ModelA.findOne expects filter?: mongoose.FilterQuery<InterfaceA> as it's first parameter and

ModelB.findOne expects filter?: mongoose.FilterQuery<InterfaceB>.

I don't care about these differences though and hoped that Typescript would just figure out that they're basically the same and union them. I just want compatible functions I can call and get something along the lines of Document<InterfaceA> | Document<InterfaceB> as res.

What would be a simple solution to achieve this? Is there a way to do it without having to resort to wrapping this in an extra function each time?

Body:
This is about a type error in Typescript.

I have two Mongoose Models with different types of documents. They share some properties and I want to be able to use findOne on the union type of both Models. I am told the two function signatures are incompatible by Typescript.

I am dealing with two collections. All documents that share a collection have the same fields. Between collections, the documents share some of their properties. General things like createdAt and _id but also more specific things. However, they also differ in a few key ways, which is why I separated them in the first place.

I now have two Mongoose Models for these two collections. Let's call them ModelA and ModelB. Inside a function, I have some code where it doesn't matter which of the two collections I am dealing with. The function could look like this:

async function foo(model: ModelA | ModelB, query: any) {
    const res = await model.findOne(query);
    console.log(res);
}

The above code underlines findOne with the error:

Each member of the union type
'{ <ResultDoc = Document<unknown, any, InterfaceA> & InterfaceA & { _id: ObjectId; }>(filter?:
FilterQuery<InterfaceA>, projection?: ProjectionType<InterfaceA>, options?: QueryOptions<...>,
callback?: Callback<...>): Query<...>; <ResultDoc = Document<...> & ... 1 more ...
& { ...; }>(filter?: FilterQuery<...>, projection?: Projectio...'
has signatures, but none of those signatures are compatible with each other.

Looking at the signature I see that, indeed,

ModelA.findOne expects filter?: mongoose.FilterQuery<InterfaceA> as it's first parameter and

ModelB.findOne expects filter?: mongoose.FilterQuery<InterfaceB>.

I don't care about these differences though and hoped that Typescript would just figure out that they're basically the same and union them. I just want compatible functions I can call and get something along the lines of Document<InterfaceA> | Document<InterfaceB> as res.

What would be a simple solution to achieve this? Is there a way to do it without having to resort to wrapping this in an extra function each time?


问:
How to make Visual Studio Code Autocomplete for Library Function, not user-defined element as first suggestion
I'm using JavaScript React in VSCode and the autocomplete's first suggestion is to make an element of whatever word I'm using. See image:

After pressing tab:

This makes me always have to press the down arrow each time and is annoying. How can I make suggestions like isRequired the first result so I dont need to always press the down key to select it

I changed the language to JavaScript react but it still thinks i'm creating my own elements, and only suggests react syntax below it.


问:
Producing incorrect `asin(x)` result using a Taylor Series
I am struggling to understand what error I have with my Taylor series asin(x) method.

The expansion being implemented is:

Thanks in advance for any recommendations!

*Edit: removed the asin_x = -asin_x; negation per the recommendation from @Sam Varshavchik.  Now it works as it should.

```<code>Decimal Decimal::get_asin() const {

    /*
        Perform a Taylor Series estimation of
        the natural logarithm of this number.
    */

    Decimal one(ONE);
    Decimal two(TWO);

    Decimal x = *this;
    Decimal asin_x = x;

    Decimal asin_x_iter = x;

    Decimal asin_power(3);

    Decimal num_coef(1);
    Decimal den_coef(2);

    Decimal last;

    // Perform the calculation until the last 'last_iter' Decimal
    // is the same as the current calculation 'term'.

    while (last.get_Integer().get_Whole_Number() != asin_x.get_Integer().get_Whole_Number()) {

        last = asin_x;

        asin_x_iter *= x;
        asin_x_iter *= x;

        asin_x += (one / (den_coef * asin_power)) * (num_coef * asin_x_iter);

        num_coef   *= asin_power;
        asin_power += one;
        den_coef   *= asin_power;
        asin_power += one;
    }

    return asin_x;
}
</code>```

I have checked on this and other StackExchange forums, and have not found clarification.  All of the similar questions I looked at used factorial, power functions, or other build-in functions. The only operators usable here are the standard math operators plus negation.

When running the asin(x), I get the result where x = 0.2 results in x = 0.19869011034924140647463691595020, when it should be x = 0.20135792079033079145512555221762.

Body:
I am struggling to understand what error I have with my Taylor series asin(x) method.

The expansion being implemented is:

Thanks in advance for any recommendations!

*Edit: removed the asin_x = -asin_x; negation per the recommendation from @Sam Varshavchik.  Now it works as it should.

Decimal Decimal::get_asin() const {

    /*
        Perform a Taylor Series estimation of
        the natural logarithm of this number.
    */

    Decimal one(ONE);
    Decimal two(TWO);

    Decimal x = *this;
    Decimal asin_x = x;

    Decimal asin_x_iter = x;

    Decimal asin_power(3);

    Decimal num_coef(1);
    Decimal den_coef(2);

    Decimal last;

    // Perform the calculation until the last 'last_iter' Decimal
    // is the same as the current calculation 'term'.

    while (last.get_Integer().get_Whole_Number() != asin_x.get_Integer().get_Whole_Number()) {

        last = asin_x;

        asin_x_iter *= x;
        asin_x_iter *= x;

        asin_x += (one / (den_coef * asin_power)) * (num_coef * asin_x_iter);

        num_coef   *= asin_power;
        asin_power += one;
        den_coef   *= asin_power;
        asin_power += one;
    }

    return asin_x;
}

I have checked on this and other StackExchange forums, and have not found clarification.  All of the similar questions I looked at used factorial, power functions, or other build-in functions. The only operators usable here are the standard math operators plus negation.

When running the asin(x), I get the result where x = 0.2 results in x = 0.19869011034924140647463691595020, when it should be x = 0.20135792079033079145512555221762.


问:
Why does my app's icon appear before my splash screen image in android jetpack compose?
I made a dictionary app and there is a splash screen from the dictionary app , and I show an image on the splash screen. When I completed the app, I changed the icon of the app and when I change the icon of the app, this icon appears on the screen for a while before my picture on the splash screen. However, before changing the icon of the app, such a thing did not happen when it was default. I want to change this, so I want only the picture I showed on the splash screen to be displayed. By the way, the icon of the application and the picture I show on the splash screen are different from each other.

Have you encountered something like this before?

here is my splash screen

```<code>@Composable
fun SplashScreen(
    navController: NavController,
    viewModel : SplashScreenViewModel = hiltViewModel()) {

    val context: Context = LocalContext.current

    val scale = remember {
        Animatable(0f)
    }

    LaunchedEffect(key1 = true) {
        scale.animateTo(
            targetValue = 1f,
            animationSpec = tween(
                durationMillis = 500,
                easing = {
                    OvershootInterpolator(2f).getInterpolation(it)
                }
            )
        )

        delay(3000L)

        navController.navigate(Screen.MainScreen.route)
    }

    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {

        Image(
            painter = painterResource(id = R.drawable.ic_splash_screen_dictionary2),
            contentDescription = "Logo",
            modifier = Modifier.scale(scale.value)
        )
    }

}
</code>```

Body:
I made a dictionary app and there is a splash screen from the dictionary app , and I show an image on the splash screen. When I completed the app, I changed the icon of the app and when I change the icon of the app, this icon appears on the screen for a while before my picture on the splash screen. However, before changing the icon of the app, such a thing did not happen when it was default. I want to change this, so I want only the picture I showed on the splash screen to be displayed. By the way, the icon of the application and the picture I show on the splash screen are different from each other.

Have you encountered something like this before?

here is my splash screen

@Composable
fun SplashScreen(
    navController: NavController,
    viewModel : SplashScreenViewModel = hiltViewModel()) {

    val context: Context = LocalContext.current

    val scale = remember {
        Animatable(0f)
    }

    LaunchedEffect(key1 = true) {
        scale.animateTo(
            targetValue = 1f,
            animationSpec = tween(
                durationMillis = 500,
                easing = {
                    OvershootInterpolator(2f).getInterpolation(it)
                }
            )
        )

        delay(3000L)

        navController.navigate(Screen.MainScreen.route)
    }

    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {

        Image(
            painter = painterResource(id = R.drawable.ic_splash_screen_dictionary2),
            contentDescription = "Logo",
            modifier = Modifier.scale(scale.value)
        )
    }

}


问:
command is not executed in a controller
I would like to run a command via a controller. My command run normaly in cli (tests are done)
My controller call the command and I got immediately

```<code> [OK] success
</code>```

from the command return but tests did not run.

my controller
`

```<code>    <?php

namespace App\Controller\Api;

use OpenApi\Annotations as OA;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Process\Process;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;

class UnitTestController extends AbstractController
{
    private $kernel;

    public function __construct(KernelInterface $kernel)
    {
        $this->kernel = $kernel;
    }
    #[Route('/unit_tests', name: 'unit_test', methods: 'GET')]
    public function unitTest(): Response
    {
        $application = new Application($this->kernel);
        $application->setAutoExit(false);

        $input = new ArrayInput([
            'command' => 'mapi:unitTests',
        ]);
        $output = new BufferedOutput();
        $application->run($input, $output);

        // return the output, don't use if you used NullOutput()
        $content = $output->fetch();
        dd($content);

    }
}
</code>```

`

and my command
`

```<code><?php

namespace App\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Process\Process;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;

#[AsCommand(
    name: 'mapi:unitTests',
    description: 'lancement des tests unitaires',
)]
class unitTestCommand extends Command
{
    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     * @throws ClientExceptionInterface
     * @throws DecodingExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ServerExceptionInterface
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        ini_set('max_execution_time', 300);
        $process = Process::fromShellCommandline('php vendor/bin/phpunit');
        $process->run();
        $io->success('success');

        return Command::SUCCESS;
    }
}

</code>```

edit: no error, unit tests from command are not executed. when I run the command from the cli, everything is ok
`

Title: command is not executed in a controller

Body:
I would like to run a command via a controller. My command run normaly in cli (tests are done)
My controller call the command and I got immediately

 [OK] success

from the command return but tests did not run.

my controller
`

    <?php

namespace App\Controller\Api;

use OpenApi\Annotations as OA;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Process\Process;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;

class UnitTestController extends AbstractController
{
    private $kernel;

    public function __construct(KernelInterface $kernel)
    {
        $this->kernel = $kernel;
    }
    #[Route('/unit_tests', name: 'unit_test', methods: 'GET')]
    public function unitTest(): Response
    {
        $application = new Application($this->kernel);
        $application->setAutoExit(false);

        $input = new ArrayInput([
            'command' => 'mapi:unitTests',
        ]);
        $output = new BufferedOutput();
        $application->run($input, $output);

        // return the output, don't use if you used NullOutput()
        $content = $output->fetch();
        dd($content);

    }
}

`

and my command
`

<?php

namespace App\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Process\Process;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;

#[AsCommand(
    name: 'mapi:unitTests',
    description: 'lancement des tests unitaires',
)]
class unitTestCommand extends Command
{
    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     * @throws ClientExceptionInterface
     * @throws DecodingExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ServerExceptionInterface
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        ini_set('max_execution_time', 300);
        $process = Process::fromShellCommandline('php vendor/bin/phpunit');
        $process->run();
        $io->success('success');

        return Command::SUCCESS;
    }
}

edit: no error, unit tests from command are not executed. when I run the command from the cli, everything is ok
`


问:
HADOOP exceeding memory limit
I am receiving follow message under the unhealthy node section.

```<code> 1/1 local-dirs usable space is below configured utilization percentage/no more usable space [ /tmp/hadoop-User/nm-local-dir : used space above threshold of 90.0% ]
1/1 log-dirs usable space is below configured utilization percentage/no more usable space [ C:/hadoop-3.3.0/logs/userlogs : used space above threshold of 90.0% ]
</code>```

I saw a solution previously, either clean up the disk where the hadoop node is running on or increase the limit in yarn file. I do not want to increase the value in yarn file, I want to clean up the disk. Can anybody tell me what should I delete, i.e. where is the location on which hadoop is running its jobs?

Title: HADOOP exceeding memory limit

Body:
I am receiving follow message under the unhealthy node section.

 1/1 local-dirs usable space is below configured utilization percentage/no more usable space [ /tmp/hadoop-User/nm-local-dir : used space above threshold of 90.0% ]
1/1 log-dirs usable space is below configured utilization percentage/no more usable space [ C:/hadoop-3.3.0/logs/userlogs : used space above threshold of 90.0% ]

I saw a solution previously, either clean up the disk where the hadoop node is running on or increase the limit in yarn file. I do not want to increase the value in yarn file, I want to clean up the disk. Can anybody tell me what should I delete, i.e. where is the location on which hadoop is running its jobs?


问:
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist
I'm working on a chrome extension and I'm trying to detect the input value in the popup.js file like this:

```<code>// popup.js

// Set up a listener for when the popup is opened
document.addEventListener("DOMContentLoaded", function () {
  // Get a reference to the input field
  var inputField = document.getElementById("input-field");
  // Set up a listener for when the user types in the input field
  // send a message to the background script to check if it's working
  chrome.runtime.sendMessage({
    type: "getSuggestion",
    prompt: inputField.value,
  });

  inputField.addEventListener("input", function () {
    // Send a message to the content script to get a suggestion
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      console.log("inputField.value: ", inputField.value);
      chrome.tabs.sendMessage(
        tabs[0].id,
        {
          type: "getSuggestion",
          prompt: inputField.value,
        },
        function (response) {
          console.log("response: ", response);
        }
      );
    });
  });
});
</code>```

and I'm trying to send it to the background.js just to console log it for the moment like this:

```<code>
// Set up a listener for messages from the content script
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.type === "getSuggestion") {
    console.log("request.prompt: ", request);
    return request.prompt;
});
</code>```

And this is the content.js script:

```<code>// Listen for messages from the background script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  // Get the suggested text from the message
  const suggestion = request.textSuggestion;

  // Modify the DOM to display the suggested text to the user
  const suggestionEl = document.createElement("div");
  suggestionEl.innerHTML = suggestion;
  suggestionEl.style.position = "absolute";
  suggestionEl.style.top = "0";
  suggestionEl.style.left = "0";
  suggestionEl.style.backgroundColor = "white";
  suggestionEl.style.padding = "10px";
  suggestionEl.style.zIndex = "9999";
  suggestionEl.style.fontSize = "16px";
  document.body.appendChild(suggestionEl);
</code>```

But I'm getting this error:
popup.html:1 Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

here is the popup.html file just in case:

```<code><!-- popup.html -->

<!DOCTYPE html>
<html>
  <head>
    <title>WordCompleter</title>
    <link rel="stylesheet" type="text/css" href="popup.css" />
  </head>
  <body>
    <div id="input-container">
      <input type="text" id="input-field" />
    </div>
    <div id="suggestion-container">
      <p id="suggestion-field"></p>
    </div>
    <script src="popup.js"></script>
  </body>
</html>
</code>```

Body:
I'm working on a chrome extension and I'm trying to detect the input value in the popup.js file like this:

// popup.js

// Set up a listener for when the popup is opened
document.addEventListener("DOMContentLoaded", function () {
  // Get a reference to the input field
  var inputField = document.getElementById("input-field");
  // Set up a listener for when the user types in the input field
  // send a message to the background script to check if it's working
  chrome.runtime.sendMessage({
    type: "getSuggestion",
    prompt: inputField.value,
  });

  inputField.addEventListener("input", function () {
    // Send a message to the content script to get a suggestion
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      console.log("inputField.value: ", inputField.value);
      chrome.tabs.sendMessage(
        tabs[0].id,
        {
          type: "getSuggestion",
          prompt: inputField.value,
        },
        function (response) {
          console.log("response: ", response);
        }
      );
    });
  });
});

and I'm trying to send it to the background.js just to console log it for the moment like this:

// Set up a listener for messages from the content script
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.type === "getSuggestion") {
    console.log("request.prompt: ", request);
    return request.prompt;
});

And this is the content.js script:

// Listen for messages from the background script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  // Get the suggested text from the message
  const suggestion = request.textSuggestion;

  // Modify the DOM to display the suggested text to the user
  const suggestionEl = document.createElement("div");
  suggestionEl.innerHTML = suggestion;
  suggestionEl.style.position = "absolute";
  suggestionEl.style.top = "0";
  suggestionEl.style.left = "0";
  suggestionEl.style.backgroundColor = "white";
  suggestionEl.style.padding = "10px";
  suggestionEl.style.zIndex = "9999";
  suggestionEl.style.fontSize = "16px";
  document.body.appendChild(suggestionEl);

But I'm getting this error:
popup.html:1 Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

here is the popup.html file just in case:

<!DOCTYPE html>

    <title>WordCompleter</title>
    <link rel="stylesheet" type="text/css" href="popup.css" />

      <input type="text" id="input-field" />


问:
RegEx for exact word search starting with Umlaut
I am slowly getting a bit frustrated with regex and German Umlaute. For a speech reader function, I need to get each single word, wrap each word in a span-tag with an index and so. It all works fine so far. But as soon as a word starts with a German Umlaut it fails.

Here is an example text:

Touch-Screen ist Englisch und wird Tatsch-Skrien ausgesprochen.
Übersetzt bedeutet Touchscreen Berührungsbildschirm. Es ist ein
berührungsempfindlicher Bildschirm. Zur Bedienung muss man mit dem
Finger die Oberfläche des Bildschirms berühren.

And this is the regular expression to find the word "Übersetzt":

```<code>/\b(Übersetzt)\b(?![^<span.*>]*<\/span>)/
</code>```

The span-tag part is needed, since each word will get wrapped in word.
So to prevent finding the same word twice, this will exclude those already span-tag wrapped words.

But it fails with words starting with an Umlaut. I added other words starting with an Umlaut, and they all failed. If an Umlaut is somewhere in the middle, it doesn't matter. But as soon as a word starts with an Umlaut, it just doesn't work. Maybe someone has a suggestion what I am missing here. Thanks for any advice or help.

I tried figuring out a solution using https://regexr.com/. But it didn't help. Even tried to use \u00dc instead of Ü didn't help in this regex.

Body:
I am slowly getting a bit frustrated with regex and German Umlaute. For a speech reader function, I need to get each single word, wrap each word in a span-tag with an index and so. It all works fine so far. But as soon as a word starts with a German Umlaut it fails.

Here is an example text:

Touch-Screen ist Englisch und wird Tatsch-Skrien ausgesprochen.
Übersetzt bedeutet Touchscreen Berührungsbildschirm. Es ist ein
berührungsempfindlicher Bildschirm. Zur Bedienung muss man mit dem
Finger die Oberfläche des Bildschirms berühren.

And this is the regular expression to find the word "Übersetzt":

/\b(Übersetzt)\b(?![^]*<\/span>)/

The span-tag part is needed, since each word will get wrapped in word.
So to prevent finding the same word twice, this will exclude those already span-tag wrapped words.

But it fails with words starting with an Umlaut. I added other words starting with an Umlaut, and they all failed. If an Umlaut is somewhere in the middle, it doesn't matter. But as soon as a word starts with an Umlaut, it just doesn't work. Maybe someone has a suggestion what I am missing here. Thanks for any advice or help.

I tried figuring out a solution using https://regexr.com/. But it didn't help. Even tried to use \u00dc instead of Ü didn't help in this regex.


问:
Post Request in ADF
I'm creating a pipeline in ADF that sends a post request, but it's returning the attached error.
Could you help what I might be doing wrong?
Below I put the code generated in the ADF for the post and the image with the error to facilitate the help.
What am I doing wrong, I can't identify my mistake.
Thank you all.

Error

Pipeline

I created the Web pipeline with the code below and it returned an error.

```<code>{

    "name": "xxxx_xxxx",

    "type": "WebActivity",

    "dependsOn": [],

    "policy": {

        "timeout": "0.12:00:00",

        "retry": 0,

        "retryIntervalInSeconds": 30,

        "secureOutput": false,

        "secureInput": false

    },

    "userProperties": [],

    "typeProperties": {

        "url": "https://xxxxxx/xxxxx/xxxx",

        "connectVia": {

            "referenceName": "AutoResolveIntegrationRuntime",

            "type": "IntegrationRuntimeReference"

        },

        "method": "POST",

        "body": {

            "fornecedor": "string",

            "tipoArquivo": "string",

            "data": [

                {

                    "id": 0,

                    "placa": "string",

                    "rastreadorNumeroSerie": "string",

                    "tipoEvento": "string",

                    "tempo": 0,

                    "rastreadorBateriaInternaAtiva": 0,

                    "rastreadorBateriaInternaTensao": 0,

                    "dataHoraEvento": "2022-12-24T14:23:14.865Z",

                    "gpsFixado": 0,

                    "latitudeInicio": 0,

                    "longitudeInicio": 0,

                    "latitudeFim": 0,

                    "longitudeFim": 0,

                    "velocidade": 0,

                    "altitude": 0,

                    "odometro": 0,

                    "bateriaExternaAtiva": 0,

                    "bateriaExternaTensao": 0,

                    "ignicao": 0,

                    "revGeoLogradouro": "string",

                    "revGeoFaixaNumeracao": "string",

                    "revGeoCep": "string",

                    "revGeoMunicipio": "string",

                    "revGeoUf": "string",

                    "horimetro": 0,

                    "sleep": 0,

                    "rpm": 0

                }

            ]

        }

    }

}
</code>```

Title: Post Request in ADF

Body:
I'm creating a pipeline in ADF that sends a post request, but it's returning the attached error.
Could you help what I might be doing wrong?
Below I put the code generated in the ADF for the post and the image with the error to facilitate the help.
What am I doing wrong, I can't identify my mistake.
Thank you all.

Error

Pipeline

I created the Web pipeline with the code below and it returned an error.

{

    "name": "xxxx_xxxx",

    "type": "WebActivity",

    "dependsOn": [],

    "policy": {

        "timeout": "0.12:00:00",

        "retry": 0,

        "retryIntervalInSeconds": 30,

        "secureOutput": false,

        "secureInput": false

    },

    "userProperties": [],

    "typeProperties": {

        "url": "https://xxxxxx/xxxxx/xxxx",

        "connectVia": {

            "referenceName": "AutoResolveIntegrationRuntime",

            "type": "IntegrationRuntimeReference"

        },

        "method": "POST",

        "body": {

            "fornecedor": "string",

            "tipoArquivo": "string",

            "data": [

                {

                    "id": 0,

                    "placa": "string",

                    "rastreadorNumeroSerie": "string",

                    "tipoEvento": "string",

                    "tempo": 0,

                    "rastreadorBateriaInternaAtiva": 0,

                    "rastreadorBateriaInternaTensao": 0,

                    "dataHoraEvento": "2022-12-24T14:23:14.865Z",

                    "gpsFixado": 0,

                    "latitudeInicio": 0,

                    "longitudeInicio": 0,

                    "latitudeFim": 0,

                    "longitudeFim": 0,

                    "velocidade": 0,

                    "altitude": 0,

                    "odometro": 0,

                    "bateriaExternaAtiva": 0,

                    "bateriaExternaTensao": 0,

                    "ignicao": 0,

                    "revGeoLogradouro": "string",

                    "revGeoFaixaNumeracao": "string",

                    "revGeoCep": "string",

                    "revGeoMunicipio": "string",

                    "revGeoUf": "string",

                    "horimetro": 0,

                    "sleep": 0,

                    "rpm": 0

                }

            ]

        }

    }

}


问:
How to return error to user if backend returns error code Redux toolkit query
i am using Redux-toolkit-query in React.js project , Now the problem i am facing is when the backend return statusCode is 0, i want to  add isError property to  true and add the response message to error, even if the status is 200 ,

```<code>const [getBrandInfo, { isLoading, isError, error }] =
    useGetBrandInfoMutation();

const userApi = apiSlice.injectEndpoints({
      endpoints: (builder) => ({
        getBrandInfo: builder.mutation({
          query: (body) => ({
            url: URL.GET_SETTINGS,
            method: "POST",
            body: body,
            responseHandler: (response) => response.json(),
            validateStatus: (response, result) =>
              response.status === 200 && result?.statusCode === 1,
          }),
          transformResponse: (response) => {
            return response;
          },
</code>```

Body:
i am using Redux-toolkit-query in React.js project , Now the problem i am facing is when the backend return statusCode is 0, i want to  add isError property to  true and add the response message to error, even if the status is 200 ,

const [getBrandInfo, { isLoading, isError, error }] =
    useGetBrandInfoMutation();

const userApi = apiSlice.injectEndpoints({
      endpoints: (builder) => ({
        getBrandInfo: builder.mutation({
          query: (body) => ({
            url: URL.GET_SETTINGS,
            method: "POST",
            body: body,
            responseHandler: (response) => response.json(),
            validateStatus: (response, result) =>
              response.status === 200 && result?.statusCode === 1,
          }),
          transformResponse: (response) => {
            return response;
          },


问:
Why am not getting correct output but getting a error df not defined
Here is the code:

import pandas as pd
import plotly.express as px

df = pd.read_csv('cases.csv')
fig = px.scatter(df, x='cases', y='date', color='country', size_max=30)

fig.show()
```
<p>and the error:</p>
<pre class="lang-bash prettyprint-override"><code>C:\Users\PC\Documents\Python_Code\pythonBar> python ScatterProject.py
Traceback (most recent call last):
  File "ScatterProject.py", line 5, in <module>
    fig = px.scatter(df,x="cases",y="date", color ="country", size_max=30)
NameError: name 'df' is not defined
</code>```

I am not getting output but a error coming that df is not defined even tho it is

I was expecting the output A graph but the unexpected error came

Body:
Here is the code:

import pandas as pd
import plotly.express as px

df = pd.read_csv('cases.csv')
fig = px.scatter(df, x='cases', y='date', color='country', size_max=30)

fig.show()

and the error:

C:\Users\PC\Documents\Python_Code\pythonBar> python ScatterProject.py
Traceback (most recent call last):
  File "ScatterProject.py", line 5, in <module>
    fig = px.scatter(df,x="cases",y="date", color ="country", size_max=30)
NameError: name 'df' is not defined

I am not getting output but a error coming that df is not defined even tho it is

I was expecting the output A graph but the unexpected error came


问:
React-i18next and Google Translate extension
I have a website available in 'en' and 'fr' using react-i18next.
When loading the Website, I check the browser settings with Javascript to detect the preferred language of the user (navigator.languages) and informs react-i18next of the language to use. I update also the "lang" attribute of the "html" tag.

Everything works perfectly expect in one case: when the browser has the "Google translate" extension configured to always translate the English pages in French. In my case, the extension always translate my Website from French (thinking it is English) to French.

How can I avoid this problem ?


问:
i18next always give me fallback language response
My Imports

import i18next from 'i18next'
import Backend from 'i18next-fs-backend'
import middleware from 'i18next-http-middleware'
```
<p>While using i18next for localization always give me fallback langauge</p>
<p>My requests header {Accept-Language:"ar"}
Code config</p>
<pre class="lang-js prettyprint-override"><code>
i18next
  .use(Backend)
  .use(middleware.LanguageDetector)
  .init({
    fallbackLng: 'en',
    backend: {
      loadPath: __dirname + '/locales/{{lng}}/translation.json',
    },
  })
</code>```

How I'm using this

app.all('*', (req: Request, res: Response) => {
  res.status(404).json({
    status: i18next.t('errorStatus'),
    message: i18next.t('error404'),
  })
})

```

It's always give me ressponse with only english response not other language file
but If I'm using like that "req.t" it's work but i need to use it like "i18next.t" for non request methodds

Body:
My Imports

import i18next from 'i18next'
import Backend from 'i18next-fs-backend'
import middleware from 'i18next-http-middleware'

While using i18next for localization always give me fallback langauge

My requests header {Accept-Language:"ar"}
Code config

i18next
  .use(Backend)
  .use(middleware.LanguageDetector)
  .init({
    fallbackLng: 'en',
    backend: {
      loadPath: __dirname + '/locales/{{lng}}/translation.json',
    },
  })

How I'm using this

app.all('*', (req: Request, res: Response) => {
  res.status(404).json({
    status: i18next.t('errorStatus'),
    message: i18next.t('error404'),
  })
})

It's always give me ressponse with only english response not other language file
but If I'm using like that "req.t" it's work but i need to use it like "i18next.t" for non request methodds


问:
How to get the values from an encapsulated array of object inside a main JSON object?
Here is an example of JSON:

```<code>    [{
     "experiences": [
    {
      "_createdAt": "2022-12-15T14:54:38Z",
      "_id": "54a3d68e-a0b5-41ad-9df6-83ac1883e935",
      "technologies": [
        {
          "_createdAt": "2022-12-15T14:24:24Z",
          "_id": "1762b3a7-5945-465f-a341-a69ecd734aea",
          "image": {
            "_type": "image",
            "asset": {
              "_ref": "image-6a43e73cef9815b015ce26d-,
              "_type": "reference"
                   }
          },
          "progress": 65,
          "title": "mysql"
        },
        {
          "_createdAt": "2022-12-15T15:03:39Z",
          "_id": "5ca79249-5038-4307-8590-3795575353b0",
          "_rev": "WjNoNn9xxkEglNz2Jueh6j",
          "_type": "skill",
          "_updatedAt": "2022-12-15T15:03:39Z",
          "image": {
            "_type": "image",
            "asset": {
              "_ref": "image-b1fba7c5cf35a37c5f8fa4e-400x170-png",
              "_type": "reference"
            }
          },
          "progress": 30,
          "title": "JavaFX"
        }
      ] }
    ]
</code>```

I wish to access the elements inside "technologies", I've tried to get  the _id and the image inside each technology like this:

```<code>experience.technologies.map((technology) =>
            {
               <img
                key={technology._id}
                className ="h-10 w-10 rounded-full"
                src={urlFor(technology.image).url()}
                />
            })
</code>```

Error:

```<code>TypeError: Cannot read properties of null (reading '_id')
</code>```

the compiler could not find the"technology._id" and or the "technology.image". I'm new to Typescript, Your help would be really appreciated, guys

Body:
Here is an example of JSON:

    [{
     "experiences": [
    {
      "_createdAt": "2022-12-15T14:54:38Z",
      "_id": "54a3d68e-a0b5-41ad-9df6-83ac1883e935",
      "technologies": [
        {
          "_createdAt": "2022-12-15T14:24:24Z",
          "_id": "1762b3a7-5945-465f-a341-a69ecd734aea",
          "image": {
            "_type": "image",
            "asset": {
              "_ref": "image-6a43e73cef9815b015ce26d-,
              "_type": "reference"
                   }
          },
          "progress": 65,
          "title": "mysql"
        },
        {
          "_createdAt": "2022-12-15T15:03:39Z",
          "_id": "5ca79249-5038-4307-8590-3795575353b0",
          "_rev": "WjNoNn9xxkEglNz2Jueh6j",
          "_type": "skill",
          "_updatedAt": "2022-12-15T15:03:39Z",
          "image": {
            "_type": "image",
            "asset": {
              "_ref": "image-b1fba7c5cf35a37c5f8fa4e-400x170-png",
              "_type": "reference"
            }
          },
          "progress": 30,
          "title": "JavaFX"
        }
      ] }
    ]

I wish to access the elements inside "technologies", I've tried to get  the _id and the image inside each technology like this:

experience.technologies.map((technology) =>
            {

            })

Error:

TypeError: Cannot read properties of null (reading '_id')

the compiler could not find the"technology._id" and or the "technology.image". I'm new to Typescript, Your help would be really appreciated, guys


问:
how can I handle solana api get_transaction method error?
I want to get transaction details using Solana API with python. There are two documents for it.

1: https://docs.solana.com/developing/clients/jsonrpc-api#gettransaction

2: https://michaelhly.github.io/solana-py/rpc/api/#solana.rpc.api.Client.get_transaction

I used this code below

```<code>solana_client = Client("https://api.mainnet-beta.solana.com")
from solders.signature import Signature
sig = Signature.from_string("3NHUEPkc7a2mPkC51umAbLdNjrwoEaCXfdJ7BjHaEhYPchy5TtrCifbJqSujyZCNRuDKDfJvpN8osx9KvSWdwMp8")
solana_client.get_transaction(sig).value.block_time
</code>```

and I got multiple errors

```<code>TypeError: Object of type Signature is not JSON serializable

TypeError: dict had unencodable value at keys: {params: because (list had unencodable value at index: [0: because (Object of type Signature is not JSON serializable)])}

TypeError: Could not encode to JSON
</code>```

Any idea how can i handle this error?

Body:
I want to get transaction details using Solana API with python. There are two documents for it.

1: https://docs.solana.com/developing/clients/jsonrpc-api#gettransaction

2: https://michaelhly.github.io/solana-py/rpc/api/#solana.rpc.api.Client.get_transaction

I used this code below

solana_client = Client("https://api.mainnet-beta.solana.com")
from solders.signature import Signature
sig = Signature.from_string("3NHUEPkc7a2mPkC51umAbLdNjrwoEaCXfdJ7BjHaEhYPchy5TtrCifbJqSujyZCNRuDKDfJvpN8osx9KvSWdwMp8")
solana_client.get_transaction(sig).value.block_time

and I got multiple errors

TypeError: Object of type Signature is not JSON serializable

TypeError: dict had unencodable value at keys: {params: because (list had unencodable value at index: [0: because (Object of type Signature is not JSON serializable)])}

TypeError: Could not encode to JSON

Any idea how can i handle this error?


问:
Celery beat stuck on start
After celery launch, I have the following output:

```<code>[2022-12-24 17:42:25,851: INFO/MainProcess] Connected to redis://localhost:6379//
[2022-12-24 17:42:25,854: INFO/MainProcess] mingle: searching for neighbors
[2022-12-24 17:42:26,506: INFO/Beat] beat: Starting...
[2022-12-24 17:42:26,862: INFO/MainProcess] mingle: all alone
[2022-12-24 17:42:26,881: INFO/MainProcess] celery@Bulrathi-Mac-mini.local ready.
</code>```

implying beat is stuck on start (indeed, periodic tasks are not executed).

I'm starting the celery like this:

```<code>celery -A app.celery worker -B -l info
</code>```

My code is

```<code>from datetime import timedelta
from celery import Celery
from celery.utils.log import get_task_logger

celery = Celery(
    __name__,
    broker='redis://localhost:6379',
    include=['tasks']
)
celery.conf.timezone = 'UTC'

logger = get_task_logger(__name__)

@celery.task
def periodic_task():
    logger.debug('yay')

CELERYBEAT_SCHEDULE = {
    'every-second': {
        'task': 'periodic_task',
        'schedule': timedelta(seconds=1),
    }
}
</code>```

I googled for the similar issues, but didn't find any suitable solution. Your help is highly appreciated, thank you in advance.

Title: Celery beat stuck on start

Body:
After celery launch, I have the following output:

[2022-12-24 17:42:25,851: INFO/MainProcess] Connected to redis://localhost:6379//
[2022-12-24 17:42:25,854: INFO/MainProcess] mingle: searching for neighbors
[2022-12-24 17:42:26,506: INFO/Beat] beat: Starting...
[2022-12-24 17:42:26,862: INFO/MainProcess] mingle: all alone
[2022-12-24 17:42:26,881: INFO/MainProcess] celery@Bulrathi-Mac-mini.local ready.

implying beat is stuck on start (indeed, periodic tasks are not executed).

I'm starting the celery like this:

celery -A app.celery worker -B -l info

My code is

from datetime import timedelta
from celery import Celery
from celery.utils.log import get_task_logger

celery = Celery(
    __name__,
    broker='redis://localhost:6379',
    include=['tasks']
)
celery.conf.timezone = 'UTC'

logger = get_task_logger(__name__)

@celery.task
def periodic_task():
    logger.debug('yay')

CELERYBEAT_SCHEDULE = {
    'every-second': {
        'task': 'periodic_task',
        'schedule': timedelta(seconds=1),
    }
}

I googled for the similar issues, but didn't find any suitable solution. Your help is highly appreciated, thank you in advance.


问:
Calculate frequency and percentage within a subgroup in R
I have a data frame called measlescases comprised of columns like "Final Classification' 'ProvinceofResidence', 'AgeCategory', 'Vaccinationstatus', etc.

I would like to calculate the number of measles cases (obtained from the 'Final Classification' column) each by 'ProvinceofResidence', 'AgeCategory', 'Vaccinationstatus'.

Can someone give me a line of code using one of these columns as examples?

Thanks

YEt to try. Still new to R


问:
How to build Logistic Regression model in stats models in loop to calculate statistics for each variable and whole model in Python?
I have function in Python like below to create Linear Regression model and to check which feature has the greatest correlation to the target using r-squared:

```<code>#Split our DataFrame into X (input) and y (output)
y = df['price']
X = df.drop('price', axis = 1)

#Create an empty dictionary that will be used to store our results
function_dict = {'predictor': [], 'r-squared':[]}
#Iterate through every column in X
for col in X.columns:
    #Create a dataframe called selected_X with only the 1 column
    selected_X = X[[col]]
    #Fit a model for our target and our selected column
    model = sm.OLS(y, sm.add_constant(selected_X)).fit()
    #Predict what our target would be for our model
    y_preds = model.predict(sm.add_constant(selected_X))
    #Add the column name to our dictionary
    function_dict['predictor'].append(col)
    #Calculate the r-squared value between the target and predicted target
    r2 = np.corrcoef(y, y_preds)[0, 1]**2
    #Add the r-squared value to our dictionary
    function_dict['r-squared'].append(r2)

#Once it's iterated through every column, turn our dictionary into a DataFrame and sort it
function_df = pd.DataFrame(function_dict).sort_values(by=['r-squared'], ascending = False)
#Display only the top 5 predictors
display(function_df.head())
</code>```

output above function is like below:

And I need to create similar function but:

For Logistic Regression model (sm.Logit)

instead of r-suared I need to have statistics like the follow:

student t statistics --> for each variable

p-value --> for each variable

standard error --> for each variable

Gini --> for the whole model

KS statistics -  Kolmogorov-Smirnov --> for the whole model

So, as a result I need somethin libe below:

```<code>predictor  | t_student | p_value | std_error  | Gini   | KS
-----------|-----------|---------|------------|--------|---------
var1       | 1.005     | 0.017   | 0.011      | 0.56   | 0.181
var2       | 0.25      | 0.045   | 1.964      | 0.56   | 0.181
var3       | 1.24      | 0.0002  | 0.567      | 0.56   | 0.181
...        | ...       | ...     | ...        | ...    | ...
</code>```

How can I change above function to meet my requirements in Python ?

Body:
I have function in Python like below to create Linear Regression model and to check which feature has the greatest correlation to the target using r-squared:

#Split our DataFrame into X (input) and y (output)
y = df['price']
X = df.drop('price', axis = 1)

#Create an empty dictionary that will be used to store our results
function_dict = {'predictor': [], 'r-squared':[]}
#Iterate through every column in X
for col in X.columns:
    #Create a dataframe called selected_X with only the 1 column
    selected_X = X[[col]]
    #Fit a model for our target and our selected column
    model = sm.OLS(y, sm.add_constant(selected_X)).fit()
    #Predict what our target would be for our model
    y_preds = model.predict(sm.add_constant(selected_X))
    #Add the column name to our dictionary
    function_dict['predictor'].append(col)
    #Calculate the r-squared value between the target and predicted target
    r2 = np.corrcoef(y, y_preds)[0, 1]**2
    #Add the r-squared value to our dictionary
    function_dict['r-squared'].append(r2)

#Once it's iterated through every column, turn our dictionary into a DataFrame and sort it
function_df = pd.DataFrame(function_dict).sort_values(by=['r-squared'], ascending = False)
#Display only the top 5 predictors
display(function_df.head())

output above function is like below:

And I need to create similar function but:

For Logistic Regression model (sm.Logit)

instead of r-suared I need to have statistics like the follow:

student t statistics --> for each variable

p-value --> for each variable

standard error --> for each variable

Gini --> for the whole model

KS statistics -  Kolmogorov-Smirnov --> for the whole model

So, as a result I need somethin libe below:

predictor  | t_student | p_value | std_error  | Gini   | KS
-----------|-----------|---------|------------|--------|---------
var1       | 1.005     | 0.017   | 0.011      | 0.56   | 0.181
var2       | 0.25      | 0.045   | 1.964      | 0.56   | 0.181
var3       | 1.24      | 0.0002  | 0.567      | 0.56   | 0.181
...        | ...       | ...     | ...        | ...    | ...

How can I change above function to meet my requirements in Python ?


问:
getLastKnownLocation is null when Myapp is Running in background in android 12
I wrote a program that when called
I get contact information and location information of the person with api
I used  "BroadcastReceiver" for this.
My problem is that when the program is open, it gives me the correct location and everything works fine, but when the program is running in the background, it shows the location as null. When I go to the program and open the program, everything is correct again

help me!

If my method is wrong, please tell me the right way

This is my problem on Android 12 and it is correct on lower Android

```<code>

if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)) {

    Toast.makeText(context, "RINGING", Toast.LENGTH_SHORT).show();

LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(context.LOCATION_SERVICE);

locationListener = new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
Lat = String.valueOf(location.getLatitude());
Lng = String.valueOf(location.getLongitude());

        }

    }

};

if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

    return;

} else {

    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, locationListener);

}

Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (location != null) {

    Latitude = location.getLatitude();
    Longitude = location.getLongitude();

}

}
</code>```

Body:
I wrote a program that when called
I get contact information and location information of the person with api
I used  "BroadcastReceiver" for this.
My problem is that when the program is open, it gives me the correct location and everything works fine, but when the program is running in the background, it shows the location as null. When I go to the program and open the program, everything is correct again

help me!

If my method is wrong, please tell me the right way

This is my problem on Android 12 and it is correct on lower Android

if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)) {

    Toast.makeText(context, "RINGING", Toast.LENGTH_SHORT).show();

LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(context.LOCATION_SERVICE);

locationListener = new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
Lat = String.valueOf(location.getLatitude());
Lng = String.valueOf(location.getLongitude());

        }

    }

};

if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

    return;

} else {

    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, locationListener);

}

Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (location != null) {

    Latitude = location.getLatitude();
    Longitude = location.getLongitude();

}

}


问:
How do you generate a series of boolean values based on conditions with both true and false?
Example,

This is checking for true conditions to create a new boolean series to add to a dataframe:

```<code>new_bool_series = bool_series1 & bool_series2 & bool_series3
df['column3'] = new_series
</code>```

This works because the logic is straight forward. the new_series variable can turn out to be true or false but I never figured out how to include a False condition:

new_series = not series1 & series2 & series3

...doesn't work...ambiguous error, and has logic problems.

new_series = series1 == False & series2 & series3

...also doesn't work and produces an error.
So I am trying to figure out the right code to generate the column 3 result, if column1 is False and column2 is True, then column 3 is True.

```<code>column1, column2, result
False, True, True
True, True, False
</code>```

Body:
Example,

This is checking for true conditions to create a new boolean series to add to a dataframe:

new_bool_series = bool_series1 & bool_series2 & bool_series3
df['column3'] = new_series

This works because the logic is straight forward. the new_series variable can turn out to be true or false but I never figured out how to include a False condition:

new_series = not series1 & series2 & series3

...doesn't work...ambiguous error, and has logic problems.

new_series = series1 == False & series2 & series3

...also doesn't work and produces an error.
So I am trying to figure out the right code to generate the column 3 result, if column1 is False and column2 is True, then column 3 is True.

column1, column2, result
False, True, True
True, True, False