问:
AWS Elemental MediaConvert not working with MP3 input
I am trying to use AWS Elemental MediaConvert for AOD (Audio on-demand) HLS streaming. Below is my Job description

```<code>{
    "OutputGroups": [
      {
        "CustomName": "HLS",
        "Name": "Apple HLS",
        "Outputs": [
          {
            "ContainerSettings": {
              "Container": "M3U8",
              "M3u8Settings": {
                "AudioFramesPerPes": 4,
                "PcrControl": "PCR_EVERY_PES_PACKET",
                "PmtPid": 480,
                "PrivateMetadataPid": 503,
                "ProgramNumber": 1,
                "PatInterval": 0,
                "PmtInterval": 0,
                "Scte35Source": "NONE",
                "NielsenId3": "NONE",
                "TimedMetadata": "NONE",
                "VideoPid": 481,
                "AudioPids": [
                  482,
                  483,
                  484,
                  485,
                  486,
                  487,
                  488,
                  489,
                  490,
                  491,
                  492
                ]
              }
            },
            "AudioDescriptions": [
              {
                "AudioTypeControl": "FOLLOW_INPUT",
                "AudioSourceName": "Audio Selector 1",
                "CodecSettings": {
                  "Codec": "AAC",
                  "AacSettings": {
                    "AudioDescriptionBroadcasterMix": "NORMAL",
                    "Bitrate": 96000,
                    "RateControlMode": "CBR",
                    "CodecProfile": "LC",
                    "CodingMode": "CODING_MODE_2_0",
                    "RawFormat": "NONE",
                    "SampleRate": 48000,
                    "Specification": "MPEG4"
                  }
                },
                "LanguageCodeControl": "FOLLOW_INPUT"
              }
            ],
            "OutputSettings": {
              "HlsSettings": {
                "AudioGroupId": "program_audio",
                "AudioTrackType": "AUDIO_ONLY_VARIANT_STREAM",
                "IFrameOnlyManifest": "EXCLUDE"
              }
            },
            "NameModifier": "string"
          }
        ],
        "OutputGroupSettings": {
          "Type": "HLS_GROUP_SETTINGS",
          "HlsGroupSettings": {
            "ManifestDurationFormat": "INTEGER",
            "SegmentLength": 10,
            "TimedMetadataId3Period": 10,
            "CaptionLanguageSetting": "OMIT",
            "Destination": "s3://<MEDIABUCKET>/HLS/",
            "TimedMetadataId3Frame": "PRIV",
            "CodecSpecification": "RFC_4281",
            "OutputSelection": "MANIFESTS_AND_SEGMENTS",
            "ProgramDateTimePeriod": 600,
            "MinSegmentLength": 0,
            "DirectoryStructure": "SINGLE_DIRECTORY",
            "ProgramDateTime": "EXCLUDE",
            "SegmentControl": "SEGMENTED_FILES",
            "ManifestCompression": "NONE",
            "ClientCache": "ENABLED",
            "StreamInfResolution": "INCLUDE"
          }
        }
      }
    ],
    "AdAvailOffset": 0,
    "Inputs": [
      {
        "AudioSelectors": {
          "Audio Selector 1": {
            "Offset": 0,
            "DefaultSelection": "DEFAULT",
            "ProgramSelection": 1
          }
        },
        "FilterEnable": "AUTO",
        "PsiControl": "USE_PSI",
        "FilterStrength": 0,
        "DeblockFilter": "DISABLED",
        "DenoiseFilter": "DISABLED",
        "TimecodeSource": "EMBEDDED",
        "FileInput": "s3://kg-media-test/inputs/test_audio.mp4"
      }
    ]
}
</code>```

But whenever I am giving an MP3 file as input it's throwing below error -

```<code>Exception: An error occurred (BadRequestException) when calling the CreateJob operation: /inputs/0/fileInput:
Should match the pattern: /^(http|https|s3)://([^/]+/)+([^/\.]+|(([^/]*)\.([mM]2[vV]|[mM][pP][eE][gG]|[aA][vV][iI]|[mM][pP]4|[fF][lL][vV]|[mM][pP][tT]|[mM][pP][gG]|[mM]4[vV]|[tT][rR][pP]|[fF]4[vV]|[mM]2[tT][sS]|[tT][sS]|264|[hH]264|[mM][kK][vV]|[mM][oO][vV]|[mM][tT][sS]|[mM]2[tT]|[wW][mM][vV]|[aA][sS][fF]|[vV][oO][bB]|3[gG][pP]|3[gG][pP][pP]|[mM][xX][fF]|[dD][iI][vV][xX]|[xX][vV][iI][dD]|[rR][aA][wW]|[dD][vV]|[gG][xX][fF]|[mM]1[vV]|3[gG]2|[vV][mM][fF]|[mM]3[uU]8|[wW][eE][bB][mM]|[lL][cC][hH]|[gG][xX][fF]_[mM][pP][eE][gG]2|[mM][xX][fF]_[mM][pP][eE][gG]2|[mM][xX][fF][hH][dD]|[wW][aA][vV]|[yY]4[mM]|[xX][mM][lL])))$/
</code>```

It looks like there is a Regex validation on the input file name and MP3 files are not allowed. But according to this documentation, MP3 is a valid input file.

If I convert that MP3 file to an MP4 file and then try then the job is producing HLS without any error.

What I am missing here?

答:
This is of course very late but your json has this.

```<code>"Destination": "s3://<MEDIABUCKET>/HLS/",
</code>```

It was probably your issue.

Body:
I am trying to use AWS Elemental MediaConvert for AOD (Audio on-demand) HLS streaming. Below is my Job description

{
    "OutputGroups": [
      {
        "CustomName": "HLS",
        "Name": "Apple HLS",
        "Outputs": [
          {
            "ContainerSettings": {
              "Container": "M3U8",
              "M3u8Settings": {
                "AudioFramesPerPes": 4,
                "PcrControl": "PCR_EVERY_PES_PACKET",
                "PmtPid": 480,
                "PrivateMetadataPid": 503,
                "ProgramNumber": 1,
                "PatInterval": 0,
                "PmtInterval": 0,
                "Scte35Source": "NONE",
                "NielsenId3": "NONE",
                "TimedMetadata": "NONE",
                "VideoPid": 481,
                "AudioPids": [
                  482,
                  483,
                  484,
                  485,
                  486,
                  487,
                  488,
                  489,
                  490,
                  491,
                  492
                ]
              }
            },
            "AudioDescriptions": [
              {
                "AudioTypeControl": "FOLLOW_INPUT",
                "AudioSourceName": "Audio Selector 1",
                "CodecSettings": {
                  "Codec": "AAC",
                  "AacSettings": {
                    "AudioDescriptionBroadcasterMix": "NORMAL",
                    "Bitrate": 96000,
                    "RateControlMode": "CBR",
                    "CodecProfile": "LC",
                    "CodingMode": "CODING_MODE_2_0",
                    "RawFormat": "NONE",
                    "SampleRate": 48000,
                    "Specification": "MPEG4"
                  }
                },
                "LanguageCodeControl": "FOLLOW_INPUT"
              }
            ],
            "OutputSettings": {
              "HlsSettings": {
                "AudioGroupId": "program_audio",
                "AudioTrackType": "AUDIO_ONLY_VARIANT_STREAM",
                "IFrameOnlyManifest": "EXCLUDE"
              }
            },
            "NameModifier": "string"
          }
        ],
        "OutputGroupSettings": {
          "Type": "HLS_GROUP_SETTINGS",
          "HlsGroupSettings": {
            "ManifestDurationFormat": "INTEGER",
            "SegmentLength": 10,
            "TimedMetadataId3Period": 10,
            "CaptionLanguageSetting": "OMIT",
            "Destination": "s3://<MEDIABUCKET>/HLS/",
            "TimedMetadataId3Frame": "PRIV",
            "CodecSpecification": "RFC_4281",
            "OutputSelection": "MANIFESTS_AND_SEGMENTS",
            "ProgramDateTimePeriod": 600,
            "MinSegmentLength": 0,
            "DirectoryStructure": "SINGLE_DIRECTORY",
            "ProgramDateTime": "EXCLUDE",
            "SegmentControl": "SEGMENTED_FILES",
            "ManifestCompression": "NONE",
            "ClientCache": "ENABLED",
            "StreamInfResolution": "INCLUDE"
          }
        }
      }
    ],
    "AdAvailOffset": 0,
    "Inputs": [
      {
        "AudioSelectors": {
          "Audio Selector 1": {
            "Offset": 0,
            "DefaultSelection": "DEFAULT",
            "ProgramSelection": 1
          }
        },
        "FilterEnable": "AUTO",
        "PsiControl": "USE_PSI",
        "FilterStrength": 0,
        "DeblockFilter": "DISABLED",
        "DenoiseFilter": "DISABLED",
        "TimecodeSource": "EMBEDDED",
        "FileInput": "s3://kg-media-test/inputs/test_audio.mp4"
      }
    ]
}

But whenever I am giving an MP3 file as input it's throwing below error -

Exception: An error occurred (BadRequestException) when calling the CreateJob operation: /inputs/0/fileInput:
Should match the pattern: /^(http|https|s3)://([^/]+/)+([^/\.]+|(([^/]*)\.([mM]2[vV]|[mM][pP][eE][gG]|[aA][vV][iI]|[mM][pP]4|[fF][lL][vV]|[mM][pP][tT]|[mM][pP][gG]|[mM]4[vV]|[tT][rR][pP]|[fF]4[vV]|[mM]2[tT][sS]|[tT][sS]|264|[hH]264|[mM][kK][vV]|[mM][oO][vV]|[mM][tT][sS]|[mM]2[tT]|[wW][mM][vV]|[aA][sS][fF]|[vV][oO][bB]|3[gG][pP]|3[gG][pP][pP]|[mM][xX][fF]|[dD][iI][vV][xX]|[xX][vV][iI][dD]|[rR][aA][wW]|[dD][vV]|[gG][xX][fF]|[mM]1[vV]|3[gG]2|[vV][mM][fF]|[mM]3[uU]8|[wW][eE][bB][mM]|[lL][cC][hH]|[gG][xX][fF]_[mM][pP][eE][gG]2|[mM][xX][fF]_[mM][pP][eE][gG]2|[mM][xX][fF][hH][dD]|[wW][aA][vV]|[yY]4[mM]|[xX][mM][lL])))$/

It looks like there is a Regex validation on the input file name and MP3 files are not allowed. But according to this documentation, MP3 is a valid input file.

If I convert that MP3 file to an MP4 file and then try then the job is producing HLS without any error.

What I am missing here?

Body:
This is of course very late but your json has this.

"Destination": "s3://<MEDIABUCKET>/HLS/",

It was probably your issue.


来源: stackexchange

问:
Asp.Net Core 3 graceful shutdown throws OperationCanceledException
I'm trying to gracefully terminate a ASP.Net Core 3.1 service (which will run in Kubernetes). When Kubernetes stops a service, it will send a SIGTERM event to the application, at which point I want in-flight requests to complete (which may take several seconds) before terminating... I think I can catch this in a hostedservice, as below, and hence not stop immediately.

