问:
Is there a way to specify custom locale directory for C++ program on macOS
In my mac, /usr/share/locale is the default locale directory where all the locales are placed. I want to specify a custom locale directory, so that a C++ program (i.e. libc/libc++) can pick up locale from there.

```<code>#include <locale>
int main() {
  std::locale a("en_US.utf-8"); // OK.
  std::locale b("en_US.utf8"); // Error. Failed to create locale for en_US.UTF8
}
</code>```

This C++ program fails to construct locale for second case, because there is no en_US.utf8 folder in /usr/share/locale directory on my mac. I would want to create en_US.utf8 by coping/linking en_US.utf-8, but the directory /usr/share/locale is write protected, i.e. you cannot alter this directory even with sudo mode. Only way to alter this directory is to restart mac in safe-mode, alter this directory and restart again in normal mode. That is not a encouraged option. So i need to copy the entire /usr/share/locale directory in a custom directory and alter the locale folders in custom directory. All i need is a way to specify that custom locale directory for my C++ program.

Any solution to make my C++ program work by altering the program at one place without altering all occurrence of locale usage(utf8 -> utf-8), is a valid solution for me.

Note: Writing a wrapper on std::locale won't work for me because as I mentioned I cannot afford to alter all usage of locale in a very large C++ project.

答:
I got the answer of my question.

```<code>PATH_LOCALE=<new_path> ./binary
</code>```

It works for mac (BSD).
Thanks.

Body:
In my mac, /usr/share/locale is the default locale directory where all the locales are placed. I want to specify a custom locale directory, so that a C++ program (i.e. libc/libc++) can pick up locale from there.

#include <locale>
int main() {
  std::locale a("en_US.utf-8"); // OK.
  std::locale b("en_US.utf8"); // Error. Failed to create locale for en_US.UTF8
}

This C++ program fails to construct locale for second case, because there is no en_US.utf8 folder in /usr/share/locale directory on my mac. I would want to create en_US.utf8 by coping/linking en_US.utf-8, but the directory /usr/share/locale is write protected, i.e. you cannot alter this directory even with sudo mode. Only way to alter this directory is to restart mac in safe-mode, alter this directory and restart again in normal mode. That is not a encouraged option. So i need to copy the entire /usr/share/locale directory in a custom directory and alter the locale folders in custom directory. All i need is a way to specify that custom locale directory for my C++ program.

Any solution to make my C++ program work by altering the program at one place without altering all occurrence of locale usage(utf8 -> utf-8), is a valid solution for me.

Note: Writing a wrapper on std::locale won't work for me because as I mentioned I cannot afford to alter all usage of locale in a very large C++ project.

Body:
I got the answer of my question.

PATH_LOCALE=<new_path> ./binary

It works for mac (BSD).
Thanks.


来源: stackexchange

问:
I have been experiencing this NOT ADirectory Error while running a code in Python
The ERROR

```<code>Traceback (most recent call last):
  File "images.py", line 11, in <module>
    for filename in os.listdir(path):
NotADirectoryError: [Errno 20] Not a directory: 'images.py'
</code>```

I m using this code but the above error keeps coming, don't know what to do next?

This is my code

```<code>import sys
import os
from PIL import Image

image_folder = sys.argv[0]
output_folder = sys.argv[1]

if not os.path.exists(output_folder):
   os.makedirs(output_folder)

for filename in os.listdir(image_folder):
  img= Image.open(f'{image_folder}{filename}')
  img.save(f'{output_folder}{filename}','png')
  print('alldone!')
</code>```

答:
The first element of your script arguments, sys.argv[0], is the path of the file executed - images.py in your case.

Change:

```<code>image_folder = sys.argv[0]
output_folder = sys.argv[1]
</code>```

To:

```<code>image_folder = sys.argv[1]
output_folder = sys.argv[2]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The ERROR

Traceback (most recent call last):
  File "images.py", line 11, in <module>
    for filename in os.listdir(path):
NotADirectoryError: [Errno 20] Not a directory: 'images.py'

I m using this code but the above error keeps coming, don't know what to do next?

This is my code

import sys
import os
from PIL import Image

image_folder = sys.argv[0]
output_folder = sys.argv[1]

if not os.path.exists(output_folder):
   os.makedirs(output_folder)

for filename in os.listdir(image_folder):
  img= Image.open(f'{image_folder}{filename}')
  img.save(f'{output_folder}{filename}','png')
  print('alldone!')

Body:
The first element of your script arguments, sys.argv[0], is the path of the file executed - images.py in your case.

Change:

image_folder = sys.argv[0]
output_folder = sys.argv[1]

To:

image_folder = sys.argv[1]
output_folder = sys.argv[2]


问:
Migration trobules upgrading from vb6 to vb.net
I want to upgrade Vb5 code to Vb.net but I don't know how to upgrade this command
strMsgDtl and vbCrLf are string:

```<code>strMsgDtl = strMsgDtl & String(75, "-") & vbCrLf
</code>```

What does the following command mean??

```<code>String(75, "-")
</code>```

答:
String(75,"-") creates a string 75 characters long, made of the "-" character.

VB.Net equivalent would be New String("-", 75)

ContentLicense: CC BY-SA 3.0

Body:
I want to upgrade Vb5 code to Vb.net but I don't know how to upgrade this command
strMsgDtl and vbCrLf are string:

strMsgDtl = strMsgDtl & String(75, "-") & vbCrLf

What does the following command mean??

String(75, "-")


问:
How to skip a page scrape when table is missing in R
I'm building a scrape that pulls the name of a player and the years he played for thousands of different players. I have built an otherwise successful function to do this but unfortunately in some instances the table with the other half of data I need (years played) does not exist. For these instances, I'd like to add a way to tell the scrape to bypass these instances. Here is the code:

(note: the object "url_final" is the list of active webpage URLs of which there are many)

```<code>library(rvest)
library(curl)
library(tidyverse)
library(httr)
df <- map_dfr(.x = url_final,
                .f = function(x){Sys.sleep(.3); cat(1);

 fyr <- read_html(curl(x, handle = curl::new_handle("useragent" = "Mozilla/5.0"))) %>%
  html_table() %>%
  .[[1]]

 fyr <- fyr %>%
  select(1) %>%
  mutate(name = str_extract(string = x, pattern = "(?<=cbb/players/).*?(?=-\\d\\.html)"))

                })
</code>```

Here is an example of an active page in which you can recreate the scrape by replacing "url_final" as the .x call in map_dfr with:

```<code>https://www.sports-reference.com/cbb/players/karl-aaker-1.html
</code>```

Here is an example of one of the instances in which there is no table and thus returns an error breaking the loop of the scrape.

```<code>https://www.sports-reference.com/cbb/players/karl-aaker-1.html
</code>```

答:
How about adding try-Catch which will ignore any errors? </p>

```<code>library(tidyverse)
library(rvest)

df <- map_dfr(.x = url_final,
              .f = function(x){Sys.sleep(.3); cat(1);
                 tryCatch({
                 fyr <- read_html(curl::curl(x,
                      handle = curl::new_handle("useragent" = "Mozilla/5.0"))) %>%
                      html_table() %>% .[[1]]

               fyr <- fyr %>%
                       select(1) %>%
                       mutate(name = str_extract(string = x,
                         pattern = "(?<=cbb/players/).*?(?=-\\d\\.html)"))
               }, error = function(e) message('Skipping url', x))
            })
</code>```

Body:
I'm building a scrape that pulls the name of a player and the years he played for thousands of different players. I have built an otherwise successful function to do this but unfortunately in some instances the table with the other half of data I need (years played) does not exist. For these instances, I'd like to add a way to tell the scrape to bypass these instances. Here is the code:

(note: the object "url_final" is the list of active webpage URLs of which there are many)

library(rvest)
library(curl)
library(tidyverse)
library(httr)
df <- map_dfr(.x = url_final,
                .f = function(x){Sys.sleep(.3); cat(1);

 fyr <- read_html(curl(x, handle = curl::new_handle("useragent" = "Mozilla/5.0"))) %>%
  html_table() %>%
  .[[1]]

 fyr <- fyr %>%
  select(1) %>%
  mutate(name = str_extract(string = x, pattern = "(?<=cbb/players/).*?(?=-\\d\\.html)"))

                })

Here is an example of an active page in which you can recreate the scrape by replacing "url_final" as the .x call in map_dfr with:

https://www.sports-reference.com/cbb/players/karl-aaker-1.html

Here is an example of one of the instances in which there is no table and thus returns an error breaking the loop of the scrape.

https://www.sports-reference.com/cbb/players/karl-aaker-1.html

Body:
How about adding try-Catch which will ignore any errors?

library(tidyverse)
library(rvest)

df <- map_dfr(.x = url_final,
              .f = function(x){Sys.sleep(.3); cat(1);
                 tryCatch({
                 fyr <- read_html(curl::curl(x,
                      handle = curl::new_handle("useragent" = "Mozilla/5.0"))) %>%
                      html_table() %>% .[[1]]

               fyr <- fyr %>%
                       select(1) %>%
                       mutate(name = str_extract(string = x,
                         pattern = "(?<=cbb/players/).*?(?=-\\d\\.html)"))
               }, error = function(e) message('Skipping url', x))
            })


问:
Full offline option using AWS DataStore and then allow an optional activation for the the cloud sync features in Android
I've started a project using AwsAppsync.

The app is going to be offline first. And we want to offer the option to sync in the cloud as an extra option later if the customer wants it. So, I configured my project like this:

In build.gradle added the following:

```<code>buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.2'
        classpath 'com.amplifyframework:amplify-tools-gradle-plugin:0.2.1'
    }
}

