问:
How to get the Downling progress from the Flutter Downloader Package
Im using flutter downloder for downloading the files from url. its working fine but i want to display a progress of downloads for user.

Can some please explain me how to get the progress data.

I got the progress Thank you.
class _Happy_hours_puzzlesState extends State<Happy_hours_puzzles> {

final ReceivePort _port = ReceivePort();
ValueNotifier _progress = ValueNotifier(0);

@override
void initState() {

print("Init State+++++++++++++++++++++++++++++++++++++");

```<code>_progress=ValueNotifier<double>(0);

IsolateNameServer.registerPortWithName(_port.sendPort, 'downloader_send_port');
_port.listen((dynamic data) {
  String id = data[0];
  DownloadTaskStatus status = data[1];
  int progress = data[2];
  _progress.value = progress.toDouble();
  print("inside port progress ${_progress.value}");
  print("status status status ${status}");
});

FlutterDownloader.registerCallback(downloadCallback);
super.initState();
</code>```

}

@override
void dispose() {

```<code>IsolateNameServer.removePortNameMapping('downloader_send_port');
_progress.dispose();
super.dispose();
</code>```

}

static void downloadCallback(String id, DownloadTaskStatus status, int progress) {
final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port')!;
send.send([id, status, progress]);
}

StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
print("inside StatefulBuilder progress ${_progress.value}");
return Container(
height: MediaQuery.of(context).size.width * 0.3,
width: MediaQuery.of(context).size.width * 0.7,
child: Center(
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10)),
child: ValueListenableBuilder(
builder: (BuildContext context, double value, child) {
return Column(
children: [
Text(puzzleName,
style: TextStyle(
fontFamily: "Open Sans",
color: Colors.purple.shade900,
fontSize: 15,
fontWeight: FontWeight.bold,
), textAlign: TextAlign.center),
SizedBox(height: 10,),

```<code>                                    LinearProgressIndicator(
                                        minHeight: 5, value: _progress.value),

                                    SizedBox(height: 10,),
                                    ElevatedButton(
                                      style: ElevatedButton.styleFrom(
                                        shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(20)),
                                        primary:
                                        (_progress.value<100 && _progress.value>-1)
                                            ? Colors.green: (value==100)?Colors.deepPurple
                                            : Colors.red,
                                      ),
                                      child: Text(
                                          (_progress.value<100 && _progress.value>-1) ? "Downloading..." : (_progress.value==100)?"Done" :"Failed Please try again",
                                          style: TextStyle(
                                            fontFamily: "Open Sans",
                                            fontSize: 12,
                                            fontWeight: FontWeight.bold,
                                            color: Colors.white,
                                          )),
                                      onPressed: (_progress.value==100 || _progress.value==-1) ?  () async {
                                       Navigator.pop(context);
                                      }:(){print("Downloading");}
                                      ,),
                                  ],
                                );
                                // return new Text(value.toString());
                              },
                              valueListenable: _progress))),
                );
              })
</code>```

Body:
Im using flutter downloder for downloading the files from url. its working fine but i want to display a progress of downloads for user.

Can some please explain me how to get the progress data.

I got the progress Thank you.
class _Happy_hours_puzzlesState extends State<Happy_hours_puzzles> {

final ReceivePort _port = ReceivePort();
ValueNotifier _progress = ValueNotifier(0);

@override
void initState() {

print("Init State+++++++++++++++++++++++++++++++++++++");

_progress=ValueNotifier<double>(0);

IsolateNameServer.registerPortWithName(_port.sendPort, 'downloader_send_port');
_port.listen((dynamic data) {
  String id = data[0];
  DownloadTaskStatus status = data[1];
  int progress = data[2];
  _progress.value = progress.toDouble();
  print("inside port progress ${_progress.value}");
  print("status status status ${status}");
});

FlutterDownloader.registerCallback(downloadCallback);
super.initState();

}

@override
void dispose() {

IsolateNameServer.removePortNameMapping('downloader_send_port');
_progress.dispose();
super.dispose();

}

static void downloadCallback(String id, DownloadTaskStatus status, int progress) {
final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port')!;
send.send([id, status, progress]);
}

StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
print("inside StatefulBuilder progress ${_progress.value}");
return Container(
height: MediaQuery.of(context).size.width * 0.3,
width: MediaQuery.of(context).size.width * 0.7,
child: Center(
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10)),
child: ValueListenableBuilder(
builder: (BuildContext context, double value, child) {
return Column(
children: [
Text(puzzleName,
style: TextStyle(
fontFamily: "Open Sans",
color: Colors.purple.shade900,
fontSize: 15,
fontWeight: FontWeight.bold,
), textAlign: TextAlign.center),
SizedBox(height: 10,),

                                    LinearProgressIndicator(
                                        minHeight: 5, value: _progress.value),

                                    SizedBox(height: 10,),
                                    ElevatedButton(
                                      style: ElevatedButton.styleFrom(
                                        shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(20)),
                                        primary:
                                        (_progress.value<100 && _progress.value>-1)
                                            ? Colors.green: (value==100)?Colors.deepPurple
                                            : Colors.red,
                                      ),
                                      child: Text(
                                          (_progress.value<100 && _progress.value>-1) ? "Downloading..." : (_progress.value==100)?"Done" :"Failed Please try again",
                                          style: TextStyle(
                                            fontFamily: "Open Sans",
                                            fontSize: 12,
                                            fontWeight: FontWeight.bold,
                                            color: Colors.white,
                                          )),
                                      onPressed: (_progress.value==100 || _progress.value==-1) ?  () async {
                                       Navigator.pop(context);
                                      }:(){print("Downloading");}
                                      ,),
                                  ],
                                );
                                // return new Text(value.toString());
                              },
                              valueListenable: _progress))),
                );
              })


来源: stackexchange

问:
ios flutter application tab view not working
In my Flutter application, tab bar are working for Android but for IOS tabs not clikable only ontap function workking in indicator .</p>

ContentLicense: CC BY-SA 4.0


问:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'documentationPluginsBootstrapper' defined in URL

`After updating Springboot version to 2.7.5, im getting error like this

Error creating bean with name 'documentationPluginsBootstrapper' defined in URL.

dependencies im using in my projects are

springfox-swagger2 -> 2.6.1

springfox-swagger-ui -> 2.6.1

springboot-starter-plugins -> 2.7.5

i have checked throughly there is no dependecies conflict...  I tried with latest springfox dependencies and  with latest springboot version 3.0.x  Tried by adding the property in app.prop file  spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER  I have added/removed @EnableWebMvc @EnableSwagger2 on configuration class.`


问:
expo-auth-session useAuthRequest: Force popup to open in web browser instead of native app
I have an expo app, where I need to authenticate the user from a 3rd party website. I am doing it this way:

```<code>const discoveryDocument = React.useMemo(
  () => ({
    authorizationEndpoint: "https://api.mydomain.de/oauth2/auth",
    tokenEndpoint: "https://api.mydomain.de/oauth2/token",
    revocationEndpoint: "https://api.mydomain.de/oauth2/revoke"
  }),
  []
);

const [request, promptAsync] = useAuthRequest(
  {
    clientId: "myclientid",
    redirectUri: redirectUri,
    scopes: ["myscope"],
    state: "customstate",
    responseType: "code"
  },
  discoveryDocument
);
</code>```

I am calling it via:

```<code>const response = await promptAsync();
</code>```

This works fine on web. The problem is, there is an native application that is linked to "mydomain.de" for a lot of our users. My app also opens the api.mydomain.de in the native app, which does not support these urls (just showing a blank page). If I disable the linking or uninstalling the app that opens the mydomain.de urls, it works fine.

Is there a way to tell my app to open this auth request always in browser and ignore possible linked native apps on my phone?

Body:
I have an expo app, where I need to authenticate the user from a 3rd party website. I am doing it this way:

const discoveryDocument = React.useMemo(
  () => ({
    authorizationEndpoint: "https://api.mydomain.de/oauth2/auth",
    tokenEndpoint: "https://api.mydomain.de/oauth2/token",
    revocationEndpoint: "https://api.mydomain.de/oauth2/revoke"
  }),
  []
);

const [request, promptAsync] = useAuthRequest(
  {
    clientId: "myclientid",
    redirectUri: redirectUri,
    scopes: ["myscope"],
    state: "customstate",
    responseType: "code"
  },
  discoveryDocument
);

I am calling it via:

const response = await promptAsync();

This works fine on web. The problem is, there is an native application that is linked to "mydomain.de" for a lot of our users. My app also opens the api.mydomain.de in the native app, which does not support these urls (just showing a blank page). If I disable the linking or uninstalling the app that opens the mydomain.de urls, it works fine.

Is there a way to tell my app to open this auth request always in browser and ignore possible linked native apps on my phone?


问:
Facing issues while running publisher on kafka
I am trying to run a publisher on ec2 kafka and while doing that I am facing issues like

```<code>[2023-01-06 10:11:21,048] ERROR Failed to create job for config/s3_connect.properties (org.apache.kafka.connect.cli.ConnectStandalone:107)
[2023-01-06 10:11:21,053] ERROR Stopping after connector error (org.apache.kafka.connect.cli.ConnectStandalone:117)
java.util.concurrent.ExecutionException: java.lang.NoClassDefFoundError: org/jctools/queues/MessagePassingQueue$Supplier
        at org.apache.kafka.connect.util.ConvertingFutureCallback.result(ConvertingFutureCallback.java:115)
        at org.apache.kafka.connect.util.ConvertingFutureCallback.get(ConvertingFutureCallback.java:99)
        at org.apache.kafka.connect.cli.ConnectStandalone.main(ConnectStandalone.java:114)
Caused by: java.lang.NoClassDefFoundError: org/jctools/queues/MessagePassingQueue$Supplier
</code>```

I was expecting the publisher to push msg to topic

Body:
I am trying to run a publisher on ec2 kafka and while doing that I am facing issues like

[2023-01-06 10:11:21,048] ERROR Failed to create job for config/s3_connect.properties (org.apache.kafka.connect.cli.ConnectStandalone:107)
[2023-01-06 10:11:21,053] ERROR Stopping after connector error (org.apache.kafka.connect.cli.ConnectStandalone:117)
java.util.concurrent.ExecutionException: java.lang.NoClassDefFoundError: org/jctools/queues/MessagePassingQueue$Supplier
        at org.apache.kafka.connect.util.ConvertingFutureCallback.result(ConvertingFutureCallback.java:115)
        at org.apache.kafka.connect.util.ConvertingFutureCallback.get(ConvertingFutureCallback.java:99)
        at org.apache.kafka.connect.cli.ConnectStandalone.main(ConnectStandalone.java:114)