The following works, but with a timeout of 5 seconds or longer, I receive an OperationCanceledException. Could anyone shed any light on why I get an OperationCanceledException or how shed any light on an alternative way to delay a SIGTERM event, to allow a graceful shutdown?

```<code>    public static int Main(string[] args)
    {
        var logger = NLogBuilder
            .ConfigureNLog("nlog.config")
            .GetCurrentClassLogger();
        try
        {
            CreateHostBuilder(args)
                .ConfigureServices((hostBuilderContext, services) => { services.AddHostedService<LifetimeEventsHostedService>(); })
                .Build()
                .Run();

            return 0;
        }
        catch (Exception e)
        {
            logger.Fatal(e, "Stopping due to exception");

            return -1;
        }
        finally
        {
            LogManager.Shutdown();
        }
    }
</code>```

This is the hosted service...

```<code>    internal class LifetimeEventsHostedService : IHostedService
    {
        private readonly Microsoft.Extensions.Logging.ILogger _logger;
        private readonly IHostApplicationLifetime _appLifetime;

        public LifetimeEventsHostedService(
            ILogger<LifetimeEventsHostedService> logger,
            IHostApplicationLifetime appLifetime)
        {
            _logger = logger;
            _appLifetime = appLifetime;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _appLifetime.ApplicationStarted.Register(OnStarted);
            _appLifetime.ApplicationStopping.Register(OnStopping);
            _appLifetime.ApplicationStopped.Register(OnStopped);

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        private void OnStarted()
        {
            _logger.LogInformation("OnStarted has been called.");

            // Perform post-startup activities here
        }

        private void OnStopping()
        {
            _logger.LogInformation("OnStopping has been called.");
            // Perform on-stopping activities here

            // This works, but a timeout of 5 seconds or more subsequently causes an OperationCanceledException
            Thread.Sleep(5000);
        }

        private void OnStopped()
        {
            _logger.LogInformation("OnStopped has been called.");

            // Perform post-stopped activities here
        }
    }
</code>```

```<code>
</code>```

答:
I'm open to alternative approaches to graceful shutdown with ASP.Net Core 3.1, as it stands, I'm using a hosted service.

Within the .Net Core app, I was setting ShutdownTimeout on the webhost, however, setting the ShutdownTimeout on the generic host, does allow me to gracefully wait a number of seconds (more than the default sigterm, which is 5 seconds) prior to shutdown. The hint from @PmanAce helped me work that out.

As such, the following codes allow me to gracefully terminate. One caveat, the Thread.Sleep in LifetimeEventsHostedService must be less than option.ShutdownTimeout.

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostBuilderContext, services) =>
            {
                services.AddHostedService<LifetimeEventsHostedService>();
                services.Configure<HostOptions>(option =>
                {
                    option.ShutdownTimeout = TimeSpan.FromSeconds(30);
                });
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseKestrel();
                webBuilder.UseStartup<Startup>();
            });
}
```

<p>The following LifetimeEventsHostedService </p>

<pre class="lang-cs prettyprint-override"><code>public class LifetimeEventsHostedService : IHostedService
{
    private readonly IHostApplicationLifetime _hostApplicationLifetime;

    public LifetimeEventsHostedService(IHostApplicationLifetime hostApplicationLifetime)
    {
        _hostApplicationLifetime = hostApplicationLifetime;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _hostApplicationLifetime.ApplicationStarted.Register(OnStarted);
        _hostApplicationLifetime.ApplicationStopping.Register(OnStopping);
        _hostApplicationLifetime.ApplicationStopped.Register(OnStopped);

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }

    private void OnStopped()
    {
        Console.WriteLine("OnStopped");
    }

    private void OnStopping()
    {
        Console.WriteLine("OnStopping");
        Console.WriteLine(DateTime.Now.ToLongTimeString());

        Thread.Sleep(15000);
        Console.WriteLine("Sleep finished");
        Console.WriteLine(DateTime.Now.ToLongTimeString());
    }

    private void OnStarted()
    {
        Console.WriteLine("OnStarted");
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to gracefully terminate a ASP.Net Core 3.1 service (which will run in Kubernetes). When Kubernetes stops a service, it will send a SIGTERM event to the application, at which point I want in-flight requests to complete (which may take several seconds) before terminating... I think I can catch this in a hostedservice, as below, and hence not stop immediately.

The following works, but with a timeout of 5 seconds or longer, I receive an OperationCanceledException. Could anyone shed any light on why I get an OperationCanceledException or how shed any light on an alternative way to delay a SIGTERM event, to allow a graceful shutdown?

    public static int Main(string[] args)
    {
        var logger = NLogBuilder
            .ConfigureNLog("nlog.config")
            .GetCurrentClassLogger();
        try
        {
            CreateHostBuilder(args)
                .ConfigureServices((hostBuilderContext, services) => { services.AddHostedService<LifetimeEventsHostedService>(); })
                .Build()
                .Run();

            return 0;
        }
        catch (Exception e)
        {
            logger.Fatal(e, "Stopping due to exception");

            return -1;
        }
        finally
        {
            LogManager.Shutdown();
        }
    }

This is the hosted service...

    internal class LifetimeEventsHostedService : IHostedService
    {
        private readonly Microsoft.Extensions.Logging.ILogger _logger;
        private readonly IHostApplicationLifetime _appLifetime;

        public LifetimeEventsHostedService(
            ILogger<LifetimeEventsHostedService> logger,
            IHostApplicationLifetime appLifetime)
        {
            _logger = logger;
            _appLifetime = appLifetime;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _appLifetime.ApplicationStarted.Register(OnStarted);
            _appLifetime.ApplicationStopping.Register(OnStopping);
            _appLifetime.ApplicationStopped.Register(OnStopped);

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        private void OnStarted()
        {
            _logger.LogInformation("OnStarted has been called.");

            // Perform post-startup activities here
        }

        private void OnStopping()
        {
            _logger.LogInformation("OnStopping has been called.");
            // Perform on-stopping activities here

            // This works, but a timeout of 5 seconds or more subsequently causes an OperationCanceledException
            Thread.Sleep(5000);
        }

        private void OnStopped()
        {
            _logger.LogInformation("OnStopped has been called.");

            // Perform post-stopped activities here
        }
    }

Body:
I'm open to alternative approaches to graceful shutdown with ASP.Net Core 3.1, as it stands, I'm using a hosted service.

Within the .Net Core app, I was setting ShutdownTimeout on the webhost, however, setting the ShutdownTimeout on the generic host, does allow me to gracefully wait a number of seconds (more than the default sigterm, which is 5 seconds) prior to shutdown. The hint from @PmanAce helped me work that out.

As such, the following codes allow me to gracefully terminate. One caveat, the Thread.Sleep in LifetimeEventsHostedService must be less than option.ShutdownTimeout.

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostBuilderContext, services) =>
            {
                services.AddHostedService<LifetimeEventsHostedService>();
                services.Configure<HostOptions>(option =>
                {
                    option.ShutdownTimeout = TimeSpan.FromSeconds(30);
                });
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseKestrel();
                webBuilder.UseStartup<Startup>();
            });
}

The following LifetimeEventsHostedService

public class LifetimeEventsHostedService : IHostedService
{
    private readonly IHostApplicationLifetime _hostApplicationLifetime;

    public LifetimeEventsHostedService(IHostApplicationLifetime hostApplicationLifetime)
    {
        _hostApplicationLifetime = hostApplicationLifetime;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _hostApplicationLifetime.ApplicationStarted.Register(OnStarted);
        _hostApplicationLifetime.ApplicationStopping.Register(OnStopping);
        _hostApplicationLifetime.ApplicationStopped.Register(OnStopped);

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }

    private void OnStopped()
    {
        Console.WriteLine("OnStopped");
    }

    private void OnStopping()
    {
        Console.WriteLine("OnStopping");
        Console.WriteLine(DateTime.Now.ToLongTimeString());

        Thread.Sleep(15000);
        Console.WriteLine("Sleep finished");
        Console.WriteLine(DateTime.Now.ToLongTimeString());
    }

    private void OnStarted()
    {
        Console.WriteLine("OnStarted");
    }
}


问:
Field having unique and not null
Suppose a field is in the table of int data type and is declared a unique key and not null.

Can I use it as primary key?

答:
Yes. This is all a primary key needs to be: unique and not nullable.

After all, "primary key" is just a name for such a column (or set of columns). Often there is just one such key. If there are two, you could make one primary and the other secondary, but beside that name there is nothing more to it. There is no actual difference between the two.

I doesn't make a difference whether you create a product table with a unique global trade item number thus:

```<code>create table product
(
  gtin int not null,
  id int not null,
  name varchar(50) not null,
  price decimal(10,2) not null,
  constraint product_gtin primary key (gtin),
  constraint product_id unique (id)
);
</code>```

or thus:

```<code>create table product
(
  gtin int not null,
  id int not null,
  name varchar(50) not null,
  price decimal(10,2) not null,
  constraint product_gtin unique (gtin),
  constraint product_id primary key (id)
);
</code>```

or thus:

```<code>create table product
(
  gtin int not null,
  id int not null,
  name varchar(50) not null,
  price decimal(10,2) not null,
  constraint product_gtin unique (gtin),
  constraint product_id unique (id)
);
</code>```

Title: Field having unique and not null

Body:
Yes. This is all a primary key needs to be: unique and not nullable.

After all, "primary key" is just a name for such a column (or set of columns). Often there is just one such key. If there are two, you could make one primary and the other secondary, but beside that name there is nothing more to it. There is no actual difference between the two.

I doesn't make a difference whether you create a product table with a unique global trade item number thus:

create table product
(
  gtin int not null,
  id int not null,
  name varchar(50) not null,
  price decimal(10,2) not null,
  constraint product_gtin primary key (gtin),
  constraint product_id unique (id)
);

or thus:

create table product
(
  gtin int not null,
  id int not null,
  name varchar(50) not null,
  price decimal(10,2) not null,
  constraint product_gtin unique (gtin),
  constraint product_id primary key (id)
);

or thus:

create table product
(
  gtin int not null,
  id int not null,
  name varchar(50) not null,
  price decimal(10,2) not null,
  constraint product_gtin unique (gtin),
  constraint product_id unique (id)
);


问:
Footer at bottom but not Fixed
I am creating a web page, and I am facing nightmares because of the footer: I have used CCS tricks to make the footer always visible at the bottom and it works perfectly but my background image, which is set to size:cover is not working.

答:
Use this
background-size: cover;</p>

Title: Footer at bottom but not Fixed

Body:
Use this
background-size: cover;


问:
How to integrate a voice to string detector in C language
I'm new to C programming, I would like to develop a game in unity including some voice detection in order to respond to gamers choices. Any ideas on how to implement this?</p>

答:
For so-called Speech To Text, you can use the KeywordRecognizer or PhraseRecognizer as part of UnityEngine.Windows.Speech. Here's an example (fill the words in the Editor Inspector pane to the right):

```<code>using System;
using System.Text;
using UnityEngine;
// Put this check around any part you want to hide on other systems.
#if UNITY_STANDALONE_WIN
    using UnityEngine.Windows.Speech;
