问:
How to make loop based on n value?
Let say i have n value 3,

The code will look like this :

```<code>//Loop 1
for i := 0; i < len(x); i++ {
        //Loop 2
        for j := 0; (j < len(x)) && (j != i); j++ {
            //Loop 3
            for k := 0; (k < len(x)) && (k != i) && (k != j); k++ {
            }
        }
    }
</code>```

However, I was trying to figure out how to make it automatically based on the value, so that when the n value is 5, it should generate:

```<code>Loop 1 {
   Loop 2 {
      Loop 3 {
         Loop 4 {
            Loop 5 {
            }
         }
      }
   }
}
</code>```

Is it possible?

答:
Here is an example of a recursion https://go.dev/play/p/cLm-QHydM37

This results in the following iterations

When length is 5: map[1:5 2:25 3:125 4:625 5:3125]

When length is 3: map[1:3 2:9 3:27 4:0 5:0]

```<code>package main

import "fmt"

func main() {
    count := map[int]int{1: 0, 2: 0, 3: 0, 4: 0, 5: 0}

    // This recursion is based on https://gobyexample.com/recursion
    var loopFunc func(current int, data []string)
    loopFunc = func(current int, data []string) {
        for i := 0; (i < len(data)) && (len(data) != current-1); i++ {
            count[current] = count[current] + 1
            loopFunc(current+1, data)
        }
    }

    loopFunc(1, make([]string, 5))
    fmt.Println(count)
}
</code>```

I might not have your loop logic exactly right but this should be a springboard for you to continue on from.

Title: How to make loop based on n value?

Body:
Let say i have n value 3,

The code will look like this :

//Loop 1
for i := 0; i < len(x); i++ {
        //Loop 2
        for j := 0; (j < len(x)) && (j != i); j++ {
            //Loop 3
            for k := 0; (k < len(x)) && (k != i) && (k != j); k++ {
            }
        }
    }

However, I was trying to figure out how to make it automatically based on the value, so that when the n value is 5, it should generate:

Loop 1 {
   Loop 2 {
      Loop 3 {
         Loop 4 {
            Loop 5 {
            }
         }
      }
   }
}

Is it possible?

Body:
Here is an example of a recursion https://go.dev/play/p/cLm-QHydM37

This results in the following iterations

When length is 5: map[1:5 2:25 3:125 4:625 5:3125]

When length is 3: map[1:3 2:9 3:27 4:0 5:0]

package main

import "fmt"

func main() {
    count := map[int]int{1: 0, 2: 0, 3: 0, 4: 0, 5: 0}

    // This recursion is based on https://gobyexample.com/recursion
    var loopFunc func(current int, data []string)
    loopFunc = func(current int, data []string) {
        for i := 0; (i < len(data)) && (len(data) != current-1); i++ {
            count[current] = count[current] + 1
            loopFunc(current+1, data)
        }
    }

    loopFunc(1, make([]string, 5))
    fmt.Println(count)
}

I might not have your loop logic exactly right but this should be a springboard for you to continue on from.


来源: stackexchange

问:
BerkleyDB doesn't Install on Ubuntu
I'm currently trying to install Berkley Db. Following the documentation when I make, I hit the following error. There is nothing online I can find about this problem:</p>

```<code>../src/repmgr/repmgr_net.c: In function '__repmgr_set_ssl_ctx':
../src/repmgr/repmgr_net.c:2897:6: error: 'repmgr_ssl_mutex_arr' undeclared (first use in this function); did you mean '__repmgr_ssl_readv'?
  if (repmgr_ssl_mutex_arr != NULL) {
      ^~~~~~~~~~~~~~~~~~~~
      __repmgr_ssl_readv
../src/repmgr/repmgr_net.c:2897:6: note: each undeclared identifier is reported only once for each function it appears in
Makefile:2795: recipe for target 'repmgr_net.lo' failed
make: *** [repmgr_net.lo] Error 1
</code>```

答:
Maybe because your  OPENSSL_VERSION_NUMBER > 0x10100000L;
Like this :

```<code>#if OPENSSL_VERSION_NUMBER < 0x10100000L
    if (repmgr_ssl_mutex_arr != NULL) {
            for (i = 0; i < CRYPTO_num_locks(); i++) {
                    if (repmgr_ssl_mutex_arr[i] != NULL)
                            __repmgr_destroy_mutex(env, repmgr_ssl_mutex_arr[i]);
            }

            repmgr_ssl_mutex_arr = NULL;
    }
#endif
</code>```

Just for an example,you can find your openssl version in this c file;

ContentLicense: CC BY-SA 4.0

Title: BerkleyDB doesn't Install on Ubuntu

Body:
I'm currently trying to install Berkley Db. Following the documentation when I make, I hit the following error. There is nothing online I can find about this problem:

../src/repmgr/repmgr_net.c: In function '__repmgr_set_ssl_ctx':
../src/repmgr/repmgr_net.c:2897:6: error: 'repmgr_ssl_mutex_arr' undeclared (first use in this function); did you mean '__repmgr_ssl_readv'?
  if (repmgr_ssl_mutex_arr != NULL) {
      ^~~~~~~~~~~~~~~~~~~~
      __repmgr_ssl_readv
../src/repmgr/repmgr_net.c:2897:6: note: each undeclared identifier is reported only once for each function it appears in
Makefile:2795: recipe for target 'repmgr_net.lo' failed
make: *** [repmgr_net.lo] Error 1

Body:
Maybe because your  OPENSSL_VERSION_NUMBER > 0x10100000L;
Like this :

#if OPENSSL_VERSION_NUMBER < 0x10100000L
    if (repmgr_ssl_mutex_arr != NULL) {
            for (i = 0; i < CRYPTO_num_locks(); i++) {
                    if (repmgr_ssl_mutex_arr[i] != NULL)
                            __repmgr_destroy_mutex(env, repmgr_ssl_mutex_arr[i]);
            }

            repmgr_ssl_mutex_arr = NULL;
    }
#endif

Just for an example,you can find your openssl version in this c file;


问:
geom_text different color labels
I'm working with a categorical dataset of averages, modeled off of the following code:

```<code>iris %>%
  group_by(Species) %>%
  summarise(
    avg_sepal_width = mean(Sepal.Width),
    avg_sepal_length = mean(Sepal.Length)
  ) %>%
  pivot_longer(cols = c(avg_sepal_width, avg_sepal_length)) -> iris_avg
</code>```

This provides me with the table:

Species
name
value

setosa
avg_sepal_width
3.428

setosa
avg_sepal_length
5.006

versicolor
avg_sepal_width
2.770

versicolor
avg_sepal_length
5.936

virginica
avg_sepal_width
2.974

virginica
avg_sepal_length
6.588

Working with this data, I cam creating a simple side-by-side bar chart using ggplot, as follows:

```<code>iris_avg %>%
  ggplot(aes(x = Species, y = value, fill = name)) +
  geom_col(position = "dodge") +
  geom_text(aes(label = value), position = position_dodge(.9), vjust = 2)
</code>```

I am trying to determine if there is a way for me to add a color =  parameter in the geom_text layer that would allow me to make the two different categories (length and width) different colors.

答:
Add color=name to the text's aes(.). If you do that by itself, it'll choose the same colors as used for fill= above it, rendering the text the same color as the bar on which they are placed; to fix that, use scale_color_manual(values=..) to specify the colors in a named-vector.

iris_avg %>%
  ggplot(aes(x = Species, y = value, fill = name)) +
  geom_col(position = "dodge") +
  geom_text(aes(label = value, color = name), position = position_dodge(.9), vjust = 2) +
  scale_color_manual(values = c(avg_sepal_length="green", avg_sepal_width="black"))
```

(Though perhaps you can find colors that don't look at ghastly.)

Title: geom_text different color labels

Body:
I'm working with a categorical dataset of averages, modeled off of the following code:

iris %>%
  group_by(Species) %>%
  summarise(
    avg_sepal_width = mean(Sepal.Width),
    avg_sepal_length = mean(Sepal.Length)
  ) %>%
  pivot_longer(cols = c(avg_sepal_width, avg_sepal_length)) -> iris_avg

This provides me with the table:

Species
name
value

setosa
avg_sepal_width
3.428

setosa
avg_sepal_length
5.006

versicolor
avg_sepal_width
2.770

versicolor
avg_sepal_length
5.936

virginica
avg_sepal_width
2.974

virginica
avg_sepal_length
6.588

Working with this data, I cam creating a simple side-by-side bar chart using ggplot, as follows:

iris_avg %>%
  ggplot(aes(x = Species, y = value, fill = name)) +
  geom_col(position = "dodge") +
  geom_text(aes(label = value), position = position_dodge(.9), vjust = 2)

I am trying to determine if there is a way for me to add a color =  parameter in the geom_text layer that would allow me to make the two different categories (length and width) different colors.

Body:
Add color=name to the text's aes(.). If you do that by itself, it'll choose the same colors as used for fill= above it, rendering the text the same color as the bar on which they are placed; to fix that, use scale_color_manual(values=..) to specify the colors in a named-vector.

iris_avg %>%
  ggplot(aes(x = Species, y = value, fill = name)) +
  geom_col(position = "dodge") +
  geom_text(aes(label = value, color = name), position = position_dodge(.9), vjust = 2) +
  scale_color_manual(values = c(avg_sepal_length="green", avg_sepal_width="black"))

(Though perhaps you can find colors that don't look at ghastly.)


问:
Adding Ranking to Datatables
I am trying to calculate rank based on the total number of points in a datatable

The Javascript is getting the correct values and ranking correctly in the console, however it is not placing the value in the datatable

```<code> $(function() {

        var table=$('#points-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: 'http://localhost/edpark/public/get/points',
            columns: [
                { data: 'rank', defaultContent: ''},
                { data: 'first_name'},
                { data: 'last_name'},
                { data: 'TotalPoints'},
            ],
                drawCallback: function () {
                api = this.api();
                var arr = api.columns(3).data()[0];  //get array of column 3 (extn)
                console.log(arr);
                var sorted = arr.slice().sort(function(a,b){return b-a});
                var ranks = arr.slice().map(function(v){ return sorted.indexOf(v)+1 });
                console.log(sorted);
                console.log(ranks);
                // interate through each row
                api.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
                    var data = this.data();
                    var rank = ranks[rowLoop];
                    data.rank = ranks[arr.indexOf(data.extn)];  //set the rank column = the array index of the extn in the ranked array
             } );
        api.rows().invalidate();
        }
        });
    })
</code>```

I have 3 rows in my dev table which have a total point of 60, 10, 5 which is being written into the console correctly, and being ranked 1,2,3

However in my table, the Rank field is still blank.

Thank you

Edit

Adding Requested HTML Code and Dataset

HTML

```<code>@extends('layouts.app')