Caused by: java.lang.NoClassDefFoundError: org/jctools/queues/MessagePassingQueue$Supplier

I was expecting the publisher to push msg to topic


问:
Next.js page is there a way to prevent reloads every time I focus on the Browser tab
I am developing my first Next.js application and have deployed my first beta version.

I notice that on the browser, if I move to another tab and revisit on the tab containing the Next js app, it reloads the page. This includes reloading any API based data etc.

Is there some setting to avoid this?

Thanks.


问:
How to check the extension of uploading file in vue.js
I want to check the extension of uploaded file. It is working fine but what if someone change the extension of uploading file. Like if someone change the .pdf extension to .png or .jpeg , then how to check this using vue.js. I have tried active storage validator gem but then there are many changes in my app. I want to write lesser code. If anyone have efficient approach, please share.</p>


问:
Excel - PowerQuery error handling - clear table data
I'm looking for a way to deal with errors from PowerQuery data connections within Excel.
For example, if an API call via PowerQuery returns 0 rows due to below code I get the following message box:

However previously loaded data of that table remains.
So what I would like to do instead, is to clear/empty the table data whenever an error is returned.
Can this be done within PowerQuery? Because I believe the table structure is lost once an error is returned. Or instead of outputting the error message can all rows of the table be deleted?

Code:

```<code>    let
sheet = "test",
URL_RelativePath = "apiPath/export",

    Source = Json.Document(Web.Contents(URL, [RelativePath=URL_RelativePath,
        ManualStatusHandling = HTTP_Errors[ErrorCode],
        Query=[
              sheet= sheet
            ]])),
         responseReturnedRows = Value.Is(Source, type list),
        Content =
        if responseReturnedRows = false and Source[status] <> 200 then error sheet & ": " & Source[title] & " " & HTTP_Errors[ErrorMsg]{List.PositionOf(HTTP_Errors[ErrorCode], Source[status] )}
        else Source,
            #"Convert To Table" = Table.FromList(#"Content", Splitter.SplitByNothing(), null, null, ExtraValues.Error),
            ...
</code>```

Thank you.

Body:
I'm looking for a way to deal with errors from PowerQuery data connections within Excel.
For example, if an API call via PowerQuery returns 0 rows due to below code I get the following message box:

However previously loaded data of that table remains.
So what I would like to do instead, is to clear/empty the table data whenever an error is returned.
Can this be done within PowerQuery? Because I believe the table structure is lost once an error is returned. Or instead of outputting the error message can all rows of the table be deleted?

Code:

    let
sheet = "test",
URL_RelativePath = "apiPath/export",

    Source = Json.Document(Web.Contents(URL, [RelativePath=URL_RelativePath,
        ManualStatusHandling = HTTP_Errors[ErrorCode],
        Query=[
              sheet= sheet
            ]])),
         responseReturnedRows = Value.Is(Source, type list),
        Content =
        if responseReturnedRows = false and Source[status] <> 200 then error sheet & ": " & Source[title] & " " & HTTP_Errors[ErrorMsg]{List.PositionOf(HTTP_Errors[ErrorCode], Source[status] )}
        else Source,
            #"Convert To Table" = Table.FromList(#"Content", Splitter.SplitByNothing(), null, null, ExtraValues.Error),
            ...

Thank you.


问:
How to set umask for user "apache"?
on Red Hat Linux system running apache webservices files created from user apache have to be modified.
How to set new mask for files created from apache ?
I changed umask in file /etc/bashrc from 022 to 002 but after restart httpd no changes on file-rights werde made.

Have anybody a hint ?

Regards
Tom

modified umask in bashrc but no effect.

Title: How to set umask for user "apache"?


问:
tsc tries to compile everything in my monorepo rather than just one package
I am at my wits end with what I imagine is a trivial problem, but multiple devs at my company have been flummoxed by this for some time.

We are mid-migration to a monorepo which will include our legacy codebase, largely so that we can pull in the types from our old API. We are using Turborepo and pnpm.

The relevant part of the file structure is as follows

```<code>├── services
│   ├── backend
│   │   ├── $some_files
│   ├── nest-api
│       ├── $some_files
</code>```

Some code in the backend package includes an import type { Baz } from "@acme/nest-api/src/modules/foo/bar/baz" statement which pulls in a type from the nest-api package. When tsc is run on the backend package, tsc attempts to build the entire nest-api package using the config from the tsconfig file in the backend package, which fails, because the nest-api package requires a more permissive config.

In the tsc logs, it refers to the files like ../nest-api/src/modules/foo/bar/baz.ts:15 - I am very confused as to how tsc is escaping its scope of all the files in backend/src and getting to this directory. Is there a simple tsconfig setting we have missed or is something else afoot?

I appreciate that this is a vague question but I really hope someone can help - I can provide more details if needed but in all honesty I'm not sure exactly what to provide!

Running turbo run build --filter nextjs should cause the repo to build successfully. Instead it fails.

Body:
I am at my wits end with what I imagine is a trivial problem, but multiple devs at my company have been flummoxed by this for some time.

We are mid-migration to a monorepo which will include our legacy codebase, largely so that we can pull in the types from our old API. We are using Turborepo and pnpm.

The relevant part of the file structure is as follows

├── services
│   ├── backend
│   │   ├── $some_files
│   ├── nest-api
│       ├── $some_files

Some code in the backend package includes an import type { Baz } from "@acme/nest-api/src/modules/foo/bar/baz" statement which pulls in a type from the nest-api package. When tsc is run on the backend package, tsc attempts to build the entire nest-api package using the config from the tsconfig file in the backend package, which fails, because the nest-api package requires a more permissive config.

In the tsc logs, it refers to the files like ../nest-api/src/modules/foo/bar/baz.ts:15 - I am very confused as to how tsc is escaping its scope of all the files in backend/src and getting to this directory. Is there a simple tsconfig setting we have missed or is something else afoot?

I appreciate that this is a vague question but I really hope someone can help - I can provide more details if needed but in all honesty I'm not sure exactly what to provide!

Running turbo run build --filter nextjs should cause the repo to build successfully. Instead it fails.


问:
When should `std::scoped_lock` be used over `std::shared_lock`?
When should std::scoped_lock be used over std::shared_lock?

I don't think I understand the use of std::scoped_lock.

Or, is std::scoped_lock just a variant of std::unique_lock for holding multiple mutexes?

Ref: "std::lock_guard or std::scoped_lock?"


问:
Intellij new switch expressions formatting
Intellij formats my switch expression this way:

```<code>        String foo = switch ( bar )
            {
                case "one" -> "Narf";
                case "two" -> "Zort";
                default -> "Poit";
            }
</code>```

And I want to be formatted in this way:

```<code>        String foo = switch(bar)
        {
            case "one" -> "Narf";
            case "two" -> "Zort";
            default -> "Poit";
        }
</code>```

I've tried multiple settings but none of them did the trick.

My checkstyle tasks keep failing every time Intellij formats a switch expression.

For now I've disabled the formatting on that lines but ideally, I would like to properly fix this.

Body:
Intellij formats my switch expression this way:

        String foo = switch ( bar )
            {
                case "one" -> "Narf";
                case "two" -> "Zort";
                default -> "Poit";
            }

And I want to be formatted in this way:

        String foo = switch(bar)
        {
            case "one" -> "Narf";
            case "two" -> "Zort";
            default -> "Poit";
        }

I've tried multiple settings but none of them did the trick.

My checkstyle tasks keep failing every time Intellij formats a switch expression.

For now I've disabled the formatting on that lines but ideally, I would like to properly fix this.


问:
Hashing string to integer (no security needed)

Possible Duplicate:

  php hash form string to integer

I am looking to hash a url like http://example.com to a integer hash, small in size preferably. I would like to know if there is any built-in php functions that can do that.

The purpose for this is for speed in my mysql database for other operations inside mysql when I am comparing this hashes.

ContentLicense: CC BY-SA 3.0


Title: Pandas qcut leaving gaps

Body:
I found this edge case in pandas qcut, I'm curios if anyone knows of any potential fix:

Normally it will generate as many unique buckets as you specify:

b = [1,2,3,4,5,5,6,7,9]

len(set([x for x in pd.qcut(b, 3, duplicates="drop")]))

> 3

Except for one array I encountered:

a = [182.0, 165.2, 118.0, 112.4, 166.8, 70.09200000000001, 288.456, 141.60000000000002, 118.0, 236.0, 141.60000000000002, 141.60000000000002, 141.60000000000002, 141.60000000000002, 141.60000000000002]

len(set(list(pd.qcut(a, 3, duplicates="drop"))))

> 2

The raw output as a list is:

[Interval(149.467, 288.456, closed='right'),
 Interval(149.467, 288.456, closed='right'),
 Interval(70.091, 141.6, closed='right'),
 Interval(70.091, 141.6, closed='right'),
 Interval(149.467, 288.456, closed='right'),
 Interval(70.091, 141.6, closed='right'),
 Interval(149.467, 288.456, closed='right'),
 Interval(70.091, 141.6, closed='right'),
 Interval(70.091, 141.6, closed='right'),
 Interval(149.467, 288.456, closed='right'),
 Interval(70.091, 141.6, closed='right'),
 Interval(70.091, 141.6, closed='right'),
 Interval(70.091, 141.6, closed='right'),
 Interval(70.091, 141.6, closed='right'),
 Interval(70.091, 141.6, closed='right')]

but in the pandas format it is:

Categories (3, interval[float64, right]): [(70.091, 141.6] < (141.6, 149.467] < (149.467, 288.456]]```


问:
Getting RegExp source without "beforhand" and "afterward" patterns
I have such a constant object:

```<code>export const Roles = {
  match: {
    Applicant: /^applicant$/,
    Employee: /^employee$/,
    Default: /^default-roles/,
  },
  value: {
    Applicant: 'applicant',
    Employee: 'employee',
  },
};
</code>```

I want to be able to get rid of Roles#match and Roles#value keys to be simply like:

```<code>export const Roles = {
    Applicant: /^applicant$/,
    Employee: /^employee$/,
    Default: /^default-roles/,
};
</code>```

so I found RegExp.source. It does remove / but not other flags like ^ and $

Body:
I have such a constant object:

export const Roles = {
  match: {
    Applicant: /^applicant$/,
    Employee: /^employee$/,
    Default: /^default-roles/,
  },
  value: {
    Applicant: 'applicant',
    Employee: 'employee',
  },
};

I want to be able to get rid of Roles#match and Roles#value keys to be simply like:

export const Roles = {
    Applicant: /^applicant$/,
    Employee: /^employee$/,
    Default: /^default-roles/,
};

so I found RegExp.source. It does remove / but not other flags like ^ and $


问:
Jupyter notebook in iframe working fine but sessions & Kernel are still running after destroying notebook - Angular
so i was using jupyter Notebook in my Angular app using iFrame, its running fine but after killing the notebook kernel & sessions are still running how to disable that?

In TS

```<code>ngOnDestroy(): void {
    this.workBookSvc.setIsConfigureComponent(false);
    if (this.updatedCodeSubscriber) {
      this.updatedCodeSubscriber.unsubscribe();
    }
    console.log("Destroyed ProCode");
    this.isDestroyed = true;
  }
</code>```

HTML

```<code> <div class="row mt-2 justify-content-center" *ngIf="!error">
    <iframe [src]="url" frameBorder="1" class="border border-3 shadow shadow-3" placeholder="iFrame" width="100%"
      height="500px"></iframe>
  </div>
</code>```

Body:
so i was using jupyter Notebook in my Angular app using iFrame, its running fine but after killing the notebook kernel & sessions are still running how to disable that?

In TS

ngOnDestroy(): void {
    this.workBookSvc.setIsConfigureComponent(false);
    if (this.updatedCodeSubscriber) {
      this.updatedCodeSubscriber.unsubscribe();
    }
    console.log("Destroyed ProCode");
    this.isDestroyed = true;
  }

HTML


问:
Solr sort by key value
I want to sort the results from Solr by key value.

Here is my scenario:

We have n products, we have m product groups.

1 product can have m product groups 1 product group has n products.

So we have a n:m relation.

Standard: the product has a sort index of 0 per product group there can be 3 Products with a sort index of 1, 2 or 3. 3 should be the first result, 2 the second, 1 the third and then the rest.

Warning: One Product can have a sort index > 0 in multiple product Groups.

Question: How should I index this information? And how should I do the sort in the query to Solr?

Title: Solr sort by key value


问:
I try to remove duplicates from this array
I try to remove duplicates from this array

let arr = [{id: "2023010600157"},{id: "2023010600158"},{id: "2023010600157"},{id: "2023010600158"}]

After I used reduce(), I found that after the first loop, the change of the prev was unexpected
enter image description here
Why does prev become the whole array after the first loop?

code here

let arr = [{
id: "2023010600157"
},{
id: "2023010600158"
},{
id: "2023010600157"
},{
id: "2023010600158"
}
]

let res = arr.reduce((prev, curr, index) => {

console.warn('loop No ${index + 1}')

console.log(prev);

console.log(curr, 'curr');

if (curr.id !== prev.id) {

prev.push(curr)

}

console.log(prev, 'prev');

return prev

},[])

console.log(res);

i tried to read log ,but i failed.


问:
How to integrate cypress-mochawesome-reporter to Gitlab pages?
How to integrate cypress-mochawesome-reporter to Gitlab pages?

Currently i have this code on my gitci-.yml

```<code>stages:
  - test

test:
  image: cypress/browsers:node18.12.0-chrome107
  stage: test
  script:
    - npm ci
    - npm run start:ci &
    - npm run html-report

</code>```

The cypress-mochawesome-reporter produce an index.html inside cypress/reports/html/index.html file after the pipeline runs

I can't find any docs or tutorial in the internet. What is the best approach on this?

Body:
How to integrate cypress-mochawesome-reporter to Gitlab pages?

Currently i have this code on my gitci-.yml

stages:
  - test

test:
  image: cypress/browsers:node18.12.0-chrome107
  stage: test
  script:
    - npm ci
    - npm run start:ci &
    - npm run html-report

The cypress-mochawesome-reporter produce an index.html inside cypress/reports/html/index.html file after the pipeline runs

I can't find any docs or tutorial in the internet. What is the best approach on this?


问:
How to prevent cyclic response with DBSet.Add() in Entity Framework?
I'm working with an ASP.NET Core 6.0 Web API using EF Core 7.0. Mostly, it's working well but I am stuck on something I can't quite figure out.

In my service layer, I am passing in a FooForCreationDto and manually mapping it to a Foo. The Foo object gets passed to the repo which calls Context.Set<T>().Add(object);

Fine.

But, the Foo object has a many-to-many relationship with a Bar object. So each object has a list of the other object. The problem is that the add method returns an object with a cyclic error, returning each objects list of the other, recursively. I want the add to just return Foo and its list of Bars, not to then also include each Bar's list of Foo's and so on, round and round.

The repo method is generic, so this should also work the other way around when adding a new Bar.

In a get method, we would have to use .Include(x => x.Bar) to include nested objects, but the return object of the Add method seems to do this by default.

How can I disable this?

I think the above is pretty clear, but here is a code example:

```<code>// Models
public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Bar> Bars { get; }
}

public class Bar
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Foo> Foos { get; }
}

// Service
public async Task<Foo> CreateFoo(FooForCreationDto fooForCreation)
{
     Foo foo = new Foo()
     foo.name = fooForCreation.name //map top level props.

     if (!fooForCreation.Bars.IsNullOrEmpty())
     {
        var bars = (List<Bar>)await _repository.Bar.GetBarsFromIds(fooForCreation.Bars);
        foo.Bars.AddRange(bars);
     }

     // everything is fine to here. Foo has a list of Bar, but Bar does not contain nested recursive Foos
     _repository.Foo.CreateFoo(foo);

     //At this point foo now has nested bars with nested foos with nested bars etc... even though createFoo has void return.
     await _repository.SaveAsync();

     return foo
 }

 // Repository : RepositoryBase
 public void CreateFoo(Foo foo)
 {
     Create(foo);
 }

 // RepositoryBase<T>
 public abstract class RepositoryBase<T> : IRepositoryBase<T> where T : class
 {
    protected MyDb RepositoryContext;
    public RepositoryBase(MyDb repositoryContext)
    => RepositoryContext = repositoryContext;

    //This add method returns foo with recursive bars and foos, which then changes what is returned from the service method.
    public void Create(T entity) => RepositoryContext.Set<T>().Add(entity);
 }
</code>```

I had a go adding the Microsoft.EntityFrameworkCore.Proxies and then adding UseLazyLoadingProxies, and then marking the lists in the model classes as virtual, but this seemed to cause all sorts of other errors I've not managed to unpick yet. For example, even it throws cyclic errors even though I have

```<code>JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Ignore
</code>```

Body:
I'm working with an ASP.NET Core 6.0 Web API using EF Core 7.0. Mostly, it's working well but I am stuck on something I can't quite figure out.

In my service layer, I am passing in a FooForCreationDto and manually mapping it to a Foo. The Foo object gets passed to the repo which calls Context.Set<T>().Add(object);

Fine.

But, the Foo object has a many-to-many relationship with a Bar object. So each object has a list of the other object. The problem is that the add method returns an object with a cyclic error, returning each objects list of the other, recursively. I want the add to just return Foo and its list of Bars, not to then also include each Bar's list of Foo's and so on, round and round.

The repo method is generic, so this should also work the other way around when adding a new Bar.

In a get method, we would have to use .Include(x => x.Bar) to include nested objects, but the return object of the Add method seems to do this by default.

How can I disable this?

I think the above is pretty clear, but here is a code example:

// Models
public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Bar> Bars { get; }
}

public class Bar
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Foo> Foos { get; }
}

// Service
public async Task<Foo> CreateFoo(FooForCreationDto fooForCreation)
{
     Foo foo = new Foo()
     foo.name = fooForCreation.name //map top level props.

     if (!fooForCreation.Bars.IsNullOrEmpty())
     {
        var bars = (List<Bar>)await _repository.Bar.GetBarsFromIds(fooForCreation.Bars);
        foo.Bars.AddRange(bars);
     }

     // everything is fine to here. Foo has a list of Bar, but Bar does not contain nested recursive Foos
     _repository.Foo.CreateFoo(foo);

     //At this point foo now has nested bars with nested foos with nested bars etc... even though createFoo has void return.
     await _repository.SaveAsync();

     return foo
 }

 // Repository : RepositoryBase
 public void CreateFoo(Foo foo)
 {
     Create(foo);
 }

 // RepositoryBase<T>
 public abstract class RepositoryBase<T> : IRepositoryBase<T> where T : class
 {
    protected MyDb RepositoryContext;
    public RepositoryBase(MyDb repositoryContext)
    => RepositoryContext = repositoryContext;

    //This add method returns foo with recursive bars and foos, which then changes what is returned from the service method.
    public void Create(T entity) => RepositoryContext.Set<T>().Add(entity);
 }

I had a go adding the Microsoft.EntityFrameworkCore.Proxies and then adding UseLazyLoadingProxies, and then marking the lists in the model classes as virtual, but this seemed to cause all sorts of other errors I've not managed to unpick yet. For example, even it throws cyclic errors even though I have

JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Ignore


问:
Why is my SMS message value "NULL" in the backup database from iphone?
From the backup of my iphone messages on my mac, majority of my message value is NONE when viewed in the database viewer.

Hi

I have taken backup of my iphone messages on my mac. But when I open the sms backup data base file (stored at ~/Library/Application Support/MobileSync/Backup/3d/3d0d7e5fb2ce288813306e4d4636395e047a3d28), most of the message values are NULL (screenshot attached)

Can someone advise why is it so?
Regards
Andy

Update - I figured out that iPhone is saving the text message as MMS. Even after I move my text message from iPhone to android they are transferred as MMS and not SMS. May be that's the issue.


问:
UITableView - Expand and Collapsible section issue
I have 15 sections with dynamic height sections and rows. By default all sections are closed. After scrolling to end of tableview, I am tapping on last section and it opens properly but when I click again to close section at that time my tableview scroll to top.

This issue occurs when some of the sections are scrolled and after that when click on any visible section.

Please anyone knows what exactly the issue.


问:
Microservice cross dependencies causing error
Sorry for the inconvenience, hope the below explanation helps.

I have Microservice architecture with spring-boot 2.6.6 and java 8

```<code>    **MS-1 pom.xml**

    <groupId>com.demo.gateway</groupId>
        <artifactId>MS-1</artifactId>
        <version>MS-1.0.0</version>
    <packaging>jar</packaging>

    <dependencies>
    <dependency>
               <groupId>junit</groupId>
               <artifactId>junit</artifactId>
               <scope>test</scope>
           </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
                   <artifactId>spring-webflux</artifactId>
    <dependency>
       </dependencies>
 ------------------------------------
    **MS-2 pom.xml**

    <groupId>com.demo.gateway</groupId>
        <artifactId>MS-2</artifactId>
        <version>MS-2.0.0</version>
    <packaging>jar</packaging>

    <dependencies>
    <dependency>
               <groupId>junit</groupId>
               <artifactId>junit</artifactId>
               <scope>test</scope>
           </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
                   <artifactId>spring-boot-starter</artifactId>
    <dependency>
       </dependencies>