#endif

public class KeywordScript : MonoBehaviour
{
    [SerializeField] string[] keywords;

    KeywordRecognizer recognizer;

    void Start()
    {
        recognizer = new KeywordRecognizer(keywords);
        recognizer.OnPhraseRecognized += OnPhraseRecognized;
        recognizer.Start();
    }

    void OnPhraseRecognized(PhraseRecognizedEventArgs args)
    {
        print(args.text);
        print(args.confidence);
    }
}
</code>```

Note at least in our project, some users had issues getting this to work depending on specific Operating System details; it also gets trickier when you take into account the various OS language settings. On top of that, words are often simply not understood properly, but this also partially depends on how many command words you filter for; if you only have a small amount of words, and you allow for high error tolerance, you may get good results in that regard.

Also note that this library is Windows-only, so you would need other approaches for e.g. Android or iOS.

Body:
For so-called Speech To Text, you can use the KeywordRecognizer or PhraseRecognizer as part of UnityEngine.Windows.Speech. Here's an example (fill the words in the Editor Inspector pane to the right):

using System;
using System.Text;
using UnityEngine;
// Put this check around any part you want to hide on other systems.
#if UNITY_STANDALONE_WIN
    using UnityEngine.Windows.Speech;
#endif

public class KeywordScript : MonoBehaviour
{
    [SerializeField] string[] keywords;

    KeywordRecognizer recognizer;

    void Start()
    {
        recognizer = new KeywordRecognizer(keywords);
        recognizer.OnPhraseRecognized += OnPhraseRecognized;
        recognizer.Start();
    }

    void OnPhraseRecognized(PhraseRecognizedEventArgs args)
    {
        print(args.text);
        print(args.confidence);
    }
}

Note at least in our project, some users had issues getting this to work depending on specific Operating System details; it also gets trickier when you take into account the various OS language settings. On top of that, words are often simply not understood properly, but this also partially depends on how many command words you filter for; if you only have a small amount of words, and you allow for high error tolerance, you may get good results in that regard.

Also note that this library is Windows-only, so you would need other approaches for e.g. Android or iOS.


问:
How to get display rows data from ag-grid in vue?
I'm using ag-grid in my vue application.

I have three items in my data:

After I filter by "Toyota" I get only one data on the grid.

I want when I click on the button I'll get the filter results (like in the grid) but when I invoke this function I get all the items. this.$refs.grid.gridOptions.rowData;

how to get only the data I can see from the grid?

app.js:

```<code>import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-balham.css";
import { AgGridVue } from "ag-grid-vue";

export const App = {
  name: "App",
  data() {
    return {
      columnDefs: null,
      rowData: null
    };
  },
  components: {
    AgGridVue
  },
  methods: {
    some: function() {
      const grid = this.$refs.grid.gridOptions;

      const rows = grid.rowData;
      console.log({ rows });
    }
  },
  beforeMount() {
    this.columnDefs = [
      { headerName: "Make", field: "make", filter: true },
      { headerName: "Model", field: "model" },
      { headerName: "Price", field: "price" }
    ];

    this.rowData = [
      { make: "Toyota", model: "Celica", price: 35000 },
      { make: "Ford", model: "Mondeo", price: 32000 },
      { make: "Porsche", model: "Boxter", price: 72000 }
    ];
  },
  template: `
    <div>
    <ag-grid-vue ref="grid" style="width: 500px; height: 300px;"
        class="ag-theme-balham"
        :columnDefs="columnDefs"
        :rowData="rowData">
    </ag-grid-vue>

    <button @click="some">Click</button>
    </div>
    `
};
</code>```

main.js:

```<code>import Vue from 'vue';
import { App } from './app';

new Vue({
  el: '#root',
  render: h => h(App)
});
</code>```

答:
I don't think ag-grid has a direct way to get that data. But you can use forEachNodeAfterFilter to loop over the data and put together your own array.

```<code>const rowData = [];
gridApi.forEachNodeAfterFilter(node => rowData.push(node.data));
</code>```

See https://www.ag-grid.com/javascript-grid-api/#accessing-row-nodes

Body:
I'm using ag-grid in my vue application.

I have three items in my data:

After I filter by "Toyota" I get only one data on the grid.

I want when I click on the button I'll get the filter results (like in the grid) but when I invoke this function I get all the items. this.$refs.grid.gridOptions.rowData;

how to get only the data I can see from the grid?

app.js:

import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-balham.css";
import { AgGridVue } from "ag-grid-vue";

export const App = {
  name: "App",
  data() {
    return {
      columnDefs: null,
      rowData: null
    };
  },
  components: {
    AgGridVue
  },
  methods: {
    some: function() {
      const grid = this.$refs.grid.gridOptions;

      const rows = grid.rowData;
      console.log({ rows });
    }
  },
  beforeMount() {
    this.columnDefs = [
      { headerName: "Make", field: "make", filter: true },
      { headerName: "Model", field: "model" },
      { headerName: "Price", field: "price" }
    ];

    this.rowData = [
      { make: "Toyota", model: "Celica", price: 35000 },
      { make: "Ford", model: "Mondeo", price: 32000 },
      { make: "Porsche", model: "Boxter", price: 72000 }
    ];
  },
  template: `

    <ag-grid-vue ref="grid" style="width: 500px; height: 300px;"
        class="ag-theme-balham"
        :columnDefs="columnDefs"
        :rowData="rowData">
    </ag-grid-vue>

    <button @click="some">Click</button>

    `
};

main.js:

import Vue from 'vue';
import { App } from './app';

new Vue({
  el: '#root',
  render: h => h(App)
});

Body:
I don't think ag-grid has a direct way to get that data. But you can use forEachNodeAfterFilter to loop over the data and put together your own array.

const rowData = [];
gridApi.forEachNodeAfterFilter(node => rowData.push(node.data));

See https://www.ag-grid.com/javascript-grid-api/#accessing-row-nodes


问:
how to sort list in alphabetical order in python?
I have a program where I take in a txt file and break up the text into individual words and puts them into a list. the next part is to sort the list alphabetically and print it.

so far I have a text file that just says:
 "the quick brown fox jumps over the lazy dog"

and my program so far looks like:

```<code>file = input("Enter File Name: ")
myList =[]

readFile = open(file, 'r')

for line in readFile:
    myList.append(line.split(" "))

myList.sort()

print(myList)
</code>```

the problem is that when I run the program the list is being created and filled with each word but when it is printed out it is not being sorted in alphabetical order. I also tried print(myList.sort()) and the only thing that prints is "none"

答:
The problem is that line.split(" ") creates a list of words in line, but myList.append adds this list to myList as a new single item (so you end up with a list of lists rather than list of words). What you probably wanted is:

```<code>myList.extend(line.split(" "))
</code>```

Body:
I have a program where I take in a txt file and break up the text into individual words and puts them into a list. the next part is to sort the list alphabetically and print it.

so far I have a text file that just says:
 "the quick brown fox jumps over the lazy dog"

and my program so far looks like:

file = input("Enter File Name: ")
myList =[]

readFile = open(file, 'r')

for line in readFile:
    myList.append(line.split(" "))

myList.sort()

print(myList)

the problem is that when I run the program the list is being created and filled with each word but when it is printed out it is not being sorted in alphabetical order. I also tried print(myList.sort()) and the only thing that prints is "none"

Body:
The problem is that line.split(" ") creates a list of words in line, but myList.append adds this list to myList as a new single item (so you end up with a list of lists rather than list of words). What you probably wanted is:

myList.extend(line.split(" "))


答: Python has two sorting functions - one which sorts the list in-place, which is what you are expecting in your code, and one which leaves the original list intact and returns a sorted list (which is what you are using).  iirc the other function is called "sorted" - but now you have the info you need to look it up.  This is probably also a previously asked question in stackoverflow, I encourage you look for and to link to the other ones.</p>

Title: how to sort list in alphabetical order in python?


问:
Implementing a Canvas in PyQt5
I have been trying to learn to using PyQt5.

I want to implement a canvas below the "Menu Bar"

class gui(QDialog):
    def __init__(self, parent=None):
        super(gui, self).__init__(parent)
        self.createTopLayout()
        self.painter = canvas(self)
        mainLayout = QGridLayout()
        mainLayout.addLayout(self.topLayout, 0, 0, 1, 2)
        mainLayout.addWidget(self.painter, 1, 0, 6, 2)
        self.setLayout(mainLayout)

    def createTopLayout(self):
        self.topLayout = QHBoxLayout()
        button1 = QPushButton("b1")
        button2 = QPushButton("b2")
        button3 = QPushButton("b3")
        styleComboBox = QComboBox()
        styleComboBox.addItems(QStyleFactory.keys())
        styleLabel = QLabel("&Style:")
        styleLabel.setBuddy(styleComboBox)
        self.topLayout.addWidget(styleLabel)
        self.topLayout.addWidget(styleComboBox)
        self.topLayout.addStretch(1)
        self.topLayout.addWidget(button1)
        self.topLayout.addWidget(button2)
        self.topLayout.addWidget(button3)
```

<p>Where my canvas is defined as</p>

<pre class="lang-py prettyprint-override"><code>class canvas(QMainWindow):
    def __init__(self, parent=None):
        super(canvas, self).__init__(parent)
        self.setGeometry(100, 100, 1000, 700)

    def paintEvent(self, e):
        cir = circle() #circle class creates a circle with random center and radius both between 0 to 100
        painter = QPainter(self)
        painter.setPen(QPen(Qt.red, 1, Qt.SolidLine))
        painter.drawEllipse(self, cir.center.x, cir.center.y, cir.radius, cir.radius)
</code>```

but for me canvas doesnt render at all let alone the ellipse.

答:
You should not use QMainWindow as a canvas, instead use a QWidget. On the other hand setGeometry will not work if you use layout since the latter handles the geometry, instead it establishes a fixed size and adequate margins. On the other hand it is recommended that the name of the classes begin with capital letters, considering the above the solution is:</p>

```<code>class Canvas(<b>QWidget</b>):
    def __init__(self, parent=None):
        super(Canvas, self).__init__(parent)
        <b>self.setFixedSize(1000, 700)
        self.setContentsMargins(100, 100, 100, 100)</b>

    def paintEvent(self, e):
        # ...</code>```

Title: Implementing a Canvas in PyQt5

Body:
I have been trying to learn to using PyQt5.

I want to implement a canvas below the "Menu Bar"

class gui(QDialog):
    def __init__(self, parent=None):
        super(gui, self).__init__(parent)
        self.createTopLayout()
        self.painter = canvas(self)
        mainLayout = QGridLayout()
        mainLayout.addLayout(self.topLayout, 0, 0, 1, 2)
        mainLayout.addWidget(self.painter, 1, 0, 6, 2)
        self.setLayout(mainLayout)

    def createTopLayout(self):
        self.topLayout = QHBoxLayout()
        button1 = QPushButton("b1")
        button2 = QPushButton("b2")
        button3 = QPushButton("b3")
        styleComboBox = QComboBox()
        styleComboBox.addItems(QStyleFactory.keys())
        styleLabel = QLabel("&Style:")
        styleLabel.setBuddy(styleComboBox)
        self.topLayout.addWidget(styleLabel)
        self.topLayout.addWidget(styleComboBox)
        self.topLayout.addStretch(1)
        self.topLayout.addWidget(button1)
        self.topLayout.addWidget(button2)
        self.topLayout.addWidget(button3)