@section('content')
<div class="container-fluid">
    @if(session()->has('success'))
        <div class="row">
            <div class="col-12 alert alert-success" role="alert">
                <strong>{{session()->get('success')}}</strong>
            </div>
        </div>
    @endif
    @if(session()->has('failure'))
        <div class="row">
            <div class="col-12 alert alert-danger" role="alert">
                <strong>{{session()->get('failure')}}</strong>
            </div>
        </div>
    @endif
    <div class="row">
        <div class="col-lg-12 col-sm-12">
            <div class="card">
                <div class="card-body">
                    <h3 class="text-center">Points Report</h3>

                    <div class="table-responsive">
                        <table class="table table-striped table-no-boreded table-hover" width="100%" id="points-table">
                            <thead class = "text-primary">
                            <h4> </h4>
                                <tr>
                                    <th class="text-center">Rank</th>
                                    <th class="text-center">First Name</th>
                                    <th class="text-center">Last Name</th>
                                    <th class="text-center">Total Points</th>
                                    <th width="10%"></th>
                                </tr>
                            </thead>
                            <tbody class = "text-center">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@endsection
</code>```

Dataset

```<code>Member_id| Points | Reason |
    1        10       --
    5        60       --
    4        10       --
    1        -5       --
</code>```

Hope this helps

答:
Solved this by adding the following to my query

```<code>SelectRaw->("RANK () OVER (ORDER BY SUM(points.value) DESC) 'rank'")
</code>```

Then I can call the rank data as per normal in a DataTable

Title: Adding Ranking to Datatables

Body:
I am trying to calculate rank based on the total number of points in a datatable

The Javascript is getting the correct values and ranking correctly in the console, however it is not placing the value in the datatable

 $(function() {

        var table=$('#points-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: 'http://localhost/edpark/public/get/points',
            columns: [
                { data: 'rank', defaultContent: ''},
                { data: 'first_name'},
                { data: 'last_name'},
                { data: 'TotalPoints'},
            ],
                drawCallback: function () {
                api = this.api();
                var arr = api.columns(3).data()[0];  //get array of column 3 (extn)
                console.log(arr);
                var sorted = arr.slice().sort(function(a,b){return b-a});
                var ranks = arr.slice().map(function(v){ return sorted.indexOf(v)+1 });
                console.log(sorted);
                console.log(ranks);
                // interate through each row
                api.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
                    var data = this.data();
                    var rank = ranks[rowLoop];
                    data.rank = ranks[arr.indexOf(data.extn)];  //set the rank column = the array index of the extn in the ranked array
             } );
        api.rows().invalidate();
        }
        });
    })

I have 3 rows in my dev table which have a total point of 60, 10, 5 which is being written into the console correctly, and being ranked 1,2,3

However in my table, the Rank field is still blank.

Thank you

Edit

Adding Requested HTML Code and Dataset

HTML

@extends('layouts.app')

@section('content')

    @if(session()->has('success'))

                {{session()->get('success')}}

    @endif
    @if(session()->has('failure'))

                {{session()->get('failure')}}

    @endif

Points Report

                                    Rank
                                    First Name
                                    Last Name
                                    Total Points

@endsection

Dataset

Member_id| Points | Reason |
    1        10       --
    5        60       --
    4        10       --
    1        -5       --

Hope this helps

Body:
Solved this by adding the following to my query

SelectRaw->("RANK () OVER (ORDER BY SUM(points.value) DESC) 'rank'")

Then I can call the rank data as per normal in a DataTable


问:
Error in one vba workbook causes other independent workbooks to stop running
I've written a number of programs that monitor devices and records data.  The programs are continuously running. I'm usually monitoring several devices using separate workbooks that are independent from each other. However, if one program gets an error, all of VBA stops, including those other programs.
Is there a way to have separate instances of VBA? So if one faults the others can still run? Thanks.</p>

答:
If you want an error in one workbook not to affect running code in another, you can use separate instances of Excel to run each macro.

To start a new instance, hold down the Alt key while opening Excel - it will ask you if you mean to start a new instance. Or you can create a new instance from VBA using CreateObject()


问:
GPS Serial Console issue on Ubuntu 20.04 on Raspberry Pi 4
I am trying to use the BerryGPS-IMUv3 (https://ozzmaker.com/berrygps-berrygps-imu-quick-start-guide/) on a RPi 4B running Ubuntu 20.04 headless. When the BerryGPS-IMU is installed, it prevents the pi from booting, presumably because it is streaming data to the pi and interrupting the boot process. The manufacturer's instructions state that the serial console needs to be disabled, but the instructions assume the user is running raspbian.

Has anyone figured out a way to disable the serial console (but keep the serial port enabled) on Ubuntu 20.04? I think I need to set the boot delay to "-2" to ignore interrupts but I'm not sure how to access that setting via ssh.

答:
Compiling U-boot did not work for me (as of today, latest Ubuntu 20.04 on Raspberry Pi 4).
I had to use the serial console to change the settings.
followed this answer: https://askubuntu.com/a/1278181/1569332
Let me try to expand it a bit.

U have to connect a serial adopter to the Pi's Tx Rx (GPIO 14,15) pins and log on to the Raspberry Pi's Serial Console (UART) from another computer. refer to this guide for a tutorial on that.
I used an Arduino (running the SoftwareSerial example -->> changed the baud rate to 115200) connected like this:
connection diagram

Rpi TXD -- Arduino pin 10

Rpi RXD -- Arduino pin 11

Rpi GND -- Arduino GND

The pi being powered off, connect the serial device(Arduino) to the other computer, open the Arduino serial monitor (or putty or sudo screen /dev/tty{your port} 115200)

Power the Rpi and you should see something similar to the boot screen.

Keep pressing ENTER (/any key) on the serial monitor/console and it should print:

Hit any key to stop autoboot:  2  0

U-Boot>

If u missed the U-Boot menu, u would be prompted to log in. Repeat steps 3 and 4 quickly.

Enter the following commands:

setenv bootdelay -2

saveenv
The response should be Saving Environment to FAT... OK

Reboot to verify.


问:
Converting EF Core queries from 2.2 to 3.0 - async await
In EF Core 2.2 I had:

```<code>      var data = await _ArticleTranslationRepository.DbSet
        .Include(arttrans => arttrans.Article)
        .ThenInclude(art => art.Category)
        .Where(trans => trans.Article != null && trans.Article.Category != null && trans.Article.Category.Id == categoryId.Value)
        .GroupBy(trans => trans.ArticleId)
        .Select(g => new { ArticleId = g.Key, TransInPreferredLang = g.OrderByDescending(trans => trans.LanguageId == lang).ThenByDescending(trans => trans.LanguageId == defaultSiteLanguage).ThenBy(trans => trans.LanguageId).FirstOrDefault() })
        .Select(at => at.TransInPreferredLang)
        .OrderBy(at => at.Article.SortIndex)
        .ToListAsync();
</code>```

Now with EF Core 3.0 I had to write:

```<code>      var data = _ArticleTranslationRepository.DbSet
  .Include(arttrans => arttrans.Article)
  .ThenInclude(art => art.Category)
  .Where(trans => trans.Article != null && trans.Article.Category != null && trans.Article.Category.Id == categoryId.Value)
    .AsEnumerable() // client side groupby is not supported (.net core 3.0 (18 nov. 2019)
  .GroupBy(trans => trans.ArticleId)
  .Select(g => new { ArticleId = g.Key, TransInPreferredLang = g.OrderByDescending(trans => trans.LanguageId == lang).ThenByDescending(trans => trans.LanguageId == defaultSiteLanguage).ThenBy(trans => trans.LanguageId).FirstOrDefault() })
  .Select(at => at.TransInPreferredLang)
  .OrderBy(at => at.Article.SortIndex)
  .ToList();

</code>```

My asp.net core mvc actionmethod is async (public virtual async Task<ICollection<…>>…)
Because I used .AsEnumerable to force client side evaluation I also had to change .ToListAsync() to .ToList() and remove the await operator.

The query is working but produces a warning:
This async method lacs 'await' operators and will run synchronously. Consider using the 'await operator ….

How can this EF Core 3.0 query be rewritten so that it uses async / await. I can't figure out how to include the AsAsyncEnumerable() in a single query/linq expression.

(I know that I can split it up in a 'server' part and a 'client-side' part, but I would like to see it in a single async linq expression as I had before in EF Core 2.2.)

答:
I had the same problem with dotnet core 5.0 and 6.0 and I solved it like this:

Install the nuget package System.Linq.Async depending of you dotnet version https://www.nuget.org/packages/System.Linq.Async

and then in your query you would be able to add the .ToAsyncEnumerable()

This a example:

```<code>        public async Task<IEnumerable<ProductTableView>> GetProduct(Pagination pagination, string identifier)
    {

        var ListProductsTable = await _context.ModelView
                                       .FromSqlRaw("GetProductByIdentifier {0}", identifier)
                                       .ToAsyncEnumerable()
                                       .Select(a => new ProductTableView
                                       {
                                           ID = a.ID,
                                           Guid = a.Guid,
                                           Guid_Product_Category = a.Guid_Product_Category,
                                           Guid_Currency = a.Guid_Currency,
                                           NameProduct = a.NameProduct,
                                       }).ToListAsync();

        return ListProductsTable;
    }
