问:
Maintain Nested and Flat index structure at the same time
I have the following document structure (there are more than 2 million of such documents):

```<code>{
  "userId": "1",
  "month": "2022-01-30",
  "feeVal1": "1.232",
  "feeVal2": "2.5",
  "feeVal3": "3.12",
  "country": "Japan",
  "region": "Asia"
},
{
  "userId": "1",
  "month": "2022-02-28",
  "feeVal1": "534.213",
  "feeVal2": "62.3",
  "feeVal3": "76.2",
  "country": "Japan",
  "region": "Asia"
},
...
{
  "userId": "2",
  "month": "2022-01-30",
  "feeVal1": "121.677",
  "feeVal2": "78.3",
  "feeVal3": "22.2",
  "country": "US",
  "region": "Americas"
},
...
</code>```

I have two types use cases:

Aggregations -> I have multiple charts where I want to display different trends:

Weekly activity for a fee (region, country etc)

Top 10 countries, users etc.

Sums for a fee for a specific month range.

etc.

For this use case the flat index structure will be used

Data grid and excel export -> I want to display the users in a data grid and in the excel export in the following format one row at a time:

|. User. |. Country. |. Fee1 2022-01-30. |. Fee1 2022-02-28. |. Fee2 2022-01-30 etc....

For this I want to use a nested index structure as the users are already organised in a way to display the data in the desired structure (in this case I will have under 100K users):

```<code>{
      "userId": "1",
      "country": "Japan",
      "region": "Asia",
      "months": [
        {
          "month": "2022-01-30",
          "feeVal1": "1.232",
          "feeVal2": "2.5",
          "feeVal3": "3.12"
        },
        {
          "month": "2022-02-28",
          "feeVal1": "1.232",
          "feeVal2": "2.5",
          "feeVal3": "3.12"
        }
      ]
    },
    {
      "userId": "2",
      "country": "US",
      "region": "Americas",
      "months": [
        {
          "month": "2022-01-30",
          "feeVal1": "1.232",
          "feeVal2": "2.5",
          "feeVal3": "3.12"
        }
      ]
    }
</code>```

Filtering will be done only on the upper level fields.

My question is if it's a bad practice to maintain same data in two different indexes (with two different structures)? I should mention that these indexes are used only for reading and statistics and they are completely refreshed every week with new data.
The only disadvantage I can think of is maintaining two different mappings.

Body:
I have the following document structure (there are more than 2 million of such documents):

{
  "userId": "1",
  "month": "2022-01-30",
  "feeVal1": "1.232",
  "feeVal2": "2.5",
  "feeVal3": "3.12",
  "country": "Japan",
  "region": "Asia"
},
{
  "userId": "1",
  "month": "2022-02-28",
  "feeVal1": "534.213",
  "feeVal2": "62.3",
  "feeVal3": "76.2",
  "country": "Japan",
  "region": "Asia"
},
...
{
  "userId": "2",
  "month": "2022-01-30",
  "feeVal1": "121.677",
  "feeVal2": "78.3",
  "feeVal3": "22.2",
  "country": "US",
  "region": "Americas"
},
...

I have two types use cases:

Aggregations -> I have multiple charts where I want to display different trends:

Weekly activity for a fee (region, country etc)

Top 10 countries, users etc.

Sums for a fee for a specific month range.

etc.

For this use case the flat index structure will be used

Data grid and excel export -> I want to display the users in a data grid and in the excel export in the following format one row at a time:

|. User. |. Country. |. Fee1 2022-01-30. |. Fee1 2022-02-28. |. Fee2 2022-01-30 etc....

For this I want to use a nested index structure as the users are already organised in a way to display the data in the desired structure (in this case I will have under 100K users):

{
      "userId": "1",
      "country": "Japan",
      "region": "Asia",
      "months": [
        {
          "month": "2022-01-30",
          "feeVal1": "1.232",
          "feeVal2": "2.5",
          "feeVal3": "3.12"
        },
        {
          "month": "2022-02-28",
          "feeVal1": "1.232",
          "feeVal2": "2.5",
          "feeVal3": "3.12"
        }
      ]
    },
    {
      "userId": "2",
      "country": "US",
      "region": "Americas",
      "months": [
        {
          "month": "2022-01-30",
          "feeVal1": "1.232",
          "feeVal2": "2.5",
          "feeVal3": "3.12"
        }
      ]
    }

Filtering will be done only on the upper level fields.

My question is if it's a bad practice to maintain same data in two different indexes (with two different structures)? I should mention that these indexes are used only for reading and statistics and they are completely refreshed every week with new data.
The only disadvantage I can think of is maintaining two different mappings.


来源: stackexchange

问:
Altair add_selection only shows last year
I am trying to build a plot which shows a map of the US with all states, colored by whether cannabis is legalied or not.

You can find the data and full code here: git@github.com:tim-thei/Canabisdata.git

My dataframe looks like this (One row per state, per year):

id
state
year
legal

1
Alabama
2011
No

2
Alaska
2011
No

| 1   | Alabama | 2022 | No    |
| 2   | Alaska  | 2022 | Yes   |

```<code>import pandas as pd
import altair as alt

select_year = alt.selection_single(
    name='select', fields=['year'], init={'year': 2022},
    bind=alt.binding_range(min=2011, max=2022, step=1)
)

alt.Chart(states, title='US-States where canabis consume is legal').mark_geoshape().encode(
    color=alt.Color('legal:N', scale=alt.Scale(
            domain=['Yes', 'No'],
            range=['#32CD32', '#DC381F'])),
    tooltip=['state:N', 'legal:N']
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(df, 'id', varlist)
).properties(
    width=1000,
    height=600
).project(
    type='albersUsa'
).add_selection(select_year).transform_filter(select_year)

</code>```

For one year this works perfectly fine, but if I want to use add_selection to have the user choose the year, all years exept the latest display white space only.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to build a plot which shows a map of the US with all states, colored by whether cannabis is legalied or not.

You can find the data and full code here: git@github.com:tim-thei/Canabisdata.git

My dataframe looks like this (One row per state, per year):

id
state
year
legal

1
Alabama
2011
No

2
Alaska
2011
No

| 1   | Alabama | 2022 | No    |
| 2   | Alaska  | 2022 | Yes   |

import pandas as pd
import altair as alt

select_year = alt.selection_single(
    name='select', fields=['year'], init={'year': 2022},
    bind=alt.binding_range(min=2011, max=2022, step=1)
)

alt.Chart(states, title='US-States where canabis consume is legal').mark_geoshape().encode(
    color=alt.Color('legal:N', scale=alt.Scale(
            domain=['Yes', 'No'],
            range=['#32CD32', '#DC381F'])),
    tooltip=['state:N', 'legal:N']
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(df, 'id', varlist)
).properties(
    width=1000,
    height=600
).project(
    type='albersUsa'
).add_selection(select_year).transform_filter(select_year)

For one year this works perfectly fine, but if I want to use add_selection to have the user choose the year, all years exept the latest display white space only.


问:
What is the correct way to pass hash slot aware keys to redis lua script?
I have a small lua script that runs in redis with cluster. The issue is that we need to make all the keys map to same slot and I am trying to pass hash slot aware keys to redis but that does not seem to work.

E.g. on cli - as simple as following fails

eval "return KEYS[1]..KEYS[2]" 2 one{tag} two{tag}

(error) CROSSSLOT Keys in request don't hash to the same slot (context='', command='EVAL', original-slot='8656', wrong-slot='4222', first-key='one{tag}', violating-key='two{tag}')

I have read documentation here and it suggest to pass keys explicity. There is also this tutorial and video from redis but it does not touch the topic of lua.

Has anyone faced this issue? If yes, could you guide me on correct way to pass the slot hash aware keys.

Thank you in advance


问:
New upload certificate fingerprint
I forgot my Key for update the APP on google play.
Google develpment team send me th enew update certificate (MD5 and SHA1) to update it.
I have several questions:

I have this command: keytool -v -list -alias aliasname -keystore projectkey.keystore, my question is: 1. How do i update it?
2. Do i have to type every HEX code on the command prompt?

Title: New upload certificate fingerprint


问:
Passing Metrics Instruments to ASP .NET Core Controllers
I would like to publish some custom metrics from ASP .NET Core Controllers (Counter and Gauge) in addition to automated-instrumentation, however I wonder if there is any established best practices for passing the metrics to Controllers (possibly Dependency Injection)?

In order to create consistent instruments I need to use the same instance created via CreateCounter and etc. so I have to access the same instance within different controllers. First, I tried to create a class to be registered as a singleton in the dependency injection, but it will easily bloated with lots of methods and looks like a service discovery pattern due to the unused metrics by specific controllers/classes.

I wonder if there is something I missed (built-in support in the API/SDK to discover/fetch metrics) or should I focus on my bespoke solution may be based on established rules not to reinvent the wheel.

Thanks,


问:
How to handle large data sets and PHPUnit tests when not using a framework?
I am new to PHPUnit and testing in general and would like some help in optimizing the test below, particularly with handling data sets.

The class under test is called User and extends WP_User, this is to say that I am testing a Wordpress website. Yes, I lied in the question when I said "not using a framework", but what I meant is I'm not using Laravel, Symfony etc. which I think provide some utilities for generating fixtures and such (couldn't fit that much in the question).

Here's the test:

```<code>public function test_create_user( array $data, array $expected ) {

   // Create the user

   $User = User::create( $data );

   $this->tester->assertInstanceOf( User::class, $User );

   // Before asserting that both the $User instance and the database have the expected values,
   // map the keys in $expected to the $User instance properties

   $map = [
      "email" => "user_email",
      "firstName" => "first_name",
      "lastName" => "last_name",
      "country" => "user_country",
      "state" => "user_state",
      "city" => "user_city",
      "addressMain" => "user_address",
      "zip" => "user_zip",
   ];

   $UserFromDb = get_user_by( "ID", $User->ID );

   foreach( $map as $dataKey => $prop ) {
      // $User extends WP_User, which automatically sets a user's data as instance properties
      // named after the database keys, so eg. the country will be set under $User->user_country
      $this->assertEquals( $data[ $dataKey ], $User->$prop );
      // $UserFromDb also is an instance of WP_User, so the same as above applies
      $this->assertEquals( $data[ $dataKey ], $UserFromDb->$prop );
   }

}

public function user_data_provider() {

   return [
      [
         [
            "email" => "email@example.com",
            "password" => "password",
            "firstName" => "John",
            "lastName" => "Doe",
            "country" => "US",
            "state" => "California",
            "city" => "Los Angeles",
            "address" => "Fake Street #1",
            "zip" => "00000",
         ],
         [
            "email" => "email@example.com",
            "firstName" => "John",
            "lastName" => "Doe",
            "country" => "US",
            "state" => "California",
            "city" => "Los Angeles",
            "address" => "Fake Street #1",
            "zip" => "00000",
         ],
      ],
      [
         [
            "email" => "email@example.com",
            "password" => "password",
            "firstName" => "John",
            "lastName" => "Doe",
            "country" => "US",
         ],
         [
            "email" => "email@example.com",
            "firstName" => "John",
            "lastName" => "Doe",
            "country" => "US",
            "state" => null,
            "city" => null,
            "address" => null,
            "zip" => null,
         ],
      ]
   ];

}
</code>```

Here are a few questions:

What would be a good way to handle that large amount of data in the data provider? How can I automate generating some fake data (remember, I'm not using Laravel or Symphony)? Also, would it be correct to call these arrays of fake data "fixtures"? Or is a fixture always a mock object?

Is it okay in this case (ie. creating a new user) to make assertions on all the properties of a class instance, as well as on the database values, in a single test?

As to #1, right now I'm thinking about creating a class that generates all these data arrays and also handles the data/properties mapping, but I'm wondering if there are some best practices or tools that can help.

Any example code, including code of a similar integration test that creates a user, would be nice!

Body:
I am new to PHPUnit and testing in general and would like some help in optimizing the test below, particularly with handling data sets.

The class under test is called User and extends WP_User, this is to say that I am testing a Wordpress website. Yes, I lied in the question when I said "not using a framework", but what I meant is I'm not using Laravel, Symfony etc. which I think provide some utilities for generating fixtures and such (couldn't fit that much in the question).

Here's the test:

public function test_create_user( array $data, array $expected ) {

   // Create the user

   $User = User::create( $data );

   $this->tester->assertInstanceOf( User::class, $User );

   // Before asserting that both the $User instance and the database have the expected values,
   // map the keys in $expected to the $User instance properties

   $map = [
      "email" => "user_email",
      "firstName" => "first_name",
      "lastName" => "last_name",
      "country" => "user_country",
      "state" => "user_state",
      "city" => "user_city",
      "addressMain" => "user_address",
      "zip" => "user_zip",
   ];

   $UserFromDb = get_user_by( "ID", $User->ID );

   foreach( $map as $dataKey => $prop ) {
      // $User extends WP_User, which automatically sets a user's data as instance properties
      // named after the database keys, so eg. the country will be set under $User->user_country
      $this->assertEquals( $data[ $dataKey ], $User->$prop );
      // $UserFromDb also is an instance of WP_User, so the same as above applies
      $this->assertEquals( $data[ $dataKey ], $UserFromDb->$prop );
   }

}

public function user_data_provider() {

   return [
      [
         [
            "email" => "email@example.com",
            "password" => "password",
            "firstName" => "John",
            "lastName" => "Doe",
            "country" => "US",
            "state" => "California",
            "city" => "Los Angeles",
            "address" => "Fake Street #1",
            "zip" => "00000",
         ],
         [
            "email" => "email@example.com",
            "firstName" => "John",
            "lastName" => "Doe",
            "country" => "US",
            "state" => "California",
            "city" => "Los Angeles",
            "address" => "Fake Street #1",
            "zip" => "00000",
         ],
      ],
      [
         [
            "email" => "email@example.com",
            "password" => "password",
            "firstName" => "John",
            "lastName" => "Doe",
            "country" => "US",
         ],
         [
            "email" => "email@example.com",
            "firstName" => "John",
            "lastName" => "Doe",
            "country" => "US",
            "state" => null,
            "city" => null,
            "address" => null,
            "zip" => null,
         ],
      ]
   ];

}

Here are a few questions:

What would be a good way to handle that large amount of data in the data provider? How can I automate generating some fake data (remember, I'm not using Laravel or Symphony)? Also, would it be correct to call these arrays of fake data "fixtures"? Or is a fixture always a mock object?

Is it okay in this case (ie. creating a new user) to make assertions on all the properties of a class instance, as well as on the database values, in a single test?

As to #1, right now I'm thinking about creating a class that generates all these data arrays and also handles the data/properties mapping, but I'm wondering if there are some best practices or tools that can help.

Any example code, including code of a similar integration test that creates a user, would be nice!


问:
How to change default deserialization behavior of reactiveMongoRepository.find() methods?
Is there any way we can intercept existing function call(like reactiveMongoRepository.find()) to avoid the serialization issue when there is unknown property or filed exist?

In mongodb collection I have a feild called Status contains 3 values (CREATED, PROCESSING, DONE). in my persistance class I have only two values in ENUM such as CREATED and DONE, but when I fetch the data I get below error.

```<code>org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [com.demo.tiller.enums.Status] for value 'PROCESSING'; nested exception is java.lang.IllegalArgumentException: No enum constant com.demo.tiller.enums.Status.PROCESSING
</code>```

I dont want to add new ENUM value everytime in my code. Instead I want to ignore unknown properties.
Something like objectmapper.setserializationinclusion(jsoninclude.include.non_null).

Body:
Is there any way we can intercept existing function call(like reactiveMongoRepository.find()) to avoid the serialization issue when there is unknown property or filed exist?

In mongodb collection I have a feild called Status contains 3 values (CREATED, PROCESSING, DONE). in my persistance class I have only two values in ENUM such as CREATED and DONE, but when I fetch the data I get below error.

org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [com.demo.tiller.enums.Status] for value 'PROCESSING'; nested exception is java.lang.IllegalArgumentException: No enum constant com.demo.tiller.enums.Status.PROCESSING

I dont want to add new ENUM value everytime in my code. Instead I want to ignore unknown properties.
Something like objectmapper.setserializationinclusion(jsoninclude.include.non_null).


问:
How to create a criteria to remove outliers in a funnel plot
I am conducting meta-analysis and applied funnel plot to assess for publication bias using metafor. First, I tried to explore the dataset to identify the outliers by creating funnel plots with 1/SE using the following code

```<code>par(mfrow = c(1, 2))
funnel(Soil_total_NPK$lnrr, Soil_total_NPK$v, yaxis="seinv",
       #xlim = c(-3, 3),
       ylab = "Precision (1/SE)",
       xlab = "Effect size (RR)", col =Soil_total_NPK$unique_id, atransf = exp)

</code>```

It seems there are some outliers due to the very small values in the variance of effect size. Does anyone know how to create a criterion to remove very minimum values in the variance? I tried to use the following code but it only removed the only one smallest value.

```<code>Soil_total_NPK1 <- Soil_total_NPK[Soil_total_NPK$v != min(Soil_total_NPK$v), ]
</code>```

Body:
I am conducting meta-analysis and applied funnel plot to assess for publication bias using metafor. First, I tried to explore the dataset to identify the outliers by creating funnel plots with 1/SE using the following code

par(mfrow = c(1, 2))
funnel(Soil_total_NPK$lnrr, Soil_total_NPK$v, yaxis="seinv",
       #xlim = c(-3, 3),
       ylab = "Precision (1/SE)",
       xlab = "Effect size (RR)", col =Soil_total_NPK$unique_id, atransf = exp)

It seems there are some outliers due to the very small values in the variance of effect size. Does anyone know how to create a criterion to remove very minimum values in the variance? I tried to use the following code but it only removed the only one smallest value.

Soil_total_NPK1 <- Soil_total_NPK[Soil_total_NPK$v != min(Soil_total_NPK$v), ]


问:
How to populate event data from firebase to table calendar
I am able to get title field from firebase for events.I would like to retrieve one more field(description) from firebase and display in table calendar subtitle.May I know what all changes I have to do.
How to retrieve additional firbase fields and show in table calendar list view subtitle

```<code>class Event {
  final String title;
  final String description;

  const Event(this.title);

  @override
  String toString() => title;
}

</code>```

Full code:

```<code>
class Event {
  final String title;

  const Event(this.title);

  @override
  String toString() => title;
}

final kToday = DateTime.now();
final kFirstDay = DateTime(kToday.year, kToday.month - 1, kToday.day);
final kLastDay = DateTime(kToday.year, kToday.month + 1, kToday.day);
final fireStore = FirebaseFirestore.instance;

class TableBasicsExample extends StatefulWidget {
  const TableBasicsExample({Key? key}) : super(key: key);

  @override
  _TableBasicsExampleState createState() => _TableBasicsExampleState();
}

class _TableBasicsExampleState extends State<TableBasicsExample> {
  late final ValueNotifier<List<Event>> _selectedEvents;
  CalendarFormat _calendarFormat = CalendarFormat.month;
  RangeSelectionMode _rangeSelectionMode = RangeSelectionMode
      .toggledOff; // Can be toggled on/off by longpressing a date
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  DateTime? _rangeStart;
  DateTime? _rangeEnd;

  @override
  void initState() {
    super.initState();

    _selectedDay = _focusedDay;
    _selectedEvents = ValueNotifier(_getEventsForDay(_selectedDay!));
    getEvents();
  }

  Map<DateTime, List<Event>> map = {};

  int getHashCode(DateTime key) {
    return key.day * 1000000 + key.month * 10000 + key.year;
  }

  getEvents() async {
    var data = await FirebaseFirestore.instance.collection('events').get();
    List<Event> eventList = [];

    for (int i = 0; i < data.docs.length; i++) {
      var time = (data.docs[i]['date'] as Timestamp).toDate();
      var title = Event(data.docs[i]['title']);
      map[time] = [title];
    }

    print(map);
  }

  @override
  void dispose() {
    _selectedEvents.dispose();
    super.dispose();
  }

  List<Event> _getEventsForDay(DateTime day) {
    final events = LinkedHashMap(equals: isSameDay, hashCode: getHashCode)
      ..addAll(map);
    return events[day] ?? [];
  }

  void _onDaySelected(DateTime selectedDay, DateTime focusedDay) {
    if (!isSameDay(_selectedDay, selectedDay)) {
      setState(() {
        _selectedDay = selectedDay;
        _focusedDay = focusedDay;
        _rangeStart = null; // Important to clean those
        _rangeEnd = null;
        _rangeSelectionMode = RangeSelectionMode.toggledOff;
      });

      _selectedEvents.value = _getEventsForDay(selectedDay);
    }
  }

  void _onRangeSelected(DateTime? start, DateTime? end, DateTime focusedDay) {
    setState(() {
      _selectedDay = null;
      _focusedDay = focusedDay;
      _rangeStart = start;
      _rangeEnd = end;
      _rangeSelectionMode = RangeSelectionMode.toggledOn;
    });

    // `start` or `end` could be null
    if (start != null) {
      _selectedEvents.value = _getEventsForDay(start);
    } else if (end != null) {
      _selectedEvents.value = _getEventsForDay(end);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('Booking Calendar'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => const CustomerOrder(),
            ),
          );
        },
        child: const Icon(Icons.add),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Card(
            clipBehavior: Clip.antiAlias,
            margin: const EdgeInsets.all(8.0),
            child: TableCalendar<Event>(
              firstDay: kFirstDay,
              lastDay: kLastDay,
              focusedDay: _focusedDay,
              selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
              rangeStartDay: _rangeStart,
              rangeEndDay: _rangeEnd,
              calendarFormat: _calendarFormat,
              rangeSelectionMode: _rangeSelectionMode,
              eventLoader: _getEventsForDay,
              weekendDays: const [DateTime.sunday, 6],
              // default is Sunday but can be changed according to locale
              startingDayOfWeek: StartingDayOfWeek.monday,
              // height between the day row and 1st date row, default is 16.0
              daysOfWeekHeight: 40.0,
              // height between the date rows, default is 52.0
              rowHeight: 60.0,
              headerStyle: const HeaderStyle(
                titleTextStyle: TextStyle(color: Colors.black, fontSize: 20.0),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(10),
                        topRight: Radius.circular(10))),
                formatButtonTextStyle:
                    TextStyle(color: Colors.white, fontSize: 16.0),
                formatButtonDecoration: BoxDecoration(
                  color: Colors.orange,
                  borderRadius: BorderRadius.all(
                    Radius.circular(5.0),
                  ),
                ),
                leftChevronIcon: Icon(
                  Icons.chevron_left,
                  color: AppColors.redShadeColor,
                  size: 28,
                ),
                rightChevronIcon: Icon(
                  Icons.chevron_right,
                  color: AppColors.redShadeColor,
                  size: 28,
                ),
              ),
              daysOfWeekStyle: const DaysOfWeekStyle(
                // Weekend days color (Sat,Sun)
                weekendStyle: TextStyle(color: AppColors.salmonColor),
              ),
              // Calendar Dates styling
              calendarStyle: const CalendarStyle(
                // Weekend dates color (Sat & Sun Column)
                weekendTextStyle: TextStyle(color: AppColors.salmonColor),
                // highlighted color for today
                todayDecoration: BoxDecoration(
                  color: Colors.orange,
                  shape: BoxShape.circle,
                ),
                // highlighted color for selected day
                selectedDecoration: BoxDecoration(
                  color: Colors.blue,
                  shape: BoxShape.circle,
                ),
                markerDecoration:
                    BoxDecoration(color: Colors.blue, shape: BoxShape.circle),
              ),
              onDaySelected: _onDaySelected,
              onRangeSelected: _onRangeSelected,
              onFormatChanged: (format) {
                if (_calendarFormat != format) {
                  setState(() {
                    _calendarFormat = format;
                  });
                }
              },
              onPageChanged: (focusedDay) {
                _focusedDay = focusedDay;
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 12.0, top: 8.0),
            child: Text(
              DateFormat('EEEE, dd MMMM, yyyy').format(_selectedDay!),
              style: Theme.of(context).textTheme.headline6,
            ),
          ),
          const SizedBox(height: 8.0),
          Expanded(
            child: ValueListenableBuilder<List<Event>>(
              valueListenable: _selectedEvents,
              builder: (context, value, _) {
                return ListView.builder(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  itemCount: value.length,
                  itemBuilder: (context, index) {
                    return Container(
                      margin: const EdgeInsets.symmetric(
                        horizontal: 12.0,
                        vertical: 4.0,
                      ),
                      decoration: BoxDecoration(
                        border: Border.all(),
                        borderRadius: BorderRadius.circular(12.0),
                      ),
                      child: ListTile(

                        onTap: () => print('${value[index]}'),
                        title: Text('${value[index]}'),

                      ),
                    );
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

</code>```

how to retrieve additional firbase fields and show in table calendar list view subtitle

Body:
I am able to get title field from firebase for events.I would like to retrieve one more field(description) from firebase and display in table calendar subtitle.May I know what all changes I have to do.
How to retrieve additional firbase fields and show in table calendar list view subtitle

class Event {
  final String title;
  final String description;

  const Event(this.title);

  @override
  String toString() => title;
}

Full code:

class Event {
  final String title;

  const Event(this.title);

  @override
  String toString() => title;
}

final kToday = DateTime.now();
final kFirstDay = DateTime(kToday.year, kToday.month - 1, kToday.day);
final kLastDay = DateTime(kToday.year, kToday.month + 1, kToday.day);
final fireStore = FirebaseFirestore.instance;

class TableBasicsExample extends StatefulWidget {
  const TableBasicsExample({Key? key}) : super(key: key);

  @override
  _TableBasicsExampleState createState() => _TableBasicsExampleState();
}

class _TableBasicsExampleState extends State<TableBasicsExample> {
  late final ValueNotifier<List<Event>> _selectedEvents;
  CalendarFormat _calendarFormat = CalendarFormat.month;
  RangeSelectionMode _rangeSelectionMode = RangeSelectionMode
      .toggledOff; // Can be toggled on/off by longpressing a date
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  DateTime? _rangeStart;
  DateTime? _rangeEnd;

  @override
  void initState() {
    super.initState();

    _selectedDay = _focusedDay;
    _selectedEvents = ValueNotifier(_getEventsForDay(_selectedDay!));
    getEvents();
  }

  Map<DateTime, List<Event>> map = {};

  int getHashCode(DateTime key) {
    return key.day * 1000000 + key.month * 10000 + key.year;
  }

  getEvents() async {
    var data = await FirebaseFirestore.instance.collection('events').get();
    List<Event> eventList = [];

    for (int i = 0; i < data.docs.length; i++) {
      var time = (data.docs[i]['date'] as Timestamp).toDate();
      var title = Event(data.docs[i]['title']);
      map[time] = [title];
    }

    print(map);
  }

  @override
  void dispose() {
    _selectedEvents.dispose();
    super.dispose();
  }

  List<Event> _getEventsForDay(DateTime day) {
    final events = LinkedHashMap(equals: isSameDay, hashCode: getHashCode)
      ..addAll(map);
    return events[day] ?? [];
  }

  void _onDaySelected(DateTime selectedDay, DateTime focusedDay) {
    if (!isSameDay(_selectedDay, selectedDay)) {
      setState(() {
        _selectedDay = selectedDay;
        _focusedDay = focusedDay;
        _rangeStart = null; // Important to clean those
        _rangeEnd = null;
        _rangeSelectionMode = RangeSelectionMode.toggledOff;
      });

      _selectedEvents.value = _getEventsForDay(selectedDay);
    }
  }

  void _onRangeSelected(DateTime? start, DateTime? end, DateTime focusedDay) {
    setState(() {
      _selectedDay = null;
      _focusedDay = focusedDay;
      _rangeStart = start;
      _rangeEnd = end;
      _rangeSelectionMode = RangeSelectionMode.toggledOn;
    });

    // `start` or `end` could be null
    if (start != null) {
      _selectedEvents.value = _getEventsForDay(start);
    } else if (end != null) {
      _selectedEvents.value = _getEventsForDay(end);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('Booking Calendar'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => const CustomerOrder(),
            ),
          );
        },
        child: const Icon(Icons.add),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Card(
            clipBehavior: Clip.antiAlias,
            margin: const EdgeInsets.all(8.0),
            child: TableCalendar<Event>(
              firstDay: kFirstDay,
              lastDay: kLastDay,
              focusedDay: _focusedDay,
              selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
              rangeStartDay: _rangeStart,
              rangeEndDay: _rangeEnd,
              calendarFormat: _calendarFormat,
              rangeSelectionMode: _rangeSelectionMode,
              eventLoader: _getEventsForDay,
              weekendDays: const [DateTime.sunday, 6],
              // default is Sunday but can be changed according to locale
              startingDayOfWeek: StartingDayOfWeek.monday,
              // height between the day row and 1st date row, default is 16.0
              daysOfWeekHeight: 40.0,
              // height between the date rows, default is 52.0
              rowHeight: 60.0,
              headerStyle: const HeaderStyle(
                titleTextStyle: TextStyle(color: Colors.black, fontSize: 20.0),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(10),
                        topRight: Radius.circular(10))),
                formatButtonTextStyle:
                    TextStyle(color: Colors.white, fontSize: 16.0),
                formatButtonDecoration: BoxDecoration(
                  color: Colors.orange,
                  borderRadius: BorderRadius.all(
                    Radius.circular(5.0),
                  ),
                ),
                leftChevronIcon: Icon(
                  Icons.chevron_left,
                  color: AppColors.redShadeColor,
                  size: 28,
                ),
                rightChevronIcon: Icon(
                  Icons.chevron_right,
                  color: AppColors.redShadeColor,
                  size: 28,
                ),
              ),
              daysOfWeekStyle: const DaysOfWeekStyle(
                // Weekend days color (Sat,Sun)
                weekendStyle: TextStyle(color: AppColors.salmonColor),
              ),
              // Calendar Dates styling
              calendarStyle: const CalendarStyle(
                // Weekend dates color (Sat & Sun Column)
                weekendTextStyle: TextStyle(color: AppColors.salmonColor),
                // highlighted color for today
                todayDecoration: BoxDecoration(
                  color: Colors.orange,
                  shape: BoxShape.circle,
                ),
                // highlighted color for selected day
                selectedDecoration: BoxDecoration(
                  color: Colors.blue,
                  shape: BoxShape.circle,
                ),
                markerDecoration:
                    BoxDecoration(color: Colors.blue, shape: BoxShape.circle),
              ),
              onDaySelected: _onDaySelected,
              onRangeSelected: _onRangeSelected,
              onFormatChanged: (format) {
                if (_calendarFormat != format) {
                  setState(() {
                    _calendarFormat = format;
                  });
                }
              },
              onPageChanged: (focusedDay) {
                _focusedDay = focusedDay;
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 12.0, top: 8.0),
            child: Text(
              DateFormat('EEEE, dd MMMM, yyyy').format(_selectedDay!),
              style: Theme.of(context).textTheme.headline6,
            ),
          ),
          const SizedBox(height: 8.0),
          Expanded(
            child: ValueListenableBuilder<List<Event>>(
              valueListenable: _selectedEvents,
              builder: (context, value, _) {
                return ListView.builder(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  itemCount: value.length,
                  itemBuilder: (context, index) {
                    return Container(
                      margin: const EdgeInsets.symmetric(
                        horizontal: 12.0,
                        vertical: 4.0,
                      ),
                      decoration: BoxDecoration(
                        border: Border.all(),
                        borderRadius: BorderRadius.circular(12.0),
                      ),
                      child: ListTile(

                        onTap: () => print('${value[index]}'),
                        title: Text('${value[index]}'),

                      ),
                    );
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

how to retrieve additional firbase fields and show in table calendar list view subtitle


问:
nextjs force incompatible "href" and "as" attributes in next/Link
I have the following routes:

```<code>/categories/[categoryId]
/products/[productId]
/content/[contentId]
</code>```

and I want to have SEO friendly URLs for them as follows:

```<code>https://example.com/category-name-c12345 - where c in c12345 is a constant prefix
https://example.com/product-name-p12345 - where p in p12345 is a constant prefix
https://example.com/content-page-name-s12345 - where s in s12345 is a constant prefix
</code>```

I tried to use next/Link component "href" and "as" attributes:

```<code><Link
    href={/categories/[categoryId]}
    as={/category-name-c12345}
>
    <a>category</a>
</Link>
</code>```

but I get an error that the "href" and the "as" attributes are incompatible.

I found the the following documentation: https://nextjs.org/docs/messages/incompatible-href-as
which makes it clear as to why they are incompatible but the problem is that the requirements come from SEO experts who claim that the structure is a world standard, so the question here is:

Is it possible that I cannot find the proper documentation for nextjs, which shows how to do the routing that I need?
Or the case is that nextjs is not capable of handling this type of routing?

Body:
I have the following routes:

/categories/[categoryId]
/products/[productId]
/content/[contentId]

and I want to have SEO friendly URLs for them as follows:

https://example.com/category-name-c12345 - where c in c12345 is a constant prefix
https://example.com/product-name-p12345 - where p in p12345 is a constant prefix
https://example.com/content-page-name-s12345 - where s in s12345 is a constant prefix

I tried to use next/Link component "href" and "as" attributes:

<Link
    href={/categories/[categoryId]}
    as={/category-name-c12345}
>
    category
</Link>

but I get an error that the "href" and the "as" attributes are incompatible.

I found the the following documentation: https://nextjs.org/docs/messages/incompatible-href-as
which makes it clear as to why they are incompatible but the problem is that the requirements come from SEO experts who claim that the structure is a world standard, so the question here is:

Is it possible that I cannot find the proper documentation for nextjs, which shows how to do the routing that I need?
Or the case is that nextjs is not capable of handling this type of routing?


问:
Java XML validation against XSD fails at first error does not validate complete XML even with custom error handler
Is there a way I can validate my XML against my XSD COMPLETELY, meaning that I want the file to continue validating even after it has found an error so I can get the complete error messages rather than just 1 or the first error message?

Currently, the execution stops when it finds the first error, prints it, and does not continue any further. I want to know if it's possible to achieve this. I tried the method mentioned here and did the same but still it's not working as expected and execution stops.

Following is the code I have:
XsdErrorHandler.class:

```<code>import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;

public class XsdErrorHandler implements ErrorHandler {
   @lombok.Getter
    private java.util.List<SAXParseException> exceptions;

    public XsdErrorHandler() {
        this.exceptions = new java.util.ArrayList<>();
    }

    @Override
    public void warning(final SAXParseException exception) throws org.xml.sax.SAXException {
       handleError(exception);
    }

    @Override
    public void error(final SAXParseException exception) throws org.xml.sax.SAXException {
        handleError(exception);
    }

    @Override
    public void fatalError(final SAXParseException exception) throws org.xml.sax.SAXException  {
        handleError(exception);
    }

    public void handleError(SAXParseException e) throws org.xml.sax.SAXException  {
        // Do nothing. This will allow the validation to continue even if there are errors.
        this.exceptions.add(e);
    }
}
</code>```

Following is my schema validator:
Main.class

```<code>import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMain {
    public static void main(String[] args) throws SAXException, IOException {
        final String xsdPath = "/xsd/myXSD.xsd";
        final String xmlPath = "/myXml.xml";
        listParsingExceptions(xsdPath, xmlPath);
    }

    private static Validator initValidator(final String xsdPath) throws SAXException {
        final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Source schemaFile = new StreamSource(TestMain.class.getResourceAsStream(xsdPath));
        final Schema schema = factory.newSchema(schemaFile);
        return schema.newValidator();
    }

    public static List<SAXParseException> listParsingExceptions(final String xsdPath, final String xmlPath) throws IOException, SAXException {
        final InputStream inputStream = TestMain.class.getResourceAsStream(xmlPath);
        final XsdErrorHandler xsdErrorHandler = new XsdErrorHandler();
        final Validator validator = initValidator(xsdPath);
        validator.setErrorHandler(xsdErrorHandler);

        try {
            validator.validate(new StreamSource(inputStream));
        } catch (SAXParseException e)
        {
            // ...
        }

        System.out.println("ERRORS : ");
        xsdErrorHandler.getExceptions().forEach(e -> System.out.println(e.getMessage()));
        return xsdErrorHandler.getExceptions();
    }
}
</code>```

Issues:

I am a bit confused about what else I need to do to make this continue working. Can someone please provide some suggestions?

Also, my XSD contains many imports and references to other XSD. When I give a relative path, then it won't work, but when I give an absolute path, then it works. Is there a way I can make it work with a relative path?

Following fails:

```<code><xsd:import namespace="urn:global:xsd:1" schemaLocation="./global.xsd"/>
</code>```

Following works:

```<code>
<xsd:import namespace="urn:global:xsd:1" schemaLocation="/Users/username/project/validation/src/main/resources/xsd/global.xsd"/>
</code>```

I tried to provide the path for XSD file using maven-jaxb2-plugin something like this but this also did not work for me

```<code>    <build>
        <plugins>
            <plugin>
                <groupId>org.jvnet.jaxb2.maven2</groupId>
                <artifactId>maven-jaxb2-plugin</artifactId>
                <version>0.14.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <schemaDirectory>${basedir}/src/main/resources/xsd</schemaDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
</code>```

I tried to write my own ClasspathResourceResolver by referencing here and added to my schemaFactory using schemaFactory.setResourceResolver(new ClasspathResourceResolver()); but that also did not work for me.

All my files are present in the XSD folder and I would like to reference using the relative path something like this ./xsdName.xsd

Body:
Is there a way I can validate my XML against my XSD COMPLETELY, meaning that I want the file to continue validating even after it has found an error so I can get the complete error messages rather than just 1 or the first error message?

Currently, the execution stops when it finds the first error, prints it, and does not continue any further. I want to know if it's possible to achieve this. I tried the method mentioned here and did the same but still it's not working as expected and execution stops.

Following is the code I have:
XsdErrorHandler.class:

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;

public class XsdErrorHandler implements ErrorHandler {
   @lombok.Getter
    private java.util.List<SAXParseException> exceptions;

    public XsdErrorHandler() {
        this.exceptions = new java.util.ArrayList<>();
    }

    @Override
    public void warning(final SAXParseException exception) throws org.xml.sax.SAXException {
       handleError(exception);
    }

    @Override
    public void error(final SAXParseException exception) throws org.xml.sax.SAXException {
        handleError(exception);
    }

    @Override
    public void fatalError(final SAXParseException exception) throws org.xml.sax.SAXException  {
        handleError(exception);
    }

    public void handleError(SAXParseException e) throws org.xml.sax.SAXException  {
        // Do nothing. This will allow the validation to continue even if there are errors.
        this.exceptions.add(e);
    }
}

Following is my schema validator:
Main.class

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMain {
    public static void main(String[] args) throws SAXException, IOException {
        final String xsdPath = "/xsd/myXSD.xsd";
        final String xmlPath = "/myXml.xml";
        listParsingExceptions(xsdPath, xmlPath);
    }

    private static Validator initValidator(final String xsdPath) throws SAXException {
        final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Source schemaFile = new StreamSource(TestMain.class.getResourceAsStream(xsdPath));
        final Schema schema = factory.newSchema(schemaFile);
        return schema.newValidator();
    }

    public static List<SAXParseException> listParsingExceptions(final String xsdPath, final String xmlPath) throws IOException, SAXException {
        final InputStream inputStream = TestMain.class.getResourceAsStream(xmlPath);
        final XsdErrorHandler xsdErrorHandler = new XsdErrorHandler();
        final Validator validator = initValidator(xsdPath);
        validator.setErrorHandler(xsdErrorHandler);

        try {
            validator.validate(new StreamSource(inputStream));
        } catch (SAXParseException e)
        {
            // ...
        }

        System.out.println("ERRORS : ");
        xsdErrorHandler.getExceptions().forEach(e -> System.out.println(e.getMessage()));
        return xsdErrorHandler.getExceptions();
    }
}

Issues:

I am a bit confused about what else I need to do to make this continue working. Can someone please provide some suggestions?

Also, my XSD contains many imports and references to other XSD. When I give a relative path, then it won't work, but when I give an absolute path, then it works. Is there a way I can make it work with a relative path?

Following fails:

<xsd:import namespace="urn:global:xsd:1" schemaLocation="./global.xsd"/>

Following works:

<xsd:import namespace="urn:global:xsd:1" schemaLocation="/Users/username/project/validation/src/main/resources/xsd/global.xsd"/>

I tried to provide the path for XSD file using maven-jaxb2-plugin something like this but this also did not work for me

    <build>
        <plugins>
            <plugin>
                <groupId>org.jvnet.jaxb2.maven2</groupId>
                <artifactId>maven-jaxb2-plugin</artifactId>
                <version>0.14.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <schemaDirectory>${basedir}/src/main/resources/xsd</schemaDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>

I tried to write my own ClasspathResourceResolver by referencing here and added to my schemaFactory using schemaFactory.setResourceResolver(new ClasspathResourceResolver()); but that also did not work for me.

All my files are present in the XSD folder and I would like to reference using the relative path something like this ./xsdName.xsd


问:
Finding concurrent occurences of values above/below a threshold in a Pandas DataFrame/Series
I need to repeatedly scan columns in a Pandas DataFrame (I will refer to this as a Series) to determine the number of times a threshold is breached. What is making this more complicated is the following:

The series is only considered to have breached the threshold if it is beyond the threshold for five consecutive points or more in the series.

The series is only considered to have returned to normative levels if for five consecutive points or more after breaching the limit the series is back within the limit.

I'm trying to count the number of times the threshold is breached and the total number of points that the threshold is considered beyond the threshold.

For example, lets say the limit is if x >= 3 and with the following Series (I've formatted this as a list so it is easier to read, however in reality x would be a column in a DataFrame with N measurements):

x = [0, 0, 0, 5, 5, 5, 5, 1, 5, 5, 5, 5, 5, 5, 0, 5, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0]

The desired result is that the threshold is breached twice, and the total number of points above the threshold is 13 (points in bold are considered in breach of the limit).

I can do this by looping through every point in the series however this is very slow. Through another question I found that the following can be used to find the number of times the series goes beyond a specified limit for more than five points:

```<code>df['breach'] = df['x'] >= limit   #Create a boolean column for when the series breaches the limit
df_limit = pd.DataFrame(df['breach'].values, columns=['breach_limit'])   #create a new dataframe using the boolean column
df_limit['count'] = df_limit['breach_limit'].groupby(df_limit['breach_limit'].diff().ne(0).cumsum()).sum().replace(0, np.nan).dropna().reset_index(drop=True) #Count based aggregate of the column which results in the counts of every set of consecutive breaches in the series.
</code>```

This would result in a count based aggregation of the total consecutive breaches. For example in the example above it would result in [4, 6, 1, 5]. You can then just discard the times that count is below five resulting in two breaches. However, this doesn't take into account allowing five points after the breach to return to normative levels or allow me to calculate the total points.

Has anyone got any suggestions for how to do this in a way which wouldn't use for loops so I can speed up the analysis which is prohibitively slow when using for loops.

Body:
I need to repeatedly scan columns in a Pandas DataFrame (I will refer to this as a Series) to determine the number of times a threshold is breached. What is making this more complicated is the following:

The series is only considered to have breached the threshold if it is beyond the threshold for five consecutive points or more in the series.

The series is only considered to have returned to normative levels if for five consecutive points or more after breaching the limit the series is back within the limit.

I'm trying to count the number of times the threshold is breached and the total number of points that the threshold is considered beyond the threshold.

For example, lets say the limit is if x >= 3 and with the following Series (I've formatted this as a list so it is easier to read, however in reality x would be a column in a DataFrame with N measurements):

x = [0, 0, 0, 5, 5, 5, 5, 1, 5, 5, 5, 5, 5, 5, 0, 5, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0]

The desired result is that the threshold is breached twice, and the total number of points above the threshold is 13 (points in bold are considered in breach of the limit).

I can do this by looping through every point in the series however this is very slow. Through another question I found that the following can be used to find the number of times the series goes beyond a specified limit for more than five points:

df['breach'] = df['x'] >= limit   #Create a boolean column for when the series breaches the limit
df_limit = pd.DataFrame(df['breach'].values, columns=['breach_limit'])   #create a new dataframe using the boolean column
df_limit['count'] = df_limit['breach_limit'].groupby(df_limit['breach_limit'].diff().ne(0).cumsum()).sum().replace(0, np.nan).dropna().reset_index(drop=True) #Count based aggregate of the column which results in the counts of every set of consecutive breaches in the series.

This would result in a count based aggregation of the total consecutive breaches. For example in the example above it would result in [4, 6, 1, 5]. You can then just discard the times that count is below five resulting in two breaches. However, this doesn't take into account allowing five points after the breach to return to normative levels or allow me to calculate the total points.

Has anyone got any suggestions for how to do this in a way which wouldn't use for loops so I can speed up the analysis which is prohibitively slow when using for loops.


问:
authenticate from GKE autopilot to firestore not working from nodejs expressjs on google cloud
trying to read and write to Firestore DB from a GKE cluster autopilot in the same project than the firestore DB

I managed to connect to the DB by adding in my code a json key service account with right permission on Firestore

however this is not secure and I want to do it through GCP cluster service account and it does not work

I do not want to do it through k8s secrets neither with GCP workload identity

any help please i am stuck ?

```<code>const express = require('express');
const app = express();
const port = 80;
app.use(require('body-parser').json());

const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');

initializeApp({
  credential: applicationDefault()
});

const db = getFirestore();

const getUsers = async () => {
    const snapshot = await db.collection('users').get();
    let users = snapshot.docs.map(doc => doc.data());
    return users
  }

app.get('/microservice1', (req, res) => {
   getUsers().then((users) => {
      console.log(users);
      res.send(users);
  });
});

app.listen(port, () => {
    console.log(`Listening on port ${port}`);
});
</code>```
```<code>
</code>```

I tried to give to the compute engine default service account the firebase admin role and owner role but it does not solve my issue

Body:
trying to read and write to Firestore DB from a GKE cluster autopilot in the same project than the firestore DB

I managed to connect to the DB by adding in my code a json key service account with right permission on Firestore

however this is not secure and I want to do it through GCP cluster service account and it does not work

I do not want to do it through k8s secrets neither with GCP workload identity

any help please i am stuck ?

const express = require('express');
const app = express();
const port = 80;
app.use(require('body-parser').json());

const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');

initializeApp({
  credential: applicationDefault()
});

const db = getFirestore();

const getUsers = async () => {
    const snapshot = await db.collection('users').get();
    let users = snapshot.docs.map(doc => doc.data());
    return users
  }

app.get('/microservice1', (req, res) => {
   getUsers().then((users) => {
      console.log(users);
      res.send(users);
  });
});

app.listen(port, () => {
    console.log(`Listening on port ${port}`);
});

I tried to give to the compute engine default service account the firebase admin role and owner role but it does not solve my issue


问:
Display results from PS in new line
I have problem to correctly display results from variable. When I use code as below then results are in one line as below.

```<code>httpd=`ps -wweo uname,pid,pcpu,pmem,args | sed -e 's|/usr/pw/apache/bin/httpd.*|httpd|' | grep -E -w 'httpd' | grep -v 'grep' | grep -v 'sed' | sed -r 's/[[:blank:]]+/;/g'`

echo $httpd
user;6374;0.0;0.0;httpd user;12571;0.0;0.0;httpd user;26473;0.0;0.0;httpd user;29933;0.0;0.0;httpd user;31980;0.1;0.0;httpd
</code>```

Without variable results are OK and this is what I execpted

```<code>  ps -wweo uname,pid,pcpu,pmem,args | sed -e 's|/usr/pw/apache/bin/httpd.*|httpd|' | grep -E -w 'httpd' | grep -v 'grep' | grep -v 'sed' | sed -r 's/[[:blank:]]+/;/g'
    user;6374;0.0;0.0;httpd
    user;12571;0.0;0.0;httpd
    user;22984;0.0;0.0;httpd
    user;26473;0.0;0.0;httpd
    user;29933;0.0;0.0;httpd
</code>```

Is there any trick to fix my results?
Thank you

Title: Display results from PS in new line

Body:
I have problem to correctly display results from variable. When I use code as below then results are in one line as below.

httpd=`ps -wweo uname,pid,pcpu,pmem,args | sed -e 's|/usr/pw/apache/bin/httpd.*|httpd|' | grep -E -w 'httpd' | grep -v 'grep' | grep -v 'sed' | sed -r 's/[[:blank:]]+/;/g'`

echo $httpd
user;6374;0.0;0.0;httpd user;12571;0.0;0.0;httpd user;26473;0.0;0.0;httpd user;29933;0.0;0.0;httpd user;31980;0.1;0.0;httpd

Without variable results are OK and this is what I execpted

  ps -wweo uname,pid,pcpu,pmem,args | sed -e 's|/usr/pw/apache/bin/httpd.*|httpd|' | grep -E -w 'httpd' | grep -v 'grep' | grep -v 'sed' | sed -r 's/[[:blank:]]+/;/g'
    user;6374;0.0;0.0;httpd
    user;12571;0.0;0.0;httpd
    user;22984;0.0;0.0;httpd
    user;26473;0.0;0.0;httpd
    user;29933;0.0;0.0;httpd

Is there any trick to fix my results?
Thank you


问:
Respawn with SQl server: -"BeginExecuteNonQuery: CommandText property has not been initialized
I am trying to use the respawn library in my Xunit test project.

My fixture class looks like this:

```<code>public class DBFixture : IAsyncLifetime
    {
        private readonly Checkpoint checkpointSystem;

        public string ConnectionString
        {
            get => @"Data Source=.\SQLEXPRESS;Initial Catalog=MyDB;User Id=user;Pwd=pass";
        }

        public DatabaseFixture()
        {
            checkpointSystem = new Checkpoint
            {
                DbAdapter = DbAdapter.SqlServer,
                TablesToInclude = new[] { "MyTable" },
                SchemasToInclude = new[] { "MyDB" }
            };
        }

         public async Task ResetAsync()
        {

            using (var conn = new SqlConnection(this.ConnectionString))
            {
                conn.Open();
                try
                {
                    await this.checkpointSystem.Reset(conn);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }
</code>```

The problem is that when I try to call from my test class the resetASync method I got this error:

"BeginExecuteNonQuery: CommandText property has not been initialized

I have also tried as the github page suggest "Respawner.CreateAsync", but I guess that that method is not available with the version 4.0 of respawn (I am using that version, since the more recent ones are not compatible with net framework 4.8, which is the .net used in the test project, for the time being it is not possible to migrate that project to .net core)

I also tried implementing remote async like this:

```<code>public async Task ResetAsync()
        {

            await checkpointSystem.Reset(this.ConnectionString);
        }
</code>```

Same problem though. I guess the documentation I checked does not offer a good example for projects using SQl server and the version 4.0 of respawn. But after looking for examples in Github in classes like these ones I cannot still figure out how to use it.

https://github.com/FredrikAugust/bibliotek/blob/436f4ef795dc565caccd6190d73bc3ea005c5507/Application.IntegrationTests/Common/DbFixture.cs

or
https://github.com/renetguerra/Inventory.DDD.API/blob/18bf28cc77aa1c9113f8790a5dba2cecf360a5e6/Inventory.DDD.Integrations.Tests/TestBase.cs

Body:
I am trying to use the respawn library in my Xunit test project.

My fixture class looks like this:

public class DBFixture : IAsyncLifetime
    {
        private readonly Checkpoint checkpointSystem;

        public string ConnectionString
        {
            get => @"Data Source=.\SQLEXPRESS;Initial Catalog=MyDB;User Id=user;Pwd=pass";
        }

        public DatabaseFixture()
        {
            checkpointSystem = new Checkpoint
            {
                DbAdapter = DbAdapter.SqlServer,
                TablesToInclude = new[] { "MyTable" },
                SchemasToInclude = new[] { "MyDB" }
            };
        }

         public async Task ResetAsync()
        {

            using (var conn = new SqlConnection(this.ConnectionString))
            {
                conn.Open();
                try
                {
                    await this.checkpointSystem.Reset(conn);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }

The problem is that when I try to call from my test class the resetASync method I got this error:

"BeginExecuteNonQuery: CommandText property has not been initialized

I have also tried as the github page suggest "Respawner.CreateAsync", but I guess that that method is not available with the version 4.0 of respawn (I am using that version, since the more recent ones are not compatible with net framework 4.8, which is the .net used in the test project, for the time being it is not possible to migrate that project to .net core)

I also tried implementing remote async like this:

public async Task ResetAsync()
        {

            await checkpointSystem.Reset(this.ConnectionString);
        }

Same problem though. I guess the documentation I checked does not offer a good example for projects using SQl server and the version 4.0 of respawn. But after looking for examples in Github in classes like these ones I cannot still figure out how to use it.

https://github.com/FredrikAugust/bibliotek/blob/436f4ef795dc565caccd6190d73bc3ea005c5507/Application.IntegrationTests/Common/DbFixture.cs

or
https://github.com/renetguerra/Inventory.DDD.API/blob/18bf28cc77aa1c9113f8790a5dba2cecf360a5e6/Inventory.DDD.Integrations.Tests/TestBase.cs


问:
Show the geny motion emulator
When I run the Genie Motion simulator, it does not appear in the active devices section, but when I restart Android Studio, it is displayed. How can I activate the Genie Motion device without restarting Android Studio?

It used to work correctly. But I didn't use this simulator for a few months, then when I came back to use it again, I saw that it had such a problem that I must restart Android Studio to test the application.

Title: Show the geny motion emulator


问:
How to fetch the lists the members of the current conversation using Cloud adapter in Chatbot
Recently we have upgraded the .net version from 3 to 6 and updated bot builder. As 'BotFrameworkAdapter' is obselete , we have used CloudAdapter instead.

In BotFrameworkAdapter, method 'GetConversationMembersAsync' gets the list of members of the current conversation. We need the same replacement of this method in Cloud adapter to return the channel account of the current conversation members .

GetConversationMembersAsync in BotFrameworkAdapter,

Is there any alternative method in Cloud adapter to get the current conversation member


问:
I am trying to connect to MongoDB using mongoose, but finding problem in the connection error shows:
```<code>
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
    at NativeConnection.Connection.openUri (D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\node_modules\mongoose\lib\connection.js:695:11)
    at D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\node_modules\mongoose\lib\index.js:417:10
    at D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
    at new Promise (<anonymous>)
    at promiseOrCallback (D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
    at Mongoose._promiseOrCallback (D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\node_modules\mongoose\lib\index.js:1270:10)
    at Mongoose.connect (D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\node_modules\mongoose\lib\index.js:416:20)
    at dbConnect (D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\src\configs\database.config.ts:7:14)
    at Object.<anonymous> (D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\src\server.ts:9:10)
    at Module._compile (node:internal/modules/cjs/loader:1155:14)

</code>```

i am using typescript for nodejs and dont know to solve this

Body:
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
    at NativeConnection.Connection.openUri (D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\node_modules\mongoose\lib\connection.js:695:11)
    at D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\node_modules\mongoose\lib\index.js:417:10
    at D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
    at new Promise (<anonymous>)
    at promiseOrCallback (D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
    at Mongoose._promiseOrCallback (D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\node_modules\mongoose\lib\index.js:1270:10)
    at Mongoose.connect (D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\node_modules\mongoose\lib\index.js:416:20)
    at dbConnect (D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\src\configs\database.config.ts:7:14)
    at Object.<anonymous> (D:\Movies + data\website Desighns\Angular-Restaurant-Web-App\backend\src\server.ts:9:10)
    at Module._compile (node:internal/modules/cjs/loader:1155:14)

i am using typescript for nodejs and dont know to solve this


问:
Import function from submodule A to submodule B
I have the following structure:

```<code>/module_a
    /py
        /function_a.py
/module_b
    /py
       /function_b.py
</code>```

function_b tries to import function_a

#This is function_b.py
from ...module_a.py import function_a

OUT:
ImportError: attempted relative import with no known parent package
```

How to import a function from one sub-module to another?

Body:
I have the following structure:

/module_a
    /py
        /function_a.py
/module_b
    /py
       /function_b.py

function_b tries to import function_a

#This is function_b.py
from ...module_a.py import function_a

OUT:
ImportError: attempted relative import with no known parent package

How to import a function from one sub-module to another?


问:
BootstrapVue - Date Time form input
How do you get a  to be of a date time format? This does not work:

```<code><b-form-input type="datetime-local"></b-form-input>
</code>```

and yet it states in the docs that it should. Could it be because I am using Vue 3?

Title: BootstrapVue - Date Time form input

Body:
How do you get a  to be of a date time format? This does not work:

and yet it states in the docs that it should. Could it be because I am using Vue 3?


问:
Dataframe replace with NaN if condition
I have a dataframe composed by many columns. A column is called DP FILTRO SEZ. 4 L1.
I need to replace the values of this column if a condition is verified. I don't want to build a for cycle with an if condition.
I wrote this:

data_clean['DP FILTRO SEZ. 4 L1'].mask(data_clean['DP FILTRO SEZ. 4 L1'] > upper ,'NaN', inplace=True)

Where data_clean is the dataframe and upper is the bound (float64). I need to replace the values greater than upper with NaN.

This code gives an error: '>' not supported between instances of 'numpy.ndarray' and 'str'

I think the problem is due to the dataframe column name (it is seen as a string), so I tried this: data_clean[data_clean.iloc[1::,['DP FILTRO SEZ. 4 L1']]>upper]=np.nan

I wanted to apply the condition from row 1 of the dataframe (excluding the column name), but I got the following error:.iloc requires numeric indexers, got ['DP FILTRO SEZ. 4 L1']

Title: Dataframe replace with NaN if condition


问:
I am looking to have two Seaborn lmplots side by side with each one maintaining the titles above
I saw several answers regarding subplots but I am unsure how to set it up using my code. I have two functions that give me two lmplots from Seaborn and I would like to get the figure shown below. How can I make the two lmplots look like the other figure which was obtained using R.

```<code>import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
</code>```
```<code>Martin2015_df = pd.read_csv('Martin2015_data.csv',
                            sep= '\t',
                            on_bad_lines= 'warn',
                            na_values=" "
                           ) #Creates the dataframe from the file

Martin2015_df.shape #Allows to see if the file -> dataframe code works
</code>```
```<code>def R_plotA(): #Defining the function
    """ Replicates the scatter plot of daily nest predation
    rate and compares it to the growth rate from the Martin2015_data.csv
    file. It then saves that image to what the current working directory is.
    """
colors = sns.color_palette(["#F88078", "#00BA38", "#619CFF"]) # Selecting color to be used

RPA = sns.lmplot(data=Martin2015_df,
                x="nstldpr",
                y="krate",
                hue="site",
                palette=colors,
                markers=[".", "^", "s"],
                ci=None,
                height=6,
                facet_kws={'legend_out': True}
               ) #Creates the figure

RPA.set(xlim = (0.000, 0.1000), ylim = (0.25, 0.600)) #Sets the axes limits

plt.title("A", x = 0) #Adds a title
plt.ylabel("Growth rate") #Adds a Y label
plt.xlabel("Daily nest predation rate") #Adds an X label

sns.move_legend(RPA, loc = "lower center", bbox_to_anchor = (0.5, -0.05), ncol = 4) #Adjusts the legend
# title
new_title = 'site'
RPA._legend.set_title(new_title)
# replace labels
new_labels = ['Arizona - temperate', 'Venezuela - tropical', 'Malaysia - tropical']
for t, l in zip(RPA._legend.texts, new_labels):
    t.set_text(l)

plt.grid(axis = "both") #Adds apropriate gridlines

plt.savefig("Martin_FigureA.png", orientation = "portrait", bbox_inches = "tight") #Saves figure

R_plotA()
plt.show()
</code>```

The image show is a result of R_plotA()

```<code>def R_plotB(): #Defining the function
    """ Replicates the scatter plot of daily nest predation
    rate and compares it to the growth rate from the Martin2015_data.csv
    file. It then saves that image to what the current working directory is.
    """
colors = sns.color_palette(["#F88078", "#00BA38", "#619CFF"]) # Selecting color to be used

RPB = sns.lmplot(data=Martin2015_df,
                x="krate",
                y="nstl",
                hue="site",
                palette=colors,
                markers=[".", "^", "s"],
                ci=None,
                height=6,
                facet_kws={'legend_out': True}
               ) #Creates the figure

RPB.set(xlim = (0.220, 0.600), ylim = (7, 30)) #Sets the axes limits

plt.title("B", x = 0) #Adds a title
plt.ylabel("Nestling period") #Adds a Y label
plt.xlabel("Growth rate") #Adds an X label

sns.move_legend(RPB, loc = "lower center", bbox_to_anchor = (0.5, -0.05), ncol = 4) #Adjusts the legend
# title
new_title = 'site'
RPB._legend.set_title(new_title)

# replace labels
new_labels = ['Arizona - temperate', 'Venezuela - tropical', 'Malaysia - tropical']
for t, l in zip(RPB._legend.texts, new_labels):
    t.set_text(l)

plt.grid(axis = "both") #Adds apropriate gridlines

plt.savefig("Martin_FigureB.png", orientation = "portrait", bbox_inches = "tight") #Saves figure

R_plotB()
plt.show()
</code>```

The followinf image is a rsult from R_plotB

How can i make the above images look like this figure combined

Also how do I make "site" appear on the left of the legend rather then on top.

Thank you!

Body:
I saw several answers regarding subplots but I am unsure how to set it up using my code. I have two functions that give me two lmplots from Seaborn and I would like to get the figure shown below. How can I make the two lmplots look like the other figure which was obtained using R.

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

Martin2015_df = pd.read_csv('Martin2015_data.csv',
                            sep= '\t',
                            on_bad_lines= 'warn',
                            na_values=" "
                           ) #Creates the dataframe from the file

Martin2015_df.shape #Allows to see if the file -> dataframe code works

def R_plotA(): #Defining the function
    """ Replicates the scatter plot of daily nest predation
    rate and compares it to the growth rate from the Martin2015_data.csv
    file. It then saves that image to what the current working directory is.
    """
colors = sns.color_palette(["#F88078", "#00BA38", "#619CFF"]) # Selecting color to be used

RPA = sns.lmplot(data=Martin2015_df,
                x="nstldpr",
                y="krate",
                hue="site",
                palette=colors,
                markers=[".", "^", "s"],
                ci=None,
                height=6,
                facet_kws={'legend_out': True}
               ) #Creates the figure

RPA.set(xlim = (0.000, 0.1000), ylim = (0.25, 0.600)) #Sets the axes limits

plt.title("A", x = 0) #Adds a title
plt.ylabel("Growth rate") #Adds a Y label
plt.xlabel("Daily nest predation rate") #Adds an X label

sns.move_legend(RPA, loc = "lower center", bbox_to_anchor = (0.5, -0.05), ncol = 4) #Adjusts the legend
# title
new_title = 'site'
RPA._legend.set_title(new_title)
# replace labels
new_labels = ['Arizona - temperate', 'Venezuela - tropical', 'Malaysia - tropical']
for t, l in zip(RPA._legend.texts, new_labels):
    t.set_text(l)

plt.grid(axis = "both") #Adds apropriate gridlines

plt.savefig("Martin_FigureA.png", orientation = "portrait", bbox_inches = "tight") #Saves figure

R_plotA()
plt.show()

The image show is a result of R_plotA()

def R_plotB(): #Defining the function
    """ Replicates the scatter plot of daily nest predation
    rate and compares it to the growth rate from the Martin2015_data.csv
    file. It then saves that image to what the current working directory is.
    """
colors = sns.color_palette(["#F88078", "#00BA38", "#619CFF"]) # Selecting color to be used

RPB = sns.lmplot(data=Martin2015_df,
                x="krate",
                y="nstl",
                hue="site",
                palette=colors,
                markers=[".", "^", "s"],
                ci=None,
                height=6,
                facet_kws={'legend_out': True}
               ) #Creates the figure

RPB.set(xlim = (0.220, 0.600), ylim = (7, 30)) #Sets the axes limits

plt.title("B", x = 0) #Adds a title
plt.ylabel("Nestling period") #Adds a Y label
plt.xlabel("Growth rate") #Adds an X label

sns.move_legend(RPB, loc = "lower center", bbox_to_anchor = (0.5, -0.05), ncol = 4) #Adjusts the legend
# title
new_title = 'site'
RPB._legend.set_title(new_title)

# replace labels
new_labels = ['Arizona - temperate', 'Venezuela - tropical', 'Malaysia - tropical']
for t, l in zip(RPB._legend.texts, new_labels):
    t.set_text(l)

plt.grid(axis = "both") #Adds apropriate gridlines

plt.savefig("Martin_FigureB.png", orientation = "portrait", bbox_inches = "tight") #Saves figure

R_plotB()
plt.show()

The followinf image is a rsult from R_plotB

How can i make the above images look like this figure combined

Also how do I make "site" appear on the left of the legend rather then on top.

Thank you!


问:
How to let nestjs repond on public IP
I setup my app (angular,graphql,nestjs) on VM windows 10,
I run angular on IP:192.168.xx.xx:4410 and the IP forwarded to my public IP then I linked angular with nestjs with same IP as shown below

in angular :const uri = "http://192.168.xx.xx:3000/graphql";
Nesjs runs on : await app.listen(3000,'192.168.xx.xx');
Once I wanted to access to my project in different machine in same LAN I could use the app but when I want to access to my app from outside my LAN I got the interface but it doesn't connect with nestjs
I got this error POST http://192.168.xx.xx:3000/graphql net::ERR_CONNECTION_TIMED_OUT
ERROR Error: Http failure response for http://192.168.xx.xx:3000/graphql: 0 Unknown Error
But when I change the link between Angular and nestjs to :
const uri = "http://localhost:3000/graphql";
and nestjs run on localhost too like this : await app.listen(3000);
I got this error POST http://localhost:3000/graphql net::ERR_CONNECTION_REFUSED

Title: How to let nestjs repond on public IP


问:
Why is my array that I get via ajax (js) empty (POST)?
When I send an array via ajax, the post key does not show up. The key links is not visible in the POST.

My js code:

```<code>function update() {
var linkArr = [];
linkKeys.forEach(key => {
    if ($('input[name="' + key['value'] + '"').length) {
        linkArr[key['value']] = [];
        $('input[name="' + key['value'] + '"]').each(function () {
            linkArr[key['value']].push(($(this).val()));
        });
    }
});
$.ajax({
    type: 'POST',
    url: '/update',
    data: {
         links: linkArr
        }
    });
}
</code>```

My php code:

```<code>public function update(Request $request): JsonResponse
    {
        if ($request->isXmlHttpRequest()) {
            $payload = $_POST;
            var_dump($payload);
        }
     }
</code>```

Body:
When I send an array via ajax, the post key does not show up. The key links is not visible in the POST.

My js code:

function update() {
var linkArr = [];
linkKeys.forEach(key => {
    if ($('input[name="' + key['value'] + '"').length) {
        linkArr[key['value']] = [];
        $('input[name="' + key['value'] + '"]').each(function () {
            linkArr[key['value']].push(($(this).val()));
        });
    }
});
$.ajax({
    type: 'POST',
    url: '/update',
    data: {
         links: linkArr
        }
    });
}

My php code:

public function update(Request $request): JsonResponse
    {
        if ($request->isXmlHttpRequest()) {
            $payload = $_POST;
            var_dump($payload);
        }
     }


问:
Reset MQTT broker after disconnecting to connect to a different device
I'm currently using the mosquittopp library in C++ to handle the connection with different devices (one at a time).
When we decide to disconnect from device #1 (by unplugging it from the computer from example) ; I receive correctly the on_disconnect signal. After that, I do a lib_cleanup() and lib_init() to reinitialize the broker : if I don't do that, plugging in the device will immediately reconnect it (but I want to be able to let go of a connection manually).

However, even with that, after plugging in the device, I still receive the on_connect signal without having to input ip address and port.

Is there any way to safely and cleanly completely cleanup the connection from MQTT broker ?
I'm expecting the issue to be because loop_forever() continues to run somehow, but even if I call stop() I still have the issues...

Here is the order of the calls and signals I have :

```<code>connectBrooker()
run() -> calls loop_forever()
on_connect()
// *operations here with messages and subscriptions*
// **unplugging the device** -> on_disconnect()
lib_cleanup()
lib_init()
// **plugging the device** -> after some small amount of time, on_connect() then run() -> calls loop_forever()
</code>```

Body:
I'm currently using the mosquittopp library in C++ to handle the connection with different devices (one at a time).
When we decide to disconnect from device #1 (by unplugging it from the computer from example) ; I receive correctly the on_disconnect signal. After that, I do a lib_cleanup() and lib_init() to reinitialize the broker : if I don't do that, plugging in the device will immediately reconnect it (but I want to be able to let go of a connection manually).

However, even with that, after plugging in the device, I still receive the on_connect signal without having to input ip address and port.

Is there any way to safely and cleanly completely cleanup the connection from MQTT broker ?
I'm expecting the issue to be because loop_forever() continues to run somehow, but even if I call stop() I still have the issues...

Here is the order of the calls and signals I have :

connectBrooker()
run() -> calls loop_forever()
on_connect()
// *operations here with messages and subscriptions*
// **unplugging the device** -> on_disconnect()
lib_cleanup()
lib_init()
// **plugging the device** -> after some small amount of time, on_connect() then run() -> calls loop_forever()


问:
Decode umlauts with a python sql-query through ssh-connection
I'm trying to establish a ssh connection to mysql-database via python. I get the data i request but with encoded umlauts..

Example: instead of "Jörg" I receive something like "J\xf6rg".

So the question is, how can I put some additional code in the actual query in order to make everything work right.

In the terminal everything works fine as soon as I add --default-character-set-utf8 but I don't know how to really do this in python. Adding a charset=utf8 in the pymsql connector didnt help..

Here is my code:

with SSHTunnelForwarder(

        '231.323.2.12.',

        ssh_username="myname",

        ssh_password="mypw",

        remote_bind_address=("127.0.0.1", 3306)) as tunnel:

        port = tunnel.local_bind_port

        db_connection = pymysql.connect(host="127.0.01",
                        port=port, db="kalender",user="oktay"
                        password="mypw")

        cursor = db_connection.cursor()

        query =  '''SELECT
                          CONCAT("[",
                            GROUP_CONCAT(
                              CONCAT("{BID:'",BID,"'"),

                              CONCAT("Benutzer:'",Benutzer,"'"),

                              CONCAT(",Vorname:'",Vorname,"'}")
                                        )
                                ,"]")
                     AS json FROM termincal_ben;
                  '''

  #my last attempt to set the charset to utf8..

 cursor.execute('SET character_set_connection=utf8;')

 cursor.execute(query)

 result = cursor.fetchall()

  print(result)

 db_connection.close()
```


问:
Possible to add a team as an owner of a Github organization?
We are setting up a Github enterprise with enterprise organizations under an enterprise account. We have enabled SAML SSO, SCIM and Team Synchronization with Azure AD at the organization level. All works.

Is is possible to set a team within the organization as an Owner of the organization? If so, how?

This will enable us to control owners to the organization through our AD groups. Currently, I can only find how to add individual members to this role.


问:
Video frames appear to be rendering with incorrect format using WebRTC
In my project, I use the Zoom Video SDK to receive frames in a YUV 420i format.

I'm doing an experiment trying to render these frames using the WebRTC RTCMTLNSVideoView, but I seem to have a format conversion issue, as the frames rendered on the screen appear severely mangled (see attached images).

Here are the basics of what I'm doing:

```<code>class VideoFrameZoom {
    private let data: ZMVideoSDKYUVRawDataI420
    let timestamp: CMTime
    let dimensions: CGSize

    init(_ data: ZMVideoSDKYUVRawDataI420) {
        self.data = data
        timestamp = CMTime(seconds: CACurrentMediaTime(), preferredTimescale: 1_000_000)
        dimensions = CGSize(width: Int(data.streamWidth), height: Int(data.streamHeight))
    }
}

extension VideoFrameZoom: VideoFrame {
    var pixelBuffer: CVPixelBuffer? {
        var outPixelBuffer: CVPixelBuffer?

        var planeAddresses: [UnsafeMutableRawPointer?] = [
            UnsafeMutableRawPointer(data.yBuffer),
            UnsafeMutableRawPointer(data.uBuffer),
            UnsafeMutableRawPointer(data.vBuffer),
        ]

        var planeWidths: [Int] = [
            Int(data.streamWidth),
            Int(data.streamWidth / 2),
            Int(data.streamWidth / 2),
        ]

        var planeHeights: [Int] = [
            Int(data.streamHeight),
            Int(data.streamHeight / 2),
            Int(data.streamHeight / 2),
        ]

        var planeBytesPerRow: [Int] = planeWidths

        let pixelBufferAttributes: CFDictionary? = nil
        assert(data.canAddRef())
        data.addRef()

        CVPixelBufferCreateWithPlanarBytes(
            kCFAllocatorDefault,
            Int(data.streamWidth),
            Int(data.streamHeight),
            kCVPixelFormatType_420YpCbCr8Planar,
            nil,
            0,
            3,
            &planeAddresses,
            &planeWidths,
            &planeHeights,
            &planeBytesPerRow,
            onPixelBufferReleased,
            bridge(obj: data),
            pixelBufferAttributes,
            &outPixelBuffer
        )

        return outPixelBuffer
    }
}

// ...

let buffer = videoFrameZoom.pixelBuffer!

let rtcVideoFrame =
  RTCVideoFrame(buffer: buffer,
                rotation: RTCVideoRotation._90,
                timeStampNs: Int64(timeStampNs))
</code>```

This frame then gets rendered by the RTCMTLNSVideoView after passing through a RTCVideoTrack

This results in frames where I can occasionally see artifacts of the original image, but clearly is not correct:

With the previous renderer we used in the project, our video renders correctly (note that the previous renderer used the same var pixelBuffer code from above), so this rules out an issue with the video source.

Should I be using a different format than kCVPixelFormatType_420YpCbCr8Planar to feed to WebRTC?

Body:
In my project, I use the Zoom Video SDK to receive frames in a YUV 420i format.

I'm doing an experiment trying to render these frames using the WebRTC RTCMTLNSVideoView, but I seem to have a format conversion issue, as the frames rendered on the screen appear severely mangled (see attached images).

Here are the basics of what I'm doing:

class VideoFrameZoom {
    private let data: ZMVideoSDKYUVRawDataI420
    let timestamp: CMTime
    let dimensions: CGSize

    init(_ data: ZMVideoSDKYUVRawDataI420) {
        self.data = data
        timestamp = CMTime(seconds: CACurrentMediaTime(), preferredTimescale: 1_000_000)
        dimensions = CGSize(width: Int(data.streamWidth), height: Int(data.streamHeight))
    }
}

extension VideoFrameZoom: VideoFrame {
    var pixelBuffer: CVPixelBuffer? {
        var outPixelBuffer: CVPixelBuffer?

        var planeAddresses: [UnsafeMutableRawPointer?] = [
            UnsafeMutableRawPointer(data.yBuffer),
            UnsafeMutableRawPointer(data.uBuffer),
            UnsafeMutableRawPointer(data.vBuffer),
        ]

        var planeWidths: [Int] = [
            Int(data.streamWidth),
            Int(data.streamWidth / 2),
            Int(data.streamWidth / 2),
        ]

        var planeHeights: [Int] = [
            Int(data.streamHeight),
            Int(data.streamHeight / 2),
            Int(data.streamHeight / 2),
        ]

        var planeBytesPerRow: [Int] = planeWidths

        let pixelBufferAttributes: CFDictionary? = nil
        assert(data.canAddRef())
        data.addRef()

        CVPixelBufferCreateWithPlanarBytes(
            kCFAllocatorDefault,
            Int(data.streamWidth),
            Int(data.streamHeight),
            kCVPixelFormatType_420YpCbCr8Planar,
            nil,
            0,
            3,
            &planeAddresses,
            &planeWidths,
            &planeHeights,
            &planeBytesPerRow,
            onPixelBufferReleased,
            bridge(obj: data),
            pixelBufferAttributes,
            &outPixelBuffer
        )

        return outPixelBuffer
    }
}

// ...

let buffer = videoFrameZoom.pixelBuffer!

let rtcVideoFrame =
  RTCVideoFrame(buffer: buffer,
                rotation: RTCVideoRotation._90,
                timeStampNs: Int64(timeStampNs))

This frame then gets rendered by the RTCMTLNSVideoView after passing through a RTCVideoTrack

This results in frames where I can occasionally see artifacts of the original image, but clearly is not correct:

With the previous renderer we used in the project, our video renders correctly (note that the previous renderer used the same var pixelBuffer code from above), so this rules out an issue with the video source.

Should I be using a different format than kCVPixelFormatType_420YpCbCr8Planar to feed to WebRTC?


问:
Intellij plugin, directory open listener
I am developing an intellij plugin which is in fact an icon pack.
I would like to make sure that when folders are opened, their icons change and the same when we close them.
How can I achieve this?
Is there a Listener class that would do what I want?

As an example on the picture:

1 and 3 are open folders => put icon folder open.

2 folder close => leave icon folder closed

Thanks in advance.
Ricko