Where my canvas is defined as

class canvas(QMainWindow):
    def __init__(self, parent=None):
        super(canvas, self).__init__(parent)
        self.setGeometry(100, 100, 1000, 700)

    def paintEvent(self, e):
        cir = circle() #circle class creates a circle with random center and radius both between 0 to 100
        painter = QPainter(self)
        painter.setPen(QPen(Qt.red, 1, Qt.SolidLine))
        painter.drawEllipse(self, cir.center.x, cir.center.y, cir.radius, cir.radius)

but for me canvas doesnt render at all let alone the ellipse.

Body:
You should not use QMainWindow as a canvas, instead use a QWidget. On the other hand setGeometry will not work if you use layout since the latter handles the geometry, instead it establishes a fixed size and adequate margins. On the other hand it is recommended that the name of the classes begin with capital letters, considering the above the solution is:

class Canvas(QWidget):
    def __init__(self, parent=None):
        super(Canvas, self).__init__(parent)
        self.setFixedSize(1000, 700)
        self.setContentsMargins(100, 100, 100, 100)

    def paintEvent(self, e):
        # ...


问:
Add CLLocationManagerDelegate to a separate class
I would like to remove the CLLocationManagerDelegate from my ViewController and add to a separate class and make it reusable. I'm quite new to swift so I'm asking your help maybe you can point me in the right direction.

My goal is to call my LocationHandler class every time when I want the user's location and most of the times I would like to handle the location differently (e.g. just save it as it is or other time check the location and if it meets certain rules then save it etc...)

I would like to pass in a function to my LocationHandler class if it possible to handle the location change.