</code>```

Body:
In EF Core 2.2 I had:

      var data = await _ArticleTranslationRepository.DbSet
        .Include(arttrans => arttrans.Article)
        .ThenInclude(art => art.Category)
        .Where(trans => trans.Article != null && trans.Article.Category != null && trans.Article.Category.Id == categoryId.Value)
        .GroupBy(trans => trans.ArticleId)
        .Select(g => new { ArticleId = g.Key, TransInPreferredLang = g.OrderByDescending(trans => trans.LanguageId == lang).ThenByDescending(trans => trans.LanguageId == defaultSiteLanguage).ThenBy(trans => trans.LanguageId).FirstOrDefault() })
        .Select(at => at.TransInPreferredLang)
        .OrderBy(at => at.Article.SortIndex)
        .ToListAsync();

Now with EF Core 3.0 I had to write:

      var data = _ArticleTranslationRepository.DbSet
  .Include(arttrans => arttrans.Article)
  .ThenInclude(art => art.Category)
  .Where(trans => trans.Article != null && trans.Article.Category != null && trans.Article.Category.Id == categoryId.Value)
    .AsEnumerable() // client side groupby is not supported (.net core 3.0 (18 nov. 2019)
  .GroupBy(trans => trans.ArticleId)
  .Select(g => new { ArticleId = g.Key, TransInPreferredLang = g.OrderByDescending(trans => trans.LanguageId == lang).ThenByDescending(trans => trans.LanguageId == defaultSiteLanguage).ThenBy(trans => trans.LanguageId).FirstOrDefault() })
  .Select(at => at.TransInPreferredLang)
  .OrderBy(at => at.Article.SortIndex)
  .ToList();

My asp.net core mvc actionmethod is async (public virtual async Task<ICollection<…>>…)
Because I used .AsEnumerable to force client side evaluation I also had to change .ToListAsync() to .ToList() and remove the await operator.

The query is working but produces a warning:
This async method lacs 'await' operators and will run synchronously. Consider using the 'await operator ….

How can this EF Core 3.0 query be rewritten so that it uses async / await. I can't figure out how to include the AsAsyncEnumerable() in a single query/linq expression.

(I know that I can split it up in a 'server' part and a 'client-side' part, but I would like to see it in a single async linq expression as I had before in EF Core 2.2.)

Body:
I had the same problem with dotnet core 5.0 and 6.0 and I solved it like this:

Install the nuget package System.Linq.Async depending of you dotnet version https://www.nuget.org/packages/System.Linq.Async

and then in your query you would be able to add the .ToAsyncEnumerable()

This a example:

        public async Task<IEnumerable<ProductTableView>> GetProduct(Pagination pagination, string identifier)
    {

        var ListProductsTable = await _context.ModelView
                                       .FromSqlRaw("GetProductByIdentifier {0}", identifier)
                                       .ToAsyncEnumerable()
                                       .Select(a => new ProductTableView
                                       {
                                           ID = a.ID,
                                           Guid = a.Guid,
                                           Guid_Product_Category = a.Guid_Product_Category,
                                           Guid_Currency = a.Guid_Currency,
                                           NameProduct = a.NameProduct,
                                       }).ToListAsync();

        return ListProductsTable;
    }


问:
How can I sync text together with a narrated audio file and make the text scroll together with the audio (like karaoke)?
In my app, I would like to play an audio file and show text so that the user can read along with the audio. I would like this text to scroll automatically so the user doesn't lose their position.

To get the auto-scrolling to work, I thought I could animate a list view that displays the correct text based on timestamps, however, that would make adding new audio laborious as I would have to manually go through each audio and add the text with timestamps so I am hoping there is a better way to do this.

How can I sync an audio file together with text without having to create timestamps?
Is it possible to use a speech recognition library in Flutter to do this?

答:
Karaoke usually uses Lyric(LRC) file format to display lyrics. The format is similar to how subtitle(SRT) files are - where timestamp is defined with the text to be displayed. There are tools to help you generate Lyric files like Aegisub.

There's yet to be a way to sync audio and text without timestamps. If you're leaning into that approach, the closest that I've seen so far is auto-generated captions - something similar to how it's applied on YouTube.

Parsing Lyrics

This is not a complete sample, but you can use lyrics_parser plugin to parse the timestamp(milliseconds) and text. You may consider storing the timestamp-lyrics in a Map or List<Model> depending on your preference.

Highlight Text

To highlight the lyrics, you can consider using highlightable plugin.

Lyrics

Populate a ListView row dynamically
depending on the size the View can handle (width / estimated String length). Say a character has an estimated 5.0 in width. A ListView row with a width 200 can handle an estimated 36 characters per row if we bump the estimated character width to 5.5 - to factor in spacing and padding. Add a new ListView row if the size exceeds the estimated row width.

To fetch the view's width, you can use LayoutBuilder. This widget fetches its parent widget's dimensions.

LayoutBuilder(builder: (context, constraints) {
  debugPrint('Max width: ${constraints.maxWidth}');
})
```
<p><strong>Auto scroll</strong></p>
<p>To manage auto scroll feature, you can keep track the first timestamp displayed on the row and use ScrollController.animateTo() to navigate to the specific row.</p>
<p><strong>Time sync</strong></p>
<p>For syncing time, you can consider using Timer.periodic, and highlight the text using <code>highlightable</code> plugin when the timestamp on the ticker matches with the lyrics'</p>
<pre class="lang-dart prettyprint-override"><code>Row(
  children: [
    HighlightText(
      lyricsText,
      detectWords: true, // set to true to highlight text
    ),
    ...
  ],
)
</code>```

Body:
Karaoke usually uses Lyric(LRC) file format to display lyrics. The format is similar to how subtitle(SRT) files are - where timestamp is defined with the text to be displayed. There are tools to help you generate Lyric files like Aegisub.

There's yet to be a way to sync audio and text without timestamps. If you're leaning into that approach, the closest that I've seen so far is auto-generated captions - something similar to how it's applied on YouTube.

Parsing Lyrics

This is not a complete sample, but you can use lyrics_parser plugin to parse the timestamp(milliseconds) and text. You may consider storing the timestamp-lyrics in a Map or List<Model> depending on your preference.

Highlight Text

To highlight the lyrics, you can consider using highlightable plugin.

Lyrics

Populate a ListView row dynamically
depending on the size the View can handle (width / estimated String length). Say a character has an estimated 5.0 in width. A ListView row with a width 200 can handle an estimated 36 characters per row if we bump the estimated character width to 5.5 - to factor in spacing and padding. Add a new ListView row if the size exceeds the estimated row width.

To fetch the view's width, you can use LayoutBuilder. This widget fetches its parent widget's dimensions.

LayoutBuilder(builder: (context, constraints) {
  debugPrint('Max width: ${constraints.maxWidth}');
})

Auto scroll

To manage auto scroll feature, you can keep track the first timestamp displayed on the row and use ScrollController.animateTo() to navigate to the specific row.

Time sync

For syncing time, you can consider using Timer.periodic, and highlight the text using highlightable plugin when the timestamp on the ticker matches with the lyrics'

Row(
  children: [
    HighlightText(
      lyricsText,
      detectWords: true, // set to true to highlight text
    ),
    ...
  ],
)


问:
upload multiple csv files into one dataframe while defining variable types (using tidyverse)
I have a list of csv files in a specific path. I am hoping to upload all of them into one dataframe. This is the code I use:

```<code>d <-
    list.files(path,pattern="*.csv", full.names = T) %>%
    map_dfr(read_csv)
</code>```

Trouble is that some of these columns (for example the column array_values) are strings that are then converted into numbers. I tried all sorts of ways to convert the variables  but can't get it to work unless I have a much more complicated code in which I upload the files one by one, convert and then add to the larger dataframe. Would love to learn if there is a simple way to add it to the code here.

Thanks!

答:
Assuming that you have mutliple datasets and having some trouble in some of the columns which are not unique among all the datasets. you can also acheive this using below:

```<code>library(dplyr)

path <- 'your path'
filename <- list.files(path, pattern = "*.csv", recursive = TRUE)
filename <- stringr::str_subset(filename,pattern="test")

#Creating a custom function to loop on all files
read_csv_files <- function(x){
    df <- read_csv(path = paste(path, x, sep = "/"))
    df$yourcol <- as.character(df$yourcol) # you can change datatype for the respective columns as per your needs
    fName <- x
    df <- cbind(fName,df)
    return(df)
}