apply plugin: 'com.amplifyframework.amplifytools'
</code>```

And added those dependencies:

```<code>implementation 'com.amplifyframework:core:0.10.0'
implementation 'com.amplifyframework:aws-api:0.10.0' // If using cloud sync
implementation 'com.amplifyframework:aws-datastore:0.10.0'
</code>```

And then using the Amplify CLI:

copy
Generate models at any time by executing this Amplify CLI command:

```<code>amplify codegen models
</code>```

After this in the onCreate of the activity:

```<code>ModelProvider modelProvider = AmplifyModelProvider.getInstance();
Amplify.addPlugin(AWSDataStorePlugin.forModels(modelProvider));
Amplify.configure(getApplicationContext());
</code>```

With this i can Query, update and delete the data.

Is this enough for a full offline experience?

Now, based on the documentation, to add online sync feature, I have to do the following:

Using the Amplify CLI:

```<code>amplify push
</code>```

This will create the amplifyconfiguration.json with the sync configuration.

Now, this information seems to be set in build time. So, how can I enable/disable this feature to be used just when I need it? The documentation mention the following:

```<code>ModelProvider modelProvider = AmplifyModelProvider.getInstance();
Amplify.addPlugin(AWSDataStorePlugin.forModels(modelProvider));
Amplify.addPlugin(new AWSApiPlugin()); // If using remote model synchronization
Amplify.configure(getApplicationContext());
</code>```

So, would be adding that "new AWSApiPlugin()" the only thing I need to do to enable/disable this feature? Thanks!

Any tutorial/book good enough to explain this? I've read several documentation(including the official) and I wasn't able to find something about this particular case. It is always with online sync from the get go.

答: From a high level, yes this is fairly accurate. DataStore doesn't require a backend it will just work as a local DB of sorts that you can use for offline including queries. When you add in a backend with amplify push (this deploys an AppSync API backed by DynamoDB) and connect it with AWSApiPlugin it will begin syncing. The best tutorial is in the docs: https://docs.amplify.aws

Body:
I've started a project using AwsAppsync.

The app is going to be offline first. And we want to offer the option to sync in the cloud as an extra option later if the customer wants it. So, I configured my project like this:

In build.gradle added the following:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.2'
        classpath 'com.amplifyframework:amplify-tools-gradle-plugin:0.2.1'
    }
}

apply plugin: 'com.amplifyframework.amplifytools'

And added those dependencies:

implementation 'com.amplifyframework:core:0.10.0'
implementation 'com.amplifyframework:aws-api:0.10.0' // If using cloud sync
implementation 'com.amplifyframework:aws-datastore:0.10.0'

And then using the Amplify CLI:

copy
Generate models at any time by executing this Amplify CLI command:

amplify codegen models

After this in the onCreate of the activity:

ModelProvider modelProvider = AmplifyModelProvider.getInstance();
Amplify.addPlugin(AWSDataStorePlugin.forModels(modelProvider));
Amplify.configure(getApplicationContext());

With this i can Query, update and delete the data.

Is this enough for a full offline experience?

Now, based on the documentation, to add online sync feature, I have to do the following:

Using the Amplify CLI:

amplify push

This will create the amplifyconfiguration.json with the sync configuration.

Now, this information seems to be set in build time. So, how can I enable/disable this feature to be used just when I need it? The documentation mention the following:

ModelProvider modelProvider = AmplifyModelProvider.getInstance();
Amplify.addPlugin(AWSDataStorePlugin.forModels(modelProvider));
Amplify.addPlugin(new AWSApiPlugin()); // If using remote model synchronization
Amplify.configure(getApplicationContext());

So, would be adding that "new AWSApiPlugin()" the only thing I need to do to enable/disable this feature? Thanks!

Any tutorial/book good enough to explain this? I've read several documentation(including the official) and I wasn't able to find something about this particular case. It is always with online sync from the get go.


问:
xHTML markup checker integrated in Selenium
Recently, I thought about how can I improve the quality of the projects, by using Continuous checking of xHTML source at Continuous Integration machine.

Look, we have a project

http://sourceforge.net/projects/jtidy - jTidy
JTidy is a Java port of HTML Tidy, a HTML syntax checker and pretty printer.

It can validate the xHTML through a command-line interface. Or this tool can be extended in the way we need, because all source code are open.

We can overwrite every Selenium validation method, such as assertTextPresent, or any other, so it will be calling the jTidy(by providing current state's HTML source), and if some errors or warnings will occur - it can be saved to Continuous Integration machine build's logs - so any project's related can see this info.

We can not to rewrite all the Selenium methods, to integrate this call on every step, but to make this calls where we want(after DOM manupulations).

Yes, we can use W3C markup validators for our sites, but there isn't any possibility to validate not initial state of page's source with this validators. After page creation, there might be lots of DOM manipulations which can produce markup errors/warnings - we can find it immediately with this scheme.

One of the benefits of using Continuous integration is that you have quick feedback from code - how it integrates with existing code base, test whether unit and functional tests pass. Why not to get an additional useful info, such as instant xHTML markup validation status. The earlier we identify the problem, the easier to fix it.

I haven't found anything on this theme in google yet.
And want to know, what do you think about this idea?

答:
Seems like a worthwhile idea.

I've done two similar things with CI before:

I've used Ant's XMLValidate task to validate static xhtml files as part of the build process

I've used httpunit to pull pages that I then parsed as xml

But the idea of tying into Selenium to validate the content inherently during a functional test run is novel to me.

OwnerDisplayName: Fedyashev Nikita

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jeffrey Fredrick


问:
System.NullReferenceException: Object reference not set to an instance of an object

Possible Duplicates:
  What is a NullReferenceException in .NET?
  System.NullReferenceException: Object reference not set to an instance of an object

I am using the following code.

```<code>public partial class SectionControls_SingleBanners : SectionControlBaseClass
{
    private SingleBanners _section;

    protected void Page_PreRender(object sender, EventArgs e) {
        updateViews();

        if (RssCapable(this._section.GetType()) && _section.BannersEntries.Rows.Count > 0)  {
</code>```

So here on this code I am getting the error

```<code>this._section.GetType();
</code>```

How can this problem be fixed?

答:
The answer is in the error Object Reference not set to an Instance of an Object...

You declared the object _section, but you have not set a reference to it?

Something like:

```<code>private SingleBanners _section = new SingleBanners();
</code>```

The way you've declared the private SingleBanners _section; the reference to the object _section will be null!

Body:
Possible Duplicates:
  What is a NullReferenceException in .NET?
  System.NullReferenceException: Object reference not set to an instance of an object

I am using the following code.

public partial class SectionControls_SingleBanners : SectionControlBaseClass
{
    private SingleBanners _section;

    protected void Page_PreRender(object sender, EventArgs e) {
        updateViews();

        if (RssCapable(this._section.GetType()) && _section.BannersEntries.Rows.Count > 0)  {

So here on this code I am getting the error

this._section.GetType();

How can this problem be fixed?

Body:
The answer is in the error Object Reference not set to an Instance of an Object...

You declared the object _section, but you have not set a reference to it?

Something like:

private SingleBanners _section = new SingleBanners();

The way you've declared the private SingleBanners _section; the reference to the object _section will be null!


问:
Custom Alexa skill to write to unique dynamoDB
I currently have a custom Alexa skill that is live.
The skill writes and reads from a dynamoDB table but I want each user to have their own unique table.
Right now all users data gets inputted and read from one single table that is connected to the skill.
Is there a way for a new user to automatically create a new unique dynamoDB table when the user launches and uses the skill so that each user can only access their own data?

Thanks in advance!

答:
I don't understand why you would want each user to have their own exclusive DynamoDB table, but I'll leave that up to you. The use-case you mention should be possible, but note that the limit on the number of DDB tables is 256 per region. Refer to the points below:

In the Lambda function's input event invoked from Alexa, the "userId" parameter can be used to identify each user uniquely. Note: Normally, disabling and re-enabling a skill generates a new identifier.

Using the userId check if a DDB table with the same name exists, if not create a table and continue. If the complete userId cannot be set as the DDB table name, you could use tags.


问:
how to add timer in ReactJS hooks
I am trying to add timer,
problem statement - when user click on button, it should call timer to start and after 3 seconds it should perform something.

my code which is not working

```<code>const [timer, setTimer] = useState(3);

useEffect(() => {
    if (timer > 0) {
      setTimeout(() => setTimer(timer - 1), 1000);
    } else {
      window.close();
    }
  }, [timer]);

function submitStartTimer(){                /*Button onClick=submitStartTimer()*/
    setTimer(3);
    swal({
      title: "Thank You!",
      text:
        "You have successfully Submitted your Data! This tab is going to close!",
      icon: "success",
      button: false,
    });
}
</code>```

but the tab automatically gets close after 3 seconds, i know because of useEffect, but how can i start useEffect after click of submitStartTimer()?

答:
I got the solution, a little modification by using Rahul's answer help me to solve it.</p>

```<code>const [timer, setTimer] = useState(-1);

  useEffect(() => {
    if (timer > 0) {
      setTimeout(() => setTimer(timer - 1), 1000);
    } else if (timer === 0) {
      window.close();
    }
  }, [timer]);

function submitStartTimer(){
  setTimer(3);
    swal({
      title: "Thank You!",
      text:
        "You have successfully Submitted your Data! This tab is going to close!",
      icon: "success",
      button: false,
    });
}
</code>```

Title: how to add timer in ReactJS hooks

Body:
I am trying to add timer,
problem statement - when user click on button, it should call timer to start and after 3 seconds it should perform something.

my code which is not working

const [timer, setTimer] = useState(3);

useEffect(() => {
    if (timer > 0) {
      setTimeout(() => setTimer(timer - 1), 1000);
    } else {
      window.close();
    }
  }, [timer]);

function submitStartTimer(){                /*Button onClick=submitStartTimer()*/
    setTimer(3);
    swal({
      title: "Thank You!",
      text:
        "You have successfully Submitted your Data! This tab is going to close!",
      icon: "success",
      button: false,
    });
}

but the tab automatically gets close after 3 seconds, i know because of useEffect, but how can i start useEffect after click of submitStartTimer()?

Body:
I got the solution, a little modification by using Rahul's answer help me to solve it.

const [timer, setTimer] = useState(-1);

  useEffect(() => {
    if (timer > 0) {
      setTimeout(() => setTimer(timer - 1), 1000);
    } else if (timer === 0) {
      window.close();
    }
  }, [timer]);

function submitStartTimer(){
  setTimer(3);
    swal({
      title: "Thank You!",
      text:
        "You have successfully Submitted your Data! This tab is going to close!",
      icon: "success",
      button: false,
    });
}


问:
MaterialDesignXamlToolkit with WPF class library?
Sorry for the duplicate, but my low reputation does not allow me to comment on posts.

i am trying to use MaterialDesignXamlToolkit with WPF with class library, exactly as in this post: How to include MaterialDesignXamlToolkit to WPF class library?

-so i installed Material Design nuGet and added ResourceDictionary named MaterialDesign.xaml, where I copied and paste this code:

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
        <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
        <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
        <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
    </ResourceDictionary.MergedDictionaries>
</code>```

then I created a new WPF page where I added Resource, so my xaml looks like this:

```<code><Page x:Class="test.Page1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:local="clr-namespace:test"
  mc:Ignorable="d"
  d:DesignHeight="450" d:DesignWidth="800"
  Title="Page1"

  xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
  TextElement.Foreground="{DynamicResource MaterialDesignBody}"
  TextElement.FontWeight="Regular"
  TextElement.FontSize="13"
  TextOptions.TextFormattingMode="Ideal"
  TextOptions.TextRenderingMode="Auto"
  Background="{DynamicResource MaterialDesignPaper}"
  FontFamily="{DynamicResource MaterialDesignFont}">
<Page.Resources>
    <ResourceDictionary Source="/MyAsembly;component/ResourceDictionary/MaterialDesign.xaml" />
</Page.Resources>

<Grid>
    <materialDesign:Card Padding="32" Margin="16">
        <TextBlock Style="{DynamicResource MaterialDesignTitleTextBlock}">My First Material Design App</TextBlock>
    </materialDesign:Card>
</Grid>
</code>```

Of course I got an error: The resource {MaterialDesignBody, MaterialDesignPaper, MaterialDesignFont} could not be resolved

as @Marija Rakic mentions in the post, I dried to add dummy lines to my Page1.xaml.cs class

```<code>using MaterialDesignColors;
using MaterialDesignThemes.Wpf;
using System.Windows.Controls;

namespace test
{
    /// <summary>
    /// Interaction logic for Page1.xaml
    /// </summary>
    public partial class Page1 : Page
    {
        public Page1()
        {
            ColorZoneAssist.SetMode(new GroupBox(), ColorZoneMode.Accent);
            Hue hue = new Hue("name", System.Windows.Media.Color.FromArgb(1, 2, 3, 4), System.Windows.Media.Color.FromArgb(1, 5, 6, 7));
            InitializeComponent();
        }
    }
}
</code>```

but it didn't help. The error was still there. So I tried @Trygve solution and created one more class named MaterialDesign.xaml.cs where I added an assembly

```<code>using System.IO;
using System.Reflection;
using System.Windows;

namespace test
{
    partial class MaterialDesign: ResourceDictionary
    {
        public MaterialDesign() {
            Assembly.LoadFrom(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MaterialDesignThemes.Wpf.dll"));
            Assembly.LoadFrom(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MaterialDesignColors.dll"));
            InitializeComponent();
        }
    }
}
</code>```

and added a reference to MaterialDesign.xaml:

```<code>x:Class="test.MaterialDesign"
</code>```

but it also didn't work and mentioned error is still there.I don't know where I'm making a mistake ..

答:
This is how i get it running:

App.xaml

```<code><ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Dark.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.DeepPurple.xaml" />
        </ResourceDictionary.MergedDictionaries>
</code>```

MainWindow.xaml

```<code><Window x:Class="PRWSolution.UI.View.Shell.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:PRWSolution.UI.View"
    xmlns:language="clr-namespace:PRWSolution.UI.Properties.Langs"
    xmlns:setting="clr-namespace:PRWSolution.UI.Properties"
    mc:Ignorable="d"
    xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
    DataContext="{Binding Main, Source={StaticResource Locator}}"
    TextElement.Foreground="{DynamicResource MaterialDesignBody}"
    Background="{DynamicResource MaterialDesignPaper}"
    TextElement.FontWeight="Medium"
    TextElement.FontSize="14"
    WindowState="Maximized"
    WindowStyle="None"
    FontFamily="{materialDesign:MaterialDesignFont}"
    Title="MainWindow"
    Height="800"
    Width="1080">
</code>```

Also a big help is the Homepage from MaterialDesign. When you follow the instructions it will work for sure.
MaterialDesign In XAML

Body:
Sorry for the duplicate, but my low reputation does not allow me to comment on posts.

i am trying to use MaterialDesignXamlToolkit with WPF with class library, exactly as in this post: How to include MaterialDesignXamlToolkit to WPF class library?

-so i installed Material Design nuGet and added ResourceDictionary named MaterialDesign.xaml, where I copied and paste this code:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
        <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
        <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
        <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
    </ResourceDictionary.MergedDictionaries>

then I created a new WPF page where I added Resource, so my xaml looks like this:

<Page x:Class="test.Page1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:local="clr-namespace:test"
  mc:Ignorable="d"
  d:DesignHeight="450" d:DesignWidth="800"
  Title="Page1"

  xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
  TextElement.Foreground="{DynamicResource MaterialDesignBody}"
  TextElement.FontWeight="Regular"
  TextElement.FontSize="13"
  TextOptions.TextFormattingMode="Ideal"
  TextOptions.TextRenderingMode="Auto"
  Background="{DynamicResource MaterialDesignPaper}"
  FontFamily="{DynamicResource MaterialDesignFont}">
<Page.Resources>
    <ResourceDictionary Source="/MyAsembly;component/ResourceDictionary/MaterialDesign.xaml" />
</Page.Resources>

<Grid>
    <materialDesign:Card Padding="32" Margin="16">
        <TextBlock Style="{DynamicResource MaterialDesignTitleTextBlock}">My First Material Design App</TextBlock>
    </materialDesign:Card>
</Grid>

Of course I got an error: The resource {MaterialDesignBody, MaterialDesignPaper, MaterialDesignFont} could not be resolved

as @Marija Rakic mentions in the post, I dried to add dummy lines to my Page1.xaml.cs class

using MaterialDesignColors;
using MaterialDesignThemes.Wpf;
using System.Windows.Controls;

namespace test
{
    ///
    /// Interaction logic for Page1.xaml
    ///
    public partial class Page1 : Page
    {
        public Page1()
        {
            ColorZoneAssist.SetMode(new GroupBox(), ColorZoneMode.Accent);
            Hue hue = new Hue("name", System.Windows.Media.Color.FromArgb(1, 2, 3, 4), System.Windows.Media.Color.FromArgb(1, 5, 6, 7));
            InitializeComponent();
        }
    }
}

but it didn't help. The error was still there. So I tried @Trygve solution and created one more class named MaterialDesign.xaml.cs where I added an assembly

using System.IO;
using System.Reflection;
using System.Windows;

namespace test
{
    partial class MaterialDesign: ResourceDictionary
    {
        public MaterialDesign() {
            Assembly.LoadFrom(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MaterialDesignThemes.Wpf.dll"));
            Assembly.LoadFrom(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MaterialDesignColors.dll"));
            InitializeComponent();
        }
    }
}

and added a reference to MaterialDesign.xaml:

x:Class="test.MaterialDesign"

but it also didn't work and mentioned error is still there.I don't know where I'm making a mistake ..

Body:
This is how i get it running:

App.xaml

<ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Dark.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.DeepPurple.xaml" />
        </ResourceDictionary.MergedDictionaries>

MainWindow.xaml

<Window x:Class="PRWSolution.UI.View.Shell.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:PRWSolution.UI.View"
    xmlns:language="clr-namespace:PRWSolution.UI.Properties.Langs"
    xmlns:setting="clr-namespace:PRWSolution.UI.Properties"
    mc:Ignorable="d"
    xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
    DataContext="{Binding Main, Source={StaticResource Locator}}"
    TextElement.Foreground="{DynamicResource MaterialDesignBody}"
    Background="{DynamicResource MaterialDesignPaper}"
    TextElement.FontWeight="Medium"
    TextElement.FontSize="14"
    WindowState="Maximized"
    WindowStyle="None"
    FontFamily="{materialDesign:MaterialDesignFont}"
    Title="MainWindow"
    Height="800"
    Width="1080">

Also a big help is the Homepage from MaterialDesign. When you follow the instructions it will work for sure.
MaterialDesign In XAML


问:
How to handle colon (:) in the name when using Selenium in Python
I am trying to search a number in a web page (https://muisca.dian.gov.co/WebRutMuisca/DefConsultaEstadoRUT.faces).

I know the name of the input element is: "vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit", however when I try to find the element I got this error:

```<code>"NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"[name="vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit"]"}
  (Session info: chrome=81.0.4044.138)"
</code>```

This is what I have tried:

```<code>from selenium import webdriver
driver = webdriver.Chrome("C:\\Users\\jcherrerab\\Anaconda3\\Lib\\site-packages\\selenium\\webdriver\\chrome\\chromedriver.exe")
driver.get("https://muisca.dian.gov.co/WebRutMuisca/DefConsultaEstadoRUT.faces")
driver.find_element_by_name("vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit").send_keys("860003020")
</code>```

Can you help me pls?

答:
The name attribute of the <input> element contains the : character as in:

```<code>vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit
</code>```

And : bears a special effect when used within a css-selectors. Hence your program fails to find the desired element and raises NoSuchElementException

Solution

To find the element you can use either of the following Locator Strategies:

Using css_selector:

```<code>driver.find_element_by_css_selector("input[name='vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit']")
</code>```

Using xpath:

```<code>driver.find_element_by_xpath("//input[@name='vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit']")
</code>```

Best practices

As you are invoking send_keys() ideally you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit']"))).send_keys("860003020")
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit']"))).send_keys("860003020")
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Browser Snapshot:

Reference

You can find a couple of relevant discussions in:

Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element while trying to click Next button with selenium

Body:
I am trying to search a number in a web page (https://muisca.dian.gov.co/WebRutMuisca/DefConsultaEstadoRUT.faces).

I know the name of the input element is: "vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit", however when I try to find the element I got this error:

"NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"[name="vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit"]"}
  (Session info: chrome=81.0.4044.138)"

This is what I have tried:

from selenium import webdriver
driver = webdriver.Chrome("C:\\Users\\jcherrerab\\Anaconda3\\Lib\\site-packages\\selenium\\webdriver\\chrome\\chromedriver.exe")
driver.get("https://muisca.dian.gov.co/WebRutMuisca/DefConsultaEstadoRUT.faces")
driver.find_element_by_name("vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit").send_keys("860003020")

Can you help me pls?

Body:
The name attribute of the <input> element contains the : character as in:

vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit

And : bears a special effect when used within a css-selectors. Hence your program fails to find the desired element and raises NoSuchElementException

Solution

To find the element you can use either of the following Locator Strategies:

Using css_selector:

driver.find_element_by_css_selector("input[name='vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit']")

Using xpath:

driver.find_element_by_xpath("//input[@name='vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit']")

Best practices

As you are invoking send_keys() ideally you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit']"))).send_keys("860003020")

Using XPATH:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='vistaConsultaEstadoRUT:formConsultaEstadoRUT:numNit']"))).send_keys("860003020")

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Browser Snapshot:

Reference

You can find a couple of relevant discussions in:

Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element while trying to click Next button with selenium


问:
Is it legal to use \\ in // C++ comment? (LaTeX equation in C++ comment)
For documentation purpose I need to add some LaTeX equations in my C++ comments, by example:

```<code>//
// \begin{eqnarray*}
//   y_1 &=& x_1 \\
//   y_2 &=& x_2
// \end{eqnarray*}
//
int main() {}
</code>```

With clang++ (version 9.0.1-10) I can compile my code without problem:

```<code>clang++ -Wall prog.cpp
</code>```

but with g++ (version 9.2.1)

```<code>g++ -Wall prog.cpp
</code>```

I get this warning:

```<code>prog.cpp:3:1: warning: multi-line comment [-Wcomment]
    3 | //   y_1 &=& x_1 \\
      | ^
</code>```

My question: which compiler is right? Can I legally use \\ inside C++ // comment?

答:
which compiler is right?

Both. The warning is not about "legal usage of \" the warning is about multiline comment.

In C a \ character on the end of the line means to ignore the newline. So the two lines:

```<code>// blabla\
abcabc
</code>```

and:

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

Are exactly equivalent. The double backslash \\ is just a backslash \ that is escaped by \, so it is first substituted by a backslash, then preprocessor detects backslashes followed by a newline and deletes newlines. That's why it's dangerous.

```<code>int a = 1;
// increase a \\
a++;
printf("%d\n", a); // will print `1`
</code>```

Body:
For documentation purpose I need to add some LaTeX equations in my C++ comments, by example:

//
// \begin{eqnarray*}
//   y_1 &=& x_1 \\
//   y_2 &=& x_2
// \end{eqnarray*}
//
int main() {}

With clang++ (version 9.0.1-10) I can compile my code without problem:

clang++ -Wall prog.cpp

but with g++ (version 9.2.1)

g++ -Wall prog.cpp

I get this warning:

prog.cpp:3:1: warning: multi-line comment [-Wcomment]
    3 | //   y_1 &=& x_1 \\
      | ^

My question: which compiler is right? Can I legally use \\ inside C++ // comment?

Body:
which compiler is right?

Both. The warning is not about "legal usage of \" the warning is about multiline comment.

In C a \ character on the end of the line means to ignore the newline. So the two lines:

// blabla\
abcabc

and:

// blabalabcbc

Are exactly equivalent. The double backslash \\ is just a backslash \ that is escaped by \, so it is first substituted by a backslash, then preprocessor detects backslashes followed by a newline and deletes newlines. That's why it's dangerous.

int a = 1;
// increase a \\
a++;
printf("%d\n", a); // will print `1`


问:
uiop:launch-program and nodejs
I'm trying to launch node, write JS and read back the answer. Why does the following code not work but hangs at the read-line? echo "console.log(1+1)" | node works fine.

```<code>(defvar node-process (uiop:launch-program '("/usr/local/bin/node")
                                          :input :stream
                                          :output :stream
                                          :error-output :stream))

(defvar node-stream (make-two-way-stream (uiop:process-info-output node-process)
                                         (uiop:process-info-input node-process)))

(write-line "console.log(1+1)" node-stream)
(force-output node-stream)
(format t "~s~%" (read-line node-stream))
</code>```

答:
It appears that node only emit output after EOF is read when in non-interactive mode, so you need to close the input stream before reading.

Add
(close (two-way-stream-input-stream node-stream))
after force-output and before read-line.

Title: uiop:launch-program and nodejs

Body:
I'm trying to launch node, write JS and read back the answer. Why does the following code not work but hangs at the read-line? echo "console.log(1+1)" | node works fine.

(defvar node-process (uiop:launch-program '("/usr/local/bin/node")
                                          :input :stream
                                          :output :stream
                                          :error-output :stream))

(defvar node-stream (make-two-way-stream (uiop:process-info-output node-process)
                                         (uiop:process-info-input node-process)))

(write-line "console.log(1+1)" node-stream)
(force-output node-stream)
(format t "~s~%" (read-line node-stream))


问:
Is there an easy way in Javascript to add parameterised event listeners to dynamically generated HTML elements?
I have an ordered list whose list items are generated using Javascript (as the number of items/their contents is variable), and I would like to add an event listener to each item dependant on which element of the list it is - so I want the 1st item to call foo(1), the 2nd element to call foo(2), the 30th element to call foo(30), etc. However, currently all elements are ending up with a listener identical to that of the last element. Code I'm using is shown below:

```<code>document.getElementById("mylist").innerHTML = "";
  for (i = 0; i < listitems.length; i++) {
    var li = document.createElement("li");
    li.setAttribute("id", "listitem" + i);
    li.addEventListener("click",function(){foo(i)})
    document.getElementById("mylist").appendChild(li);
  }
</code>```

答:
You have to try as below to capture variable inside for loop to set event listener. Find Creating closures in loops: A common mistake in this document.

Update your event listener assignment as li.addEventListener("click", function(){ var index = i; return foo(index); });.

Complete code is as below.

```<code>document.getElementById("mylist").innerHTML = "";
for (i = 0; i < listitems.length; i++) {
    var li = document.createElement("li");
    li.setAttribute("id", "listitem" + i);
    li.addEventListener("click", function(){ var index = i; return foo(index); });
    document.getElementById("mylist").appendChild(li);
}
</code>```

Body:
I have an ordered list whose list items are generated using Javascript (as the number of items/their contents is variable), and I would like to add an event listener to each item dependant on which element of the list it is - so I want the 1st item to call foo(1), the 2nd element to call foo(2), the 30th element to call foo(30), etc. However, currently all elements are ending up with a listener identical to that of the last element. Code I'm using is shown below:

document.getElementById("mylist").innerHTML = "";
  for (i = 0; i < listitems.length; i++) {
    var li = document.createElement("li");
    li.setAttribute("id", "listitem" + i);
    li.addEventListener("click",function(){foo(i)})
    document.getElementById("mylist").appendChild(li);
  }

Body:
You have to try as below to capture variable inside for loop to set event listener. Find Creating closures in loops: A common mistake in this document.

Update your event listener assignment as li.addEventListener("click", function(){ var index = i; return foo(index); });.

Complete code is as below.

document.getElementById("mylist").innerHTML = "";
for (i = 0; i < listitems.length; i++) {
    var li = document.createElement("li");
    li.setAttribute("id", "listitem" + i);
    li.addEventListener("click", function(){ var index = i; return foo(index); });
    document.getElementById("mylist").appendChild(li);
}


问:
Angular 9: interceptor cyclic dependency while injecting lazy loaded service
I face Cannot instantiate cyclic dependency! InjectionToken HTTP_INTERCEPTORS error while injecting my lazy loaded service in the interceptor.

However, so strange my problem is being solved by adding an empty setTimeout(() to the service injection in the interceptor. I am wondering why that happens though...

the lazy loaded LanguageService:

```<code>import { HttpClient } from '@angular/common/http';
@Injectable()

export class LanguageService {

  constructor(private http: HttpClient,
    private _translate: TranslateService) {
    this.getLanguages();
  }
// ....
</code>```

the interceptor:

```<code>import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { LanguageService } from '../app/blog/services/language.service';

@Injectable()

export class LanguageInterceptor implements HttpInterceptor {
    private _languageService:LanguageService;

    constructor(private injector: Injector) {
        /*  This way Works!
            setTimeout(() => {
            this._languageService = this.injector.get(LanguageService)
         })*/

            this._languageService = this.injector.get(LanguageService)

    }

    intercept(req: HttpRequest<any>, next: HttpHandler) {

</code>```

the interceptor barrel:

```<code>import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { LanguageInterceptor } from './lang-interceptor';

export const httpInterceptorProviders = [
  { provide: HTTP_INTERCEPTORS, useClass: LanguageInterceptor, multi: true }
];
</code>```

the shared module

```<code>import { NgModule } from '@angular/core';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClient, HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { httpInterceptorProviders } from 'src/utilities/interceptor-barrel';
import { ShareModule } from '@ngx-share/core';
import { FormsModule, ReactiveFormsModule }   from '@angular/forms';

export function HttpLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http, '../assets/i18n/', '.json');
}

const MODULES = [
    HttpClientModule,
    HttpClientJsonpModule,
    CommonModule,
    RouterModule,
    ShareModule,
    FormsModule,
    ReactiveFormsModule
];

@NgModule({
    imports: [
        MODULES,
        TranslateModule.forRoot({
            defaultLanguage: 'en',
            loader: {
                provide: TranslateLoader,
                useFactory: (HttpLoaderFactory),
                deps: [HttpClient]
            }
        }),
    ],
    exports: [
        MODULES,
        TranslateModule
    ],
    declarations: [],
    providers: [
        httpInterceptorProviders
    ],
})
</code>```

the lazy loaded module:

```<code> // ....
imports: [
        SharedModule
    ]
 // ....
 providers: [
        LanguageService
    ]
</code>```

答: The problem is in where you include your interceptors. Your Interceptors should be part of your app/core module.</p>

Body:
I face Cannot instantiate cyclic dependency! InjectionToken HTTP_INTERCEPTORS error while injecting my lazy loaded service in the interceptor.

However, so strange my problem is being solved by adding an empty setTimeout(() to the service injection in the interceptor. I am wondering why that happens though...

the lazy loaded LanguageService:

import { HttpClient } from '@angular/common/http';
@Injectable()

export class LanguageService {

  constructor(private http: HttpClient,
    private _translate: TranslateService) {
    this.getLanguages();
  }
// ....

the interceptor:

import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { LanguageService } from '../app/blog/services/language.service';

@Injectable()

export class LanguageInterceptor implements HttpInterceptor {
    private _languageService:LanguageService;

    constructor(private injector: Injector) {
        /*  This way Works!
            setTimeout(() => {
            this._languageService = this.injector.get(LanguageService)
         })*/

            this._languageService = this.injector.get(LanguageService)

    }

    intercept(req: HttpRequest<any>, next: HttpHandler) {

the interceptor barrel:

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { LanguageInterceptor } from './lang-interceptor';

export const httpInterceptorProviders = [
  { provide: HTTP_INTERCEPTORS, useClass: LanguageInterceptor, multi: true }
];

the shared module

import { NgModule } from '@angular/core';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClient, HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { httpInterceptorProviders } from 'src/utilities/interceptor-barrel';
import { ShareModule } from '@ngx-share/core';
import { FormsModule, ReactiveFormsModule }   from '@angular/forms';

export function HttpLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http, '../assets/i18n/', '.json');
}

const MODULES = [
    HttpClientModule,
    HttpClientJsonpModule,
    CommonModule,
    RouterModule,
    ShareModule,
    FormsModule,
    ReactiveFormsModule
];

@NgModule({
    imports: [
        MODULES,
        TranslateModule.forRoot({
            defaultLanguage: 'en',
            loader: {
                provide: TranslateLoader,
                useFactory: (HttpLoaderFactory),
                deps: [HttpClient]
            }
        }),
    ],
    exports: [
        MODULES,
        TranslateModule
    ],
    declarations: [],
    providers: [
        httpInterceptorProviders
    ],
})

the lazy loaded module:

 // ....
imports: [
        SharedModule
    ]
 // ....
 providers: [
        LanguageService
    ]


问:
ISTIO GRPC Gateway configuration
I am trying to setup ISTIO Gateway with GRPC. I am using example from:https://github.com/h3poteto/istio-grpc-example.

This example does not contain Gateway. I added the Gateway:

```<code>kind: Gateway
metadata:
  name: my-gateway
  namespace: istio-grpc-example
spec:
  selector:
    istio: ingressgateway
  servers:
  - port:
      number: 80
      name: grpc-wildcard
      protocol: GRPC
    hosts:
    - "*"
</code>```

and modified the VirtualService:

```<code>apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: backend
  namespace: istio-grpc-example
spec:
  hosts:
    - "backend"
  gateways:
  - my-gateway
  http:
  - match:
    - port: 50051
    route:
    - destination:
        host: backend
        subset: v0
      weight: 90
    - destination:
        host: backend
        subset: v1
      weight: 10
</code>```

Is there somethig else I should do? I still cannot go through Gateway… Received an error when querying services endpoint.

Thank you!

答:
As I mentioned in comments

Have you tried with wildcard hosts? * instead of backend?

You need to change virtual service hosts.

```<code>spec:
  hosts:
    - "backend"
</code>```

to

```<code>spec:
  hosts:
    - "*"
</code>```

And @Ondra add that other thing he changed was the gateway port number.

I changed the port number from 80 to 31400 and changed the host from "backend" to "*". Now it looks like everything is working. – Ondra

Title: ISTIO GRPC Gateway configuration

Body:
I am trying to setup ISTIO Gateway with GRPC. I am using example from:https://github.com/h3poteto/istio-grpc-example.

This example does not contain Gateway. I added the Gateway:

kind: Gateway
metadata:
  name: my-gateway
  namespace: istio-grpc-example
spec:
  selector:
    istio: ingressgateway
  servers:
  - port:
      number: 80
      name: grpc-wildcard
      protocol: GRPC
    hosts:
    - "*"

and modified the VirtualService:

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: backend
  namespace: istio-grpc-example
spec:
  hosts:
    - "backend"
  gateways:
  - my-gateway
  http:
  - match:
    - port: 50051
    route:
    - destination:
        host: backend
        subset: v0
      weight: 90
    - destination:
        host: backend
        subset: v1
      weight: 10

Is there somethig else I should do? I still cannot go through Gateway… Received an error when querying services endpoint.

Thank you!

Body:
As I mentioned in comments

Have you tried with wildcard hosts? * instead of backend?

You need to change virtual service hosts.

spec:
  hosts:
    - "backend"

to

spec:
  hosts:
    - "*"

And @Ondra add that other thing he changed was the gateway port number.

I changed the port number from 80 to 31400 and changed the host from "backend" to "*". Now it looks like everything is working. – Ondra


问:
(intermediate value)}.then is not a function
I am trying to generate a backup from my REST API made with node js, but when trying to execute the code that generates the backup file, it throws me that it is not a function .then(dump => { fs.writeFileSync, this is the code with the error

var mysqlDump = require('mysqldump');
var fs = require('fs');

const dump = mysqlDump({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'demo',
    tables:['sales_orders'], // only these tables
   // where: {'estado': 'id < 1000'}, // Only test players with id < 1000
    //ifNotExist:true, // Create table if not exist
}.then(dump => {
    fs.writeFileSync('test.sql', dump); // Create data.sql file with dump result

}));

module.exports = dump;```

答:
There is missing ")" closing tag after }). Try this: </p>

```<code>var mysqlDump = require('mysqldump');
var fs = require('fs');

const dump = mysqlDump({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'demo',
    tables:['sales_orders'], // only these tables
   // where: {'estado': 'id < 1000'}, // Only test players with id < 1000
    //ifNotExist:true, // Create table if not exist
}).then(dump => {
    fs.writeFileSync('test.sql', dump); // Create data.sql file with dump result
    });

module.exports = dump;
</code>```

Body:
There is missing ")" closing tag after }). Try this:

var mysqlDump = require('mysqldump');
var fs = require('fs');

const dump = mysqlDump({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'demo',
    tables:['sales_orders'], // only these tables
   // where: {'estado': 'id < 1000'}, // Only test players with id < 1000
    //ifNotExist:true, // Create table if not exist
}).then(dump => {
    fs.writeFileSync('test.sql', dump); // Create data.sql file with dump result
    });

module.exports = dump;


问:
Limelight Video player (Shuffle functionality)
I figured out there is no functionality of SHUFFLE in you delve player. I am trying to implement such functionality using delve player's javascript api.  Some strange reason we are not able to get this functionality because DelvePlayer.doSetMedia function is not working as it should under onMediaComplete event. Although DelvePlayer.doSetMedia is working on button click

please see code snippet below

```<code>function delvePlayerCallback(playerId, eventName, data) {

var id = "limelight_player_20758";
if (eventName == 'onPlayerLoad' && (DelvePlayer.getPlayers() == null || DelvePlayer.getPlayers().length == 0)) {
  DelvePlayer.registerPlayer(id);
}

switch (eventName) {

  case 'onMediaComplete':
        var playIndex = 0;
        channel = DelvePlayer.doGetCurrentChannel();
        media_count = channel.mediaList.length;
        if(media_count > 1)
        {
            getRandomNum = randomFromTo(0, (media_count > 1) ? media_count - 1 : 0) ;

            //alert(getRandomNum + ' ' + channel.mediaList[getRandomNum].id + ' ' + channel.mediaList[getRandomNum].title + ' current index: ' + DelvePlayer.doGetCurrentIndex());

             //this function is not working
             DelvePlayer.doSetMedia(channel.mediaList[getRandomNum].id,true); // this function is not working

            //DelvePlayer.doPlay();
        }

    break;

    case 'onError' :
        alert ('error');
    break;
}   }
</code>```

Please advise

答:
are servers working?
check the link. maybe it is your answer too.

http://www.longtailvideo.com/support/forums/jw-player/setup-issues-and-embedding/7211/streaming-with-limelight

Body:
I figured out there is no functionality of SHUFFLE in you delve player. I am trying to implement such functionality using delve player's javascript api.  Some strange reason we are not able to get this functionality because DelvePlayer.doSetMedia function is not working as it should under onMediaComplete event. Although DelvePlayer.doSetMedia is working on button click

please see code snippet below

function delvePlayerCallback(playerId, eventName, data) {

var id = "limelight_player_20758";
if (eventName == 'onPlayerLoad' && (DelvePlayer.getPlayers() == null || DelvePlayer.getPlayers().length == 0)) {
  DelvePlayer.registerPlayer(id);
}

switch (eventName) {

  case 'onMediaComplete':
        var playIndex = 0;
        channel = DelvePlayer.doGetCurrentChannel();
        media_count = channel.mediaList.length;
        if(media_count > 1)
        {
            getRandomNum = randomFromTo(0, (media_count > 1) ? media_count - 1 : 0) ;

            //alert(getRandomNum + ' ' + channel.mediaList[getRandomNum].id + ' ' + channel.mediaList[getRandomNum].title + ' current index: ' + DelvePlayer.doGetCurrentIndex());

             //this function is not working
             DelvePlayer.doSetMedia(channel.mediaList[getRandomNum].id,true); // this function is not working

            //DelvePlayer.doPlay();
        }

    break;

    case 'onError' :
        alert ('error');
    break;
}   }

Please advise


问:
Convert one response object to another object(pojo) in Spring webflux flux responce without subscribing it
I am trying to consume one rest api which returns response in FLUX.
My target is to consume rest api and process flux response object (Convert one response object-1 to another object-2(pojo) in Spring 5 webflux ) and return object-2 with response to caller application without subscribing it.</p>

答:
The best way to do this is using webclient as rest client that allows you to get Flux as response and then use map to convert the object to any other type and the use webclient again to submit the new response.
For example:

```<code>FLux<Foo> response = webClient.get()
            .uri("/foo")
            .retrieve()
            .bodyToFlux(GithubRepo.class);
Flux<Bar> converted = response.map(response -> convertToBar(response));

webClient.post()
            .uri("/bar")
            .body(converted, Bar.class)
            .retrieve();
</code>```

Here you have a complete tutorial on how to use webclient.

https://www.baeldung.com/spring-5-webclient

Body:
The best way to do this is using webclient as rest client that allows you to get Flux as response and then use map to convert the object to any other type and the use webclient again to submit the new response.
For example:

FLux<Foo> response = webClient.get()
            .uri("/foo")
            .retrieve()
            .bodyToFlux(GithubRepo.class);
Flux<Bar> converted = response.map(response -> convertToBar(response));

webClient.post()
            .uri("/bar")
            .body(converted, Bar.class)
            .retrieve();

Here you have a complete tutorial on how to use webclient.

https://www.baeldung.com/spring-5-webclient


问:
How to draw 3D model in PyGlet
I was able to get a 3D model in .obj format, but I don't know how to draw it on the screen. Here's my code:

```<code>import pyglet

model = pyglet.resource.model('untitled.obj')
window = pyglet.window.Window()

@window.event
def on_draw():
    window.clear()
    model.draw()

pyglet.app.run()
</code>```

But it outputs this error:

```<code>pyglet.gl.lib.GLException: b'\xed\xe5\xe4\xee\xef\xf3\xf1\xf2\xe8\xec\xee\xe5 \xe7\xed\xe0\xf7\xe5\xed\xe8\xe5'
</code>```

If you do the following

```<code>model = pyglet.resource.model('untitled.obj')
print(model)
</code>```

Output:

```<code><pyglet.model.Model object at 0x02E356E8>
</code>```

答: I'm pretty sure pyglet is just made for 2d stuff. The .draw() function rasterisers 2d images pixel by pixel, but more complicated rendering methods are needed for 3d models, even a simple cube. You may need to write a lot more code for this project. A simple way may be to raycast, as in the original doom game, which gives very simple 3d graphics which can have textures. Unfortunately, this method makes complicated shapes impossible and you have to code all the models in your project, not using external sources such as blender. There are numerous methods of compressing a 3d model into a 2d image, but a .draw() function just isn't enough. depending on what kind of game/program you're making, you may want to se raycasting or other methods, But I'd recommend using some other game engine t create 3d games. Unity is a good example, unreal engine too.

Title: How to draw 3D model in PyGlet

Body:
I was able to get a 3D model in .obj format, but I don't know how to draw it on the screen. Here's my code:

import pyglet

model = pyglet.resource.model('untitled.obj')
window = pyglet.window.Window()

@window.event
def on_draw():
    window.clear()
    model.draw()

pyglet.app.run()

But it outputs this error:

pyglet.gl.lib.GLException: b'\xed\xe5\xe4\xee\xef\xf3\xf1\xf2\xe8\xec\xee\xe5 \xe7\xed\xe0\xf7\xe5\xed\xe8\xe5'

If you do the following

model = pyglet.resource.model('untitled.obj')
print(model)

Output:

<pyglet.model.Model object at 0x02E356E8>


问:
Is it possible to Store AWS API gateway API keys in secret manager and rotate them
I want to create multiple API keys and distribute among the customers, Once I create an API key and attach it to usage plan I want to save it to secrets manager, Can secret manager apply the rotation policy to the API keys in API gateway or we need to develop our own mechanism for it?
I see it can apply rotation policy to AWS database credentials but didn't see the same for AWS API keys.</p>

答:
There is not a solution like RDS where you simply enter credentials and it does it for you, however, there is a native solution supported by Secrets Manager that I believe will service your purpose.

Secrets Manager has support for a Lambda Rotation, whereby it will invoke a Lambda of your choosing with that Lambda performing its required tasks then returning the new key back to be stored in Secrets Manager.

So your solution would look similar to this

```<code>Secrets Manager -> Invoke Lambda -> Create new key and retire old key(s) -> Return new key to secrets manager
</code>```

Body:
There is not a solution like RDS where you simply enter credentials and it does it for you, however, there is a native solution supported by Secrets Manager that I believe will service your purpose.

Secrets Manager has support for a Lambda Rotation, whereby it will invoke a Lambda of your choosing with that Lambda performing its required tasks then returning the new key back to be stored in Secrets Manager.

So your solution would look similar to this

Secrets Manager -> Invoke Lambda -> Create new key and retire old key(s) -> Return new key to secrets manager


问:
WampServer Hosting
about 6 months ago I got into coding, and I've always wanted to start my own game just for fun on the side.

I have wampserver on my computer, and was wondering if that server could publicly host things on the internet?

答:
I just put a wamp server up on a box in my house just for funsies.
Here is a wampserver forum post with links to the info you seek.

Here is the basic rundown though:

Open up your router to port 80 and forward it to the box you are serving on.

Get setup on a DNS server, I used freedns.afraid.org.

In wamp you are gonna set apache to use virtual hosts (this is in the link).

After that you should be cool.

Title: WampServer Hosting


问:
Why does this apt-key adv command give an error?
This is a snippet of a Dockerfile that is exhibiting an error that I don't understand:

```<code>FROM dorowu/ubuntu-desktop-lxde-vnc
LABEL maintainer "bpinaya@wpi.edu"

# Adding keys for ROS
RUN sh -c 'echo "deb http://packages.ros.org/ros/ubuntu $(lsb_release -sc) main" > /etc/apt/sources.list.d/ros-latest.list'
RUN apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-key 421C365BD9FF1F717815A3895523BAEEB01FA116
</code>```

Gives this result

```<code>RUN apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-key 421C365BD9FF1F717815A3895523BAEEB01FA116
 ---> Running in 7bb30729ec87
Warning: apt-key output should not be parsed (stdout is not a terminal)
Executing: /tmp/apt-key-gpghome.HkofyyhjvI/gpg.1.sh --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-key 421C365BD9FF1F717815A3895523BAEEB01FA116
gpg: failed to start the dirmngr '/usr/bin/dirmngr': No such file or directory
gpg: connecting dirmngr at '/tmp/apt-key-gpghome.HkofyyhjvI/S.dirmngr' failed: No such file or directory
gpg: keyserver receive failed: No dirmngr
The command '/bin/sh -c apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-key 421C365BD9FF1F717815A3895523BAEEB01FA116' returned a non-zero code: 2
</code>```

答:
I wanted to comment but don't have enough reputation to. Please consider my answer as an appendix to @brian-elliott 's answer. Dirmngr seems to have some strange default setup to use tor or some non-standard DNS. So make sure you have something like this:

```<code>standard-resolver
keyserver keyserver.ubuntu.com
keyserver keys.gnupg.net
</code>```

in your ~/.gnupg/dirmngr.conf

Body:
This is a snippet of a Dockerfile that is exhibiting an error that I don't understand:

FROM dorowu/ubuntu-desktop-lxde-vnc
LABEL maintainer "bpinaya@wpi.edu"

# Adding keys for ROS
RUN sh -c 'echo "deb http://packages.ros.org/ros/ubuntu $(lsb_release -sc) main" > /etc/apt/sources.list.d/ros-latest.list'
RUN apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-key 421C365BD9FF1F717815A3895523BAEEB01FA116

Gives this result

RUN apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-key 421C365BD9FF1F717815A3895523BAEEB01FA116
 ---> Running in 7bb30729ec87
Warning: apt-key output should not be parsed (stdout is not a terminal)
Executing: /tmp/apt-key-gpghome.HkofyyhjvI/gpg.1.sh --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-key 421C365BD9FF1F717815A3895523BAEEB01FA116
gpg: failed to start the dirmngr '/usr/bin/dirmngr': No such file or directory
gpg: connecting dirmngr at '/tmp/apt-key-gpghome.HkofyyhjvI/S.dirmngr' failed: No such file or directory
gpg: keyserver receive failed: No dirmngr
The command '/bin/sh -c apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-key 421C365BD9FF1F717815A3895523BAEEB01FA116' returned a non-zero code: 2

Body:
I wanted to comment but don't have enough reputation to. Please consider my answer as an appendix to @brian-elliott 's answer. Dirmngr seems to have some strange default setup to use tor or some non-standard DNS. So make sure you have something like this:

standard-resolver
keyserver keyserver.ubuntu.com
keyserver keys.gnupg.net

in your ~/.gnupg/dirmngr.conf


问:
Need code sugg. for my spec to create small admin application
My Spec : Login, Logout, dashboard, I need to render 150 inputs in single form, need to download pdf file for saved inputs. And each inputs need to save input blur action and also form submission.

The existing application has build nodeJs with expressJs with jade template for rendering. Backend(mySql) connection has builded laravel (lumen).

FrontEnd - NodeJS, ExpressJs, Jade template
Backend - Laravel Lumen

Provide some suggestion to best language for my requirement to code.

Had some suggestion like

Laravel + VueJs

NodeJs + ExpressJs + ReactJs

NodeJs + ExpressJs

Thanks in advance

答:
You can create REST API using NodeJS and Express framework. If it just uploading file and auth you can use middleware function and the library you can use like multer and jsonwebtoken for uploading and user validation.. i prefer hbs instead of jade because it HTML based.
I hope this helps</p>


问:
Check Contact Number and Email is fake or not?
Is there any way to find out number or mail entered by user is fake or not?
Using angular7 anf firebase?</p>

答:
On the frontend side you can just validate the format of email or number

But if you need to verify if it is fake or real you might need to enable one time password implementation on backend side


问:
Using Java for light control
when reading Eckel's Thinking in Java, I found design for controlling Greenhouse. It really struck me, since he was mentioning in comment lines "here put the hardware code for controlling light" and stuff, and I want to know - how would I make such a simple thing, as controlling physical light, or traffic light with Java program?

How would I connect light to PC and power it, through software control?

I believe assembly language with some microcontroller is the way, but I do not intend to learn assembly language yet, so I want to know if there's possibility to do this with Java?

Thanks,
M.

答: I've recently been playing around with Arduino. It's not too difficult to write a Java program which talks to the board over serial, with the board controlling motors, leds or the like. The Arduino programming language is quite simple and based on C so with some java knowledge this should be straightforward.</p>

Title: Using Java for light control


问:
How do I remove the layer of control box of the second(child) form within the MDI form as parent form in C#?
```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

    namespace SchoolDemo
{
    public partial class MDI : Form
    {
        public MDI()
        {
            InitializeComponent();
        }

        private void MDI_Load(object sender, EventArgs e)
        {
            Demo naya = new Demo();
            {
                naya.MdiParent = this;
                naya.WindowState = FormWindowState.Maximized;
            };
            naya.Show();
        }
    }
}
</code>```

[^This is the code of my MDI form]

In the right hand corner you can see there is a extra layer of max, min and close options.
I have already disabled control box in child form but I am still getting this.

答:
According to your description, you want to remove the layer of control box of the child

form.

You can try the following code to solve this problem.

Child form code:

```<code>  private void Demo_Load(object sender, EventArgs e)
        {
            ControlBox = false;
        }
</code>```

Body:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

    namespace SchoolDemo
{
    public partial class MDI : Form
    {
        public MDI()
        {
            InitializeComponent();
        }

        private void MDI_Load(object sender, EventArgs e)
        {
            Demo naya = new Demo();
            {
                naya.MdiParent = this;
                naya.WindowState = FormWindowState.Maximized;
            };
            naya.Show();
        }
    }
}

[^This is the code of my MDI form]

In the right hand corner you can see there is a extra layer of max, min and close options.
I have already disabled control box in child form but I am still getting this.

Body:
According to your description, you want to remove the layer of control box of the child

form.

You can try the following code to solve this problem.

Child form code:

  private void Demo_Load(object sender, EventArgs e)
        {
            ControlBox = false;
        }


问:
React: React-table not rendering data multiple different state variables
I am using this react-table component library. I have a data state variable with three state variables in it and I am making three API calls to fetch data for all three of them. Then, in JSX I am destructuring that response.data and passing it inside data of react-table component. But, it's not working.

Code for my react-table component:

```<code>import React, { Component } from "react";
// react component for creating dynamic tables
import ReactTable from "react-table";

import axios from "axios";
import {
  Card,
  CardBody,
  CardHeader,
  CardTitle,
  Row,
  Col,
  Dropdown,
  DropdownToggle,
  DropdownMenu,
  DropdownItem,
} from "reactstrap";

class DataViewTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {
        system: [],
        measurements: [],
        measurementData: [],
      },
      isLoading: false,
      dropdownOpen: false,
    };
  }

  signal = axios.CancelToken.source();

  componentDidMount() {
    this.handleGetSystemInfo();
    this.handleGetMeasurementsInfo();
    this.handleGetMeasurementDataInfo();
    this.addFilterPlaceholder();
  }

  componentUnMount() {
    this.signal.cancel("Api is being canceled");
  }
  handleGetSystemInfo = async () => {
    this.setState({ isLoading: true });
    await axios
      .get("http://www.mocky.io/v2/5ed488f83300005f00f7a20e")
      .then((response) => {
        // handle success
        console.log("system:", response.data);
        this.setState({ system: response.data });
      })
      .catch((error) => {
        // handle error
        if (axios.isCancel(error)) {
          console.log("Unable to fetch system data", error.message);
        } else {
          this.setState({ isLoading: false });
        }
      });
  };
  handleGetMeasurementsInfo = async () => {
    this.setState({ isLoading: true });
    await axios
      .get("http://www.mocky.io/v2/5ed4899d3300003f00f7a212")
      .then((response) => {
        // handle success
        console.log("measurements:", response.data);
        this.setState({ measurements: response.data });
      })
      .catch((error) => {
        // handle error
        if (axios.isCancel(error)) {
          console.log("Unable to fetch measurements info", error.message);
        } else {
          this.setState({ isLoading: false });
        }
      });
  };
  handleGetMeasurementDataInfo = async () => {
    this.setState({ isLoading: true });
    await axios
      .get("http://www.mocky.io/v2/5ed48a113300007900f7a213")
      .then((response) => {
        // handle success
        console.log("measurement data:", response.data);
        this.setState({ measurementData: response.data });
      })
      .catch((error) => {
        // handle error
        if (axios.isCancel(error)) {
          console.log("Unable to fetch measurementData", error.message);
        } else {
          this.setState({ isLoading: false });
        }
      });
  };

  addFilterPlaceholder = () => {
    const filters = document.querySelectorAll("div.rt-th > input");
    for (let filter of filters) {
      filter.placeholder = "Search..";
    }
  };

  toggleDropdown = () => {
    this.setState((state) => {
      return {
        dropdownOpen: !state.dropdownOpen,
      };
    });
  };

  render() {
    const { dropdownOpen } = this.state;
    const { system, measurementData, measurements } = this.state.data;
    return (
      <>
        <div className="content">
          <Row className="mt-5">
            <Col xs={12} md={12}>
              <Card>
                <CardHeader>
                  <CardTitle tag="h4">Table of data</CardTitle>
                  <hr />
                  <Dropdown
                    isOpen={dropdownOpen}
                    toggle={this.toggleDropdown}
                    className="shipsDropdown"
                  >
                    <DropdownToggle caret>Ships</DropdownToggle>
                    <DropdownMenu>
                      <DropdownItem>Foo Action</DropdownItem>
                      <DropdownItem divider />
                      <DropdownItem>Bar Action</DropdownItem>
                      <DropdownItem divider />
                      <DropdownItem>Quo Action</DropdownItem>
                    </DropdownMenu>
                  </Dropdown>
                </CardHeader>
                <CardBody>
                  <ReactTable
                    data={(system, measurements, measurementData)}
                    filterable
                    resizable={false}
                    columns={[
                      {
                        Header: "System",
                        accessor: "name",
                      },
                      {
                        Header: "Measurement",
                        accessor: "name",
                      },
                      {
                        Header: "Value",
                        accessor: "values.temp1, values.temp2",
                      },
                      {
                        Header: "Min",
                        accessor: "",
                      },
                      {
                        Header: "Max",
                        accessor: "",
                      },
                      {
                        Header: "Avg",
                        accessor: "",
                      },
                      {
                        Header: "Last",
                        accessor: "",
                      },
                      {
                        Header: "Bar",
                        accessor: "",
                      },
                    ]}
                    showPaginationTop
                    showPaginationBottom={false}
                    className="-striped -highlight"
                  />
                </CardBody>
              </Card>
            </Col>
          </Row>
        </div>
      </>
    );
  }
}

export default DataViewTable;
</code>```

Adding CodeSandbox link

答:
There are multiple things that need to be handled correctly here

You have set state as measurementData, measurements and system directly and not under data in the axios request so you must use them directly

```<code> constructor(props) {
    super(props);
    this.state = {
        system: [],
        measurements: [],
        measurementData: [],
      ...
    };
  }
</code>```

You are not passing the cancelToken to the axios request. Also a separate cancelToken must be used individual calls

```<code>this.signalToken = axios.CancelToken.source();
await axios
      .get("http://www.mocky.io/v2/5ed48a113300007900f7a213", {
         cancelToken: this.signalToken.token
      })

</code>```

and so on for the other requests and cancel the request like

```<code>this.signalToken.cancel();
this.measurementsToken.cancel()
this.measurementsDataToken.cancel()

</code>```

The data to ReactTable should be an array of merged resource if they have the same format. However they have different format, you should consider rendering multiple ReactTables

```<code><ReactTable
    data={[...system, ...measurements, ...measurementData]}
    filterable
    resizable={false}

</code>```

Body:
I am using this react-table component library. I have a data state variable with three state variables in it and I am making three API calls to fetch data for all three of them. Then, in JSX I am destructuring that response.data and passing it inside data of react-table component. But, it's not working.

Code for my react-table component:

import React, { Component } from "react";
// react component for creating dynamic tables
import ReactTable from "react-table";

import axios from "axios";
import {
  Card,
  CardBody,
  CardHeader,
  CardTitle,
  Row,
  Col,
  Dropdown,
  DropdownToggle,
  DropdownMenu,
  DropdownItem,
} from "reactstrap";

class DataViewTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {
        system: [],
        measurements: [],
        measurementData: [],
      },
      isLoading: false,
      dropdownOpen: false,
    };
  }

  signal = axios.CancelToken.source();

  componentDidMount() {
    this.handleGetSystemInfo();
    this.handleGetMeasurementsInfo();
    this.handleGetMeasurementDataInfo();
    this.addFilterPlaceholder();
  }

  componentUnMount() {
    this.signal.cancel("Api is being canceled");
  }
  handleGetSystemInfo = async () => {
    this.setState({ isLoading: true });
    await axios
      .get("http://www.mocky.io/v2/5ed488f83300005f00f7a20e")
      .then((response) => {
        // handle success
        console.log("system:", response.data);
        this.setState({ system: response.data });
      })
      .catch((error) => {
        // handle error
        if (axios.isCancel(error)) {
          console.log("Unable to fetch system data", error.message);
        } else {
          this.setState({ isLoading: false });
        }
      });
  };
  handleGetMeasurementsInfo = async () => {
    this.setState({ isLoading: true });
    await axios
      .get("http://www.mocky.io/v2/5ed4899d3300003f00f7a212")
      .then((response) => {
        // handle success
        console.log("measurements:", response.data);
        this.setState({ measurements: response.data });
      })
      .catch((error) => {
        // handle error
        if (axios.isCancel(error)) {
          console.log("Unable to fetch measurements info", error.message);
        } else {
          this.setState({ isLoading: false });
        }
      });
  };
  handleGetMeasurementDataInfo = async () => {
    this.setState({ isLoading: true });
    await axios
      .get("http://www.mocky.io/v2/5ed48a113300007900f7a213")
      .then((response) => {
        // handle success
        console.log("measurement data:", response.data);
        this.setState({ measurementData: response.data });
      })
      .catch((error) => {
        // handle error
        if (axios.isCancel(error)) {
          console.log("Unable to fetch measurementData", error.message);
        } else {
          this.setState({ isLoading: false });
        }
      });
  };

  addFilterPlaceholder = () => {
    const filters = document.querySelectorAll("div.rt-th > input");
    for (let filter of filters) {
      filter.placeholder = "Search..";
    }
  };

  toggleDropdown = () => {
    this.setState((state) => {
      return {
        dropdownOpen: !state.dropdownOpen,
      };
    });
  };

  render() {
    const { dropdownOpen } = this.state;
    const { system, measurementData, measurements } = this.state.data;
    return (
      <>

          <Row className="mt-5">
            <Col xs={12} md={12}>
              <Card>
                <CardHeader>
                  <CardTitle tag="h4">Table of data</CardTitle>

                  <Dropdown
                    isOpen={dropdownOpen}
                    toggle={this.toggleDropdown}
                    className="shipsDropdown"
                  >
                    <DropdownToggle caret>Ships</DropdownToggle>
                    <DropdownMenu>
                      <DropdownItem>Foo Action</DropdownItem>
                      <DropdownItem divider />
                      <DropdownItem>Bar Action</DropdownItem>
                      <DropdownItem divider />
                      <DropdownItem>Quo Action</DropdownItem>
                    </DropdownMenu>
                  </Dropdown>
                </CardHeader>
                <CardBody>
                  <ReactTable
                    data={(system, measurements, measurementData)}
                    filterable
                    resizable={false}
                    columns={[
                      {
                        Header: "System",
                        accessor: "name",
                      },
                      {
                        Header: "Measurement",
                        accessor: "name",
                      },
                      {
                        Header: "Value",
                        accessor: "values.temp1, values.temp2",
                      },
                      {
                        Header: "Min",
                        accessor: "",
                      },
                      {
                        Header: "Max",
                        accessor: "",
                      },
                      {
                        Header: "Avg",
                        accessor: "",
                      },
                      {
                        Header: "Last",
                        accessor: "",
                      },
                      {
                        Header: "Bar",
                        accessor: "",
                      },
                    ]}
                    showPaginationTop
                    showPaginationBottom={false}
                    className="-striped -highlight"
                  />
                </CardBody>
              </Card>
            </Col>
          </Row>

      </>
    );
  }
}

export default DataViewTable;

Adding CodeSandbox link

Body:
There are multiple things that need to be handled correctly here

You have set state as measurementData, measurements and system directly and not under data in the axios request so you must use them directly

 constructor(props) {
    super(props);
    this.state = {
        system: [],
        measurements: [],
        measurementData: [],
      ...
    };
  }

You are not passing the cancelToken to the axios request. Also a separate cancelToken must be used individual calls

this.signalToken = axios.CancelToken.source();
await axios
      .get("http://www.mocky.io/v2/5ed48a113300007900f7a213", {
         cancelToken: this.signalToken.token
      })

and so on for the other requests and cancel the request like

this.signalToken.cancel();
this.measurementsToken.cancel()
this.measurementsDataToken.cancel()

The data to ReactTable should be an array of merged resource if they have the same format. However they have different format, you should consider rendering multiple ReactTables

<ReactTable
    data={[...system, ...measurements, ...measurementData]}
    filterable
    resizable={false}


问:
Subdomain Mapping to AWS server
We have domain name registration with GoDaddy and website has been hosted with Bigrock and the name servers have been updated accordingly. Now we are hosting an application in AWS and we intend to create a subdomain and direct to to AWS while retaining the pimary site as is in Bigrock. Please suggest best way to do this.</p>

答: You would create either a A record (IPv4 IP address), AAAA (IPv6 IP Address) or CNAME (another domain) of subdomain.example.com and set it to the value of your AWS resource.

Title: Subdomain Mapping to AWS server


问:
How to execute gcloud command in bash script from crontab -e
I am trying execute some gcloud commands in bash script from crontab. The script execute sucessfully from command shell but not from the cron job.

I have tried with:

Settng the full path to gcloud like:

```<code> /etc/bash_completion.d/gcloud
 /home/Arturo/.config/gcloud
 /usr/bin/gcloud
 /usr/lib/google-cloud-sdk/bin/gcloud
</code>```

Setting in the begin the script:

```<code>  /bin/bash -l
</code>```

Setting in the crontab:

```<code>51 21 30 5 6 CLOUDSDK_PYTHON=/usr/bin/python2.7;
/home/myuser/folder1/myscript.sh param1 param2 param3 -f >>
/home/myuser/folder1/mylog.txt`
</code>```

Setting inside the script:

export CLOUDSDK_PYTHON=/usr/bin/python2.7

Setting inside the script:

sudo ln -s /home/myuser/google-cloud-sdk/bin/gcloud /usr/bin/gcloud

Version Ubuntu 18.04.3 LTS
command to execute: gcloud config set project myproject

but nothing is working, maybe I am doing something wrongly. I hope you can help me.

答:
You need to set your user in your crontab, for it to run the gcloud command. As well explained in this other post here, you need to modify your crontab to fetch the data in your Cloud SDK, for the execution to occur properly - it doesn't seem that you have made this configuration.

Another option that I would recommend you to try out, it's using a Cloud Scheduler to run your gcloud commands. This way, you can use gcloud for your cron jobs in a more integrated and easy way. You can verify more information about this option here: Creating and configuring cron jobs

Let me know if the information helped you!

Body:
I am trying execute some gcloud commands in bash script from crontab. The script execute sucessfully from command shell but not from the cron job.

I have tried with:

Settng the full path to gcloud like:

 /etc/bash_completion.d/gcloud
 /home/Arturo/.config/gcloud
 /usr/bin/gcloud
 /usr/lib/google-cloud-sdk/bin/gcloud

Setting in the begin the script:

  /bin/bash -l

Setting in the crontab:

51 21 30 5 6 CLOUDSDK_PYTHON=/usr/bin/python2.7;
/home/myuser/folder1/myscript.sh param1 param2 param3 -f >>
/home/myuser/folder1/mylog.txt`

Setting inside the script:

export CLOUDSDK_PYTHON=/usr/bin/python2.7

Setting inside the script:

sudo ln -s /home/myuser/google-cloud-sdk/bin/gcloud /usr/bin/gcloud

Version Ubuntu 18.04.3 LTS
command to execute: gcloud config set project myproject

but nothing is working, maybe I am doing something wrongly. I hope you can help me.


答:
Your LanguageService should not be added to the providers of the lazy loaded module. It should not be added to any providers array of a module. It should have a providedIn: 'root' in the decorator:

```<code>@Injectable({ providedIn: 'root' })
export class LanguageService {}

//  lazy loaded module
imports: [
  SharedModule
]

// ....
providers: []

</code>```

Interceptors on the other hand, should either be declared in your core module, which is included in the App root once. Or in a lazy loaded module, to define a interceptor just for that lazy loaded module

You should restructure your application. Split up your SharedModule to -only- (!important) include components/pipes/directives. These are things that should go in a SharedModule. What -definitely- should not go in there, are application related services and imports.

By the looks of it, your SharedModule should be a CoreModule, and only be imported (not exported) in your AppModule. You should -not- import this module in a lazy loaded module. In your case it will redeclare the HttpClientModule -without- the interceptors, because they are declared in the root and not in the lazy module, making you have the issues you're facing.

Angular itself has a good overview of what kind of modules there are, and what they should and should not contain, and where they should be or should not be imported:

There are five general categories of feature modules which tend to fall into the following groups:

Domain feature modules.

Routed feature modules.

Routing modules.

Service feature modules.

Widget feature modules.

Title: Angular 9: interceptor cyclic dependency while injecting lazy loaded service

Body:
Your LanguageService should not be added to the providers of the lazy loaded module. It should not be added to any providers array of a module. It should have a providedIn: 'root' in the decorator:

@Injectable({ providedIn: 'root' })
export class LanguageService {}

//  lazy loaded module
imports: [
  SharedModule
]

// ....
providers: []

Interceptors on the other hand, should either be declared in your core module, which is included in the App root once. Or in a lazy loaded module, to define a interceptor just for that lazy loaded module

You should restructure your application. Split up your SharedModule to -only- (!important) include components/pipes/directives. These are things that should go in a SharedModule. What -definitely- should not go in there, are application related services and imports.

By the looks of it, your SharedModule should be a CoreModule, and only be imported (not exported) in your AppModule. You should -not- import this module in a lazy loaded module. In your case it will redeclare the HttpClientModule -without- the interceptors, because they are declared in the root and not in the lazy module, making you have the issues you're facing.

Angular itself has a good overview of what kind of modules there are, and what they should and should not contain, and where they should be or should not be imported:

There are five general categories of feature modules which tend to fall into the following groups:

Domain feature modules.

Routed feature modules.

Routing modules.

Service feature modules.

Widget feature modules.