something like this: (this is just a pseudo code, I don't know how to do it properly in swift)

let locationHandler = LocationHandler()

locationHandler.handleLocationChange = (locations: [CLLocation]) - > {...}

locationHandler.getCurrentLocation()

My first problem is when I create an instance from my LocationHandler the getCurrentLocation function is running properly but the didUpdateLocations never rise (I think there is something with the delegation)

Second is I have no idea how to pass a function into a class as a parameter

here is my LocationHandler class

```<code>import Foundation
import CoreLocation

class LocationHandler: NSObject, CLLocationManagerDelegate{

    let locationManager = CLLocationManager()

    override init(){
        super.init()

        locationManager.delegate = self

    }

    func getCurrentLocation(){

        if CLLocationManager.locationServicesEnabled() {
            switch CLLocationManager.authorizationStatus() {
                case .notDetermined, .restricted, .denied:
                    print("No access")
                case .authorizedAlways, .authorizedWhenInUse:
                    print("Access")
                @unknown default:
                break
            }
            } else {
                print("Location services are not enabled")
        }

        locationManager.requestWhenInUseAuthorization()
        locationManager.requestLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
          if let location = locations.first {
              print("Found user's location: \(location)")
              //do something with the location
          }
      }

      func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
          print("Failed to find user's location: \(error.localizedDescription)")
      }

}

</code>```

and I use it in the viewcontroller like this:

```<code>  let locationHandler = LocationHandler()
  locationHandler.getCurrentLocation()
</code>```

答: As written, you have to ensure that the LocationHandler instance is a property of the view controller, not a local variable. You want to make sure it doesn’t fall out of scope and is deallocated before the delegate method has a chance to be called.

Body:
I would like to remove the CLLocationManagerDelegate from my ViewController and add to a separate class and make it reusable. I'm quite new to swift so I'm asking your help maybe you can point me in the right direction.

My goal is to call my LocationHandler class every time when I want the user's location and most of the times I would like to handle the location differently (e.g. just save it as it is or other time check the location and if it meets certain rules then save it etc...)

I would like to pass in a function to my LocationHandler class if it possible to handle the location change.

something like this: (this is just a pseudo code, I don't know how to do it properly in swift)

let locationHandler = LocationHandler()

locationHandler.handleLocationChange = (locations: [CLLocation]) - > {...}

locationHandler.getCurrentLocation()

My first problem is when I create an instance from my LocationHandler the getCurrentLocation function is running properly but the didUpdateLocations never rise (I think there is something with the delegation)

Second is I have no idea how to pass a function into a class as a parameter

here is my LocationHandler class

import Foundation
import CoreLocation

class LocationHandler: NSObject, CLLocationManagerDelegate{

    let locationManager = CLLocationManager()

    override init(){
        super.init()

        locationManager.delegate = self

    }

    func getCurrentLocation(){

        if CLLocationManager.locationServicesEnabled() {
            switch CLLocationManager.authorizationStatus() {
                case .notDetermined, .restricted, .denied:
                    print("No access")
                case .authorizedAlways, .authorizedWhenInUse:
                    print("Access")
                @unknown default:
                break
            }
            } else {
                print("Location services are not enabled")
        }

        locationManager.requestWhenInUseAuthorization()
        locationManager.requestLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
          if let location = locations.first {
              print("Found user's location: \(location)")
              //do something with the location
          }
      }

      func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
          print("Failed to find user's location: \(error.localizedDescription)")
      }

}

and I use it in the viewcontroller like this:

  let locationHandler = LocationHandler()
  locationHandler.getCurrentLocation()


问:
scroll snap is not stopping at top / bottom of page
https://jonathanrace77.github.io/index.html

Scroll-snap is working great... except when it gets to the top or bottom of the screen and you are able to keep scrolling past the content...

I can't figure out how to stop this from happening.

```<code>html {
  overflow: scroll;
  height: 100vh;
  scroll-snap-type: mandatory;
  scroll-snap-points-y: repeat(100vh);
  scroll-snap-type: y mandatory;
}

section {
  height: 100vh;
  scroll-snap-align: start;
  position: relative;
}
</code>```

答:
A combo of </p>

```<code>main {
  position: absolute;
  width: 100vw;
  top: 0;
  left: 0;
}
</code>```

<p>&</p>

```<code>.top {
  position: absolute;
  padding: 0;
  top: 0;
  width: 100vw;
  bottom: -10vh;
  display: block;
  z-index: 2;
  height: 10vh;
}
</code>```

<p>...was screwing things up. After randomly deleting sections of CSS, this managed to fix it. </p>

Body:
https://jonathanrace77.github.io/index.html

Scroll-snap is working great... except when it gets to the top or bottom of the screen and you are able to keep scrolling past the content...

I can't figure out how to stop this from happening.

html {
  overflow: scroll;
  height: 100vh;
  scroll-snap-type: mandatory;
  scroll-snap-points-y: repeat(100vh);
  scroll-snap-type: y mandatory;
}

section {
  height: 100vh;
  scroll-snap-align: start;
  position: relative;
}

Body:
A combo of

main {
  position: absolute;
  width: 100vw;
  top: 0;
  left: 0;
}

&

.top {
  position: absolute;
  padding: 0;
  top: 0;
  width: 100vw;
  bottom: -10vh;
  display: block;
  z-index: 2;
  height: 10vh;
}

...was screwing things up. After randomly deleting sections of CSS, this managed to fix it.


问:
How to get all trigrams of a string in clojure
Suppose I have a string "This is a string". The tri-grams would be "Thi", "his", "is ", "s i" etc. I want to return a vector of all the trim-grams. How can I do that?</p>

答:
You can use partition or partition-all depending on whether you are
interested also in the last "non-tri-grams":

user=> (doc partition)
-------------------------
clojure.core/partition
([n coll] [n step coll] [n step pad coll])
  Returns a lazy sequence of lists of n items each, at offsets step
  apart. If step is not supplied, defaults to n, i.e. the partitions
  do not overlap. If a pad collection is supplied, use its elements as
  necessary to complete last partition upto n items. In case there are
  not enough padding elements, return a partition with less than n items.
```

<pre class="lang-clj prettyprint-override"><code>(user=> (doc partition-all)
-------------------------
clojure.core/partition-all
([n] [n coll] [n step coll])
  Returns a lazy sequence of lists like partition, but may include
  partitions with fewer than n items at the end.  Returns a stateful
  transducer when no collection is provided.
</code>```

E.g.

user=> (partition 3 1 "This is a string")
((\T \h \i)
 (\h \i \s)
 (\i \s \space)
 (\s \space \i)
 (\space \i \s)
 (\i \s \space)
 (\s \space \a)
 (\space \a \space)
 (\a \space \s)
 (\space \s \t)
 (\s \t \r)
 (\t \r \i)
 (\r \i \n)
 (\i \n \g))
```

<p>To get the strings back, join the chars:</p>

<pre class="lang-clj prettyprint-override"><code>user=> (map clojure.string/join (partition 3 1 "This is a string"))
("Thi"
 "his"
 "is "
 "s i"
 " is"
 "is "
 "s a"
 " a "
 "a s"
 " st"
 "str"
 "tri"
 "rin"
 "ing")
</code>```

Or replace with partition-all accordingly:

user=> (map clojure.string/join (partition-all 3 1 "This is a string"))
("Thi"
 ; ...
 "rin"
 "ing"
 "ng"  ; XXX
 "g")  ; XXX

```

Body:
You can use partition or partition-all depending on whether you are
interested also in the last "non-tri-grams":

user=> (doc partition)
-------------------------
clojure.core/partition
([n coll] [n step coll] [n step pad coll])
  Returns a lazy sequence of lists of n items each, at offsets step
  apart. If step is not supplied, defaults to n, i.e. the partitions
  do not overlap. If a pad collection is supplied, use its elements as
  necessary to complete last partition upto n items. In case there are
  not enough padding elements, return a partition with less than n items.

(user=> (doc partition-all)
-------------------------
clojure.core/partition-all
([n] [n coll] [n step coll])
  Returns a lazy sequence of lists like partition, but may include
  partitions with fewer than n items at the end.  Returns a stateful
  transducer when no collection is provided.

E.g.

user=> (partition 3 1 "This is a string")
((\T \h \i)
 (\h \i \s)
 (\i \s \space)
 (\s \space \i)
 (\space \i \s)
 (\i \s \space)
 (\s \space \a)
 (\space \a \space)
 (\a \space \s)
 (\space \s \t)
 (\s \t \r)
 (\t \r \i)
 (\r \i \n)
 (\i \n \g))

To get the strings back, join the chars:

user=> (map clojure.string/join (partition 3 1 "This is a string"))
("Thi"
 "his"
 "is "
 "s i"
 " is"
 "is "
 "s a"
 " a "
 "a s"
 " st"
 "str"
 "tri"
 "rin"
 "ing")

Or replace with partition-all accordingly:

user=> (map clojure.string/join (partition-all 3 1 "This is a string"))
("Thi"
 ; ...
 "rin"
 "ing"
 "ng"  ; XXX
 "g")  ; XXX


问:
How to make the getJSON wait before running the rest of the code?
I wrote a simple function in which your city location is determined. However, I am wondering if there is a way to force the function to wait for the getJSON and then move to the next line of code? In the example, you will see that it shows "Alert 1" skips "Alert 2" and goes directly to "Alert 3" and then shows the "Alert 2". Thank you in advance.

Best regards,
George

var Alpha;

function Location(){
 alert(Alpha + " 1");
 $.getJSON("http://freegeoip.net/json/?callback=?", function(location){
  Alpha = location.city;
  alert(Alpha + " 2");
 });
 alert(Alpha + " 3");
}

$(document).ready(function() {
 Location();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

答:
getJSON() is a shorthand Ajax function so,
$.ajaxSetup({async : false}); will do the trick</p>

ContentLicense: CC BY-SA 3.0


问:
Renaming integers within a data.frame
Using R...

I have a data.frame with five variables.

One of the variables colr has values ranging from 1 to 5.

Defined as an integer with values   1, 2, 3, 4, and 5.

Problem: I would like to build a regression model where the values within colr, the integers 1,2,3,4, and 5 are reported as independent variables with the following names.

1 = Silver,
2 = Blue,
3 = Pink,
4 = Other than Silver, Blue or Pink,
5 = Color Not Reported.

Question: Is there a way to extract or rename these values in a way that is different from the following (as this process does not rename, eg. 1 to Silver in the summary regression output):

```<code>lm(dependent variable ~ + I(colr.f == 1) +
                          I(colr.f == 2) +
                          I(colr.f == 3) +
                          I(colr.f == 4) +
                          I(colr.f == 5),
                          data = df)
</code>```

I am open to any method that would allow me to create and name these different values independently but would prefer to see if there is a way to do so using the tidyverse or dplyr as this is something I have to do frequently when building multivariate models.

Thank you for any help.

答:
I'm not sure I'm understanding your question the right way, but can't you just use

```<code>library(dplyr)
df <- df %>%
 mutate(color=factor(colr.f, levels=c(1:5), labels=c("silver", "blue", "pink", "not s, b, p", "not reported"))

</code>```

and then just run the regression on color only.

/edit for clarification. Making up some data:

```<code>df <- data.frame(
  x=rnorm(100),
  color=factor(rep(c(1,2,3,4,5), each=20),
               labels=c("Silver", "Blue", "Pink", "Not S, B, P", "Not reported")),
  y=rnorm(100, 4))

m1 <- lm(y~x+color, data=df)
m2 <- lm(y~x+color-1, data=df)
summary(m1)
Call:
lm(formula = y ~ x + color, data = df)

Residuals:
     Min       1Q   Median       3Q      Max
-1.96394 -0.59647  0.00237  0.56916  2.13392

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)
(Intercept)        3.93238    0.19312  20.362   <2e-16 ***
x                  0.13588    0.09856   1.379    0.171
colorBlue         -0.07862    0.27705  -0.284    0.777
colorPink         -0.02167    0.27393  -0.079    0.937
colorNot S, B, P   0.15238    0.27221   0.560    0.577
colorNot reported  0.14139    0.27230   0.519    0.605
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.8606 on 94 degrees of freedom
Multiple R-squared:  0.0268,    Adjusted R-squared:  -0.02496
F-statistic: 0.5177 on 5 and 94 DF,  p-value: 0.7623

summary(m2)

Call:
lm(formula = y ~ x + color - 1, data = df)

Residuals:
     Min       1Q   Median       3Q      Max
-1.96394 -0.59647  0.00237  0.56916  2.13392

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)
x                  0.13588    0.09856   1.379    0.171
colorSilver        3.93238    0.19312  20.362   <2e-16 ***
colorBlue          3.85376    0.19570  19.692   <2e-16 ***
colorPink          3.91071    0.19301  20.262   <2e-16 ***
colorNot S, B, P   4.08477    0.19375  21.083   <2e-16 ***
colorNot reported  4.07377    0.19256  21.156   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.8606 on 94 degrees of freedom
Multiple R-squared:  0.9578,    Adjusted R-squared:  0.9551
F-statistic: 355.5 on 6 and 94 DF,  p-value: < 2.2e-16
</code>```

The first model is a model with intercept, therefore one of the factor levels must be dropped to avoid perfect multicollinearity. In this case, the "effect" of silver is the value of the intercept, while the "effect" of the other colors is the intercept coefficient value + their respective coefficient value.

The second model is estimated without intercept (without constant), so you can see the individual effects. However, you should probably know what you are doing before estimating the model without intercept.

Title: Renaming integers within a data.frame

Body:
Using R...

I have a data.frame with five variables.

One of the variables colr has values ranging from 1 to 5.

Defined as an integer with values   1, 2, 3, 4, and 5.

Problem: I would like to build a regression model where the values within colr, the integers 1,2,3,4, and 5 are reported as independent variables with the following names.

1 = Silver,
2 = Blue,
3 = Pink,
4 = Other than Silver, Blue or Pink,
5 = Color Not Reported.

Question: Is there a way to extract or rename these values in a way that is different from the following (as this process does not rename, eg. 1 to Silver in the summary regression output):

lm(dependent variable ~ + I(colr.f == 1) +
                          I(colr.f == 2) +
                          I(colr.f == 3) +
                          I(colr.f == 4) +
                          I(colr.f == 5),
                          data = df)

I am open to any method that would allow me to create and name these different values independently but would prefer to see if there is a way to do so using the tidyverse or dplyr as this is something I have to do frequently when building multivariate models.

Thank you for any help.

Body:
I'm not sure I'm understanding your question the right way, but can't you just use

library(dplyr)
df <- df %>%
 mutate(color=factor(colr.f, levels=c(1:5), labels=c("silver", "blue", "pink", "not s, b, p", "not reported"))

and then just run the regression on color only.

/edit for clarification. Making up some data:

df <- data.frame(
  x=rnorm(100),
  color=factor(rep(c(1,2,3,4,5), each=20),
               labels=c("Silver", "Blue", "Pink", "Not S, B, P", "Not reported")),
  y=rnorm(100, 4))

m1 <- lm(y~x+color, data=df)
m2 <- lm(y~x+color-1, data=df)
summary(m1)
Call:
lm(formula = y ~ x + color, data = df)

Residuals:
     Min       1Q   Median       3Q      Max
-1.96394 -0.59647  0.00237  0.56916  2.13392

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)
(Intercept)        3.93238    0.19312  20.362   <2e-16 ***
x                  0.13588    0.09856   1.379    0.171
colorBlue         -0.07862    0.27705  -0.284    0.777
colorPink         -0.02167    0.27393  -0.079    0.937
colorNot S, B, P   0.15238    0.27221   0.560    0.577
colorNot reported  0.14139    0.27230   0.519    0.605
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.8606 on 94 degrees of freedom
Multiple R-squared:  0.0268,    Adjusted R-squared:  -0.02496
F-statistic: 0.5177 on 5 and 94 DF,  p-value: 0.7623

summary(m2)

Call:
lm(formula = y ~ x + color - 1, data = df)

Residuals:
     Min       1Q   Median       3Q      Max
-1.96394 -0.59647  0.00237  0.56916  2.13392

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)
x                  0.13588    0.09856   1.379    0.171
colorSilver        3.93238    0.19312  20.362   <2e-16 ***
colorBlue          3.85376    0.19570  19.692   <2e-16 ***
colorPink          3.91071    0.19301  20.262   <2e-16 ***
colorNot S, B, P   4.08477    0.19375  21.083   <2e-16 ***
colorNot reported  4.07377    0.19256  21.156   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.8606 on 94 degrees of freedom
Multiple R-squared:  0.9578,    Adjusted R-squared:  0.9551
F-statistic: 355.5 on 6 and 94 DF,  p-value: < 2.2e-16

The first model is a model with intercept, therefore one of the factor levels must be dropped to avoid perfect multicollinearity. In this case, the "effect" of silver is the value of the intercept, while the "effect" of the other colors is the intercept coefficient value + their respective coefficient value.

The second model is estimated without intercept (without constant), so you can see the individual effects. However, you should probably know what you are doing before estimating the model without intercept.


问:
Shape line issue with drawing shape in .NET, c#
I want to draw a shape with square, diamond, and cross shape. The square line is solid, and fine. However, the line of both diamond and cross look like dashed or dotted. I want all shapes have solid line.

Any ideas?

Below is the code, and shapes:

http://www.sendspace.com/file/n3wljs

```<code>private void CreateVariousShapes()
{
    Bitmap bitmap = new Bitmap(17, 17);
    Graphics graphics = Graphics.FromImage(bitmap);
    Pen pen = new Pen(Color.Black);
    pen.Width = 1;
    pen.DashStyle = DashStyle.Solid;
    Brush brush = new SolidBrush(Color.White);

    //graphics.FillRectangle(brush, 0, 0, 16, 16);

    //graphics.DrawRectangle(pen, 0, 0, 16, 16);

    FillDiamond(brush, graphics);
    DrawDiamond(pen, graphics);

    DrawCross(pen, graphics);

    //bitmap.Save(MapPath("SquareDiamondCross.png"),ImageFormat.Png);
    //bitmap.Save(MapPath("SquareCross.png"), ImageFormat.Png);
    //bitmap.Save(MapPath("SquareDiamond.png"), ImageFormat.Png);
    bitmap.Save(MapPath("DiamondCross.png"), ImageFormat.Png);
}

private void FillDiamond(Brush brush, Graphics graphics)
{
    Point[] points = new Point[]
                        { new Point(0,8),
                        new Point(8,16),
                        new Point(16,8),
                        new Point(8,0),

                        };

    graphics.FillPolygon(brush, points);
}

private void DrawDiamond(Pen pen, Graphics graphics)
{
    Point[] points = new Point[]
                        { new Point(0,8),
                        new Point(8,16),
                        new Point(16,8),
                        new Point(8,0),
                        };
    graphics.DrawPolygon(pen, points);
}