bind_data <- lapply(filename, read_csv_files) %>%
bind_rows()
</code>```

Hope this will help. will be happy to connect incase required.

Body:
I have a list of csv files in a specific path. I am hoping to upload all of them into one dataframe. This is the code I use:

d <-
    list.files(path,pattern="*.csv", full.names = T) %>%
    map_dfr(read_csv)

Trouble is that some of these columns (for example the column array_values) are strings that are then converted into numbers. I tried all sorts of ways to convert the variables  but can't get it to work unless I have a much more complicated code in which I upload the files one by one, convert and then add to the larger dataframe. Would love to learn if there is a simple way to add it to the code here.

Thanks!

Body:
Assuming that you have mutliple datasets and having some trouble in some of the columns which are not unique among all the datasets. you can also acheive this using below:

library(dplyr)

path <- 'your path'
filename <- list.files(path, pattern = "*.csv", recursive = TRUE)
filename <- stringr::str_subset(filename,pattern="test")

#Creating a custom function to loop on all files
read_csv_files <- function(x){
    df <- read_csv(path = paste(path, x, sep = "/"))
    df$yourcol <- as.character(df$yourcol) # you can change datatype for the respective columns as per your needs
    fName <- x
    df <- cbind(fName,df)
    return(df)
}

bind_data <- lapply(filename, read_csv_files) %>%
bind_rows()

Hope this will help. will be happy to connect incase required.


问:
Flutter: right overflowed by 23 pixels ("add task" button)
so basically i'm making a button "add task" for my to-do list app and it shows "right overflowed by 23 pixels"

Here's my "home_page.dart" code for the "add task" button

```<code>_addTaskBar(){
  return Container(
   margin: const EdgeInsets.only(left:20, right:20, top:10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(DateFormat.yMMMMd().format(DateTime.now()),
                  style: subHeadingStyle,
                  ),
                  Text("Today",
                  style: headingStyle,
                  )
                ],
              ),
            MyButton(label: "+ Add Task", onTap: ()=>null)
          ],
        ),
    );
}
</code>```

And this is my "button.dart" code for the "add task" button as well

```<code> class MyButton extends StatelessWidget {
  final String label;
  final Function()? onTap;
  const MyButton({ Key? key, required this.label, required this.onTap}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 120,
        height: 60,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          color: primaryClr
        ),
        child: Text(
          label,
          style: const TextStyle(
            color: Colors.white,
          ),
        ),
      ),
    );
  }
}
</code>```

The result of the code is this
enter image description here

I need help to anyone who can solve this issue of mine. Thank you

答:
This error is because the size you have given is overflowing meaning that it is not fitting in the screen.
Try using params of columns and rows(mainaxisalignment, crossaxisalignment) for getting the widget fit in every screen.</p>

Body:
so basically i'm making a button "add task" for my to-do list app and it shows "right overflowed by 23 pixels"

Here's my "home_page.dart" code for the "add task" button

_addTaskBar(){
  return Container(
   margin: const EdgeInsets.only(left:20, right:20, top:10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(DateFormat.yMMMMd().format(DateTime.now()),
                  style: subHeadingStyle,
                  ),
                  Text("Today",
                  style: headingStyle,
                  )
                ],
              ),
            MyButton(label: "+ Add Task", onTap: ()=>null)
          ],
        ),
    );
}

And this is my "button.dart" code for the "add task" button as well

 class MyButton extends StatelessWidget {
  final String label;
  final Function()? onTap;
  const MyButton({ Key? key, required this.label, required this.onTap}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 120,
        height: 60,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          color: primaryClr
        ),
        child: Text(
          label,
          style: const TextStyle(
            color: Colors.white,
          ),
        ),
      ),
    );
  }
}

The result of the code is this
enter image description here

I need help to anyone who can solve this issue of mine. Thank you


问:
Best way to accept multiple tcp clients?
I have a client/server infrastructure. At present they use a TcpClient and TcpListener to send a receive data between all the clients and server.

What I currently do is when data is received (on it's own thread), it is put in a queue for another thread to process in order to free the socket so it is ready and open to receive new data.

```<code>                // Enter the listening loop.
                while (true)
                {
                    Debug.WriteLine("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    using (client = server.AcceptTcpClient())
                    {
                        data = new List<byte>();

                        // Get a stream object for reading and writing
                        using (NetworkStream stream = client.GetStream())
                        {
                            // Loop to receive all the data sent by the client.
                            int length;

                            while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                            {
                                var copy = new byte[length];
                                Array.Copy(bytes, 0, copy, 0, length);
                                data.AddRange(copy);
                            }
                        }
                    }

                    receivedQueue.Add(data);
                }
</code>```

However I wanted to find out if there is a better way to do this. For example if there are 10 clients and they all want to send data to the server at the same time, one will get through while all the others will fail.Or if one client has a slow connection and hogs the socket all other communication will halt.

Is there not some way to be able to receive data from all clients at the same time and add the received data in the queue for processing when it has finished downloading?

答:
You should use asynchronous method of reading the data, an example is:

```<code>// Enter the listening loop.
while (true)
{
    Debug.WriteLine("Waiting for a connection... ");

    client = server.AcceptTcpClient();

    ThreadPool.QueueUserWorkItem(new WaitCallback(HandleTcp), client);
}

private void HandleTcp(object tcpClientObject)
{
    TcpClient client = (TcpClient)tcpClientObject;
    // Perform a blocking call to accept requests.

    data = new List<byte>();

    // Get a stream object for reading and writing
    using (NetworkStream stream = client.GetStream())
    {
        // Loop to receive all the data sent by the client.
        int length;

        while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
        {
            var copy = new byte[length];
            Array.Copy(bytes, 0, copy, 0, length);
            data.AddRange(copy);
        }
    }

    receivedQueue.Add(data);
}
</code>```

Also you should consider using AutoResetEvent or ManualResetEvent to be notified when new data is added to the collection so the thread that handle the data will know when data is received, and if you are using 4.0 you better switch off to using BlockingCollection instead of Queue.

ContentLicense: CC BY-SA 3.0

Body:
I have a client/server infrastructure. At present they use a TcpClient and TcpListener to send a receive data between all the clients and server.

What I currently do is when data is received (on it's own thread), it is put in a queue for another thread to process in order to free the socket so it is ready and open to receive new data.

                // Enter the listening loop.
                while (true)
                {
                    Debug.WriteLine("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    using (client = server.AcceptTcpClient())
                    {
                        data = new List<byte>();

                        // Get a stream object for reading and writing
                        using (NetworkStream stream = client.GetStream())
                        {
                            // Loop to receive all the data sent by the client.
                            int length;

                            while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                            {
                                var copy = new byte[length];
                                Array.Copy(bytes, 0, copy, 0, length);
                                data.AddRange(copy);
                            }
                        }
                    }

                    receivedQueue.Add(data);
                }

However I wanted to find out if there is a better way to do this. For example if there are 10 clients and they all want to send data to the server at the same time, one will get through while all the others will fail.Or if one client has a slow connection and hogs the socket all other communication will halt.

Is there not some way to be able to receive data from all clients at the same time and add the received data in the queue for processing when it has finished downloading?

Body:
You should use asynchronous method of reading the data, an example is:

// Enter the listening loop.
while (true)
{
    Debug.WriteLine("Waiting for a connection... ");

    client = server.AcceptTcpClient();

    ThreadPool.QueueUserWorkItem(new WaitCallback(HandleTcp), client);
}

private void HandleTcp(object tcpClientObject)
{
    TcpClient client = (TcpClient)tcpClientObject;
    // Perform a blocking call to accept requests.

    data = new List<byte>();

    // Get a stream object for reading and writing
    using (NetworkStream stream = client.GetStream())
    {
        // Loop to receive all the data sent by the client.
        int length;

        while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
        {
            var copy = new byte[length];
            Array.Copy(bytes, 0, copy, 0, length);
            data.AddRange(copy);
        }
    }

    receivedQueue.Add(data);
}

Also you should consider using AutoResetEvent or ManualResetEvent to be notified when new data is added to the collection so the thread that handle the data will know when data is received, and if you are using 4.0 you better switch off to using BlockingCollection instead of Queue.


问:
Count the number of object
I am using below code to print the obj.key, however I want to count the number of objects generated. Could you please help?

Code used:

```<code>for obj in buck.objects.filter(Prefix=recent_ocr_path):
 if obj.size > 0:  # Verifying presence of files
  print(obj.key)
</code>```

Output received using above command:

```<code>Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-00-4594cf63
Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-04-82b265de
Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-07-66179192
Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-11-713879f1
</code>```

I am looking for command to display output as "4".

答:
```<code>#use can use the gt filter for size and use count method
bucks=buck.objects.filter(Prefix=recent_ocr_path, size__gt=0)
count=bucks.count()
print(count)
</code>```

Title: Count the number of object

Body:
I am using below code to print the obj.key, however I want to count the number of objects generated. Could you please help?

Code used:

for obj in buck.objects.filter(Prefix=recent_ocr_path):
 if obj.size > 0:  # Verifying presence of files
  print(obj.key)

Output received using above command:

Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-00-4594cf63
Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-04-82b265de
Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-07-66179192
Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-11-713879f1

I am looking for command to display output as "4".


问:
Is it possible to run a Cookiecutter template file without creating the local folder?
When I use cookiecutter, especially in the first phases of the project, I find myself debugging the instantiated copy of the template, finding the problem, and then having to go back to the template to fix it there as well.

This all feels redundant, and I feel that if it was possible to run the template files without physically coping them and instantiating them everytime I change something would make the development much faster.

Is there any way to test the cookiecutter template files without instantiating the project?

答:
Unfortunately you cannot do this otherwise and there is a good reason to be that way: The errors, you may find, may be just errors in your code, but may be caused by the values, provided by the user, or the defaults you provided in the cookiecutter.json, or the way you use those in your templates...

What I do in your situation is the following:
I don't template my project at the very beginning. I am writing the code just the way it is without cookiecutter. On the way, I am writing down notes what I want to put in the template. I am marking what should be turned into variable, what should be the default value, variable file and foldernames, etc.

When I am done with my bootstrap and I think it is good enough to fire version 1.0, I start templating it after my notes and then test the template one more time to ensure that I haven't missed something.

Yes, after that point, you will have to evolve the template and you won't be able to avoid this redundant testing, but it is not so intensive as at the beginning.


问:
How to center tabs in MaterialTopTabNavigator in ReactNative
I added tabStyle: { width: "auto" } to fit the tabs of MaterialTopTabNavigator to the width of the text, but by adding this, the tabs are moved to the left side as shown in the image below.

Tabs are too far to the left.

The answer to this question says to remove tabStyle, but if I remove tabStyle, all tabs will have the same width.

I thought about using my own component in the tabBar, but I gave up because I couldn't reproduce the animation when moving the tab.

I thought about using paddingHorizontal to force it to be centered, but I decided against it because it might not be centered if the font size is changed in the OS.

If you know more about this, please let me know how to solve it.

The design I want to implement (edited in Paint)

```<code>import { View, Text, StyleSheet, Button, SafeAreaView } from "react-native";
import React, { useRef } from "react";
import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs";

const Tab = createMaterialTopTabNavigator();

const Page = () => {
  return (
        <Tab.Navigator
          tabBarOptions={{
            labelStyle: {
              fontSize: 14,
              fontWeight: "bold",
            },
            activeTintColor: "#ffffff",
            inactiveTintColor: "#000000",
            pressOpacity: 1,
            indicatorStyle: {
              backgroundColor: "black",
              height: 30,
              borderRadius: 30,
              top: 9,
            },
            tabStyle: {
              width: "auto",
            },
          }}
        >
          <Tab.Screen name="Home" component={Home} />
          <Tab.Screen name="Message" component={Message} />
          <Tab.Screen name="Store" component={Store} />
        </Tab.Navigator>
  );
};

export default Page;

</code>```

答:
I think this should definitely work. If not, let me know.</p>
```<code>import { View, Text, StyleSheet, Button, SafeAreaView } from "react-native";
import React, { useRef } from "react";
import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs";

const Tab = createMaterialTopTabNavigator();

const Page = () => {
  return (
        <Tab.Navigator
          tabBarOptions={{
            labelStyle: {
              fontSize: 14,
              fontWeight: "bold",
            },
            activeTintColor: "#ffffff",
            inactiveTintColor: "#000000",
            pressOpacity: 1,
            indicatorStyle: {
              backgroundColor: "black",
              height: 30,
              borderRadius: 30,
              top: 9,
            },
            tabStyle: {
              width: "auto",
            },
          }}
        >
          <View style={{flexDirection:"row", justifyContent:"center"}}>
          <View>
          <Tab.Screen name="Home" component={Home} />
          <Tab.Screen name="Message" component={Message} />
          <Tab.Screen name="Store" component={Store} />
          </View>
          </View>

          // If the above does not work than use the below one and comment the above part

        //  <View style={{flexDirection:"row", justifyContent:"center"}}>
        //  <Tab.Screen name="Home" component={Home} />
        //  <Tab.Screen name="Message" component={Message} />
        //  <Tab.Screen name="Store" component={Store} />
        //  </View>

        </Tab.Navigator>
  );
};
</code>```

Body:
I added tabStyle: { width: "auto" } to fit the tabs of MaterialTopTabNavigator to the width of the text, but by adding this, the tabs are moved to the left side as shown in the image below.

Tabs are too far to the left.

The answer to this question says to remove tabStyle, but if I remove tabStyle, all tabs will have the same width.

I thought about using my own component in the tabBar, but I gave up because I couldn't reproduce the animation when moving the tab.

I thought about using paddingHorizontal to force it to be centered, but I decided against it because it might not be centered if the font size is changed in the OS.

If you know more about this, please let me know how to solve it.

The design I want to implement (edited in Paint)

import { View, Text, StyleSheet, Button, SafeAreaView } from "react-native";
import React, { useRef } from "react";
import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs";

const Tab = createMaterialTopTabNavigator();

const Page = () => {
  return (
        <Tab.Navigator
          tabBarOptions={{
            labelStyle: {
              fontSize: 14,
              fontWeight: "bold",
            },
            activeTintColor: "#ffffff",
            inactiveTintColor: "#000000",
            pressOpacity: 1,
            indicatorStyle: {
              backgroundColor: "black",
              height: 30,
              borderRadius: 30,
              top: 9,
            },
            tabStyle: {
              width: "auto",
            },
          }}
        >
          <Tab.Screen name="Home" component={Home} />
          <Tab.Screen name="Message" component={Message} />
          <Tab.Screen name="Store" component={Store} />
        </Tab.Navigator>
  );
};

export default Page;

Body:
I think this should definitely work. If not, let me know.

import { View, Text, StyleSheet, Button, SafeAreaView } from "react-native";
import React, { useRef } from "react";
import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs";

const Tab = createMaterialTopTabNavigator();

const Page = () => {
  return (
        <Tab.Navigator
          tabBarOptions={{
            labelStyle: {
              fontSize: 14,
              fontWeight: "bold",
            },
            activeTintColor: "#ffffff",
            inactiveTintColor: "#000000",
            pressOpacity: 1,
            indicatorStyle: {
              backgroundColor: "black",
              height: 30,
              borderRadius: 30,
              top: 9,
            },
            tabStyle: {
              width: "auto",
            },
          }}
        >
          <View style={{flexDirection:"row", justifyContent:"center"}}>
          <View>
          <Tab.Screen name="Home" component={Home} />
          <Tab.Screen name="Message" component={Message} />
          <Tab.Screen name="Store" component={Store} />
          </View>
          </View>

          // If the above does not work than use the below one and comment the above part

        //  <View style={{flexDirection:"row", justifyContent:"center"}}>
        //  <Tab.Screen name="Home" component={Home} />
        //  <Tab.Screen name="Message" component={Message} />
        //  <Tab.Screen name="Store" component={Store} />
        //  </View>

        </Tab.Navigator>
  );
};


问:
Get-Help is not seeing the MAML help files when used against commands in my module
I've been trying to improve our PS documentation and started playing with PlatyPS. So far, it's been great, I have nice markdown docs now. I'm also able to generate MAML for use with CLI documentation from it and have been able to remove the doc-comment strings from my modules.

Unfortunately, when I import my module it's unable to see the MAML help files and Get-Help for my exported function is very barebones.

My understanding is that when packaging MAML within a module, they need to be placed as follows:

```<code>MyModuleName/
  |_ en-US/
     |_ MyModuleName-help.xml
</code>```

However, I have done this, but I am still unable to see the proper help documentation from the command line with Get-Help or -?. This is my first foray into using external help documentation that doesn't use doc-comments, so I'm hoping I'm missing a step or making a MAML beginner's mistake.

答:
As it turns out, I was hitting a problem when generating the MAML from the markdown source. I was following this guide to PlatyPS and New-ExternalHelp was not generating help for the commands I happened to be testing with.

These commands were not named with the Verb-Noun nomenclature, and the files shared a name with their matching function. I took one of the functions and gave it a Verb-Noun name instead and did the same with its corresponding .md file. With a pattern of Verb-Noun.md, New-ExternalHelp now generated the command's MAML and placed them inside of MyModuleName-help.xml.

However, this is not what I wanted. These particular functions are named like commands on purpose, and I do not want to follow the Verb-Noun nomenclature for them. An edge case, probably, but I did find a solution for this as well. After a bit of testing, only the command name in the source .md file for that command matters as far as MAML generation.

The filename needs to match the Verb-Noun.md pattern, but you can have the command called FunctionName inside and the help will generate correctly for the command FunctionName, not Verb-Noun. Now when I import the module, I get the correct help topic for the commands that were previously missing.

Now my .md file no longer matches the command name but that isn't the end of the world.

Body:
I've been trying to improve our PS documentation and started playing with PlatyPS. So far, it's been great, I have nice markdown docs now. I'm also able to generate MAML for use with CLI documentation from it and have been able to remove the doc-comment strings from my modules.

Unfortunately, when I import my module it's unable to see the MAML help files and Get-Help for my exported function is very barebones.

My understanding is that when packaging MAML within a module, they need to be placed as follows:

MyModuleName/
  |_ en-US/
     |_ MyModuleName-help.xml

However, I have done this, but I am still unable to see the proper help documentation from the command line with Get-Help or -?. This is my first foray into using external help documentation that doesn't use doc-comments, so I'm hoping I'm missing a step or making a MAML beginner's mistake.


问:
How to plot many lines from stacked dataframe column in one plot? [python]
I have a dataframe that looks like this:

```<code>                timestamp       Value       Color
--------------------------------------------------
 0    2018-03-04 07:11:08          34         Red
 1    2018-03-04 07:11:09          34         Red
 2    2018-03-04 07:11:10          35         Red
 3    2018-03-04 07:11:12          36         Red
 4    2018-03-04 07:11:14          24         Red
 5    2018-03-04 07:11:15          34         Red
...
55    2018-03-04 07:12:17          34        Blue
56    2018-03-04 07:12:18          35        Blue
57    2018-03-04 07:12:19          36        Blue
58    2018-03-04 07:12:20          37        Blue
59    2018-03-04 07:12:21          35        Blue
60    2018-03-04 07:12:22          32        Blue
</code>```

And so over the course of 60 seconds, for each time stamp, there is a value recorded, but the values are split between two colors, Red and Blue. And so, within this dataframe we see time series curves for two different curves occurring at different times, one after the other, and not overlapping. What I want to do is plot them. However, I want to ignore the timestamps, so that it is assumed they start at the same time, and so just treating each color as an array of ordered values, ignoring time skips and assuming equally spaced time intervals. I simply want to plot the Red curve and the Blue curve on the same chart. How can this be done in python?
I am trying simply

```<code>plt.plot(Blue, Red)
</code>```

Though I am not sure how to account for the x-axis, which I simply want to be seconds.

Body:
I have a dataframe that looks like this:

                timestamp       Value       Color
--------------------------------------------------
 0    2018-03-04 07:11:08          34         Red
 1    2018-03-04 07:11:09          34         Red
 2    2018-03-04 07:11:10          35         Red
 3    2018-03-04 07:11:12          36         Red
 4    2018-03-04 07:11:14          24         Red
 5    2018-03-04 07:11:15          34         Red
...
55    2018-03-04 07:12:17          34        Blue
56    2018-03-04 07:12:18          35        Blue
57    2018-03-04 07:12:19          36        Blue
58    2018-03-04 07:12:20          37        Blue
59    2018-03-04 07:12:21          35        Blue
60    2018-03-04 07:12:22          32        Blue

And so over the course of 60 seconds, for each time stamp, there is a value recorded, but the values are split between two colors, Red and Blue. And so, within this dataframe we see time series curves for two different curves occurring at different times, one after the other, and not overlapping. What I want to do is plot them. However, I want to ignore the timestamps, so that it is assumed they start at the same time, and so just treating each color as an array of ordered values, ignoring time skips and assuming equally spaced time intervals. I simply want to plot the Red curve and the Blue curve on the same chart. How can this be done in python?
I am trying simply

plt.plot(Blue, Red)

Though I am not sure how to account for the x-axis, which I simply want to be seconds.

Body:
df = pandas.DataFrame({
            'times':list(pandas.date_range('2020-01-01',periods=10,freq='15T')) +
                    list(pandas.date_range('2020-01-01',periods=10,freq='15T')),
            'colors':['red']*10 + ['blue'] * 10,
            'value': numpy.random.randint(0,255,20)
    })

gives us something like your dataframe

                 times colors  value
0  2020-01-01 00:00:00    red    224
1  2020-01-01 00:15:00    red     47
2  2020-01-01 00:30:00    red     25
3  2020-01-01 00:45:00    red    211
4  2020-01-01 01:00:00    red     18
5  2020-01-01 01:15:00    red    119
6  2020-01-01 01:30:00    red     52
7  2020-01-01 01:45:00    red    246
8  2020-01-01 02:00:00    red     54
9  2020-01-01 02:15:00    red    156
10 2020-01-01 00:00:00   blue     42
11 2020-01-01 00:15:00   blue     55
12 2020-01-01 00:30:00   blue    151
13 2020-01-01 00:45:00   blue    236
14 2020-01-01 01:00:00   blue    207
15 2020-01-01 01:15:00   blue    165
16 2020-01-01 01:30:00   blue    131
17 2020-01-01 01:45:00   blue    199
18 2020-01-01 02:00:00   blue    247
19 2020-01-01 02:15:00   blue     61

we can pivot this using

 df2 = df.pivot(index='times',columns=['colors'],values=['value'])

which gives us

                        value
colors               blue  red
times
2020-01-01 00:00:00    70  225
2020-01-01 00:15:00   162   78
2020-01-01 00:30:00   188   37
2020-01-01 00:45:00   134  234
2020-01-01 01:00:00    46   73
2020-01-01 01:15:00    76   60
2020-01-01 01:30:00   143   61
2020-01-01 01:45:00   150  198
2020-01-01 02:00:00    82  159
2020-01-01 02:15:00   127   94

now we can easily just plot it...

df2.plot()
pyplot.show()

you can drop the value part of the column name with

df2 = df2.droplevel(0,axis=1)
df2.plot()
pyplot.show()

The other option is to just call it individually

BLUE = df[df['colors'] == 'blue']
RED = df[df['colors'] == 'red']
pyplot.plot(BLUE['times'],BLUE['value'])
pyplot.plot(RED['times'],RED['value'])
pyplot.show()

you could use pandas groupby also (dont do this one probably :P )

def plot_it(group,values):
    pyplot.plot(values['times'],values['value'])
df.groupby(['colors']).apply(plot_it)
pyplot.show()

but really the "right" way to handle it is probably the first option
(to pivot it to the shape you want)

---- Edit (based on comments) ----

if you dont want the months and to just treat it as a list of y values, just use range as your x

BLUE = df[df['colors'] == 'blue']
RED = df[df['colors'] == 'red']
pyplot.plot(range(len(BLUE)),BLUE['value'])
pyplot.plot(range(len(RED)),RED['value'])
pyplot.show()


问:
Send email from .NET Core using Microsoft 365 Family subscription
I have an Office 365 Family subscription (thus using outlook.com) and are trying to send email from a C# application I'm working on. Does anybody know if this is even possible?
From my research there seems to be a lot of people having issue with this approach but I'm trying hard to find out if it's supported</p>

答: And for anybody else having problems with using smtp.office365.com and sending email through code. You need to add an "app password" in your Microsoft Account. The regular password you use to login to outlook.com will not work</p>


问:
Flutter compileSdkVersion 31 cause "BluetoothAdapter has been deprecated"
I changed SDK Version to 31 and cause the following error. I tried to update the ServiceManager.java according to this link BluetoothAdapter deprecated but it does not work.

How can I solve this error? Please help

答:
These steps solve the problem

Delete pubspec.lock

Run flutter pub cache repair

Run flutter pub get


问:
Snackbar action gets null pointer after moving to another fragment
Fragment A invokes a snackbar with an action button. When user clicks action, it starts new activity with intent.
It's working fine. However, if the user moves to Fragment B while snackbar keeps appearing, then press action button, now it doesn't start new activity but crash.

How can I prevent crashing in this situation and make intent workable?
here is my code.
fragment A

```<code>binding.theButton.setOnClickListener {

    val proSnack = Snackbar.make(view!!, activity!!.getString(R.string.this_is_pro_function), Snackbar.LENGTH_LONG)
    proSnack.setAction(R.string.check, View.OnClickListener {
        activity!!.startActivity(Intent(activity, ProActivity::class.java))
    })
    proSnack.show()

    }
}