----------------------------------
    **MS-3 pom.xml**
<groupId>com.demo.gateway</groupId>
        <artifactId>MS-3</artifactId>
        <version>MS-3.0.0</version>
    <packaging>war</packaging>

<dependencies>
<dependency>
            <groupId>com.demo.gateway</groupId>
            <artifactId>MS-1</artifactId>
            <version>MS-1.0.0</version>
        </dependency>
<dependency>
            <groupId>com.demo.gateway</groupId>
            <artifactId>MS-2</artifactId>
            <version>MS-2.0.0</version>
        </dependency>
</dependencies>

MS-3 is configured as spring boot service, When I start the service it is working fine.
--------------------------------------------
**MS-4 pom.xml**
<groupId>com.demo.gateway</groupId>
        <artifactId>MS-3</artifactId>
        <version>MS-3.0.0</version>
    <packaging>war</packaging>
<dependencies>
<dependency>
            <groupId>com.demo.gateway</groupId>
            <artifactId>MS-3</artifactId>
            <version>MS-3.0.0</version>
        </dependency>
</dependencies>

    MS-4 also configured as spring boot service, service is not starting. Giving Dynamic proxy injection error:

   org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'queuedThreadPool'
    is expected to be of type 'org.eclipse.jetty.util.thread.QueuedThreadPool' but was actually of type 'com.sun.proxy.$Proxy173'

</code>```

Any help on this is much appreciated. No proper details found anywhere.

I need to bring the MS-4 service up on adding MS-3 as dependency and make API calls with all configurations

Body:
Sorry for the inconvenience, hope the below explanation helps.

I have Microservice architecture with spring-boot 2.6.6 and java 8

    **MS-1 pom.xml**

    <groupId>com.demo.gateway</groupId>
        <artifactId>MS-1</artifactId>
        <version>MS-1.0.0</version>
    <packaging>jar</packaging>

    <dependencies>
    <dependency>
               <groupId>junit</groupId>
               <artifactId>junit</artifactId>
               <scope>test</scope>
           </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
                   <artifactId>spring-webflux</artifactId>
    <dependency>
       </dependencies>
 ------------------------------------
    **MS-2 pom.xml**

    <groupId>com.demo.gateway</groupId>
        <artifactId>MS-2</artifactId>
        <version>MS-2.0.0</version>
    <packaging>jar</packaging>

    <dependencies>
    <dependency>
               <groupId>junit</groupId>
               <artifactId>junit</artifactId>
               <scope>test</scope>
           </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
                   <artifactId>spring-boot-starter</artifactId>
    <dependency>
       </dependencies>

----------------------------------
    **MS-3 pom.xml**
<groupId>com.demo.gateway</groupId>
        <artifactId>MS-3</artifactId>
        <version>MS-3.0.0</version>
    <packaging>war</packaging>

<dependencies>
<dependency>
            <groupId>com.demo.gateway</groupId>
            <artifactId>MS-1</artifactId>
            <version>MS-1.0.0</version>
        </dependency>
<dependency>
            <groupId>com.demo.gateway</groupId>
            <artifactId>MS-2</artifactId>
            <version>MS-2.0.0</version>
        </dependency>
</dependencies>

MS-3 is configured as spring boot service, When I start the service it is working fine.
--------------------------------------------
**MS-4 pom.xml**
<groupId>com.demo.gateway</groupId>
        <artifactId>MS-3</artifactId>
        <version>MS-3.0.0</version>
    <packaging>war</packaging>
<dependencies>
<dependency>
            <groupId>com.demo.gateway</groupId>
            <artifactId>MS-3</artifactId>
            <version>MS-3.0.0</version>
        </dependency>
</dependencies>

    MS-4 also configured as spring boot service, service is not starting. Giving Dynamic proxy injection error:

   org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'queuedThreadPool'
    is expected to be of type 'org.eclipse.jetty.util.thread.QueuedThreadPool' but was actually of type 'com.sun.proxy.$Proxy173'

Any help on this is much appreciated. No proper details found anywhere.

I need to bring the MS-4 service up on adding MS-3 as dependency and make API calls with all configurations


问:
Inserting pandas dataframe to existing excel worksheet but it's wrong position
I'm still a beginner in python and now started working with openpyxl. I want to insert a pandas dataframe, which I generated from a txt file, into an existing excel workbook with existing worksheets. I want to overwrite existing values. The problem:
The dataframe data doesn't appear at the right spot in the excel worksheet.It starts at A3 instead of A1.
Furthermore, the indeces are transferred to the worksheet too, which I don't want.

If I try to use to_excel instead of the code I'm using right now, I always get the error code: zipfile.BadZipFile: File is not a zip file excel dataframe

Thanks for your help!

First, I'm opening my excel workbook and worksheet, then reading my txt file into a pd dataframe. With the for loop and enumerate I want insert the values of the dataframe into the worksheet

```<code>wb=openpyxl.load_workbook("test.xlsx")
ws=wb["Sheet2"]
df=pd.read_csv(path,sep=";", low_memory=False, header=None, nrows=15, index_col=False)

rows = dataframe_to_rows(df)
for r_idx, row in enumerate(rows, 1):
    for c_idx, value in enumerate(row, 1):
        ws.cell(row=r_idx, column=c_idx, value=value)

wb.save("test2.xlsx")
</code>```

Body:
I'm still a beginner in python and now started working with openpyxl. I want to insert a pandas dataframe, which I generated from a txt file, into an existing excel workbook with existing worksheets. I want to overwrite existing values. The problem:
The dataframe data doesn't appear at the right spot in the excel worksheet.It starts at A3 instead of A1.
Furthermore, the indeces are transferred to the worksheet too, which I don't want.

If I try to use to_excel instead of the code I'm using right now, I always get the error code: zipfile.BadZipFile: File is not a zip file excel dataframe

Thanks for your help!

First, I'm opening my excel workbook and worksheet, then reading my txt file into a pd dataframe. With the for loop and enumerate I want insert the values of the dataframe into the worksheet

wb=openpyxl.load_workbook("test.xlsx")
ws=wb["Sheet2"]
df=pd.read_csv(path,sep=";", low_memory=False, header=None, nrows=15, index_col=False)

rows = dataframe_to_rows(df)
for r_idx, row in enumerate(rows, 1):
    for c_idx, value in enumerate(row, 1):
        ws.cell(row=r_idx, column=c_idx, value=value)

wb.save("test2.xlsx")


问:
how to get calendar item change log?
it's supposoed to work with this commandlet

Get-CalendarDiagnosticObjects

but it's obviously missing from these modules

```<code>3.0.0      ExchangeOnlineManagement            PSGallery            This is a General Availability (GA) release of the Exchange Online Powershell V3 module....
0.11.0     ExchangePowerShell                  PSGallery            The EP (ExchangePowerShell) Powershell module is a collection of commandlets that can be
</code>```

The term 'Get-CalendarDiagnosticObjects' is not recognized as the name of a cmdlet,

whereas:

```<code>Connect-ExchangeOnline
get-mailbox
</code>```

works fine!

seems that V3 of the module is quite new? any idea?

Title: how to get calendar item change log?

Body:
it's supposoed to work with this commandlet

Get-CalendarDiagnosticObjects

but it's obviously missing from these modules

3.0.0      ExchangeOnlineManagement            PSGallery            This is a General Availability (GA) release of the Exchange Online Powershell V3 module....
0.11.0     ExchangePowerShell                  PSGallery            The EP (ExchangePowerShell) Powershell module is a collection of commandlets that can be

The term 'Get-CalendarDiagnosticObjects' is not recognized as the name of a cmdlet,

whereas:

Connect-ExchangeOnline
get-mailbox

works fine!

seems that V3 of the module is quite new? any idea?


问:
SSRS doesn't display all the data when toggle option is used (only one page for display ~1000 rows)
I have issue in SSRS where I have a report for some indicators, but
underneath some of the indicators I want to display detailed info rows for that indicator. Because of that I used toggle option so I don't see rows of detailed info rows unless I need them. And everything is on this one page which is ok.

But issue comes in a case where there is almost 2000 rows for detailed info for certain indicator and when I expand tablix I don't see all the data but only 1400 rows for example and don't see anything what was after that tablix in the report.

When I try to display data without toggling option there is about 50+ pages instead of only 2 (I think SSRS want's all tablix's content to be on 1 page which in this case can't be done and everything else on the rest).

Is there a solution for this?

I tired grouping of data and putting option page break after new group but no luck.


问:
I am not getting OnDeviceRemoved() or OnDeviceAdded() callbacks when add/remove an AudioEndpoint
`I am using the IMMNotificationClient interface and have registered for RegisterEndpointNotificationCallback (I am using the code samples from Device Events from msdn library). When I remove/add an audio endpoint, I do get OnDeviceStateChanged, OnDefaultDeviceChange, OnPropertyValueChanged callbacks, but not the OnDeviceRemoved or OnDeviceAdded.

OnDeviceRemoved or OnDeviceAdded are not being called when I insert or remove a headphone. Only OnDeviceStateChanged  and OnDefaultDeviceChange are being called.