private void DrawCross(Pen pen, Graphics graphics)
{
    graphics.DrawLine(pen, 4, 2, 2, 4);

    graphics.DrawLine(pen, 2, 12, 4, 14);

    graphics.DrawLine(pen, 12, 14, 14, 12);

    graphics.DrawLine(pen, 12, 2, 14, 4);

    graphics.DrawLine(pen, 2, 4, 6, 8);
    graphics.DrawLine(pen, 2, 12, 6, 8);

    graphics.DrawLine(pen, 4, 14, 8, 10);
    graphics.DrawLine(pen, 12, 14, 8, 10);

    graphics.DrawLine(pen, 14, 12, 10, 8);
    graphics.DrawLine(pen, 14, 4, 10, 8);

    graphics.DrawLine(pen, 12, 2, 8, 6);
    graphics.DrawLine(pen, 4, 2, 8, 6);
}
</code>```

答:
Set the following graphics properties:

```<code>graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
</code>```

Hopefully you will get what you want.

Body:
I want to draw a shape with square, diamond, and cross shape. The square line is solid, and fine. However, the line of both diamond and cross look like dashed or dotted. I want all shapes have solid line.

Any ideas?

Below is the code, and shapes:

http://www.sendspace.com/file/n3wljs

private void CreateVariousShapes()
{
    Bitmap bitmap = new Bitmap(17, 17);
    Graphics graphics = Graphics.FromImage(bitmap);
    Pen pen = new Pen(Color.Black);
    pen.Width = 1;
    pen.DashStyle = DashStyle.Solid;
    Brush brush = new SolidBrush(Color.White);

    //graphics.FillRectangle(brush, 0, 0, 16, 16);

    //graphics.DrawRectangle(pen, 0, 0, 16, 16);

    FillDiamond(brush, graphics);
    DrawDiamond(pen, graphics);

    DrawCross(pen, graphics);

    //bitmap.Save(MapPath("SquareDiamondCross.png"),ImageFormat.Png);
    //bitmap.Save(MapPath("SquareCross.png"), ImageFormat.Png);
    //bitmap.Save(MapPath("SquareDiamond.png"), ImageFormat.Png);
    bitmap.Save(MapPath("DiamondCross.png"), ImageFormat.Png);
}

private void FillDiamond(Brush brush, Graphics graphics)
{
    Point[] points = new Point[]
                        { new Point(0,8),
                        new Point(8,16),
                        new Point(16,8),
                        new Point(8,0),

                        };

    graphics.FillPolygon(brush, points);
}

private void DrawDiamond(Pen pen, Graphics graphics)
{
    Point[] points = new Point[]
                        { new Point(0,8),
                        new Point(8,16),
                        new Point(16,8),
                        new Point(8,0),
                        };
    graphics.DrawPolygon(pen, points);
}

private void DrawCross(Pen pen, Graphics graphics)
{
    graphics.DrawLine(pen, 4, 2, 2, 4);

    graphics.DrawLine(pen, 2, 12, 4, 14);

    graphics.DrawLine(pen, 12, 14, 14, 12);

    graphics.DrawLine(pen, 12, 2, 14, 4);

    graphics.DrawLine(pen, 2, 4, 6, 8);
    graphics.DrawLine(pen, 2, 12, 6, 8);

    graphics.DrawLine(pen, 4, 14, 8, 10);
    graphics.DrawLine(pen, 12, 14, 8, 10);

    graphics.DrawLine(pen, 14, 12, 10, 8);
    graphics.DrawLine(pen, 14, 4, 10, 8);

    graphics.DrawLine(pen, 12, 2, 8, 6);
    graphics.DrawLine(pen, 4, 2, 8, 6);
}

Body:
Set the following graphics properties:

graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;

Hopefully you will get what you want.


问:
Custom loss function for predicting interget outputs?
I'm currenly working on a dataset where I've to predict an integer output. It starts from 1 to N. I've build a network with loss function mse. But I feel like mse loss function may not be an ideal loss function to minimize in the case of integer output.

I'm also round my prediction to get integer output. Is there a way to make/optimize the model better in case of integer output.

Can anyone provide some help on how to deal with integer output/targets. This is the loss function I'm using right now.

```<code>model.compile(optimizer=SGD(0.001), loss='mse')
</code>```

答:
You are using the wrong loss, mean squared error is a loss for regression, and you have a classification problem (discrete outputs, not continuous).

So for this your model should have a softmax output layer:

```<code>model.add(Dense(N, activation="softmax"))
</code>```

And you should be using a classification loss:

```<code>model.compile(optimizer=SGD(0.001), loss='sparse_categorical_crossentropy')
</code>```

Assuming your labels are integers in the [0, N-1] range (off by one), this should work. To make a prediction, you should do:

```<code>output = np.argmax(model.predict(some_data), axis=1) + 1
</code>```

The +1 is because integer labels go from 0 to N-1

Body:
I'm currenly working on a dataset where I've to predict an integer output. It starts from 1 to N. I've build a network with loss function mse. But I feel like mse loss function may not be an ideal loss function to minimize in the case of integer output.

I'm also round my prediction to get integer output. Is there a way to make/optimize the model better in case of integer output.

Can anyone provide some help on how to deal with integer output/targets. This is the loss function I'm using right now.

model.compile(optimizer=SGD(0.001), loss='mse')

Body:
You are using the wrong loss, mean squared error is a loss for regression, and you have a classification problem (discrete outputs, not continuous).

So for this your model should have a softmax output layer:

model.add(Dense(N, activation="softmax"))

And you should be using a classification loss:

model.compile(optimizer=SGD(0.001), loss='sparse_categorical_crossentropy')

Assuming your labels are integers in the [0, N-1] range (off by one), this should work. To make a prediction, you should do:

output = np.argmax(model.predict(some_data), axis=1) + 1

The +1 is because integer labels go from 0 to N-1


问:
Gender is enum with FEMALE, MALE
So then when we use class with main method, how do we go about it in this case?

For example:

```<code>System.out.print("Enter a name: ");
String name = sc.next();
</code>```

But the question if gender is of type Gender, how would we apply it then in same situation with a scanner?

Would it start something like this:

```<code>Gender gender = sc.
</code>```

Question is what comes next after sc.

As well as let's say we created an object

```<code>Employee employee = new Employee (gender);
</code>```

And then gender in brackets comes underlined red as I can't figure out how to apply type Gender in scanner after sc.

答:
Use Gender.valueOf(sc.next())

Since Gender is an enum, the method static Gender valueOf(String) is automatically created.

You just use it like this:

```<code>String femaleString = "FEMALE";
Gender femaleGender = Gender.valueOf(femaleString);

String maleString = "MALE";
Gender maleGender = Gender.valueOf(maleString);
</code>```

Of course, you might want to elaborate your input and allow lowercase input and/or just M or F. So you might want such a converter:

```<code>enum Gender {
  FEMALE, MALE;

  public static Gender fromString(String str) {
    String normalized = str.toUpperCase();
    return Arrays.stream(Gender.values())
      .filter(g -> g.name().startsWith(normalized))
      .findFirst()
      .orThrow(() -> new IllegalArgumentException("No gender starting with " + str));
  }
}
</code>```

And then the usage becomes:

```<code>Gender gender = Gender.fromString(sc.next());
</code>```

Title: Gender is enum with FEMALE, MALE

Body:
So then when we use class with main method, how do we go about it in this case?

For example:

System.out.print("Enter a name: ");
String name = sc.next();

But the question if gender is of type Gender, how would we apply it then in same situation with a scanner?

Would it start something like this:

Gender gender = sc.

Question is what comes next after sc.

As well as let's say we created an object

Employee employee = new Employee (gender);

And then gender in brackets comes underlined red as I can't figure out how to apply type Gender in scanner after sc.

Body:
Use Gender.valueOf(sc.next())

Since Gender is an enum, the method static Gender valueOf(String) is automatically created.

You just use it like this:

String femaleString = "FEMALE";
Gender femaleGender = Gender.valueOf(femaleString);

String maleString = "MALE";
Gender maleGender = Gender.valueOf(maleString);

Of course, you might want to elaborate your input and allow lowercase input and/or just M or F. So you might want such a converter:

enum Gender {
  FEMALE, MALE;

  public static Gender fromString(String str) {
    String normalized = str.toUpperCase();
    return Arrays.stream(Gender.values())
      .filter(g -> g.name().startsWith(normalized))
      .findFirst()
      .orThrow(() -> new IllegalArgumentException("No gender starting with " + str));
  }
}

And then the usage becomes:

Gender gender = Gender.fromString(sc.next());


问:
Does JNI preserve errno?
I'm writing some JNI code to wrap some C functions. Some of these C functions set errno is case of an error. My code would be simpler if I could move the exception handling from the JNI code to the Java code. My plan is to have to JNI function return null in case of an error and then in the Java code query errno and construct and throw and exception there. For this to work JNI would have to leave errno untouched.

答:
If I were you, I'd have gone with the exception as soon as possible

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/errno.h>
#include "recipeNo019_ThrowException.h"

JNIEXPORT void JNICALL Java_recipeNo019_ThrowException_throwException
  (JNIEnv * env, jobject obj) {

  char exceptionBuffer[1024];

  if(fopen("/this_will_fail", "r") == NULL) {

    sprintf (exceptionBuffer, "%d:%s", errno, strerror(errno));
    (*env)->ThrowNew (env,
                    (*env)->FindClass (env, "java/lang/Exception"),
                    exceptionBuffer);
  }

}
</code>```

and then, in Java code, I'd have decomposed the error code and error message.

Then, inside Java you can easily access both: errno and message.

```<code>
public static native void throwException();

...
...

try {
  throwException();
} catch(Exception ex) {
  ex.getMessage();
}
</code>```

Update

Note that with JNI being involved into play, things may get complicated (especially with shared data - errno).

You can imagine one of the scenarios - like this:

```<code>public static class ErrnoGenerator implements Runnable {

  boolean shouldIFail = false;
  ThrowException exceptionGenerator = null;

  public ErrnoGenerator(
             ThrowException exceptionGenerator,
             boolean shouldIFail) {
    this.exceptionGenerator = exceptionGenerator;
    this.shouldIFail = shouldIFail;
  }

  public void run() {
    try {
      if(shouldIFail) {
        exceptionGenerator.throwException( shouldIFail );
        Thread.sleep(1000);
        System.out.println(
            "true:    expected == 2: "
          + exceptionGenerator.getErrno());
      } else {
        Thread.sleep(500);
        exceptionGenerator.throwException( shouldIFail );
        System.out.println(
            "false: no expectations: "
          + exceptionGenerator.getErrno());
      }
    } catch (InterruptedException e) {
    }
  }
}

public static void main(String[] args) {
  ThrowException thx = new ThrowException();

  Thread t1 = new Thread(new ErrnoGenerator(thx, true));
  Thread t2 = new Thread(new ErrnoGenerator(thx, false));
  t1.start();
  t2.start();
  while(t1.isAlive() || t2.isAlive());
}
</code>```

However, even without Java based threads calling JNI, you can enter race condition as well

```<code>// This will set errno to "2"
thx.throwException( true );
try {
  Path file = Paths.get("/tmp/path-to-file");
  byte[] buf = "hello".getBytes();
  Files.write(file, buf);
} catch(Exception ex) {
}

// it's gone - errno contains something completely
// different to what you have expected to be found
System.out.println(
    "true:    expected == 2: "
  + thx.getErrno());
</code>```

Title: Does JNI preserve errno?

Body:
If I were you, I'd have gone with the exception as soon as possible

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/errno.h>
#include "recipeNo019_ThrowException.h"

JNIEXPORT void JNICALL Java_recipeNo019_ThrowException_throwException
  (JNIEnv * env, jobject obj) {

  char exceptionBuffer[1024];

  if(fopen("/this_will_fail", "r") == NULL) {

    sprintf (exceptionBuffer, "%d:%s", errno, strerror(errno));
    (*env)->ThrowNew (env,
                    (*env)->FindClass (env, "java/lang/Exception"),
                    exceptionBuffer);
  }

}

and then, in Java code, I'd have decomposed the error code and error message.

Then, inside Java you can easily access both: errno and message.

public static native void throwException();

...
...

try {
  throwException();
} catch(Exception ex) {
  ex.getMessage();
}

Update

Note that with JNI being involved into play, things may get complicated (especially with shared data - errno).

You can imagine one of the scenarios - like this:

public static class ErrnoGenerator implements Runnable {