binding.backText.setOnClickListener{
    activity?.supportFragmentManager?.popBackStackImmediate()
}
</code>```

答:
```<code> activity!!.startActivity(Intent(activity, ProActivity::class.java))
</code>```

The problem is here. You can check activity. It is null. Using !! is a bad practice. You can change it to

```<code>activity?.startActivity(Intent(activity, ProActivity::class.java))
</code>```

But the activity is null. It does not open a new activity

Body:
Fragment A invokes a snackbar with an action button. When user clicks action, it starts new activity with intent.
It's working fine. However, if the user moves to Fragment B while snackbar keeps appearing, then press action button, now it doesn't start new activity but crash.

How can I prevent crashing in this situation and make intent workable?
here is my code.
fragment A

binding.theButton.setOnClickListener {

    val proSnack = Snackbar.make(view!!, activity!!.getString(R.string.this_is_pro_function), Snackbar.LENGTH_LONG)
    proSnack.setAction(R.string.check, View.OnClickListener {
        activity!!.startActivity(Intent(activity, ProActivity::class.java))
    })
    proSnack.show()

    }
}

binding.backText.setOnClickListener{
    activity?.supportFragmentManager?.popBackStackImmediate()
}

Body:
 activity!!.startActivity(Intent(activity, ProActivity::class.java))

The problem is here. You can check activity. It is null. Using !! is a bad practice. You can change it to

activity?.startActivity(Intent(activity, ProActivity::class.java))

But the activity is null. It does not open a new activity


问:
List the updated files without using go build again
I am just starting with Go. I've a question regarding gorilla/mux.

I am trying to list out the files inside a directory; and the response will be sent back from GET request to list the files.
Now, when I create a new file inside directory; the GET request doesn't list the new file.
I understand I need to run go build again. Can I do it without building it again ?

```<code>type Images struct {
    Image     string `json:"image"`
    Path      string `json:"path"`
    Timestamp string `json:"timestamp"`
    Labels    string `json:"labels"`
    Version   string `json:"version"`
}