问:
jQuery: Getting Ajax object from within either $.ajaxSetup() or $.ajaxPrefilter()
I'm working on a web app which makes multiple API calls using jQuery's ajax. Because all of these requests are to my own API and use very similar sets of data, I'm hoping to use the features of either the $.ajaxSetup() or $.ajaxPrefilter() to make a generalized config, avoiding repetition and and reducing the footprint of my app significantly.

I'm using a function in the xhr config to calculate upload progress as a percentage which would also need to move. The behaviour of this is to be the same in every API call, but what I was hoping to do is provide a smaller "progress" function, unique to each ajax call that can then do whatever it wants with that percentage data once calculated. This would allow for easy operation and minimal code in all subsequent ajax calls.

If everything is written into the same ajax call as below - it works great! The progress function logs upload progress to console as expected.

```<code>$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
            this.progress_percentage = parseInt(evt.loaded / evt.total * 100);
            if(typeof this.progress === 'function'){
                this.progress(this.progress_percentage); // <--- Run ajax-call specific function if defined.
            }
            }else{
                console.warn('Content-length is not set. Unable to display upload progress.');
            }
        }, false);

        return xhr;
    },
    progress: function(e) {
        console.log('Called by xhr(). Progress: ' + e) // <-- Output logged successfully.
    }
});
</code>```

The difficulty comes in when moving the xhr function into the generalized config.

Because at that point the ajax object has not been created yet, I'm unsure of how to access it and check for the presence of the progress() function. To illustrate:

```<code>$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    options.xhr = function() {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
            this.progress_percentage = parseInt(evt.loaded / evt.total * 100);
            if(typeof this.progress === 'function'){
                this.progress(this.progress_percentage); // <--- progress function will NEVER be defined at this point because as far as prefilter is concerned, the ajax object has not been created yet and no call-specific behaviour can be set. "this" points to the window and NOT the ajax  object.
            }
            }else{
                console.warn('Content-length is not set. Unable to display upload progress.');
            }
        }, false);

        return xhr;
        }
});
</code>```

I was expecting there to be some way to access the ajax object from it's setup functions but have been unable to find anything in the documentation. Hoping for either a way to do that, or some advice on how to refactor my code to get this running!

I realise upload progress is a fairly simple function and there will certainly be a lib for it, but as I have other configs and features within the app that would also benefit, I'd much prefer to get this running instead, if at all possible.

What would you suggest? Thank you.

Body:
I'm working on a web app which makes multiple API calls using jQuery's ajax. Because all of these requests are to my own API and use very similar sets of data, I'm hoping to use the features of either the $.ajaxSetup() or $.ajaxPrefilter() to make a generalized config, avoiding repetition and and reducing the footprint of my app significantly.

I'm using a function in the xhr config to calculate upload progress as a percentage which would also need to move. The behaviour of this is to be the same in every API call, but what I was hoping to do is provide a smaller "progress" function, unique to each ajax call that can then do whatever it wants with that percentage data once calculated. This would allow for easy operation and minimal code in all subsequent ajax calls.

If everything is written into the same ajax call as below - it works great! The progress function logs upload progress to console as expected.

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
            this.progress_percentage = parseInt(evt.loaded / evt.total * 100);
            if(typeof this.progress === 'function'){
                this.progress(this.progress_percentage); // <--- Run ajax-call specific function if defined.
            }
            }else{
                console.warn('Content-length is not set. Unable to display upload progress.');
            }
        }, false);

        return xhr;
    },
    progress: function(e) {
        console.log('Called by xhr(). Progress: ' + e) // <-- Output logged successfully.
    }
});

The difficulty comes in when moving the xhr function into the generalized config.

Because at that point the ajax object has not been created yet, I'm unsure of how to access it and check for the presence of the progress() function. To illustrate:

$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    options.xhr = function() {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
            this.progress_percentage = parseInt(evt.loaded / evt.total * 100);
            if(typeof this.progress === 'function'){
                this.progress(this.progress_percentage); // <--- progress function will NEVER be defined at this point because as far as prefilter is concerned, the ajax object has not been created yet and no call-specific behaviour can be set. "this" points to the window and NOT the ajax  object.
            }
            }else{
                console.warn('Content-length is not set. Unable to display upload progress.');
            }
        }, false);

        return xhr;
        }
});

I was expecting there to be some way to access the ajax object from it's setup functions but have been unable to find anything in the documentation. Hoping for either a way to do that, or some advice on how to refactor my code to get this running!

I realise upload progress is a fairly simple function and there will certainly be a lib for it, but as I have other configs and features within the app that would also benefit, I'd much prefer to get this running instead, if at all possible.

What would you suggest? Thank you.


问:
Question on OpenAPI oneof with only `required`
I've got a question about OpenAPI specification (3.0.0). Here is part of the specification document:

```<code>Area:
  type: object
  oneOf:
    - required:
      - tacs
    - required:
      - areaCode
  properties:
    tacs:
      type: array
      items:
        $ref: '#/components/schemas/Tac'
      minItems: 1
    areaCode:
        $ref: '#/components/schemas/AreaCode'
</code>```

Ref: https://forge.3gpp.org/rep/all/5G_APIs/-/blob/TSG97-Rel16/TS29571_CommonData.yaml#L1263

(definitions of Tac and AreadCode can be found in the same file but these are not the focus on the question)

According to https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/, oneOf validates the value against exactly one of the subschemas.

Does it mean JSON payload must have one property - either tacs or areaCode but not both? or it means something else?

Thanks.

I did a google search but didn't find explanation (official or unofficial) on this type of definition.

Body:
I've got a question about OpenAPI specification (3.0.0). Here is part of the specification document:

Area:
  type: object
  oneOf:
    - required:
      - tacs
    - required:
      - areaCode
  properties:
    tacs:
      type: array
      items:
        $ref: '#/components/schemas/Tac'
      minItems: 1
    areaCode:
        $ref: '#/components/schemas/AreaCode'

Ref: https://forge.3gpp.org/rep/all/5G_APIs/-/blob/TSG97-Rel16/TS29571_CommonData.yaml#L1263

(definitions of Tac and AreadCode can be found in the same file but these are not the focus on the question)

According to https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/, oneOf validates the value against exactly one of the subschemas.

Does it mean JSON payload must have one property - either tacs or areaCode but not both? or it means something else?

Thanks.

I did a google search but didn't find explanation (official or unofficial) on this type of definition.


问:
awsIotClient.publish(topic, payload); function taking so long to response and service getting stuck with no error msg
I am implementing a feature where at first service will send a request and depending on the asynchronous response service need to send another response. So I am using a onMessage Listner to listen from the AWS Topic, and depending on the response I need to send request in batch.

for example --> 1st req is upper limit of a keys, then I will send the full data in group of that upper limit.

So I am using a observer class to make the other request. But while requesting second time service is getting stuck.

What might be the cause of the function to stop suddenly? The debugging pointer is also suddenly disappearing after coming to that  awsIotClient.publish(topic, payload); function

Need help in approach, and please suggest what I might doing wrong.


问:
Change session.gc_maxlifetime and session.cookie_lifetime in Docker php-apache
I want to increase the session lifetime in php.ini.
Unfortunatelly I cannot use ini_set in php script itself, due to other circumstances like using some compozer stuff.

Anyway, usually on a root server I would simply change those settings in the native php.ini.
But inside the container, build by image php:7.4-apache, I cannot find the right place to do it.

Does anyone know which php.ini is used inside the container?

I tried this in my Dockerfile:

```<code>RUN sed -i "s/session.gc_maxlifetime = 1440/session.gc_maxlifetime = 604800/g" /usr/local/etc/php/php.ini-production
RUN sed -i "s/session.cookie_lifetime = 0/session.cookie_lifetime = 604800/g" /usr/local/etc/php/php.ini-production

RUN sed -i "s/session.gc_maxlifetime = 1440/session.gc_maxlifetime = 604800/g" /usr/local/etc/php/php.ini-development
RUN sed -i "s/session.cookie_lifetime = 0/session.cookie_lifetime = 604800/g" /usr/local/etc/php/php.ini-development
</code>```

The change is there in the container, but when I have a look in my phpinfo(), I can see, that still the default session time of 1440 is set for session.gc_maxlifetime.

phpinfo

Body:
I want to increase the session lifetime in php.ini.
Unfortunatelly I cannot use ini_set in php script itself, due to other circumstances like using some compozer stuff.

Anyway, usually on a root server I would simply change those settings in the native php.ini.
But inside the container, build by image php:7.4-apache, I cannot find the right place to do it.

Does anyone know which php.ini is used inside the container?

I tried this in my Dockerfile:

RUN sed -i "s/session.gc_maxlifetime = 1440/session.gc_maxlifetime = 604800/g" /usr/local/etc/php/php.ini-production
RUN sed -i "s/session.cookie_lifetime = 0/session.cookie_lifetime = 604800/g" /usr/local/etc/php/php.ini-production

RUN sed -i "s/session.gc_maxlifetime = 1440/session.gc_maxlifetime = 604800/g" /usr/local/etc/php/php.ini-development
RUN sed -i "s/session.cookie_lifetime = 0/session.cookie_lifetime = 604800/g" /usr/local/etc/php/php.ini-development

The change is there in the container, but when I have a look in my phpinfo(), I can see, that still the default session time of 1440 is set for session.gc_maxlifetime.

phpinfo


问:
Cannot access data from body in back-end
I am trying to create a contact form submission, which is supposed to send information through email. I am having the following problem: when I send the data from the front-end to the back-end, req.body I get undefined. The thing is, when I log just the req, I get the data in the body object, but when I try to do it the other way(req.body), I get undefined.

This is my code on the front-end:

```<code>const handleSubmit = (e) => {
        e.preventDefault()
        setButtonText('Sending...')
        const res = axios.post("http://localhost:3000/contact", formDetails);
        res.then((res) => {
            console.log(res.json());
        }).catch(err => console.log(err))

        setButtonText('Send')
        // let result = response.json()
        setFormDetails(formInitialDetails)
        // if (result.code === 200) {
        //     setStatus({success: true, message:'Message Sent Successfully'})
        // }else{
        //     setStatus({success: false, message:'Something went wrong'})
        // }
   }
</code>```

This is my code on the back-end