  boolean shouldIFail = false;
  ThrowException exceptionGenerator = null;

  public ErrnoGenerator(
             ThrowException exceptionGenerator,
             boolean shouldIFail) {
    this.exceptionGenerator = exceptionGenerator;
    this.shouldIFail = shouldIFail;
  }

  public void run() {
    try {
      if(shouldIFail) {
        exceptionGenerator.throwException( shouldIFail );
        Thread.sleep(1000);
        System.out.println(
            "true:    expected == 2: "
          + exceptionGenerator.getErrno());
      } else {
        Thread.sleep(500);
        exceptionGenerator.throwException( shouldIFail );
        System.out.println(
            "false: no expectations: "
          + exceptionGenerator.getErrno());
      }
    } catch (InterruptedException e) {
    }
  }
}

public static void main(String[] args) {
  ThrowException thx = new ThrowException();

  Thread t1 = new Thread(new ErrnoGenerator(thx, true));
  Thread t2 = new Thread(new ErrnoGenerator(thx, false));
  t1.start();
  t2.start();
  while(t1.isAlive() || t2.isAlive());
}

However, even without Java based threads calling JNI, you can enter race condition as well

// This will set errno to "2"
thx.throwException( true );
try {
  Path file = Paths.get("/tmp/path-to-file");
  byte[] buf = "hello".getBytes();
  Files.write(file, buf);
} catch(Exception ex) {
}

// it's gone - errno contains something completely
// different to what you have expected to be found
System.out.println(
    "true:    expected == 2: "
  + thx.getErrno());


问:
React Hooks - Ref is not available inside useEffect
I am using ReactHooks. I am trying to access ref of User component in useEffect function, but I am getting elRef.current value as null, though I passed elRef.current as second argument to useEffect.  I am supposed to get reference to an element, but outside (function body) of useEffect, ref value is available. Why is that ? How can I get elRef.current value inside useEffect?

code

```<code>import React, { Component, useState, useRef, useEffect } from "react";

const useFetch = url => {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(
    () => {
      setIsLoading(true);
      fetch(url)
        .then(response => {
          if (!response.ok) throw Error(response.statusText);
          return response.json();
        })
        .then(json => {
          setIsLoading(false);
          setData(json.data);
        })
        .catch(error => {
          setIsLoading(false);
          setError(error);
        });
    },
    [url]
  );

  return { data, isLoading, error };
};

const User = ({ id }) => {
  const elRef = useRef(null);
  const { data: user } = useFetch(`https://reqres.in/api/users/${id}`);

  useEffect(() => {
    console.log("ref", elRef.current);
  }, [elRef.current]);
  if (!user) return null;
  return <div ref={elRef}>{user.first_name + " " + user.last_name}</div>;
};

class App extends Component {
  state = {
    userId: 1
  };

  handleNextClick = () => {
    this.setState(prevState => ({
      userId: prevState.userId + 1
    }));
  };

  handlePrevNext = () => {
    this.setState(prevState => ({
      userId: prevState.userId - 1
    }));
  };
  render() {
    return (
      <div>
        <button
          onClick={() => this.handlePrevClick()}
          disabled={this.state.userId === 1}
        >
          Prevoius
        </button>
        <button onClick={() => this.handleNextClick()}>Next</button>
        <User id={this.state.userId} />
      </div>
    );
  }
}

export default App;
</code>```

Codesandbox link

Thanks !

答:
The assumption here is that useEffect needs to detect changes to ref.current, so needs to have the ref or ref.currentin the dependencies list. I think this is due to es-lint being a bit over-pedantic.

Actually, the whole point of useEffect is that it guarantees not to run until the rendering is complete and the DOM is ready to go. That is how it handles side-effects.

So by the time useEffect is executed, we can be sure that elRef.current is set.

The problem with your code is that you don't run the renderer with
 until after user is populated. So the DOM node you want elRef to reference doesn't yet exist. That is why you get the null logging - nothing to do with dependencies.

BTW: one possible alternative is to populate the div inside the effect hook:

useEffect(
  () => {
    if(!user) return;
    elRef.current.innerHTML = `${user.first_name} ${user.last_name}`;
  }, [user]
);
...
//if (!user) return null;// Remove this line
return

; //return div every time.
```

That way the if (!user) return null; line in the User component is unnecessary. Remove it, and elRef.current is guaranteed to be populated with the div node from the very beginning.

Body:
I am using ReactHooks. I am trying to access ref of User component in useEffect function, but I am getting elRef.current value as null, though I passed elRef.current as second argument to useEffect.  I am supposed to get reference to an element, but outside (function body) of useEffect, ref value is available. Why is that ? How can I get elRef.current value inside useEffect?

code

import React, { Component, useState, useRef, useEffect } from "react";

const useFetch = url => {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(
    () => {
      setIsLoading(true);
      fetch(url)
        .then(response => {
          if (!response.ok) throw Error(response.statusText);
          return response.json();
        })
        .then(json => {
          setIsLoading(false);
          setData(json.data);
        })
        .catch(error => {
          setIsLoading(false);
          setError(error);
        });
    },
    [url]
  );

  return { data, isLoading, error };
};

const User = ({ id }) => {
  const elRef = useRef(null);
  const { data: user } = useFetch(`https://reqres.in/api/users/${id}`);

  useEffect(() => {
    console.log("ref", elRef.current);
  }, [elRef.current]);
  if (!user) return null;
  return
{user.first_name + " " + user.last_name}
;
};

class App extends Component {
  state = {
    userId: 1
  };

  handleNextClick = () => {
    this.setState(prevState => ({
      userId: prevState.userId + 1
    }));
  };

  handlePrevNext = () => {
    this.setState(prevState => ({
      userId: prevState.userId - 1
    }));
  };
  render() {
    return (

        <button
          onClick={() => this.handlePrevClick()}
          disabled={this.state.userId === 1}
        >
          Prevoius
        </button>
        <button onClick={() => this.handleNextClick()}>Next</button>
        <User id={this.state.userId} />

    );
  }
}

export default App;

Codesandbox link

Thanks !

Body:
The assumption here is that useEffect needs to detect changes to ref.current, so needs to have the ref or ref.currentin the dependencies list. I think this is due to es-lint being a bit over-pedantic.

Actually, the whole point of useEffect is that it guarantees not to run until the rendering is complete and the DOM is ready to go. That is how it handles side-effects.

So by the time useEffect is executed, we can be sure that elRef.current is set.

The problem with your code is that you don't run the renderer with <div ref={elRef}...> until after user is populated. So the DOM node you want elRef to reference doesn't yet exist. That is why you get the null logging - nothing to do with dependencies.

BTW: one possible alternative is to populate the div inside the effect hook:

useEffect(
  () => {
    if(!user) return;
    elRef.current.innerHTML = `${user.first_name} ${user.last_name}`;
  }, [user]
);
...
//if (!user) return null;// Remove this line
return <div ref={elRef}></div>; //return div every time.

That way the if (!user) return null; line in the User component is unnecessary. Remove it, and elRef.current is guaranteed to be populated with the div node from the very beginning.


问:
Next js routing triggers useEffect
I'm trying to fetch data inside useEffect using axios but it fetches the data everytime I change the page. Is there a way to not trigger useEffect when changing the page? I tried to use shawllow push but it didn't work. I can't fetch on server side because I use next/router inside axios interceptor. </p>

```<code>   import { useRouter } from 'next/router';
   const router = useRouter();
   router.push('/', '/', { shallow: true })
</code>```

<p>With the above code, it will trigger useEffect when switching routes. </p>

```<code>  useEffect(() => {
    fetch.get('/endpoint').then(response => {
     // do stuff
    });
  }, []);
</code>```

答:
If you have something in useEffect that you only want to run once, add an empty array as the dependency array.

Example:

```<code>  useEffect(() => {
      // your axios fetch here
  }, []);
</code>```

Empty array as the dependencies means the effect is run once. If you don't specify the dependencies, the effect will run after every render.

Title: Next js routing triggers useEffect

Body:
I'm trying to fetch data inside useEffect using axios but it fetches the data everytime I change the page. Is there a way to not trigger useEffect when changing the page? I tried to use shawllow push but it didn't work. I can't fetch on server side because I use next/router inside axios interceptor.

   import { useRouter } from 'next/router';
   const router = useRouter();
   router.push('/', '/', { shallow: true })

With the above code, it will trigger useEffect when switching routes.

  useEffect(() => {
    fetch.get('/endpoint').then(response => {
     // do stuff
    });
  }, []);

Body:
If you have something in useEffect that you only want to run once, add an empty array as the dependency array.

Example:

  useEffect(() => {
      // your axios fetch here
  }, []);

Empty array as the dependencies means the effect is run once. If you don't specify the dependencies, the effect will run after every render.


问:
How to get an object in Firestore (iOS)
How do you get an object in Firestore by its id in Swift? I would then need to use this object to generate content in the UI. I am using SwiftUI.
The object I am trying to get is a user and it has the following structure:

```<code>struct AppUser: Codable {

    var id: String
    var displayName: String
    var photoURL: String
    var points: Int
    var knownLanguageCodes: Set<String>

}
</code>```

The each document in the "users" collection has the fields in the AppUser struct. Ideally, I would like to write a function that returns an AppUser object from Firestore:

```<code>func getUser(withId id: String) -> AppUser {
    //I don't know how to write this function
}
</code>```

The object would then be used like this:

```<code>struct ProfileHeadingView: View {

    let userId: String
    let user = getUser(withId: userId)

    var body: some View {
        HStack {
            ImageView(withURL: self.user.photoURL)
                .frame(width: 90, height: 90)
                .clipShape(Circle())
            VStack (alignment: .leading) {
                Text(self.user.displayName)
                    .font(.largeTitle)
                    .fontWeight(.heavy)
                HStack {
                    Text(String(self.user.points))
                        .font(.title)
                    Spacer()
                }
            }.padding(.horizontal)
        }
    }
}
</code>```

答:
Most of Firebase's APIs are asynchronous - this is due to the fact that most of them involve a network call, which is much slower than code gets executed on your phone!

So, your getUser method would need to be rewritten like this:

import FirebaseFirestoreSwift

func getUser(userId: String, completion: @escaping (_ user: AppUser?, _ error: Error?) -> Void) {
  db.collection("users").document(userId).getDocument { (snapshot, error) in
    let user = try? snapshot?.data(as: AppUser.self)
    completion(user, error)
  }
}