var images []Images

func getImages(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(images)
}

func main() {
    r := mux.NewRouter()

    files, err := ioutil.ReadDir(os.Args[1])

    if err != nil {
        log.Fatal(err)
    }

    for _, file := range files {
        images = append(images, Images{Image: file.Name(), Path: os.Args[1]})
    }
    fmt.Println(images)

    // Route handles & endpoints
    r.HandleFunc("/images", getImages).Methods("GET")

    log.Fatal(http.ListenAndServe(":8080", r))
}
</code>```

答:
The application reads the list of files at startup. To update the list of files, you must restart the application.  You do not need to run go build to get an updated list of files.

To get an up-to-date list of files on every request, read the list of files in the request handler function:

```<code>func getImages(w http.ResponseWriter, r *http.Request) {
    files, err := ioutil.ReadDir(os.Args[1])
    if err != nil {
        http.Error(w, "Internal server error", 500)
        return
    }

    var images []Images
    for _, file := range files {
        images = append(images, Images{Image: file.Name(), Path: os.Args[1]})
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(images)
}
</code>```

Remove the corresponding code from main() and the images package-level variable.

Body:
I am just starting with Go. I've a question regarding gorilla/mux.

I am trying to list out the files inside a directory; and the response will be sent back from GET request to list the files.
Now, when I create a new file inside directory; the GET request doesn't list the new file.
I understand I need to run go build again. Can I do it without building it again ?

type Images struct {
    Image     string `json:"image"`
    Path      string `json:"path"`
    Timestamp string `json:"timestamp"`
    Labels    string `json:"labels"`
    Version   string `json:"version"`
}

var images []Images

func getImages(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(images)
}

func main() {
    r := mux.NewRouter()

    files, err := ioutil.ReadDir(os.Args[1])

    if err != nil {
        log.Fatal(err)
    }

    for _, file := range files {
        images = append(images, Images{Image: file.Name(), Path: os.Args[1]})
    }
    fmt.Println(images)

    // Route handles & endpoints
    r.HandleFunc("/images", getImages).Methods("GET")

    log.Fatal(http.ListenAndServe(":8080", r))
}

Body:
The application reads the list of files at startup. To update the list of files, you must restart the application.  You do not need to run go build to get an updated list of files.

To get an up-to-date list of files on every request, read the list of files in the request handler function:

func getImages(w http.ResponseWriter, r *http.Request) {
    files, err := ioutil.ReadDir(os.Args[1])
    if err != nil {
        http.Error(w, "Internal server error", 500)
        return
    }

    var images []Images
    for _, file := range files {
        images = append(images, Images{Image: file.Name(), Path: os.Args[1]})
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(images)
}

Remove the corresponding code from main() and the images package-level variable.


问:
Can't get Boost C++ Libraries to work in an AWS Linux Environment
I am trying to transfer a C++ project started by a colleague to a AWS Cloud9 environment.The project was originally developed on Mac and makes use of the Boost library.

I've set up the AWS Cloud9 environment to use Amazon Linux. Once the environment created I import the project using the "Upload Local Folder" function.

The project is uploaded in the environment/projectName path.

I think try to install boost on the environment. I run the following commands to download boost

```<code>sudo yum install boost
sudo yum install boost-devel
</code>```

I checked and boost is present at the following filepath:

```<code>/usr/include/boost
</code>```

However, when I try to compile my code, I get a series of errors along the line of:

```<code> lib/Category.h:12:10: fatal error: boost/container_hash/hash.hpp: No such file or directory
 #include <boost/container_hash/hash.hpp>
</code>```

The makefile used has the -Ilib and -lboost_program_option flags. I've been looking for what they mean to no success.

I use g++.

I've tried including the -I and pointing to the boost path to no success. I have the feeling it can be due to an include path.

Thanks!

答:
Amazon Linux 2 has boost 1.53. This is too old, and container_hash has not been yet available.

You have to manually build newer version of boost.

Body:
I am trying to transfer a C++ project started by a colleague to a AWS Cloud9 environment.The project was originally developed on Mac and makes use of the Boost library.

I've set up the AWS Cloud9 environment to use Amazon Linux. Once the environment created I import the project using the "Upload Local Folder" function.

The project is uploaded in the environment/projectName path.

I think try to install boost on the environment. I run the following commands to download boost

sudo yum install boost
sudo yum install boost-devel

I checked and boost is present at the following filepath:

/usr/include/boost

However, when I try to compile my code, I get a series of errors along the line of:

 lib/Category.h:12:10: fatal error: boost/container_hash/hash.hpp: No such file or directory
 #include <boost/container_hash/hash.hpp>

The makefile used has the -Ilib and -lboost_program_option flags. I've been looking for what they mean to no success.

I use g++.

I've tried including the -I and pointing to the boost path to no success. I have the feeling it can be due to an include path.

Thanks!


问:
Multiple Windows using window.open()
So as we all know if you click on a submit button that has embedded in it a onClick(windown.open(...)) this opens a new window with all the lovely attributes you specify. However if then proceed to click on the parent window and again click on the 'submit' button without closing the previous popup window, then that same window is overwritten with the new data.

Now I need a way for that window.open() script to create new windows every time it is clicked. SO in theory I could click the parent "submit" button 2 consecutive times and have 2 different child windows appear.

I'm sure it's trivial but I can't seem to find anything.

答: In my case, the browser was blocking the pop-up window. I just allowed it to open the pop-up window.

Title: Multiple Windows using window.open()


问:
How do I get rid of the unknown property name errors in Visual Studio?
When using jQuery UI and ThemeRoller the CSS files created contain several CSS properties that are not known by Visual Studio, such as zoom and opacity.  How can I keep these from showing up as errors in the error list when the CSS file is open in the editor pane?

In the spirit of SO, I'll add the solution I found as a response.

答: Go to Tools --> Options --> Text Editor --> CSS --> CSS Specific (or Validation) and uncheck the Detect unknown properties checkbox.

OwnerDisplayName: tvanfosson

ContentLicense: CC BY-SA 2.5


问:
Printf Problem with While Loop
I'm creating a temperature converter in C. Basically, you input a minimum and maximum value in degrees Celsius, along with a step, and it displays that information in a list, along with the Fahrenheit equivalent. On some occasions, I have noticed the last Fahrenheit entry not being displayed when it should. For example, when you input a lower limit of 10, a higher limit of 30, and a step of 4, it cuts off the last Fahrenheit temperature. I know it's something to do with the last while loop, but I just can't figure it out.</p>

```<code>#include <stdio.h>

int main (int argc, const char * argv[]) {
double l, h, s;
double lf, hf, sf;
/* Number rows in tables */
int num1, num2;
num1 = 1;
num2 = 1;

/* Lower limit input */
printf("Please give a lower limit: ");
scanf("%4lf", &l);
while (l < 0) {
        printf("Lower limit must be greater than 0: ");
        scanf("%4lf", &l);
}

/* Stores value for Fahrenheit conversion */
lf = l;

/* Higher limit input */
printf("Please give a higher limit: ");
scanf("%4lf", &h);
while (h <= l) {
        printf("Higher limit must be greater than lower limit: ");
        scanf("%4lf", &h);
}

while (h >= 50000) {
        printf("Higher limit must be less than 50000: ");
        scanf("%4lf", &h);
}

hf = h;

/* Step input */
printf("Please input step: ");
scanf("%4lf", &s);
while (s <= 0) {
        printf("Step must be greater than 0: ");
        scanf("%4lf", &s);
}

while (s >= h - l) {
        printf("Step must be less than the difference in temperatures: ");
        scanf("%4lf", &s);
}

sf = s;

/* Celsius table */
printf("\nCelsius\n-------\n");
while (l <= h) {
    printf("%i. %4lf\n", num1, l);
    num1++;
    l = l + s;
}

/* Fahrenheit table */
printf("\nFahrenheit\n----------\n");
/* Converts Celsius to Fahrenheit */
lf = (lf * 1.8) + 32;
hf = (hf * 1.8) + 32;
sf = sf * 1.8;
printf("Lower input: %4lf\n", lf);
printf("Higher input: %4lf\n", hf);
printf("Step: %4lf\n----------\n", sf);
/* This while loop sometimes cuts off the last entry */
while (lf <= hf) {
    printf("%i. %4lf\n", num2, lf);
    num2++;
    lf = lf + sf;
}

return 0;

}
</code>```

答:
The problem is with comparing the doubles, you might get into a situation where something like  10 + 1.8 evaluates to 11.800000001 and thus missing the end value.

The solution to your problem would be to first calculate the number of steps:

```<code>int steps = (h - l) / s + 1; //Might want to apply rounding
</code>```

And then use a for/while loop over the integer variable instead:

```<code>for (int i = 0; i < steps; ++i) {
    double t = l + (h - l) * i / (steps - 1);
}

for (int i = 0; i < steps; ++i) {
    double tf = lf + (hf - lf) * i / (steps - 1);
}
</code>```

Title: Printf Problem with While Loop

Body:
I'm creating a temperature converter in C. Basically, you input a minimum and maximum value in degrees Celsius, along with a step, and it displays that information in a list, along with the Fahrenheit equivalent. On some occasions, I have noticed the last Fahrenheit entry not being displayed when it should. For example, when you input a lower limit of 10, a higher limit of 30, and a step of 4, it cuts off the last Fahrenheit temperature. I know it's something to do with the last while loop, but I just can't figure it out.

#include <stdio.h>

int main (int argc, const char * argv[]) {
double l, h, s;
double lf, hf, sf;
/* Number rows in tables */
int num1, num2;
num1 = 1;
num2 = 1;

/* Lower limit input */
printf("Please give a lower limit: ");
scanf("%4lf", &l);
while (l < 0) {
        printf("Lower limit must be greater than 0: ");
        scanf("%4lf", &l);
}

/* Stores value for Fahrenheit conversion */
lf = l;

/* Higher limit input */
printf("Please give a higher limit: ");
scanf("%4lf", &h);
while (h <= l) {
        printf("Higher limit must be greater than lower limit: ");
        scanf("%4lf", &h);
}

while (h >= 50000) {
        printf("Higher limit must be less than 50000: ");
        scanf("%4lf", &h);
}

hf = h;

/* Step input */
printf("Please input step: ");
scanf("%4lf", &s);
while (s <= 0) {
        printf("Step must be greater than 0: ");
        scanf("%4lf", &s);
}

while (s >= h - l) {
        printf("Step must be less than the difference in temperatures: ");
        scanf("%4lf", &s);
}

sf = s;

/* Celsius table */
printf("\nCelsius\n-------\n");
while (l <= h) {
    printf("%i. %4lf\n", num1, l);
    num1++;
    l = l + s;
}

/* Fahrenheit table */
printf("\nFahrenheit\n----------\n");
/* Converts Celsius to Fahrenheit */
lf = (lf * 1.8) + 32;
hf = (hf * 1.8) + 32;
sf = sf * 1.8;
printf("Lower input: %4lf\n", lf);
printf("Higher input: %4lf\n", hf);
printf("Step: %4lf\n----------\n", sf);
/* This while loop sometimes cuts off the last entry */
while (lf <= hf) {
    printf("%i. %4lf\n", num2, lf);
    num2++;
    lf = lf + sf;
}

return 0;

}

Body:
The problem is with comparing the doubles, you might get into a situation where something like  10 + 1.8 evaluates to 11.800000001 and thus missing the end value.

The solution to your problem would be to first calculate the number of steps:

int steps = (h - l) / s + 1; //Might want to apply rounding

And then use a for/while loop over the integer variable instead:

for (int i = 0; i < steps; ++i) {
    double t = l + (h - l) * i / (steps - 1);
}

for (int i = 0; i < steps; ++i) {
    double tf = lf + (hf - lf) * i / (steps - 1);
}


问:
SQL - Return The Greater of a Partition
I have the following table -

My goal is to return the Company/ID row with the highest "count" respective to a partition done by the ID.

So the expected output should look like this :

My current code returns a count partitioned on all ids. I just want it to return the one with the highest count.

Current code -

```<code>select distinct Company, Id, count(*) over (partition by ID)
from table1
where company in ("Facebook","Apple")
</code>```

My output:

答:
Your base query is incorrect. You partition by ID regardless of the company, but in your request comments you clarify that you want to count per ID and company. This would have to be

```<code>select distinct company, id, count(*) over (partition by company, id)
from table1
where company in ('Facebook','Apple');
</code>```

But that query boils down to be a mere aggregation and doesn't need window functions at all. It is evaluating the count for each single row, only to dismiss duplicates later with DISTINCT. DISTINCT is a costly operation, so why not simply aggregate your rows in the first place?

```<code>select company, id, count(*)
from table1
where company in ('Facebook','Apple')
group by company, id;
</code>```

Now you only want to keep the rows with the highest count per company, and this is where window functions come into play:

```<code>select  company, id, total
from
(
  select
    company,
    id,
    count(*) as total,
    max(count(*)) over (partition by company) as max_total
  from table1
  where company in ('Facebook','Apple')
  group by company, id
) aggregated
where total = max_total;
</code>```

Title: SQL - Return The Greater of a Partition

Body:
I have the following table -

My goal is to return the Company/ID row with the highest "count" respective to a partition done by the ID.

So the expected output should look like this :

My current code returns a count partitioned on all ids. I just want it to return the one with the highest count.

Current code -

select distinct Company, Id, count(*) over (partition by ID)
from table1
where company in ("Facebook","Apple")

My output:

Body:
Your base query is incorrect. You partition by ID regardless of the company, but in your request comments you clarify that you want to count per ID and company. This would have to be

select distinct company, id, count(*) over (partition by company, id)
from table1
where company in ('Facebook','Apple');

But that query boils down to be a mere aggregation and doesn't need window functions at all. It is evaluating the count for each single row, only to dismiss duplicates later with DISTINCT. DISTINCT is a costly operation, so why not simply aggregate your rows in the first place?

select company, id, count(*)
from table1
where company in ('Facebook','Apple')
group by company, id;

Now you only want to keep the rows with the highest count per company, and this is where window functions come into play:

select  company, id, total
from
(
  select
    company,
    id,
    count(*) as total,
    max(count(*)) over (partition by company) as max_total
  from table1
  where company in ('Facebook','Apple')
  group by company, id
) aggregated
where total = max_total;


问:
Non nullable instance field must be initalised
im new to Dart-flutter.

i have watching a tutorial video from udemy course writing in dart pad

so i also wrote in dartpad. but it showing error in it.

this is the code wrote in udemy..

```<code>import 'dart:convert';

 void main(){
  var rawJson = '{"url": "https://helo.com","id": 2}';
  var parsedJson = json.decode(rawJson);
  var imageModel = new ImageModel.fromJson(parsedJson);

  print(imageModel.url);
 }

class ImageModel{
  int id;
  String url;

  ImageModel.fromJson(parsedJson) {
    id = parsedJson['id'];
    url = parsedJson['url'];
  }

   ImageModel(this.id, this.url);
}
</code>```

in that video it runs, but for me it shows error as

```<code>Error compiling to JavaScript:
Info: Compiling with sound null safety
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:15:3:
Error: This constructor should initialize field 'id' because its type 'int' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:12:7:
Info: 'id' is defined here.
  int id;
      ^^
lib/main.dart:15:3:
Error: This constructor should initialize field 'url' because its type 'String' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:13:10:
Info: 'url' is defined here.
  String url;
         ^^^
Error: Compilation failed.
</code>```

i have no idea what the problem is..
can you guys help me to troubleshoot the error

答:
Try using null safe code:
eg:

int? id;
String? url;

Body:
im new to Dart-flutter.

i have watching a tutorial video from udemy course writing in dart pad

so i also wrote in dartpad. but it showing error in it.

this is the code wrote in udemy..

import 'dart:convert';

 void main(){
  var rawJson = '{"url": "https://helo.com","id": 2}';
  var parsedJson = json.decode(rawJson);
  var imageModel = new ImageModel.fromJson(parsedJson);

  print(imageModel.url);
 }

class ImageModel{
  int id;
  String url;

  ImageModel.fromJson(parsedJson) {
    id = parsedJson['id'];
    url = parsedJson['url'];
  }

   ImageModel(this.id, this.url);
}

in that video it runs, but for me it shows error as

Error compiling to JavaScript:
Info: Compiling with sound null safety
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:15:3:
Error: This constructor should initialize field 'id' because its type 'int' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:12:7:
Info: 'id' is defined here.
  int id;
      ^^
lib/main.dart:15:3:
Error: This constructor should initialize field 'url' because its type 'String' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:13:10:
Info: 'url' is defined here.
  String url;
         ^^^
Error: Compilation failed.

i have no idea what the problem is..
can you guys help me to troubleshoot the error


问:
Spring-Content 1.2.7: Identifier for the ContentStore
What I intend to do: I'd like to use multiple ContentStores in the same system: one for freshly uploaded files (filesystem), one for (long term) archiving (AWS S3 or maybe GCS).

What I tried (and what actually does work):

Extended class File by another attribute private String contentStoreName;

Creating two ContentStores like described here: Spring-Content: Moving files from content store to another content store

Extending gettingstarted.FileContentController.setContent(Long, MultipartFile) by setting an identifier for the used ContentStore: f.get().setContentStoreName("regular");

Getting the content in dependence of the stored contentStoreName:

```<code>InputStream input;
if (Objects.equals(f.get().getContentStoreName(), "archive")) {
    input = archiveContentStore.getContent(f.get());
} else {
    input = regularContentStore.getContent(f.get());
}
</code>```

Changing the contentStoreName when moving from one ContentStore to another:

```<code>Resource resource = regularContentStore.getResource(fileEntity.get());
archiveContentStore.setContent(fileEntity.get(), resource);
fileEntity.get().setContentStoreName("archive");
filesRepo.save(fileEntity.get());
</code>```

The smell about this: Despite this code works, I guess it's not the intended way, because Spring-content usually does a lot with annotations and some magic in the background. But I can't find an annotation for an identifier / name for the ContentStore.

Question: Is there a more intended way of doing this in Spring-Content?

答:
Beyond supporting multiple storage modules in a single application (via the FilesystemContentStore, et al annotations) Spring Content does not currently provide any logic for supporting classes of storage.  That would be a layer that you need to create on top of Spring Content as you are starting to do.

In terms of Spring Content annotations it might be helpful for you to understand what modules manage what annotations.

Spring Content storage modules; FS, S3, etc all implement ContentStore and in doing so all provide management of the @ContentId and @ContentLength attributes (in addition to managing the actual content operations).  Looks like you are using the ContentStore API (getContent/setContent) and therefore your entity's content id and length attributes will be managed for you.

Spring Content REST then provides management of @MimeType and @OriginalFileName attributes (in addition to providing comprehensive REST endpoints).  My guess is that you are not using this and instead providing your own custom controller REST API that uses the 'contentStoreName' attribute to decide which store to put/get the content from.  This approach seems fine.

That is all to say that a slightly more elegant approach, perhaps, that would allow you to use Spring Content REST might be to implement your own custom Archiving Storage module and encapsulate the "switching" logic you have above in its setContent/getContent/unsetContent methods.  Note, this is actually quite easy (just 4 or 5 classes and I would point you at the GCP and Azure modules for inspiration).  Note, that the REST API (for ContentStore) only calls those 3 APIs too so those are the only ones you would need to implement.  This would mean you get to use Spring Content REST and all the features it provides; set of rest endpoints, byte range support and so on as well as encapsulating your "archiving" logic nicely.

Body:
What I intend to do: I'd like to use multiple ContentStores in the same system: one for freshly uploaded files (filesystem), one for (long term) archiving (AWS S3 or maybe GCS).

What I tried (and what actually does work):

Extended class File by another attribute private String contentStoreName;

Creating two ContentStores like described here: Spring-Content: Moving files from content store to another content store

Extending gettingstarted.FileContentController.setContent(Long, MultipartFile) by setting an identifier for the used ContentStore: f.get().setContentStoreName("regular");

Getting the content in dependence of the stored contentStoreName:

InputStream input;
if (Objects.equals(f.get().getContentStoreName(), "archive")) {
    input = archiveContentStore.getContent(f.get());
} else {
    input = regularContentStore.getContent(f.get());
}

Changing the contentStoreName when moving from one ContentStore to another:

Resource resource = regularContentStore.getResource(fileEntity.get());
archiveContentStore.setContent(fileEntity.get(), resource);
fileEntity.get().setContentStoreName("archive");
filesRepo.save(fileEntity.get());

The smell about this: Despite this code works, I guess it's not the intended way, because Spring-content usually does a lot with annotations and some magic in the background. But I can't find an annotation for an identifier / name for the ContentStore.

Question: Is there a more intended way of doing this in Spring-Content?


问:
is there any way to put a right path on JAVA_HOME?
here the image show my current problem I do my best to modify the path. the path of JAVA_HOME is right but I've been confuse because that is always show up even though that I already modified it .if I try to put the directory path of my SDK it's the same error.

image link:https://i.stack.imgur.com/LeipD.png

答: Change like this in your Environment Variables.


问:
Angular + Spring Boot: Forwarding all Angular routes to Angular and all API to the Spring Controllers
I have a Spring Boot app and an Angular app. I want to serve the Angular App from the Spring Boot App. I build the Angular App and moved all files, including the index.html file, into /resources/static/ and just to be sure also to resources/public/. I also put the index.html into resources/templates.
I received 404 when calling any of the angular routes e.g. mywebsite.com/login

Then I added a controller to forward all requests to my Angular App:

```<code>@Controller
public class RedirectToAngularController {

  /**
  * Should redirect all routes to FrontEnd, but doesn't work.
  */
  @RequestMapping({"/", "/login", "/login/**"})
  public String redirectLogin() {
    log.info("Forwarding request to Angular (index.html)");
    return "forward:/index.html";
  }
}
</code>```

IntelliJ gives me a warning for "forward:/index.html" that it can't find the URL:

I still deployed my website and open it at myWebsite.com/login or myWebsite.com/confirm. Instead of my index.html file getting displayed I see forward:/index.html as a string in my browser. So it actually returns the string, not the file
In the logs "Forwarding request to Angular (index.html)" appears, but then it says: Cannot find GET /index.html in the next line.

So I deleted that controller and instead tried to solve this with a ResourceHandler:

```<code>@Configuration
public class WebAdapterConfig implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**/*")
              .addResourceLocations("classpath:/static/")
              .resourceChain(true)
              .addResolver(new PathResourceResolver() {
                @Override
                protected Resource getResource(String resourcePath, Resource location) throws IOException {
                  Resource requestedResource = location.createRelative(resourcePath);

                  return requestedResource.exists() && requestedResource.isReadable() ? requestedResource
                          : new ClassPathResource("/static/index.html");
                }
              });
    registry.setOrder(-1);
  }
}
</code>```

This was described here: Springboot/Angular2 - How to handle HTML5 urls?
and also here: https://keepgrowing.in/java/springboot/make-spring-boot-surrender-routing-control-to-angular/

But this redirects everything! I now get the index file when I open mywebsite.com/login as well as when I make a postman request to my api (e.g. GET mywebsite.com/api/users)

So I tried to narrow it down by replacing registry.addResourceHandler("/**/*") with registry.addResourceHandler("/login") or registry.addResourceHandler("/login/**", "/confirm"). But then only mywebsite.com/login/something and mywebsite.com/confirm retrun the index.html, but all other paths, including the URI for the api methods return 404!

A third approach was to add view controller:

```<code>@Configuration
public class WebAdapterConfig implements WebMvcConfigurer {

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/login").setViewName("forward:/index.html");
    registry.addViewController("/login/**").setViewName("forward:/index.html");
    registry.addViewController("/confirm").setViewName("forward:/index.html");
  }
}
</code>```

But then I always received 404 for all routes.

I also added spring web MVC to my dependencies, but this didn't seem to change anything.

```<code>dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
}
</code>```

p.s. I don't use tymeleaf as my files are coming from angular. Maybe that's why forward:/ doesn't work?

答:
Make sure no default path "/" is configured in your SpringBoot code/controller's

Ensure you are not using @EnableWebMvc annotation anywhere in your app

put all your UI files in the "../resources/public" folder (mainly your index.html shall be on this path)

This should resolve your issue's in general :)

SpringBoot automatically detects this and works well for all sorts of Single-page applications.

Body:
I have a Spring Boot app and an Angular app. I want to serve the Angular App from the Spring Boot App. I build the Angular App and moved all files, including the index.html file, into /resources/static/ and just to be sure also to resources/public/. I also put the index.html into resources/templates.
I received 404 when calling any of the angular routes e.g. mywebsite.com/login

Then I added a controller to forward all requests to my Angular App:

@Controller
public class RedirectToAngularController {

  /**
  * Should redirect all routes to FrontEnd, but doesn't work.
  */
  @RequestMapping({"/", "/login", "/login/**"})
  public String redirectLogin() {
    log.info("Forwarding request to Angular (index.html)");
    return "forward:/index.html";
  }
}