```<code>const express = require ("express")
const router = express.Router()
const cors = require("cors")
const nodemailer = require("nodemailer")

// server used to send emails
const app = express()
app.use(cors())
app.use(express.json())
app.use(router);

const contactEmail = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: "pandurskacveta@gmail.com",
        pass: "evsifhlwuujznxtj"
    }
})

contactEmail.verify((error) => {
    if (error) {
        console.log(error);
    }else{
        console.log('Ready to send');
    }
})

router.post("/contact", (res, req) => {
    console.log(req.body);
    // const name = req.body.firstName + req.body.lastName
    // const email = req.body.email
    // const message = req.body.message
    // const phone = req.body.phone
    // const mail = {
    //     from: name,
    //     to: "pandurskacveta@gmail.com",
    //     subject: "Contact Submission from Personal Portfolio",
    //     html: ` <p>Name: ${name}</p>
    //     <p>Email: ${email}</p>
    //     <p>Phone: ${phone}</p>
    //     <p>Message: ${message}</p>
    //     `
    // }
    // contactEmail.sendMail(mail, (error) => {
    //     if (error) {
    //         res.json(error)
    //     } else {
    //         res.json({code: 200, status:"Message Sent!"})
    //     }
    // })
})

app.listen(3000, () => console.log('Server Running'))
</code>```

Body:
I am trying to create a contact form submission, which is supposed to send information through email. I am having the following problem: when I send the data from the front-end to the back-end, req.body I get undefined. The thing is, when I log just the req, I get the data in the body object, but when I try to do it the other way(req.body), I get undefined.

This is my code on the front-end:

const handleSubmit = (e) => {
        e.preventDefault()
        setButtonText('Sending...')
        const res = axios.post("http://localhost:3000/contact", formDetails);
        res.then((res) => {
            console.log(res.json());
        }).catch(err => console.log(err))

        setButtonText('Send')
        // let result = response.json()
        setFormDetails(formInitialDetails)
        // if (result.code === 200) {
        //     setStatus({success: true, message:'Message Sent Successfully'})
        // }else{
        //     setStatus({success: false, message:'Something went wrong'})
        // }
   }

This is my code on the back-end

const express = require ("express")
const router = express.Router()
const cors = require("cors")
const nodemailer = require("nodemailer")

// server used to send emails
const app = express()
app.use(cors())
app.use(express.json())
app.use(router);

const contactEmail = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: "pandurskacveta@gmail.com",
        pass: "evsifhlwuujznxtj"
    }
})

contactEmail.verify((error) => {
    if (error) {
        console.log(error);
    }else{
        console.log('Ready to send');
    }
})

router.post("/contact", (res, req) => {
    console.log(req.body);
    // const name = req.body.firstName + req.body.lastName
    // const email = req.body.email
    // const message = req.body.message
    // const phone = req.body.phone
    // const mail = {
    //     from: name,
    //     to: "pandurskacveta@gmail.com",
    //     subject: "Contact Submission from Personal Portfolio",
    //     html: `
Name: ${name}

    //
Email: ${email}

    //
Phone: ${phone}

    //
Message: ${message}

    //     `
    // }
    // contactEmail.sendMail(mail, (error) => {
    //     if (error) {
    //         res.json(error)
    //     } else {
    //         res.json({code: 200, status:"Message Sent!"})
    //     }
    // })
})

app.listen(3000, () => console.log('Server Running'))


问:
update an attribute and call a method with updated attribute
I'd like to sweep through values of N in N_range using different hs values and store the outcome of each method call (htn()) separately.

This is how I could do it. Wondering how can I improve this code. It is not the most elegant one!

```<code>import numpy as np
class MyClass:
    def __init__(self, h, n, t):
        self.h = h
        self.n = n
        self.t = t

    def hnt(self):
        return self.h*self.n*self.t

n_range = np.linspace(1,10, num=10)
hs = [1,2,3]

# list of instances
my_objs = [MyClass(1,1,1), MyClass(2,0,3), MyClass(1,3,4)]

h0=[]; h1=[]; h2=[]

for i in range(len(n_range)):
    my_objs[0].n = n_range[i]
    h0.append(my_objs[0].hnt())
    my_objs[1].n = n_range[i]
    h1.append(my_objs[1].hnt())
    my_objs[2].n = n_range[i]
    h2.append(my_objs[2].hnt())
</code>```

Body:
I'd like to sweep through values of N in N_range using different hs values and store the outcome of each method call (htn()) separately.

This is how I could do it. Wondering how can I improve this code. It is not the most elegant one!

import numpy as np
class MyClass:
    def __init__(self, h, n, t):
        self.h = h
        self.n = n
        self.t = t

    def hnt(self):
        return self.h*self.n*self.t

n_range = np.linspace(1,10, num=10)
hs = [1,2,3]

# list of instances
my_objs = [MyClass(1,1,1), MyClass(2,0,3), MyClass(1,3,4)]

h0=[]; h1=[]; h2=[]

for i in range(len(n_range)):
    my_objs[0].n = n_range[i]
    h0.append(my_objs[0].hnt())
    my_objs[1].n = n_range[i]
    h1.append(my_objs[1].hnt())
    my_objs[2].n = n_range[i]
    h2.append(my_objs[2].hnt())


问:
<Route> is only ever to be used as the child of <Routes> element while using withAuthenticationRequired Auth0
if the user is not logged in and enters a URL like (/profile), he must be redirected to the login page with help of Auth0. For this purpose, I used withAuthenticationRequired and rendered it in ProtectedRoute component. It looks like this:-

```<code>import React from 'react';
import { Route } from 'react-router-dom';
import { withAuthenticationRequired } from '@auth0/auth0-react';
import Loading from './Loading';

const ProtectedRoute = ({ component, ...args }) => (
  <Route
    component={withAuthenticationRequired(component, {
      onRedirecting: () => <Loading />,
    })}
    {...args}
  />
);

export default ProtectedRoute;
</code>```

Since I am using react V6, I used the modern way to wrap the routes with ProtectedRoute but this is showing the error "A  is only ever to be used as the child of  element".

```<code> <Route exact path='/profile' element={<ProtectedRoute />}>
          <Route exact path='/profile' element={<Profile />} />
        </Route>
</code>```

Am i missing something ?

Body:
if the user is not logged in and enters a URL like (/profile), he must be redirected to the login page with help of Auth0. For this purpose, I used withAuthenticationRequired and rendered it in ProtectedRoute component. It looks like this:-

import React from 'react';
import { Route } from 'react-router-dom';
import { withAuthenticationRequired } from '@auth0/auth0-react';
import Loading from './Loading';

const ProtectedRoute = ({ component, ...args }) => (
  <Route
    component={withAuthenticationRequired(component, {
      onRedirecting: () => <Loading />,
    })}
    {...args}
  />
);

export default ProtectedRoute;

Since I am using react V6, I used the modern way to wrap the routes with ProtectedRoute but this is showing the error "A  is only ever to be used as the child of  element".

 <Route exact path='/profile' element={<ProtectedRoute />}>
          <Route exact path='/profile' element={<Profile />} />
        </Route>

Am i missing something ?


问:
Can we increment and decrement the same metric if different labels come at runtime in Prometheus
Actually, I am using Gauge Metric in Prometheus to increment and decrement the value with the dynamic label "client_name". First, we initialize the metric with the below snippet -

```<code>clientMetric = prometheus.NewGauge(prometheus.GaugeOpts{
    Name:          "Client",
    Help:          "Client operation performed",
    DynamicLabels: []string{"client_name"},
})
</code>```

Then, we can use collector() type in Prometheus to set the updated value in clientMetric with below code snippet -

```<code>prometheus.Collector(func() {
//Get the client name from client DB. So "client" is just an entry.
val clientCount int
clientName := ""
if clientList != nil && len(*clientList) > 0 {
    for _, client := range *clientList {
        if client.ClientType == "IP" {
            clientCount = clientCount + 1
            clientName = client.ClientName
        }
    }

    if client != 0 {
        clientMetric.Set(float64(clientCount), clientName)
    } else {
        clientMetric.Set(float64(clientCount), clientName)
    }
} else {
    clientMetric.Set(float64(clientCount), clientName)
}
})
</code>```