```

Note: to be able to use Firestore's Codable support, you will have to add pod 'FirebaseFirestoreSwift' to your Podfile

As for how (and when) to fetch the user, this largely depends on whether ProfileHeadingView is part of a list view (or is being navigated to from a list view), or not.

If it is part of a list view, I'd recommend fetching all users at once - you can either use a snapshot listener to listen for any updates to the users collection, or perform a one-time fetch to read the users collection once.

Then, from the list view, pass the respective user object into the ProfileHeadingView.

Title: How to get an object in Firestore (iOS)

Body:
How do you get an object in Firestore by its id in Swift? I would then need to use this object to generate content in the UI. I am using SwiftUI.
The object I am trying to get is a user and it has the following structure:

struct AppUser: Codable {

    var id: String
    var displayName: String
    var photoURL: String
    var points: Int
    var knownLanguageCodes: Set<String>

}

The each document in the "users" collection has the fields in the AppUser struct. Ideally, I would like to write a function that returns an AppUser object from Firestore:

func getUser(withId id: String) -> AppUser {
    //I don't know how to write this function
}

The object would then be used like this:

struct ProfileHeadingView: View {

    let userId: String
    let user = getUser(withId: userId)

    var body: some View {
        HStack {
            ImageView(withURL: self.user.photoURL)
                .frame(width: 90, height: 90)
                .clipShape(Circle())
            VStack (alignment: .leading) {
                Text(self.user.displayName)
                    .font(.largeTitle)
                    .fontWeight(.heavy)
                HStack {
                    Text(String(self.user.points))
                        .font(.title)
                    Spacer()
                }
            }.padding(.horizontal)
        }
    }
}

Body:
Most of Firebase's APIs are asynchronous - this is due to the fact that most of them involve a network call, which is much slower than code gets executed on your phone!

So, your getUser method would need to be rewritten like this:

import FirebaseFirestoreSwift

func getUser(userId: String, completion: @escaping (_ user: AppUser?, _ error: Error?) -> Void) {
  db.collection("users").document(userId).getDocument { (snapshot, error) in
    let user = try? snapshot?.data(as: AppUser.self)
    completion(user, error)
  }
}

Note: to be able to use Firestore's Codable support, you will have to add pod 'FirebaseFirestoreSwift' to your Podfile

As for how (and when) to fetch the user, this largely depends on whether ProfileHeadingView is part of a list view (or is being navigated to from a list view), or not.

If it is part of a list view, I'd recommend fetching all users at once - you can either use a snapshot listener to listen for any updates to the users collection, or perform a one-time fetch to read the users collection once.

Then, from the list view, pass the respective user object into the ProfileHeadingView.


问:
addScriptToEvaluateOnNewDocument Selenium (Does not work)
I need to execute addScriptToEvaluateOnNewDocument method of Google Headless Chrome in C# .Net. I basically need to execute Javascript before any other javascript is executed on the documents. Here is my code:

```<code>    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    using OpenQA.Selenium;
    using OpenQA.Selenium.Chrome;
    using OpenQA.Selenium.Interactions;

    namespace User
    {
        class Program
        {
            //public static IWebDriver driver = new ChromeDriver();
            public static IWebDriver driver;

            public static double magnification = 2;
            static void Main(string[] args)
            {
                ChromeOptions options = new ChromeOptions();
                //options.AddArgument("Page.addScriptToEvaluateOnNewDocument");
                options.AddArgument("--window-size=1920,1080");
                options.AddUserProfilePreference("Page.addScriptToEvaluateOnNewDocument", "alert('INJECTED SCRIPT')");

                driver = new ChromeDriver(options);

                var action = new OpenQA.Selenium.Interactions.Actions(driver);

                System.Threading.Thread.Sleep(1000);
                driver.Navigate().GoToUrl("https://google.com");
                System.Threading.Thread.Sleep(10000);
            }
         }
     }
</code>```

But the alert isn't fired (i have tried other JavaScript code besides alert - nothing seems to work)

答:
I have only done this in Python but it should work the same way.

The chromedriver should expose a function named execute_cdp_cmd()
You can use this to run JavaScript before the page JavaScript is run. See the python example below. Note that you should add the code shown below after creating the driver but before you get the web page.

```<code>driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
  "source": """
    alert(0);
  """
})
</code>```

I don't have a C# example, but this might help.

Body:
I need to execute addScriptToEvaluateOnNewDocument method of Google Headless Chrome in C# .Net. I basically need to execute Javascript before any other javascript is executed on the documents. Here is my code:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    using OpenQA.Selenium;
    using OpenQA.Selenium.Chrome;
    using OpenQA.Selenium.Interactions;

    namespace User
    {
        class Program
        {
            //public static IWebDriver driver = new ChromeDriver();
            public static IWebDriver driver;

            public static double magnification = 2;
            static void Main(string[] args)
            {
                ChromeOptions options = new ChromeOptions();
                //options.AddArgument("Page.addScriptToEvaluateOnNewDocument");
                options.AddArgument("--window-size=1920,1080");
                options.AddUserProfilePreference("Page.addScriptToEvaluateOnNewDocument", "alert('INJECTED SCRIPT')");

                driver = new ChromeDriver(options);

                var action = new OpenQA.Selenium.Interactions.Actions(driver);

                System.Threading.Thread.Sleep(1000);
                driver.Navigate().GoToUrl("https://google.com");
                System.Threading.Thread.Sleep(10000);
            }
         }
     }

But the alert isn't fired (i have tried other JavaScript code besides alert - nothing seems to work)

Body:
I have only done this in Python but it should work the same way.

The chromedriver should expose a function named execute_cdp_cmd()
You can use this to run JavaScript before the page JavaScript is run. See the python example below. Note that you should add the code shown below after creating the driver but before you get the web page.

driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
  "source": """
    alert(0);
  """
})

I don't have a C# example, but this might help.


问:
Videos handled by multer have no sound
I'm using multer in node.js to handle when users upload videos to my site, and it was working fine initially, which is why i'm so confused. Now the video uploaded has no sound.

here's the upload form

```<code>    <!DOCTYPE html>
<html>

<head>
    <title>Video Upload</title>
</head>

<body>
    <h1>Video Upload</h1>

    <form action="http://localhost:80/upload"
      enctype="multipart/form-data" method="POST">

    <br>Video Title  <input type="text" name="title" required/><br>
    <br>
        <input type="file" name="video" required/> <br>
        <br>

        <input type="submit" value="submit">
    </form>
</body>

</html>
</code>```

and here's the relevant backend code, with multer i also used ffmetadata to save the title of the video, and uuid/v4 for the filename.

```<code>var storage = multer.diskStorage({
    destination: function(req, file, cb){
        cb(null, __dirname + "/videos")
    },
    filename: function(req, file, cb){
        cb(null, uuid() + ".mp4")
    }
})

//max file size -- 500mb
const maxSize = 524288000;

var upload = multer({
storage: storage,
limits: {fileSize: maxSize},
fileFilter: function(req, file, cb){
var filetypes = /mp4/
var mimetype = filetypes.test(file.mimetype)
console.log(file)
var extname = filetypes.test(path.extname(file.originalname).toLowerCase());
if(mimetype && extname){
    return cb(null, true)
}

//err
cb("Error: File upload only supports the " + "following filetypes - " + filetypes);
}

}).single("video")

app.get("/upload", function(req, res){
        res.sendFile(__dirname + "/views/upload.html")
})

app.post("/upload", function(req, res){
    upload(req, res, function(err){
        console.log(req.body.title)
        if(err){
            res.send(err)
        }
        else{
            metaData.write(req.file.path, {title: req.body.title}, function(err){
                if(err){

                    res.send(err)
                }
                else{
                    res.send("uploaded")
                }
            })

        }
    })
})
</code>```

答: i fixed my problem by switching from req.file.path to req.file.filename</p>

Title: Videos handled by multer have no sound

Body:
I'm using multer in node.js to handle when users upload videos to my site, and it was working fine initially, which is why i'm so confused. Now the video uploaded has no sound.

here's the upload form

    <!DOCTYPE html>

    <title>Video Upload</title>

Video Upload

    <form action="http://localhost:80/upload"
      enctype="multipart/form-data" method="POST">

Video Title  <input type="text" name="title" required/>

        <input type="file" name="video" required/>

        <input type="submit" value="submit">
    </form>

and here's the relevant backend code, with multer i also used ffmetadata to save the title of the video, and uuid/v4 for the filename.

var storage = multer.diskStorage({
    destination: function(req, file, cb){
        cb(null, __dirname + "/videos")
    },
    filename: function(req, file, cb){
        cb(null, uuid() + ".mp4")
    }
})

//max file size -- 500mb
const maxSize = 524288000;

var upload = multer({
storage: storage,
limits: {fileSize: maxSize},
fileFilter: function(req, file, cb){
var filetypes = /mp4/
var mimetype = filetypes.test(file.mimetype)
console.log(file)
var extname = filetypes.test(path.extname(file.originalname).toLowerCase());
if(mimetype && extname){
    return cb(null, true)
}

//err
cb("Error: File upload only supports the " + "following filetypes - " + filetypes);
}

}).single("video")

app.get("/upload", function(req, res){
        res.sendFile(__dirname + "/views/upload.html")
})

app.post("/upload", function(req, res){
    upload(req, res, function(err){
        console.log(req.body.title)
        if(err){
            res.send(err)
        }
        else{
            metaData.write(req.file.path, {title: req.body.title}, function(err){
                if(err){

                    res.send(err)
                }
                else{
                    res.send("uploaded")
                }
            })

        }
    })
})


问:
How to include route handlers in multiple files in Express?
In my NodeJS express application I have app.js that has a few common routes. Then in a wf.js file I would like to define a few more routes.

How can I get app.js to recognize other route handlers defined in wf.js file?

A simple require does not seem to work.

答:
you can put all route functions in other files(modules) , and link it to the main server file.
in the main express file, add a function that will link the module to the server:

```<code>   function link_routes(app, route_collection){
       route_collection['get'].forEach(route => app.get(route.path, route.func));
       route_collection['post'].forEach(route => app.post(route.path, route.func));
       route_collection['delete'].forEach(route => app.delete(route.path, route.func));
       route_collection['put'].forEach(route => app.put(route.path, route.func));
   }
</code>```

and call that function for each route model:

```<code>link_routes(app, require('./login.js'))
</code>```

in the module files(for example - login.js file), define the functions as usual:

```<code>const login_screen = (req, res) => {
    res.sendFile(`${__dirname}/pages/login.html`);
};

const forgot_password = (req, res) => {
    console.log('we will reset the password here')
}
</code>```

and export it with the request method as a key and the value is an array of objects, each with path and function keys.

```<code>module.exports = {
   get: [{path:'/',func:login_screen}, {...} ],
   post: [{path:'/login:forgotPassword', func:forgot_password}]
};
</code>```

Body:
you can put all route functions in other files(modules) , and link it to the main server file.
in the main express file, add a function that will link the module to the server:

   function link_routes(app, route_collection){
       route_collection['get'].forEach(route => app.get(route.path, route.func));
       route_collection['post'].forEach(route => app.post(route.path, route.func));
       route_collection['delete'].forEach(route => app.delete(route.path, route.func));
       route_collection['put'].forEach(route => app.put(route.path, route.func));
   }

and call that function for each route model:

link_routes(app, require('./login.js'))

in the module files(for example - login.js file), define the functions as usual:

const login_screen = (req, res) => {
    res.sendFile(`${__dirname}/pages/login.html`);
};

const forgot_password = (req, res) => {
    console.log('we will reset the password here')
}

and export it with the request method as a key and the value is an array of objects, each with path and function keys.

module.exports = {
   get: [{path:'/',func:login_screen}, {...} ],
   post: [{path:'/login:forgotPassword', func:forgot_password}]
};