IntelliJ gives me a warning for "forward:/index.html" that it can't find the URL:

I still deployed my website and open it at myWebsite.com/login or myWebsite.com/confirm. Instead of my index.html file getting displayed I see forward:/index.html as a string in my browser. So it actually returns the string, not the file
In the logs "Forwarding request to Angular (index.html)" appears, but then it says: Cannot find GET /index.html in the next line.

So I deleted that controller and instead tried to solve this with a ResourceHandler:

@Configuration
public class WebAdapterConfig implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**/*")
              .addResourceLocations("classpath:/static/")
              .resourceChain(true)
              .addResolver(new PathResourceResolver() {
                @Override
                protected Resource getResource(String resourcePath, Resource location) throws IOException {
                  Resource requestedResource = location.createRelative(resourcePath);

                  return requestedResource.exists() && requestedResource.isReadable() ? requestedResource
                          : new ClassPathResource("/static/index.html");
                }
              });
    registry.setOrder(-1);
  }
}

This was described here: Springboot/Angular2 - How to handle HTML5 urls?
and also here: https://keepgrowing.in/java/springboot/make-spring-boot-surrender-routing-control-to-angular/

But this redirects everything! I now get the index file when I open mywebsite.com/login as well as when I make a postman request to my api (e.g. GET mywebsite.com/api/users)

So I tried to narrow it down by replacing registry.addResourceHandler("/**/*") with registry.addResourceHandler("/login") or registry.addResourceHandler("/login/**", "/confirm"). But then only mywebsite.com/login/something and mywebsite.com/confirm retrun the index.html, but all other paths, including the URI for the api methods return 404!

A third approach was to add view controller:

@Configuration
public class WebAdapterConfig implements WebMvcConfigurer {

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/login").setViewName("forward:/index.html");
    registry.addViewController("/login/**").setViewName("forward:/index.html");
    registry.addViewController("/confirm").setViewName("forward:/index.html");
  }
}

But then I always received 404 for all routes.

I also added spring web MVC to my dependencies, but this didn't seem to change anything.

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
}

p.s. I don't use tymeleaf as my files are coming from angular. Maybe that's why forward:/ doesn't work?


问:
Refactoring to Asynchrony?
I program ActionScript for the FlashPlayer. This means compiling a set of ActionScript files into a SWF file (a bunch of bytecode that gets executed by the FlashPlayer in your browser). Anything that is not compiled into the SWF file must be requested. Examples of this would include ANY textual content, media, or graphical content that wasn't originally compiled in. Unfortunately this means dealing with a lot of asynchrony. A double-edged sword since dealing with asynchrony can be a pain in the ass, but can also be a fun force? on your design.

I just want to make the point that ActionScript is single-threaded, but the FlashPlayer is multi-threaded, so things like requesting content over HTTP are done in the background and we are notified of completion via an event broadcasting system (which is built into the language). So the issue here is not a concurrency issue (although I'm interested in any concurrency literature that might be relevant).

When I'm putting together a website I will be adding in functionality a little bit at a time. A little bit at a time usually translates into small steps. And by small step I mean small enough that I don't go from needing content to loading content (e.g. XML using HTTP) in one step. So I'll use, say... Fake It, but at some point I need to implement it for real, hence my search for literature on Refactoring To Asynchrony.

Any thoughts or help would be greatly apprecated. Thanks =)

答:
There is astonishingly beautiful Reactive eXtensions for C# (all .net) and JavaScript.

It has been ported in ActionScript 3 as well and has its own wiki.

From description:
raix (Reactive And Interactive eXtensions) is a functional, composable, API for AS3 that simplifies working with data, regardless of whether its interactive (arrays) or reactive (events). raix was previously RxAs

Reactive part of it helps you to build highly asynchronous applications in simple intuitive way.

Hope it will help!

Title: Refactoring to Asynchrony?