If I check in the metrics port (http://localhost:9090/) then the data shows like:

```<code>Client{client_name="10.20.30.40", instance="50.40.30.20"}    1
Client{client_name="", instance="50.40.30.20"}               0
</code>```

Here, the issue is getting two metrics but I want only one metric should come instead of a new metric being generated and the counter of 1 should be 0

Body:
Actually, I am using Gauge Metric in Prometheus to increment and decrement the value with the dynamic label "client_name". First, we initialize the metric with the below snippet -

clientMetric = prometheus.NewGauge(prometheus.GaugeOpts{
    Name:          "Client",
    Help:          "Client operation performed",
    DynamicLabels: []string{"client_name"},
})

Then, we can use collector() type in Prometheus to set the updated value in clientMetric with below code snippet -

prometheus.Collector(func() {
//Get the client name from client DB. So "client" is just an entry.
val clientCount int
clientName := ""
if clientList != nil && len(*clientList) > 0 {
    for _, client := range *clientList {
        if client.ClientType == "IP" {
            clientCount = clientCount + 1
            clientName = client.ClientName
        }
    }

    if client != 0 {
        clientMetric.Set(float64(clientCount), clientName)
    } else {
        clientMetric.Set(float64(clientCount), clientName)
    }
} else {
    clientMetric.Set(float64(clientCount), clientName)
}
})

If I check in the metrics port (http://localhost:9090/) then the data shows like:

Client{client_name="10.20.30.40", instance="50.40.30.20"}    1
Client{client_name="", instance="50.40.30.20"}               0

Here, the issue is getting two metrics but I want only one metric should come instead of a new metric being generated and the counter of 1 should be 0


问:
Automation testing in separate repo github
I am trying to set it up so every time I set up a PR in a GitHub repo it runs the playwright automation tests in a separate repo.

Application Repo file:

```<code>name: View Test Results
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  view-test-results:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v2
        with:
          repository: benparr64/kegthat-automation-tests
          name: playwright-report
      - run: ls playwright-report/
</code>```

And automation test file:

```<code>name: Playwright Tests
on:
  push:
    branches: [ main, master ]
  pull_request:
    branches: [ main, master ]
jobs:
  test:
    timeout-minutes: 60
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - uses: actions/setup-node@v3
      with:
        node-version: 16
    - name: Install dependencies
      run: npm ci
    - name: Install Playwright Browsers
      run: npx playwright install --with-deps
    - name: Run Playwright tests
      run: npx playwright test
    - uses: actions/upload-artifact@v3
      if: always()
      with:
        name: playwright-report
        path: playwright-report/
        retention-days: 30
</code>```

This is not working at all have tried lots of different ways of doing this. One repo is called kegthat-automation-tests and the other is called kegthat-headless. I think I just need to find a way of accessing the artifact from other repo but cant figure this out...

The GitHub action for playwright tests is passing okay.

It is a problem with view test results. Current error is

```<code>Unexpected input(s) 'repository', valid inputs are ['name', 'path']
</code>```

Body:
I am trying to set it up so every time I set up a PR in a GitHub repo it runs the playwright automation tests in a separate repo.

Application Repo file:

name: View Test Results
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  view-test-results:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v2
        with:
          repository: benparr64/kegthat-automation-tests
          name: playwright-report
      - run: ls playwright-report/

And automation test file:

name: Playwright Tests
on:
  push:
    branches: [ main, master ]
  pull_request:
    branches: [ main, master ]
jobs:
  test:
    timeout-minutes: 60
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - uses: actions/setup-node@v3
      with:
        node-version: 16
    - name: Install dependencies
      run: npm ci
    - name: Install Playwright Browsers
      run: npx playwright install --with-deps
    - name: Run Playwright tests
      run: npx playwright test
    - uses: actions/upload-artifact@v3
      if: always()
      with:
        name: playwright-report
        path: playwright-report/
        retention-days: 30

This is not working at all have tried lots of different ways of doing this. One repo is called kegthat-automation-tests and the other is called kegthat-headless. I think I just need to find a way of accessing the artifact from other repo but cant figure this out...

The GitHub action for playwright tests is passing okay.

It is a problem with view test results. Current error is

Unexpected input(s) 'repository', valid inputs are ['name', 'path']


问:
Mongoose Transactions and Post Transactional Operations
I am using mongoose together with sessions to perform ACID transactions in our nodejs + express backend.

lately, I have a necessity to send a message to one of our workers (backed by RabbitMQ) to make post transactional operation. I cannot directly send the message to our worker after the commit because there is a complex workflow behind it and completing the transaction does not always mean that the code must be called.

I believe that I need to use event emitters to register .once('onCommit', ...) event, and call emit('onCommit') when the transaction is done. But this is manual approach.

I would like to know if there is out of the box support in mongoose to make post transactional operations using mongoose.ClientSession. I am seeing that mongoose sessions are by itself Event Listeners but I couldn't find any related docuementation. I guess session events are for internal use.

can anyone enlighten me?

thank you


问:
Can I integrate a Cloudflare Backend in my Wagtail CMS
I'm currently building a Wagtail CMS and i want to connect the database with my Cloudflare Database.

However, Im confused how to do that and I cant find anything concrete in the Docs as well.
All i find is AmazonAWS and ElasticSearch.

Am I missing something?

So far i wen through the docs and configured the Wagtailfrontend cache, which is needed to update my page when using Cloudflare


问:
Nginx - proxy request to URL specified in request Header
I have a strange requirement, My System is using NGNIX as a reverse proxy. where each request is redirected to URL specified in request header itself.

For e.g.
Request 1:

```<code>http://localhost/test
---
X-ROUTE = "http://backend.com"
--- other headers
</code>```

should be redirected to http://backend.com/test
Similarly

```<code>http://localhost/test
{
X-ROUTE = "http://demo.service.com"
}
</code>```

should be redirected to http://demo.service.com/test

Since the upstream server cannot directly access these URL, we have to take this approach.

Each request recivied in NGINX reverse proxy should be parsed to get the url from the 'X-ROUTE' header value and then it should be routed in the same url we recieved in X-ROUTE

Body:
I have a strange requirement, My System is using NGNIX as a reverse proxy. where each request is redirected to URL specified in request header itself.

For e.g.
Request 1:

http://localhost/test
---
X-ROUTE = "http://backend.com"
--- other headers

should be redirected to http://backend.com/test
Similarly

http://localhost/test
{
X-ROUTE = "http://demo.service.com"
}

should be redirected to http://demo.service.com/test

Since the upstream server cannot directly access these URL, we have to take this approach.

Each request recivied in NGINX reverse proxy should be parsed to get the url from the 'X-ROUTE' header value and then it should be routed in the same url we recieved in X-ROUTE


问:
Why after giving value datetime-local datetime is it not changeable?
I am using datetime-local to set the meeting time, try to give datetime but not showing up on output.

More, it shows up when tried on stackblitz but not on the project.

UPDATE

TS:

```<code>TODAY= new Date().toISOString().slice(0, 10);

ngOnInit(): void { }

DT(name:string, time:string) { (document.getElementById(name) as HTMLTextAreaElement).value = moment(this.TODAY + 'T' + time)['_i'];  }
</code>```

HTML:

```<code><input formControlName="ab" id="ab" type="datetime-local" class="form-control" [value]="DT('ab','08:30')" required>
</code>```

The good thing is its value datetime is appearing on the website, the issue is after that I am not able to change datetime.

Body:
I am using datetime-local to set the meeting time, try to give datetime but not showing up on output.

More, it shows up when tried on stackblitz but not on the project.

UPDATE

TS:

TODAY= new Date().toISOString().slice(0, 10);

ngOnInit(): void { }

DT(name:string, time:string) { (document.getElementById(name) as HTMLTextAreaElement).value = moment(this.TODAY + 'T' + time)['_i'];  }

HTML:

<input formControlName="ab" id="ab" type="datetime-local" class="form-control" [value]="DT('ab','08:30')" required>

The good thing is its value datetime is appearing on the website, the issue is after that I am not able to change datetime.


问:
I'm building Connect Four game in terminal but cannot find four adjacent elements of a line
I don't know how to debug that piece of code at the beginning of diagonal1(grid) method down to where the static method checkWin() ends, because when I run debugger it immediately closes and doesn't even reach the method checWin(). The only thing i don't understand is why the innermost for loop that iterates over line returns an empty array instead of, for example, ['X', 'X', 'X', 'X']. I need that for loop to look for four similar adjacent elements and return an array with them inside.

My code:

class Myclass {
  consructor() {
    this.playerTurn = "O";
    this.grid = [[' ',' ',' ',' ',' ',' ',' '],
                 [' ',' ',' ',' ',' ',' ',' '],
                 [' ',' ',' ',' ',' ',' ',' '],
                 [' ',' ',' ',' ',' ',' ',' '],
                 [' ',' ',' ',' ',' ',' ',' '],
                 [' ',' ',' ',' ',' ',' ',' ']]

    this.cursor = new Cursor(6, 7);

    // Initialize a 6x7 connect-four grid
    Screen.initialize(6, 7);
    Screen.setGridlines(true);

    // Replace this with real commands
    Screen.addCommand('up', 'move up', this.cursor.up);
    Screen.addCommand('down', 'move down', this.cursor.down);
    Screen.addCommand('right', 'move right', this.cursor.right);
    Screen.addCommand('left', 'move left', this.cursor.left);

    this.cursor.setBackgroundColor();
    Screen.render();
  }

  diagonal1(grid) {
    let diagonals = [];

    for (let i = 0; i < grid.length; i++) {
      for (let j = 0; j < grid[i].length; j++) {
        let diagonal = [];

        let row = i;
        let col = j;
        while (row < grid.length && col < grid[i].length) {
          diagonal.push(grid[row][col]);
          row++;
          col++;
        }
        if (diagonal.length > 4) {
          diagonals.push(diagonal);
        }
      }
    }
    return diagonals;
  }

  diagonal2(grid) {
    let diagonals = [];

    for (let i = grid.length - 1; i >= 0; i--) {
      for (let j = grid[i].length - 1; j >= 0; j--) {
        let diagonal = [];

        let row = i;
        let col = j;
        while (row >= 0 && col >= 0) {
          diagonal.push(grid[row][col]);
          row--;
          col--;
        }
        if (diagonal.length > 4) {
          diagonals.push(diagonal);
        }
      }
    }
    return diagonals;
  }

  static checkWin(grid) {
    const players = ['X', 'O'];
    const columns = grid[0].map((_, i) => grid.map(row => row[i]));
    const rows = grid;
    const obj = new ConnectFour();
    const downwardDiagonals = obj.diagonal1(grid);
    const upwardDiagonals = obj.diagonal2(grid);

    if (grid.flat().every(cell => cell === ' ')) {
      return false;
    }

    for (let player of players) {
      let winner = [];
      for (let line of [...rows, ...columns, ...downwardDiagonals, ...upwardDiagonals]) {
        // find the player that takes four cells of a line consequtively
        let currentElement = [];
        let count = 0;
        let winner = [];

        for (let i = 0; i < line.length; i++) {
          if (line[i] !== ' ' && line[i] === currentElement) {
            count++;
          } else {
            currentElement = line[i];
            count = 0;
          }
          if (count >= 4) {
            winner.push(currentElement);
          }
        }
        console.log(winner)
        return winner;
      }
      // ------------------------------
      if (winner.length >= 4) return player;

      if (grid.flat().every(cell => cell !== ' ')) {
        return "T";
      }
    }
    return false;
  }

  static endGame(winner) {
    if (winner === 'O' || winner === 'X') {
      Screen.setMessage(`Player ${winner} wins!`);
    } else if (winner === 'T') {
      Screen.setMessage(`Tie game!`);
    } else {
      Screen.setMessage(`Game Over`);
    }
    Screen.render();
    Screen.quit();
  }
}
```
<p>what the tests get back:</p>
<ol>
<li><p>Connect Four
recognizes horizontal wins:
AssertionError: expected [] to equal 'X'
at Context. (test/connect-four-spec.js:31:43)
at processImmediate (node:internal/timers:466:21)</p>
</li>
<li><p>Connect Four
recognizes vertical wins:
AssertionError: expected [] to equal 'X'
at Context. (test/connect-four-spec.js:53:43)
at processImmediate (node:internal/timers:466:21)</p>
</li>
<li><p>Connect Four
recognizes diagonal downward wins:
AssertionError: expected [] to equal 'X'
at Context. (test/connect-four-spec.js:76:43)
at processImmediate (node:internal/timers:466:21)</p>
</li>
<li><p>Connect Four
recognizes diagonal upward wins:
AssertionError: expected [] to equal 'O'
at Context. (test/connect-four-spec.js:89:43)</p>
</li>
</ol>
```

```

Body:
I don't know how to debug that piece of code at the beginning of diagonal1(grid) method down to where the static method checkWin() ends, because when I run debugger it immediately closes and doesn't even reach the method checWin(). The only thing i don't understand is why the innermost for loop that iterates over line returns an empty array instead of, for example, ['X', 'X', 'X', 'X']. I need that for loop to look for four similar adjacent elements and return an array with them inside.

My code:

class Myclass {
  consructor() {
    this.playerTurn = "O";
    this.grid = [[' ',' ',' ',' ',' ',' ',' '],
                 [' ',' ',' ',' ',' ',' ',' '],
                 [' ',' ',' ',' ',' ',' ',' '],
                 [' ',' ',' ',' ',' ',' ',' '],
                 [' ',' ',' ',' ',' ',' ',' '],
                 [' ',' ',' ',' ',' ',' ',' ']]

    this.cursor = new Cursor(6, 7);

    // Initialize a 6x7 connect-four grid
    Screen.initialize(6, 7);
    Screen.setGridlines(true);

    // Replace this with real commands
    Screen.addCommand('up', 'move up', this.cursor.up);
    Screen.addCommand('down', 'move down', this.cursor.down);
    Screen.addCommand('right', 'move right', this.cursor.right);
    Screen.addCommand('left', 'move left', this.cursor.left);

    this.cursor.setBackgroundColor();
    Screen.render();
  }

  diagonal1(grid) {
    let diagonals = [];

    for (let i = 0; i < grid.length; i++) {
      for (let j = 0; j < grid[i].length; j++) {
        let diagonal = [];

        let row = i;
        let col = j;
        while (row < grid.length && col < grid[i].length) {
          diagonal.push(grid[row][col]);
          row++;
          col++;
        }
        if (diagonal.length > 4) {
          diagonals.push(diagonal);
        }
      }
    }
    return diagonals;
  }

  diagonal2(grid) {
    let diagonals = [];

    for (let i = grid.length - 1; i >= 0; i--) {
      for (let j = grid[i].length - 1; j >= 0; j--) {
        let diagonal = [];

        let row = i;
        let col = j;
        while (row >= 0 && col >= 0) {
          diagonal.push(grid[row][col]);
          row--;
          col--;
        }
        if (diagonal.length > 4) {
          diagonals.push(diagonal);
        }
      }
    }
    return diagonals;
  }

  static checkWin(grid) {
    const players = ['X', 'O'];
    const columns = grid[0].map((_, i) => grid.map(row => row[i]));
    const rows = grid;
    const obj = new ConnectFour();
    const downwardDiagonals = obj.diagonal1(grid);
    const upwardDiagonals = obj.diagonal2(grid);

    if (grid.flat().every(cell => cell === ' ')) {
      return false;
    }

    for (let player of players) {
      let winner = [];
      for (let line of [...rows, ...columns, ...downwardDiagonals, ...upwardDiagonals]) {
        // find the player that takes four cells of a line consequtively
        let currentElement = [];
        let count = 0;
        let winner = [];

        for (let i = 0; i < line.length; i++) {
          if (line[i] !== ' ' && line[i] === currentElement) {
            count++;
          } else {
            currentElement = line[i];
            count = 0;
          }
          if (count >= 4) {
            winner.push(currentElement);
          }
        }
        console.log(winner)
        return winner;
      }
      // ------------------------------
      if (winner.length >= 4) return player;

      if (grid.flat().every(cell => cell !== ' ')) {
        return "T";
      }
    }
    return false;
  }

  static endGame(winner) {
    if (winner === 'O' || winner === 'X') {
      Screen.setMessage(`Player ${winner} wins!`);
    } else if (winner === 'T') {
      Screen.setMessage(`Tie game!`);
    } else {
      Screen.setMessage(`Game Over`);
    }
    Screen.render();
    Screen.quit();
  }
}

what the tests get back:

Connect Four
recognizes horizontal wins:
AssertionError: expected [] to equal 'X'
at Context. (test/connect-four-spec.js:31:43)
at processImmediate (node:internal/timers:466:21)

Connect Four
recognizes vertical wins:
AssertionError: expected [] to equal 'X'
at Context. (test/connect-four-spec.js:53:43)
at processImmediate (node:internal/timers:466:21)

Connect Four
recognizes diagonal downward wins:
AssertionError: expected [] to equal 'X'
at Context. (test/connect-four-spec.js:76:43)
at processImmediate (node:internal/timers:466:21)

Connect Four
recognizes diagonal upward wins:
AssertionError: expected [] to equal 'O'
at Context. (test/connect-four-spec.js:89:43)


问:
postProcessAfterInitialization called twice for sessionFactory
can somebody tell me why postProcessAfterInitialization method called twice for creating Session Factory in spring and hibernate

i expected that method called once

this is configuration part of my code and using annotation instead of xml base config

code:

```<code>package org.example.excel.Configuration;

import org.example.excel.ClassFactory.ClassBuilderFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class HibernateConfig implements BeanPostProcessor {

    private ClassBuilderFactory classBuilderFactory;

    @Autowired
    public HibernateConfig(ClassBuilderFactory classBuilderFactory) {
        this.classBuilderFactory = classBuilderFactory;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactoryBean() {
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource());
        sessionFactoryBean.setHibernateProperties(hibernateProperties());
        sessionFactoryBean.setPackagesToScan("org.example.excel.Model");
        return sessionFactoryBean;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
        dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
        dataSource.setUsername("Test");
        dataSource.setPassword("1234");
        return dataSource;
    }

    public Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
        properties.setProperty("hibernate.hbm2ddl.auto", "update");
        properties.setProperty("hibernate.current_session_context_class", "org.hibernate.context.internal.JTASessionContext");
        properties.setProperty("hibernate.show_sql", "true");
        return properties;
    }

    @Bean
    public PlatformTransactionManager hibernateTransactionManager() {
        HibernateTransactionManager tr = new HibernateTransactionManager();
        tr.setSessionFactory(sessionFactoryBean().getObject());
        return tr;
    }
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("in before" + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("in after " + beanName);
        return bean;

    }
}
</code>```

postProcessAfterInitialization method called once for every bean but called twice for sessionfactory
why?

Body:
can somebody tell me why postProcessAfterInitialization method called twice for creating Session Factory in spring and hibernate

i expected that method called once

this is configuration part of my code and using annotation instead of xml base config

code:

package org.example.excel.Configuration;

import org.example.excel.ClassFactory.ClassBuilderFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class HibernateConfig implements BeanPostProcessor {

    private ClassBuilderFactory classBuilderFactory;

    @Autowired
    public HibernateConfig(ClassBuilderFactory classBuilderFactory) {
        this.classBuilderFactory = classBuilderFactory;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactoryBean() {
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource());
        sessionFactoryBean.setHibernateProperties(hibernateProperties());
        sessionFactoryBean.setPackagesToScan("org.example.excel.Model");
        return sessionFactoryBean;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
        dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
        dataSource.setUsername("Test");
        dataSource.setPassword("1234");
        return dataSource;
    }

    public Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
        properties.setProperty("hibernate.hbm2ddl.auto", "update");
        properties.setProperty("hibernate.current_session_context_class", "org.hibernate.context.internal.JTASessionContext");
        properties.setProperty("hibernate.show_sql", "true");
        return properties;
    }

    @Bean
    public PlatformTransactionManager hibernateTransactionManager() {
        HibernateTransactionManager tr = new HibernateTransactionManager();
        tr.setSessionFactory(sessionFactoryBean().getObject());
        return tr;
    }
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("in before" + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("in after " + beanName);
        return bean;

    }
}

postProcessAfterInitialization method called once for every bean but called twice for sessionfactory
why?


问:
How to pipe each bitrate of ffmpeg output to a third party program?
My requirement is very simple. Any one can understand from below example,

fmpeg -i ../original.mkv

-c:v h264 -c:a aac -f mpegts - | myprogam \

-c:v h264 -c:a aac -vf "scale=1280:720" -f mpegts - | myprogam \

-c:v h264 -c:a aac -vf "scale=854:480" -f mpegts - | myprogam \

I want to pass each version of output to a third party python program. Any help is highly appreciated.

Thank you


问:
How to send Multipart data over RSocket?
Can someone please provide an example which illustrates how to send Multipart Data(form-data) over Rsocket.

I tried using MimeTypeUtils.parseMimeType(WellKnownMimeType.MULTIPART_MIXED.getString()). But I always get No Encoder Found Exception for MultiValueMapAdapter<K,V> type data objects.


问:
This site can't be reached error with very simple Nginx config
I'm trying to deploy my react app to an EC2 instance running CentOS. I've installed nginx, pulled the code, built the application and I now want to try and access the default HTML file located at /usr/share/nginx/html but I'm getting a This site can't be reached.

My config is very simple:

```<code>user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

server_names_hash_bucket_size 128;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  123-123-123.us-east-2.compute.amazonaws.com;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }
}
</code>```

My conf.d directory is empty, and I don't have a sites-enabled or sites-available dir.
This is what I get with sudo ss -lnpt | grep nginx:

```<code>LISTEN 0      511          0.0.0.0:80        0.0.0.0:*    users:(("nginx",pid=8524,fd=6),("nginx",pid=8523,fd=6))
LISTEN 0      511             [::]:80           [::]:*    users:(("nginx",pid=8524,fd=7),("nginx",pid=8523,fd=7))
</code>```

Body:
I'm trying to deploy my react app to an EC2 instance running CentOS. I've installed nginx, pulled the code, built the application and I now want to try and access the default HTML file located at /usr/share/nginx/html but I'm getting a This site can't be reached.

My config is very simple:

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

server_names_hash_bucket_size 128;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  123-123-123.us-east-2.compute.amazonaws.com;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }
}

My conf.d directory is empty, and I don't have a sites-enabled or sites-available dir.
This is what I get with sudo ss -lnpt | grep nginx:

LISTEN 0      511          0.0.0.0:80        0.0.0.0:*    users:(("nginx",pid=8524,fd=6),("nginx",pid=8523,fd=6))
LISTEN 0      511             [::]:80           [::]:*    users:(("nginx",pid=8524,fd=7),("nginx",pid=8523,fd=7))