问:
Writing access to a realtime database lost, after switching page
I have a little problem when writing to a DB, using firebase user authentication.

In a given page, say myPage.html; I need to access a realtime database to perform some data writing. I have code to check that I am properly logged in:

```<code>  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      // User is signed in.
      ... some useful code ...
      // OK to perform DB writes.
    } else {
      // User is signed out.
      ... Get-Out-Of-Here ...
      // NG to perform DB writes.
    }
  });
</code>```

Up to this point all is OK, I can write to the DB as expected, if I am logged in.

Then I need to perform some more writings, from another page (myOtherPage.html).

There is a link in myPage.html going to myOtherPage.html.

```<code><a href='myOtherPage.html'>Go To The Other Page</a>
</code>```

Here comes the problem:

From myOtherPage.html, I can no longer perform any data writing to the DB.

It looks like my authentication is just gone away.

What should I do to keep access to the DB even if I change page?

答:
This could be the issue if you aren't using Authentication State Persistence about which you can read here

Some code snippet from the official documention:

```<code>firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
  .then(function() {
    // Existing and future Auth states are now persisted in the current
    // session only. Closing the window would clear any existing state even
    // if a user forgets to sign out.
    // ...
    // New sign-in will be persisted with session persistence.
    return firebase.auth().signInWithEmailAndPassword(email, password);
  })
  .catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });
</code>```

And here's type of states available:

Using the 'LOCAL' state should be fine with your need and your user needs to log out himself which mean he'll stay logged in and can access your database unless he logs out.

PS: The default for web browser and React Native apps is local (provided the browser supports this storage mechanism, eg. 3rd party cookies/data are enabled) whereas it is none for Node.js backend apps.

Body:
I have a little problem when writing to a DB, using firebase user authentication.

In a given page, say myPage.html; I need to access a realtime database to perform some data writing. I have code to check that I am properly logged in:

  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      // User is signed in.
      ... some useful code ...
      // OK to perform DB writes.
    } else {
      // User is signed out.
      ... Get-Out-Of-Here ...
      // NG to perform DB writes.
    }
  });

Up to this point all is OK, I can write to the DB as expected, if I am logged in.

Then I need to perform some more writings, from another page (myOtherPage.html).

There is a link in myPage.html going to myOtherPage.html.

Go To The Other Page

Here comes the problem:

From myOtherPage.html, I can no longer perform any data writing to the DB.

It looks like my authentication is just gone away.

What should I do to keep access to the DB even if I change page?

Body:
This could be the issue if you aren't using Authentication State Persistence about which you can read here

Some code snippet from the official documention:

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
  .then(function() {
    // Existing and future Auth states are now persisted in the current
    // session only. Closing the window would clear any existing state even
    // if a user forgets to sign out.
    // ...
    // New sign-in will be persisted with session persistence.
    return firebase.auth().signInWithEmailAndPassword(email, password);
  })
  .catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });

And here's type of states available:

Using the 'LOCAL' state should be fine with your need and your user needs to log out himself which mean he'll stay logged in and can access your database unless he logs out.

PS: The default for web browser and React Native apps is local (provided the browser supports this storage mechanism, eg. 3rd party cookies/data are enabled) whereas it is none for Node.js backend apps.


来源: stackexchange

问:
Unwanted comma in the tooltips when line breaking a label in ChartsJS
I have some plots with very long labels. I used the answers found in this site to break the labels in new lines.

This is an example of my labels:

```<code>labels: [ 'Utensilios para escrita e artes','Faz de conta','Jogos',['Materiais não estruturado','/de largo alcançe/recicláveis'],['Repertório artístico-cultural e','científico de diferentes','origens étnico-raciais'],'Livros de história','Materiais para pesquisa',],
</code>```

I'm integrating ChartsJS with PHP and generating multiple charts dynamically. All the info needed to create the graphs is stored in a DB.

Since I need to display a % in all my values I'm using this callback for my tooltips

```<code>tooltips: {
            callbacks: {
                label: function(tooltipItems, data) {
                    return data.datasets[tooltipItems.datasetIndex].label +': ' + tooltipItems.value + '%';
                }
            }
        },
</code>```

The Issue is that in the tooltips the labels which had a line break using the nested arrays are shown with an unwanted comma, for example:

Even if I don't use a custom tooltip the issue remains. Does this normally happen if we break labels using nested arrays? Is there any neat way to fix this?

I know there is a different way of breaking lines using \n alongside a plugin to split them but I couldn't get it to work. When I did it the \n was replaced with an extra space but not a line break.

答:
Simply also define a tooltips.callbacks.title function as follows and it will work. Sounds weird since the function does nothing but returning the label.

```<code>tooltips: {
  callbacks: {
    title: (tooltipItems, data) => data.labels[tooltipItems[0].index],
    ...
  }
},
</code>```

Please have a look at the runnable code snippet below.

new Chart(document.getElementById("chart"), {
  type: "bar",
  data: {
    labels: [
      ['Utensilios para', 'escrita e artes'],
      ['Materiais não estruturado', 'de largo alcançe/recicláveis'],
      ['Repertório artístico-cultural e', 'científico de diferentes', 'origens étnico-raciais']
    ],
    datasets: [{
      label: "A",
      data: [5, 8, 4],
      fill: false,
      backgroundColor: "rgba(255, 99, 132, 0.2)",
      borderColor: "rgb(255, 99, 132)",
      borderWidth: 1
    },
    {
      label: "B",
      data: [3, 5, 4],
      fill: false,
      backgroundColor: "rgba(255, 159, 64, 0.2)",
      borderColor: "rgb(255, 159, 64)",
      borderWidth: 1
    },
    {
      label: "C",
      data: [6, 5, 7],
      fill: false,
      backgroundColor: "rgba(255, 205, 86, 0.2)",
      borderColor: "rgb(255, 205, 86)",
      borderWidth: 1
    }]
  },
  options: {
    tooltips: {
      callbacks: {
        title: (tooltipItems, data) => data.labels[tooltipItems[0].index],
        label: (tooltipItems, data) =>
          data.datasets[tooltipItems.datasetIndex].label + ': ' + tooltipItems.value + '%'
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="100"></canvas></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have some plots with very long labels. I used the answers found in this site to break the labels in new lines.

This is an example of my labels:

labels: [ 'Utensilios para escrita e artes','Faz de conta','Jogos',['Materiais não estruturado','/de largo alcançe/recicláveis'],['Repertório artístico-cultural e','científico de diferentes','origens étnico-raciais'],'Livros de história','Materiais para pesquisa',],

I'm integrating ChartsJS with PHP and generating multiple charts dynamically. All the info needed to create the graphs is stored in a DB.

Since I need to display a % in all my values I'm using this callback for my tooltips

tooltips: {
            callbacks: {
                label: function(tooltipItems, data) {
                    return data.datasets[tooltipItems.datasetIndex].label +': ' + tooltipItems.value + '%';
                }
            }
        },

The Issue is that in the tooltips the labels which had a line break using the nested arrays are shown with an unwanted comma, for example:

Even if I don't use a custom tooltip the issue remains. Does this normally happen if we break labels using nested arrays? Is there any neat way to fix this?

I know there is a different way of breaking lines using \n alongside a plugin to split them but I couldn't get it to work. When I did it the \n was replaced with an extra space but not a line break.

Body:
Simply also define a tooltips.callbacks.title function as follows and it will work. Sounds weird since the function does nothing but returning the label.

tooltips: {
  callbacks: {
    title: (tooltipItems, data) => data.labels[tooltipItems[0].index],
    ...
  }
},

Please have a look at the runnable code snippet below.

new Chart(document.getElementById("chart"), {
  type: "bar",
  data: {
    labels: [
      ['Utensilios para', 'escrita e artes'],
      ['Materiais não estruturado', 'de largo alcançe/recicláveis'],
      ['Repertório artístico-cultural e', 'científico de diferentes', 'origens étnico-raciais']
    ],
    datasets: [{
      label: "A",
      data: [5, 8, 4],
      fill: false,
      backgroundColor: "rgba(255, 99, 132, 0.2)",
      borderColor: "rgb(255, 99, 132)",
      borderWidth: 1
    },
    {
      label: "B",
      data: [3, 5, 4],
      fill: false,
      backgroundColor: "rgba(255, 159, 64, 0.2)",
      borderColor: "rgb(255, 159, 64)",
      borderWidth: 1
    },
    {
      label: "C",
      data: [6, 5, 7],
      fill: false,
      backgroundColor: "rgba(255, 205, 86, 0.2)",
      borderColor: "rgb(255, 205, 86)",
      borderWidth: 1
    }]
  },
  options: {
    tooltips: {
      callbacks: {
        title: (tooltipItems, data) => data.labels[tooltipItems[0].index],
        label: (tooltipItems, data) =>
          data.datasets[tooltipItems.datasetIndex].label + ': ' + tooltipItems.value + '%'
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="100"></canvas>


问:
Lopping List with in List (many to many) using map
How to loop list with another list .The number of counts are same inside each list </p>

```<code>List1 =[a,b,c,d]
List2 =[e,f,g,h]
</code>```

<p>Output </p>

```<code>a
 e
b
 f
c
 g
d
 h
</code>```

答:
I would create a dictionary for this

const list = { a: ['e'], b: ['f'], c: ['g'], d: ['h'] };

and then do this in react.

```<code>    Object.keys(list).map((key) => {
    return list[key].map((val) => {
        return `${key} \n ${val}`;
    })
    .join('\n');
    })
    .join('\n');
</code>```

Updated*: As you've asked to you would create this dictionary considering that both the list will be of same length and no duplicates, this is how I would do it.

```<code>    const l1 = ['a','b','c','d'];
    const l2 = ['e','f','g','h'];
    let l3 = {};
    l1.forEach((v, i) => {
        l3[v] = l2[i];
    });
</code>```

Body:
How to loop list with another list .The number of counts are same inside each list

List1 =[a,b,c,d]
List2 =[e,f,g,h]

Output

a
 e
b
 f
c
 g
d
 h

Body:
I would create a dictionary for this

const list = { a: ['e'], b: ['f'], c: ['g'], d: ['h'] };

and then do this in react.

    Object.keys(list).map((key) => {
    return list[key].map((val) => {
        return `${key} \n ${val}`;
    })
    .join('\n');
    })
    .join('\n');

Updated*: As you've asked to you would create this dictionary considering that both the list will be of same length and no duplicates, this is how I would do it.

    const l1 = ['a','b','c','d'];
    const l2 = ['e','f','g','h'];
    let l3 = {};
    l1.forEach((v, i) => {
        l3[v] = l2[i];
    });


问:
C++ concept check vs inheritance
What is the relationship between using virtual functions and C++ inheritance mechanisms versus using templates and something like boost concepts?

It seems like there is quite an overlap of what is possible. Namely, it appears to be possible to achieve polymorphic behavior with either approach. So, when does it make sense to favor one over the other?

The reason why I bring this up is because I have a templated container, where the containers themselves have a hierarchical relationship. I would like to write algorithms that use these containers without caring about which specific container it is. Also, some algorithms would benefit from knowing that the template type satisfied certain concepts (Comparable, for example).

So, on one hand, I want containers to behave polymorphicly. On the other, I still have to use concepts if I want to correctly implement some algorithms. What is a junior developer to do?

答:
I think of concepts as a kind of meta-interface. They categorize types after their abilities. The next C++ version supplies native concepts. I hadn't understood it until i came across C++1x's concepts and how they allow putting different yet unrelated types together. Imagine you have a Range interface. You can model that with two ways. One is a subtype relationship:

```<code>class Range {
    virtual Iterator * begin() = 0;
    virtual Iterator * end() = 0;

    virtual size_t size() = 0;
};
</code>```

Of course, every class that derives from that implements the Range interface and can be used with your functions. But now you see it is limited. What about an array? It's a range too!

```<code>T t[N];

begin() => t
end() => t + size()
size() => N
</code>```

Sadly, you cannot derive an array from that Range class implementing that interface. You need an extra method (overloading). And what about third party containers? A user of your library might want to use their containers together with your functions. But he can't change the definition of their containers. Here, concepts come into game:

```<code>auto concept Range<typename T> {
    typename iterator;
    iterator T::begin();
    iterator T::end();
    size_t T::size();
}
</code>```

Now, you say something about the supported operations of some type which can be fulfilled if T has the appropriate member functions. In your library, you would write the function generic. This allows you accept any type so long as it supports the required operations:

```<code>template<Range R>
void assign(R const& r) {
    ... iterate from r.begin() to r.end().
}
</code>```

It's a great kind of substitutability. Any type will fit the bill that adheres to the concept, and not only those types that actively implement some interface. The next C++ Standard goes further: It defines a Container concept that will be fit by plain arrays (by something caled concept map that defines how some type fits some concept) and other, existing standard containers.

The reason why I bring this up is because I have a templated container, where the containers themselves have a hierarchical relationship. I would like to write algorithms that use these containers without caring about which specific container it is. Also, some algorithms would benefit from knowing that the template type satisfied certain concepts (Comparable, for example).

You can actually do both with templates. You can keep having your hierarchical relationship to share code, and then write the algorithms in a generic fashion. For example, to communicate that your container is comparable. That's like standard random-access/forward/output/input iterator categories are implemented:

```<code>// tag types for the comparator cagetory
struct not_comparable { };
struct basic_comparable : not_comparable { };

template<typename T>
class MyVector : public BasicContainer<T> {
    typedef basic_comparable comparator_kind;
};

/* Container concept */
T::comparator_kind: comparator category
</code>```

It's a reasonable simple way to do it, actually. Now you can call a function and it will forward to the correct implementation.

```<code>template<typename Container>
void takesAdvantage(Container const& c) {
    takesAdvantageOfCompare(c, typename Container::comparator_kind());
}

// implementation for basic_comparable containers
template<typename Container>
void takesAdvantage(Container const& c, basic_comparable) {
    ...
}

// implementation for not_comparable containers
template<typename Container>
void takesAdvantage(Container const& c, not_comparable) {
    ...
}
</code>```

There are actually different techniques that can be used to implement that. Another way is to use boost::enable_if to enable or disable different implementations each time.

OwnerDisplayName: Voltaire

ContentLicense: CC BY-SA 2.5

Title: C++ concept check vs inheritance

Body:
I think of concepts as a kind of meta-interface. They categorize types after their abilities. The next C++ version supplies native concepts. I hadn't understood it until i came across C++1x's concepts and how they allow putting different yet unrelated types together. Imagine you have a Range interface. You can model that with two ways. One is a subtype relationship:

class Range {
    virtual Iterator * begin() = 0;
    virtual Iterator * end() = 0;

    virtual size_t size() = 0;
};

Of course, every class that derives from that implements the Range interface and can be used with your functions. But now you see it is limited. What about an array? It's a range too!

T t[N];

begin() => t
end() => t + size()
size() => N

Sadly, you cannot derive an array from that Range class implementing that interface. You need an extra method (overloading). And what about third party containers? A user of your library might want to use their containers together with your functions. But he can't change the definition of their containers. Here, concepts come into game:

auto concept Range<typename T> {
    typename iterator;
    iterator T::begin();
    iterator T::end();
    size_t T::size();
}

Now, you say something about the supported operations of some type which can be fulfilled if T has the appropriate member functions. In your library, you would write the function generic. This allows you accept any type so long as it supports the required operations:

template<Range R>
void assign(R const& r) {
    ... iterate from r.begin() to r.end().
}

It's a great kind of substitutability. Any type will fit the bill that adheres to the concept, and not only those types that actively implement some interface. The next C++ Standard goes further: It defines a Container concept that will be fit by plain arrays (by something caled concept map that defines how some type fits some concept) and other, existing standard containers.

The reason why I bring this up is because I have a templated container, where the containers themselves have a hierarchical relationship. I would like to write algorithms that use these containers without caring about which specific container it is. Also, some algorithms would benefit from knowing that the template type satisfied certain concepts (Comparable, for example).

You can actually do both with templates. You can keep having your hierarchical relationship to share code, and then write the algorithms in a generic fashion. For example, to communicate that your container is comparable. That's like standard random-access/forward/output/input iterator categories are implemented:

// tag types for the comparator cagetory
struct not_comparable { };
struct basic_comparable : not_comparable { };

template<typename T>
class MyVector : public BasicContainer<T> {
    typedef basic_comparable comparator_kind;
};

/* Container concept */
T::comparator_kind: comparator category

It's a reasonable simple way to do it, actually. Now you can call a function and it will forward to the correct implementation.

template<typename Container>
void takesAdvantage(Container const& c) {
    takesAdvantageOfCompare(c, typename Container::comparator_kind());
}

// implementation for basic_comparable containers
template<typename Container>
void takesAdvantage(Container const& c, basic_comparable) {
    ...
}

// implementation for not_comparable containers
template<typename Container>
void takesAdvantage(Container const& c, not_comparable) {
    ...
}

There are actually different techniques that can be used to implement that. Another way is to use boost::enable_if to enable or disable different implementations each time.

OwnerDisplayName: litb


问:
Fade in/out a WebView
my problem might be simple but the solution escapes me.

I have a WebView embeded in a NSView, and loaded with some content. I'd like to add a simple fade transition (upon a button click) which after 2 seconds just dissapears and the WebView simply shows again the original content.

I dont know if I can do this in the WebView itself through Interface Builder, or I need to user layers and CATransitions programmatically.

So far I have tried different variations of this:

```<code>[m_pView setWantsLayer:YES];

CATransition *transition = [CATransition animation];

transition.duration = 2;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;

[ [m_pView layer] addAnimation:transition forKey:nil];
</code>```

All I got is erasing the original content from the View and replace it with a blank. I suppose Im using the layers incorrectly, and maybe they arent needed at all to solve my problem.

Anyone can help me with this?

答:
Using a WebView on a layer-backed view is not supported. This is only outlined in the Leopard release notes but it's still the case in 10.6.

You'll need to do some juggling to get this to work, most probably by swapping the WebView with an NSImageView containing a screenshot of the WebView contents, fading that and then swapping the WebView back in with its new content.

ContentLicense: CC BY-SA 3.0

Title: Fade in/out a WebView

Body:
my problem might be simple but the solution escapes me.

I have a WebView embeded in a NSView, and loaded with some content. I'd like to add a simple fade transition (upon a button click) which after 2 seconds just dissapears and the WebView simply shows again the original content.

I dont know if I can do this in the WebView itself through Interface Builder, or I need to user layers and CATransitions programmatically.

So far I have tried different variations of this:

[m_pView setWantsLayer:YES];

CATransition *transition = [CATransition animation];

transition.duration = 2;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;

[ [m_pView layer] addAnimation:transition forKey:nil];

All I got is erasing the original content from the View and replace it with a blank. I suppose Im using the layers incorrectly, and maybe they arent needed at all to solve my problem.

Anyone can help me with this?


问:
Git confusion, made many changes including deleting and renaming files in goorm, how to proceed
I am rewriting my personal website and have drastically changed the way the site works, which means I have deleted many of the old files that are not needed out of my goorm workspace (many files were moved to a CDN). I have been always doing the git add, git commit -m and git push heroku master steps when pushing any changes out to heroku to make the changes live, but I’m now confused about what to do after changing so much of the file structure.
  When I do a

```<code> git status
</code>```

there are dozens of deleted files, I have changed so much, I almost think it would be better to wipe the git repo clean and start over. What is the best way to do this.?
  If I truly don’t want to revert to any previous versions, can I just delete the .git folder in my local goorm structure and start over with

```<code>git init
</code>```

or is there a better way? The web dev course I watched explained very little about git and not sure If I could create some other "v2" branch that is the new file structure. I will not be going back to a previous version of this site since I drastically changed the way the entire site functions.
Also, if I create a new git repo with git init and it has way less files than what is currently on heroku, do the files that were on heroku stay, or does a git push command overwrite everything that is at the target of the push.?
 Thanks for any info.

答:
```<code>git add .
</code>```

to commit all changes. Including deleted files.

```<code>git commit -m 'removed old files'
git push
</code>```

Done.

Body:
I am rewriting my personal website and have drastically changed the way the site works, which means I have deleted many of the old files that are not needed out of my goorm workspace (many files were moved to a CDN). I have been always doing the git add, git commit -m and git push heroku master steps when pushing any changes out to heroku to make the changes live, but I’m now confused about what to do after changing so much of the file structure.
  When I do a

 git status

there are dozens of deleted files, I have changed so much, I almost think it would be better to wipe the git repo clean and start over. What is the best way to do this.?
  If I truly don’t want to revert to any previous versions, can I just delete the .git folder in my local goorm structure and start over with

git init

or is there a better way? The web dev course I watched explained very little about git and not sure If I could create some other "v2" branch that is the new file structure. I will not be going back to a previous version of this site since I drastically changed the way the entire site functions.
Also, if I create a new git repo with git init and it has way less files than what is currently on heroku, do the files that were on heroku stay, or does a git push command overwrite everything that is at the target of the push.?
 Thanks for any info.

Body:
git add .

to commit all changes. Including deleted files.

git commit -m 'removed old files'
git push

Done.


问:
Showing TextField's error text does not work
I'm building the changePassword module on an app and I want to check that the field its not empty but its not working and I don't know why

```<code>Card(
  color: Color(0xFFDBE2EF),
  margin: EdgeInsets.symmetric(
      vertical: 10, horizontal: 25),
  child: TextField(
    controller: passwordConfirmController,
    obscureText: true,
    decoration: InputDecoration(
        border: OutlineInputBorder(),
        labelText: 'Confirmar contraseña',
        labelStyle:
            TextStyle(fontFamily: 'Montserrat')),
  ),
),
SizedBox(
  height: 20,
),
RaisedButton(
    color: Color(0xFFDBE2EF),
    onPressed: () => {
          setState(() {
            print("Valor _validate antes");
            print(_validate);
            print("Valor isEmpty");
            print(passwordController.text.isEmpty);
            passwordController.text.isEmpty
                ? _validate = true
                : _validate = false;
            _isLoading = true;
            print("Valor _validate después");
            print(_validate);
          }),
          changePass(passwordController.text),
        },
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(5),
    ),
    child: Text(
      'Actualizar',
      style: TextStyle(
          fontSize: 20,
          fontFamily: 'Montserrat',
          color: Color(0xFF002D53),
          fontWeight: FontWeight.bold),
    )),
</code>```

The values on raisedbutton where I check if the password is empty seems to be working printing the expected values, but the error text does not work

答:
You need to pass the error text to the TextField

```<code>TextField(
  decoration: InputDecoration(
    errorText:"some error",
  ),
</code>```

Body:
I'm building the changePassword module on an app and I want to check that the field its not empty but its not working and I don't know why

Card(
  color: Color(0xFFDBE2EF),
  margin: EdgeInsets.symmetric(
      vertical: 10, horizontal: 25),
  child: TextField(
    controller: passwordConfirmController,
    obscureText: true,
    decoration: InputDecoration(
        border: OutlineInputBorder(),
        labelText: 'Confirmar contraseña',
        labelStyle:
            TextStyle(fontFamily: 'Montserrat')),
  ),
),
SizedBox(
  height: 20,
),
RaisedButton(
    color: Color(0xFFDBE2EF),
    onPressed: () => {
          setState(() {
            print("Valor _validate antes");
            print(_validate);
            print("Valor isEmpty");
            print(passwordController.text.isEmpty);
            passwordController.text.isEmpty
                ? _validate = true
                : _validate = false;
            _isLoading = true;
            print("Valor _validate después");
            print(_validate);
          }),
          changePass(passwordController.text),
        },
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(5),
    ),
    child: Text(
      'Actualizar',
      style: TextStyle(
          fontSize: 20,
          fontFamily: 'Montserrat',
          color: Color(0xFF002D53),
          fontWeight: FontWeight.bold),
    )),

The values on raisedbutton where I check if the password is empty seems to be working printing the expected values, but the error text does not work

Body:
You need to pass the error text to the TextField

TextField(
  decoration: InputDecoration(
    errorText:"some error",
  ),


问:
VB Entering a Non_Numeric value crashes the program
Please consider adding a description to this question to attract more helpful responses.

```<code>Public Class Form1
    Private Sub BtnCalculateRevenue_Click(sender As Object, e As EventArgs) Handles BtnCalculateRevenue.Click
        Dim intvalue As Integer = CInt(TxtInputClassA.Text)
        Dim intvalue2 As Integer = CInt(TxtInputClassB.Text)
        Dim intvalue3 As Integer = CInt(TxtinputClassC.Text)
        Dim total As Double
        Try
            LblStatus.Text = String.Empty

            LblClassAResult.Text = (intvalue * 15).ToString("c")
            LblClassBResult.Text = (intvalue2 * 12).ToString("c")
            LblClassCResult.Text = (intvalue3 * 9).ToString("c")
            total = CDbl((intvalue * 15) + (intvalue2 * 12) + (intvalue3 * 9))
            LblTotal.Text = total.ToString("c")
        Catch
            LblStatus.Text = "Please Enter a Number"
        End Try
    End Sub

    Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles BtnExit.Click
        Me.Close()
    End Sub

    Private Sub BtnClear_Click(sender As Object, e As EventArgs) Handles BtnClear.Click
        TxtInputClassA.Clear()
        TxtInputClassB.Clear()
        TxtinputClassC.Clear()
        LblClassAResult.Text = String.Empty
        LblClassBResult.Text = String.Empty
        LblClassCResult.Text = String.Empty
        LblTotal.Text = String.Empty
    End Sub
End Class
</code>```

VB Entering a Non_Numeric value crashes the program

答:
Validation is built right into Windows Forms so you should make use of it. If you want to force the user to enter numbers in each of three TextBoxes then you can do this:

Private Sub TextBoxes_Validating(sender As Object, e As ComponentModel.CancelEventArgs) Handles TextBox3.Validating, TextBox2.Validating, TextBox1.Validating
    Dim tb = DirectCast(sender, TextBox)

    If Not Integer.TryParse(tb.Text, Nothing) Then
        'Select all the invalid text and highlight it.
        tb.SelectAll()
        tb.HideSelection = False

        MessageBox.Show("Please enter a whole number",
                        "Invalid Input",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Exclamation)

        'Remove highlight when TextBox is not focused.
        tb.HideSelection = True

        'Don't let the control lose focus while data is invalid.
        e.Cancel = True
    End If
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If ValidateChildren() Then
        'All data is valid  so proceed.
        Dim n1 = CInt(TextBox1.Text)
        Dim n2 = CInt(TextBox2.Text)
        Dim n3 = CInt(TextBox3.Text)

        '...
    End If
End Sub
```

The ValidateChildren method will raise the Validating event for every control on the form and return False if any fail validation, i.e. e.Cancel is set to True in any event handlers, so that ensures that even controls that never received focus will be validated before the data is used.

Body:
Please consider adding a description to this question to attract more helpful responses.

Public Class Form1
    Private Sub BtnCalculateRevenue_Click(sender As Object, e As EventArgs) Handles BtnCalculateRevenue.Click
        Dim intvalue As Integer = CInt(TxtInputClassA.Text)
        Dim intvalue2 As Integer = CInt(TxtInputClassB.Text)
        Dim intvalue3 As Integer = CInt(TxtinputClassC.Text)
        Dim total As Double
        Try
            LblStatus.Text = String.Empty

            LblClassAResult.Text = (intvalue * 15).ToString("c")
            LblClassBResult.Text = (intvalue2 * 12).ToString("c")
            LblClassCResult.Text = (intvalue3 * 9).ToString("c")
            total = CDbl((intvalue * 15) + (intvalue2 * 12) + (intvalue3 * 9))
            LblTotal.Text = total.ToString("c")
        Catch
            LblStatus.Text = "Please Enter a Number"
        End Try
    End Sub

    Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles BtnExit.Click
        Me.Close()
    End Sub

    Private Sub BtnClear_Click(sender As Object, e As EventArgs) Handles BtnClear.Click
        TxtInputClassA.Clear()
        TxtInputClassB.Clear()
        TxtinputClassC.Clear()
        LblClassAResult.Text = String.Empty
        LblClassBResult.Text = String.Empty
        LblClassCResult.Text = String.Empty
        LblTotal.Text = String.Empty
    End Sub
End Class

VB Entering a Non_Numeric value crashes the program

Body:
Validation is built right into Windows Forms so you should make use of it. If you want to force the user to enter numbers in each of three TextBoxes then you can do this:

Private Sub TextBoxes_Validating(sender As Object, e As ComponentModel.CancelEventArgs) Handles TextBox3.Validating, TextBox2.Validating, TextBox1.Validating
    Dim tb = DirectCast(sender, TextBox)

    If Not Integer.TryParse(tb.Text, Nothing) Then
        'Select all the invalid text and highlight it.
        tb.SelectAll()
        tb.HideSelection = False

        MessageBox.Show("Please enter a whole number",
                        "Invalid Input",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Exclamation)

        'Remove highlight when TextBox is not focused.
        tb.HideSelection = True

        'Don't let the control lose focus while data is invalid.
        e.Cancel = True
    End If
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If ValidateChildren() Then
        'All data is valid  so proceed.
        Dim n1 = CInt(TextBox1.Text)
        Dim n2 = CInt(TextBox2.Text)
        Dim n3 = CInt(TextBox3.Text)

        '...
    End If
End Sub

The ValidateChildren method will raise the Validating event for every control on the form and return False if any fail validation, i.e. e.Cancel is set to True in any event handlers, so that ensures that even controls that never received focus will be validated before the data is used.


问:
How to select all from table except one column using MySQL query?
I want to select all columns from a table except one column using MySQL.
I know we can select all columns using this

```<code><?php
$query = SELECT * FROM posts;
?>
</code>```

But how can I leave one specific column from the table?

答:
Instead of using * you list all the columns on the table, leaving out the one you don't want

MySQL has an information scheme that will list all the columns in the table; you can query it and use the returned results to paste into your code so you don't have to type it out. For example, write this:

```<code>SELECT CONCAT(column_name, ',') FROM information_schema.columns WHERE table_name = 'posts' AND column_name NOT IN ('column name to exclude')
</code>```

Then copy the result and paste into your code , removing the last comma

Many query tools will also help you formulate queries in this way, or show you the queries they are running and you can copy it/paste it into your code

You might find it easier to do you database access via a library that lets you treat tables like objects; I'm not a php programmer but over in C# we have things like entity framework, a library where we can make our code side Person object have 4 properties (Name, Age, Job, SSN) and tell it that it is backed by the tblPerson table (with 5 columns) and it won't download the 5th column when doing its queries. Pretty sure php will have something like that that means you don't have to spend your life writing endless SELECT blah, blah2, blah3 ...

There is a benefit in not using * sometimes, as your queries and code carry on working if someone adds a column to a table with the same name as another column. If you had:

```<code>SELECT * FROM person JOIN address ON ...
</code>```

And person had a Status column that was used in the front end app, if someone later adds another Status column to address, you'll start getting two Status columns back and your front end might not treat the second correctly; it might overwrite the first or cause a crash. If you avoided using * and picked the columns you wanted by name, the system would carry on working even with the new column

Body:
I want to select all columns from a table except one column using MySQL.
I know we can select all columns using this

<?php
$query = SELECT * FROM posts;
?>

But how can I leave one specific column from the table?

Body:
Instead of using * you list all the columns on the table, leaving out the one you don't want

MySQL has an information scheme that will list all the columns in the table; you can query it and use the returned results to paste into your code so you don't have to type it out. For example, write this:

SELECT CONCAT(column_name, ',') FROM information_schema.columns WHERE table_name = 'posts' AND column_name NOT IN ('column name to exclude')

Then copy the result and paste into your code , removing the last comma

Many query tools will also help you formulate queries in this way, or show you the queries they are running and you can copy it/paste it into your code

You might find it easier to do you database access via a library that lets you treat tables like objects; I'm not a php programmer but over in C# we have things like entity framework, a library where we can make our code side Person object have 4 properties (Name, Age, Job, SSN) and tell it that it is backed by the tblPerson table (with 5 columns) and it won't download the 5th column when doing its queries. Pretty sure php will have something like that that means you don't have to spend your life writing endless SELECT blah, blah2, blah3 ...

There is a benefit in not using * sometimes, as your queries and code carry on working if someone adds a column to a table with the same name as another column. If you had:

SELECT * FROM person JOIN address ON ...

And person had a Status column that was used in the front end app, if someone later adds another Status column to address, you'll start getting two Status columns back and your front end might not treat the second correctly; it might overwrite the first or cause a crash. If you avoided using * and picked the columns you wanted by name, the system would carry on working even with the new column


问:
Getting "DSO missing from command line" with custom glibc
I am trying to link a program with a custom GLIBC installation. I have tried the following options, but got the same error

```<code>objs/ngx_modules.o \
-Wl,--emit-relocs -Wl,--dynamic-linker=/opt/glibc-2.23-install/lib/ld-2.23.so -ldl -Wl,-rpath-link,/opt/glibc-2.23-install/lib -lcrypt -lpcre -lz \
-Wl,-E
/usr/bin/ld: objs/src/core/ngx_shmtx.o: undefined reference to symbol 'sem_post@@GLIBC_2.2.5'
/opt/glibc-2.23-install/lib/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
</code>```

and

```<code>objs/ngx_modules.o \
-Wl,--emit-relocs -Wl,--dynamic-linker=/opt/glibc-2.23-install/lib/ld-2.23.so -ldl -L/opt/glibc-2.23-install/lib -lcrypt -lpcre -lz \
-Wl,-E
/usr/bin/ld: objs/src/core/ngx_shmtx.o: undefined reference to symbol 'sem_post@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
objs/Makefile:226: recipe for target 'objs/nginx' failed
</code>```

and

```<code>objs/ngx_modules.o \
-Wl,--emit-relocs -Wl,--dynamic-linker=/opt/glibc-2.23-install/lib/ld-2.23.so -ldl -L/opt/glibc-2.23-install/lib/libpthread.so -lcrypt -lpcre -lz \
-Wl,-E
/usr/bin/ld: objs/src/core/ngx_shmtx.o: undefined reference to symbol 'sem_post@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
objs/Makefile:226: recipe for target 'objs/nginx' failed
</code>```

Any alternative then?

答:
-Wl,--emit-relocs -Wl,--dynamic-linker=/opt/glibc-2.23-install/lib/ld-2.23.so -ldl -L/opt/glibc-2.23-install/lib/libpthread.so -lcrypt -lpcre -lz \
  -Wl,-E

Furious activity is no substitute for understanding. The command you want:

```<code>gcc objs/ngx_modules.o  \
  -Wl,-E -Wl,--dynamic-linker=/opt/glibc-2.23-install/lib/ld-2.23.so \
  -L/opt/glibc-2.23-install/lib \
  -lcrypt -lpcre -lz -lpthread
</code>```

Body:
I am trying to link a program with a custom GLIBC installation. I have tried the following options, but got the same error

objs/ngx_modules.o \
-Wl,--emit-relocs -Wl,--dynamic-linker=/opt/glibc-2.23-install/lib/ld-2.23.so -ldl -Wl,-rpath-link,/opt/glibc-2.23-install/lib -lcrypt -lpcre -lz \
-Wl,-E
/usr/bin/ld: objs/src/core/ngx_shmtx.o: undefined reference to symbol 'sem_post@@GLIBC_2.2.5'
/opt/glibc-2.23-install/lib/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

and

objs/ngx_modules.o \
-Wl,--emit-relocs -Wl,--dynamic-linker=/opt/glibc-2.23-install/lib/ld-2.23.so -ldl -L/opt/glibc-2.23-install/lib -lcrypt -lpcre -lz \
-Wl,-E
/usr/bin/ld: objs/src/core/ngx_shmtx.o: undefined reference to symbol 'sem_post@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
objs/Makefile:226: recipe for target 'objs/nginx' failed

and

objs/ngx_modules.o \
-Wl,--emit-relocs -Wl,--dynamic-linker=/opt/glibc-2.23-install/lib/ld-2.23.so -ldl -L/opt/glibc-2.23-install/lib/libpthread.so -lcrypt -lpcre -lz \
-Wl,-E
/usr/bin/ld: objs/src/core/ngx_shmtx.o: undefined reference to symbol 'sem_post@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
objs/Makefile:226: recipe for target 'objs/nginx' failed

Any alternative then?

Body:
-Wl,--emit-relocs -Wl,--dynamic-linker=/opt/glibc-2.23-install/lib/ld-2.23.so -ldl -L/opt/glibc-2.23-install/lib/libpthread.so -lcrypt -lpcre -lz \
  -Wl,-E

Furious activity is no substitute for understanding. The command you want:

gcc objs/ngx_modules.o  \
  -Wl,-E -Wl,--dynamic-linker=/opt/glibc-2.23-install/lib/ld-2.23.so \
  -L/opt/glibc-2.23-install/lib \
  -lcrypt -lpcre -lz -lpthread


问:
why iconv read more bytes than i specified
I use

```<code>size_t iconv(iconv_t cd,   char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft);
</code>```

to convert UTF-16BE to GB2312.

inbytesleft is bytes number to be convert. After conversion, inbytesleft is bytes number of not converted.

After one call, I found inbytesleft is -2, according to iconv man page this function should read at most inbytesleft.
Who can tell my why and how to fix this?

code to be convert is

```<code>"保单验证"
</code>```

Thanks

答:
How are you getting the input data into your program?

I've tested the situation using this code and it seems to work:

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

int main(){
    char data[10] = {0x4f,0xdd,0x53,0x55,0x9a,0x8c,0x8b,0xc1, 0, 0};
    char outdata[20];
    char *dataptr;
    char *outdataptr;
    iconv_t cd;
    size_t result;
    size_t inbytesleft = 8;
    size_t outbytesleft = 20;
    int i;

    cd = iconv_open("GB2312", "UTF-16BE");
    dataptr = data;
    outdataptr = outdata;
    result = iconv(cd, &dataptr, &inbytesleft, &outdataptr, &outbytesleft);
    if(result == -1)
        printf("Error: %d\n", errno);
    printf("      result: %zd\n", result);
    printf(" inbytesleft: %zd\n", inbytesleft);
    printf("outbytesleft: %zd\n", outbytesleft);

    for(i = 20; i > outbytesleft; i--){
        if(i != 20)
            printf(",");
        printf("0x%02x", *((unsigned char *)&(outdata[20-i])));
    }
    printf("\n");

    return 0;
}
</code>```

It prints

```<code>      result: 0
 inbytesleft: 0
outbytesleft: 12
0xb1,0xa3,0xb5,0xa5,0xd1,0xe9,0xd6,0xa4
</code>```

Which appears to be correct.

The array of items in the variable data is the UTF-16BE encoding of 保单验证

If this doesn't help, could you post your code for analysis?

Body:
I use

size_t iconv(iconv_t cd,   char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft);

to convert UTF-16BE to GB2312.

inbytesleft is bytes number to be convert. After conversion, inbytesleft is bytes number of not converted.

After one call, I found inbytesleft is -2, according to iconv man page this function should read at most inbytesleft.
Who can tell my why and how to fix this?

code to be convert is

"保单验证"

Thanks

Body:
How are you getting the input data into your program?

I've tested the situation using this code and it seems to work:

#include <stdio.h>
#include <iconv.h>
#include <errno.h>

int main(){
    char data[10] = {0x4f,0xdd,0x53,0x55,0x9a,0x8c,0x8b,0xc1, 0, 0};
    char outdata[20];
    char *dataptr;
    char *outdataptr;
    iconv_t cd;
    size_t result;
    size_t inbytesleft = 8;
    size_t outbytesleft = 20;
    int i;

    cd = iconv_open("GB2312", "UTF-16BE");
    dataptr = data;
    outdataptr = outdata;
    result = iconv(cd, &dataptr, &inbytesleft, &outdataptr, &outbytesleft);
    if(result == -1)
        printf("Error: %d\n", errno);
    printf("      result: %zd\n", result);
    printf(" inbytesleft: %zd\n", inbytesleft);
    printf("outbytesleft: %zd\n", outbytesleft);

    for(i = 20; i > outbytesleft; i--){
        if(i != 20)
            printf(",");
        printf("0x%02x", *((unsigned char *)&(outdata[20-i])));
    }
    printf("\n");

    return 0;
}

It prints

      result: 0
 inbytesleft: 0
outbytesleft: 12
0xb1,0xa3,0xb5,0xa5,0xd1,0xe9,0xd6,0xa4

Which appears to be correct.

The array of items in the variable data is the UTF-16BE encoding of 保单验证

If this doesn't help, could you post your code for analysis?


问:
How can I programmatically click a button on a MessageBox
I have a radiobutton when i check it , it should give a message

```<code>DialogResult click = MessageBox.Show("Would you like to convert the actual values to US Customary ?\n Clicking No changes just the unit system.", "Change Unit Systems to US Customary", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

if (click == DialogResult.Yes)
{
    //some code
}
</code>```

how can I answer this message from internal code in a button to be NO ?

答:
When you click on radio button you send the appropiate delegate function(action) and Messagebox result.
The action handles yes/no cases.</p>

```<code>public void HandleMessageBoxResult(DialogResult result, Action<DialogResult> action)
{
    action(result);
}

public void Radio1Action(DialogResult result)
{
    switch (result)
    {
        case DialogResult.Yes:
            MessageBox.Show("Yes Clicked for Radio1");
            break;
        case DialogResult.No:
            MessageBox.Show("No Clicked for Radio1");
            break;
    }
}

public void Radio2Action(DialogResult result)
{
    switch (result)
    {
        case DialogResult.Yes:
            MessageBox.Show("Yes Clicked for radioButton2");
            break;
        case DialogResult.No:
            MessageBox.Show("No Clicked for radioButton2");
            break;
    }
}

private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
    if(radioButton1.Checked)
    {
        DialogResult result = MessageBox.Show("Message for radioButton1", "title", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
        HandleMessageBoxResult(result, Radio1Action);
    }
}

private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
    if (radioButton2.Checked)
    {
        DialogResult result = MessageBox.Show("Message for radioButton2", "title", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
        HandleMessageBoxResult(result, Radio2Action);
    }
}
</code>```

Body:
I have a radiobutton when i check it , it should give a message

DialogResult click = MessageBox.Show("Would you like to convert the actual values to US Customary ?\n Clicking No changes just the unit system.", "Change Unit Systems to US Customary", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

if (click == DialogResult.Yes)
{
    //some code
}

how can I answer this message from internal code in a button to be NO ?

Body:
When you click on radio button you send the appropiate delegate function(action) and Messagebox result.
The action handles yes/no cases.

public void HandleMessageBoxResult(DialogResult result, Action<DialogResult> action)
{
    action(result);
}

public void Radio1Action(DialogResult result)
{
    switch (result)
    {
        case DialogResult.Yes:
            MessageBox.Show("Yes Clicked for Radio1");
            break;
        case DialogResult.No:
            MessageBox.Show("No Clicked for Radio1");
            break;
    }
}

public void Radio2Action(DialogResult result)
{
    switch (result)
    {
        case DialogResult.Yes:
            MessageBox.Show("Yes Clicked for radioButton2");
            break;
        case DialogResult.No:
            MessageBox.Show("No Clicked for radioButton2");
            break;
    }
}

private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
    if(radioButton1.Checked)
    {
        DialogResult result = MessageBox.Show("Message for radioButton1", "title", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
        HandleMessageBoxResult(result, Radio1Action);
    }
}

private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
    if (radioButton2.Checked)
    {
        DialogResult result = MessageBox.Show("Message for radioButton2", "title", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
        HandleMessageBoxResult(result, Radio2Action);
    }
}


问:
Not able to get response with @Controller, while @RestController works fine
I am trying to map the URL /function/hash in my project to a specific HTML page html/hashcode.html. This is a spring boot project without using thymeleaf.

This is my code:

// package ...;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FunctionController {
    @RequestMapping("/function/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}
```

<p>The above code returns a 404 when I try to access <code>localhost:8080/function/hash</code>.</p>

<p>I also tried</p>

<pre class="lang-java prettyprint-override"><code>@Controller
@RequestMapping("/function")
public class FunctionController {
    @RequestMapping("/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}
</code>```

which also yields a 404 when I go to localhost:8080/function/hash.

Directly using @RequestMapping("/hash") to map the page to /hash works, in case you wonder if the return value of the function is incorrect.

I also find that using multiple layer url like @RequestMapping("/api/test") is working in @RestController classes, but somehow it doesn't work in this @Controller class above.

答:
If the html files are static resources, consider the static content support in Spring Boot.

Configure a spring.resources.static-locations to specify the resource localtions.

```<code>spring.resources.static-locations=file:/opt/files/,classpath:/static-files
</code>```

And set the mapping pattern if you do not want to map it the root path.

```<code>pring.mvc.static-path-pattern=/content/**
</code>```

(Or spring.webflux.static-path-pattern for Spring webflux application)

Now you can view the resources via http://localhost:8080/content/some.html

Body:
I am trying to map the URL /function/hash in my project to a specific HTML page html/hashcode.html. This is a spring boot project without using thymeleaf.

This is my code:

// package ...;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FunctionController {
    @RequestMapping("/function/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}

The above code returns a 404 when I try to access localhost:8080/function/hash.

I also tried

@Controller
@RequestMapping("/function")
public class FunctionController {
    @RequestMapping("/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}

which also yields a 404 when I go to localhost:8080/function/hash.

Directly using @RequestMapping("/hash") to map the page to /hash works, in case you wonder if the return value of the function is incorrect.

I also find that using multiple layer url like @RequestMapping("/api/test") is working in @RestController classes, but somehow it doesn't work in this @Controller class above.

Body:
If the html files are static resources, consider the static content support in Spring Boot.

Configure a spring.resources.static-locations to specify the resource localtions.

spring.resources.static-locations=file:/opt/files/,classpath:/static-files

And set the mapping pattern if you do not want to map it the root path.

pring.mvc.static-path-pattern=/content/**

(Or spring.webflux.static-path-pattern for Spring webflux application)

Now you can view the resources via http://localhost:8080/content/some.html


问:
How to create an Super set enum using existing enum in Typescript
I need create an enum using the another like as follows

```<code>enum problems{
   eazy,
   medium,
   hard,
}

enum moreProblems{
  eazy,
  medium,
  hard,
  frenzy
</code>```

}

I need to moreProblems enum using the enum Problems

答:
Use case: When enum B must contain all values from enum A and some additional values.

You can also create enums that extend other TypeScript enums by using const assertions like so:

```<code>const GameResultEnum = {
       WINNER: 'Winner',
       LOSER: 'Loser'
       } as const;
type GameResultEnum = typeof GameResultEnum[keyof typeof GameResultEnum];

const SoccerGameResultEnum = { ...GameResultEnum, DRAW: 'Draw' } as const;
type SoccerGameResultEnum = typeof SoccerGameResultEnum[keyof typeof
SoccerGameResultEnum];
</code>```

Implementation:

```<code>let gameResult: GameResultEnum, soccerGameResult: SoccerGameResultEnum;

gameResult = GameResultEnum.WINNER; // no errors
gameResult = SoccerGameResultEnum.WINNER; // SoccerGameResultEnum can also be used
gameResult = SoccerGameResultEnum.DRAW; // correctly throws errors
</code>```

I found the solution here

Body:
I need create an enum using the another like as follows

enum problems{
   eazy,
   medium,
   hard,
}

enum moreProblems{
  eazy,
  medium,
  hard,
  frenzy

}

I need to moreProblems enum using the enum Problems

Body:
Use case: When enum B must contain all values from enum A and some additional values.

You can also create enums that extend other TypeScript enums by using const assertions like so:

const GameResultEnum = {
       WINNER: 'Winner',
       LOSER: 'Loser'
       } as const;
type GameResultEnum = typeof GameResultEnum[keyof typeof GameResultEnum];

const SoccerGameResultEnum = { ...GameResultEnum, DRAW: 'Draw' } as const;
type SoccerGameResultEnum = typeof SoccerGameResultEnum[keyof typeof
SoccerGameResultEnum];

Implementation:

let gameResult: GameResultEnum, soccerGameResult: SoccerGameResultEnum;

gameResult = GameResultEnum.WINNER; // no errors
gameResult = SoccerGameResultEnum.WINNER; // SoccerGameResultEnum can also be used
gameResult = SoccerGameResultEnum.DRAW; // correctly throws errors

I found the solution here


问:
Increment counter continuously on mouse click in React.js
I am trying to implement counter in React.js which increments the value continuously on click but I am not getting the appropriate result, code works fine in plain html/js.

https://codesandbox.io/s/autumn-wood-fhsjx?file=/src/App.js

```<code>import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [value, setValue] = useState(0);

  const continuosIncerment = () => {
    console.log(`Setting ${value}`);

    setValue(value + 1);

    timer = setTimeout(function() {
      continuosIncerment();
    }, 1000);
  };

  function timeoutClear() {
    clearTimeout(timer);
  }

  return (
    <div className="App">
      <button
        onMouseLeave={timeoutClear}
        onMouseUp={timeoutClear}
        onMouseDown={continuosIncerment}
      >
        Increment
      </button>
      <div>Value = {value} </div>
    </div>
  );
}
</code>```

答:
This is the code for a timer that I used on my app, maybe it can help you.</p>
```<code>import React, { useState, useEffect } from "react";
import "./clock.css";

function Clock() {
  const [isRunning, setIsRunning] = useState(false);
  const [seconds, setSeconds] = useState(0);
  const [minutes, setMinutes] = useState(0);
  const [hours, setHours] = useState(0);

  const toggleOn = () => {
    setIsRunning(!isRunning);
  };

  const reset = () => {
    setMinutes(0);
    setSeconds(0);
    setIsRunning(false);
    setHours(0);
  };

  useEffect(() => {
    let interval = null;
    if (isRunning) {
      interval = setInterval(() => {
        setSeconds((seconds) => seconds + 1);
      }, 1000);
      if (seconds > 60) {
        setMinutes((minutes) => minutes + 1);
        setSeconds(0);
      }
      if (minutes > 60) {
        setHours((hours) => {
          return hours + 1;
        });
        setMinutes(0);
      }
    } else if (!isRunning && seconds !== 0) {
      clearInterval(interval);
    }
    return () => clearInterval(interval);
  }, [isRunning, seconds]);

  const formatedTime = () => {
    let formatedSeconds = seconds < 10 ? `0${seconds}` : seconds;
    let formatedMinutes = () => {
      if (hours >= 1) {
        if (minutes < 10) {
          return `0${minutes}`;
        } else return minutes;
      } else if (hours < 1) {
        return minutes;
      }
    };
    let formatedHours = hours < 1 ? " " : `${hours}:`;
    let formatedTime = `${formatedHours}${formatedMinutes()}:${formatedSeconds}`;
    return formatedTime;
  };

  return (
    <div className="clock">
      <h1>{formatedTime()}</h1>
      <div>
        <button className="btn btn-primary m-1" onClick={toggleOn}>
          {isRunning ? "Pause" : "Start"}
        </button>
        <button className="btn btn-primary m-1" onClick={reset}>
          Reset
        </button>
      </div>
    </div>
  );
}

export default Clock;
</code>```

Body:
I am trying to implement counter in React.js which increments the value continuously on click but I am not getting the appropriate result, code works fine in plain html/js.

https://codesandbox.io/s/autumn-wood-fhsjx?file=/src/App.js

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [value, setValue] = useState(0);

  const continuosIncerment = () => {
    console.log(`Setting ${value}`);

    setValue(value + 1);

    timer = setTimeout(function() {
      continuosIncerment();
    }, 1000);
  };

  function timeoutClear() {
    clearTimeout(timer);
  }

  return (

      <button
        onMouseLeave={timeoutClear}
        onMouseUp={timeoutClear}
        onMouseDown={continuosIncerment}
      >
        Increment
      </button>

Value = {value}

  );
}

Body:
This is the code for a timer that I used on my app, maybe it can help you.

import React, { useState, useEffect } from "react";
import "./clock.css";

function Clock() {
  const [isRunning, setIsRunning] = useState(false);
  const [seconds, setSeconds] = useState(0);
  const [minutes, setMinutes] = useState(0);
  const [hours, setHours] = useState(0);

  const toggleOn = () => {
    setIsRunning(!isRunning);
  };

  const reset = () => {
    setMinutes(0);
    setSeconds(0);
    setIsRunning(false);
    setHours(0);
  };

  useEffect(() => {
    let interval = null;
    if (isRunning) {
      interval = setInterval(() => {
        setSeconds((seconds) => seconds + 1);
      }, 1000);
      if (seconds > 60) {
        setMinutes((minutes) => minutes + 1);
        setSeconds(0);
      }
      if (minutes > 60) {
        setHours((hours) => {
          return hours + 1;
        });
        setMinutes(0);
      }
    } else if (!isRunning && seconds !== 0) {
      clearInterval(interval);
    }
    return () => clearInterval(interval);
  }, [isRunning, seconds]);

  const formatedTime = () => {
    let formatedSeconds = seconds < 10 ? `0${seconds}` : seconds;
    let formatedMinutes = () => {
      if (hours >= 1) {
        if (minutes < 10) {
          return `0${minutes}`;
        } else return minutes;
      } else if (hours < 1) {
        return minutes;
      }
    };
    let formatedHours = hours < 1 ? " " : `${hours}:`;
    let formatedTime = `${formatedHours}${formatedMinutes()}:${formatedSeconds}`;
    return formatedTime;
  };

  return (
    <div className="clock">
      <h1>{formatedTime()}</h1>
      <div>
        <button className="btn btn-primary m-1" onClick={toggleOn}>
          {isRunning ? "Pause" : "Start"}
        </button>
        <button className="btn btn-primary m-1" onClick={reset}>
          Reset
        </button>
      </div>
    </div>
  );
}

export default Clock;


问:
Firebase Datasnapshot returns null value
I want to retrieve this value from this node ("id"), and the value i get is null. I have googled so many solutions that this might have to do with asynchronous way or something, i guess?

This is the database, and the highlighted node is the value i would like to get:

This is my code:

```<code>            reference = FirebaseDatabase.getInstance().getReference();
            id = null;
            Query lastQuery = reference.child("Donation Request").orderByKey().limitToLast(1);
            lastQuery.addListenerForSingleValueEvent(new ValueEventListener()
            {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot)
                {
                    if (dataSnapshot.child("id").exists())
                    {
                        id = dataSnapshot.child("id").getValue().toString();
                        int index = Integer.parseInt(id) + 1;
                        id = Integer.toString(index);
                        Toast.makeText(getApplicationContext(), "It works!!!", Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        id = "1";
                        Toast.makeText(getApplicationContext(), "It doesn't work.", Toast.LENGTH_SHORT).show();
                    }
                }
                @Override
                public void onCancelled(@NonNull DatabaseError databaseError)
                {

                }
            });
</code>```

Most appreciated if someone can help me out of this!

答:
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

Your onDataChange needs to handle this list by looping over dataSnapshot.getChildren()):

```<code>reference = FirebaseDatabase.getInstance().getReference();
id = null;
Query lastQuery = reference.child("Donation Request").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener()
{
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot)
    {
        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
            if (snapshot.hasChild("id"))
            {
                id = snapshot.child("id").getValue(String.class);
                int index = Integer.parseInt(id) + 1;
                id = Integer.toString(index);
                Toast.makeText(getApplicationContext(), "It works!!!", Toast.LENGTH_SHORT).show();
            }
            else
            {
                id = "1";
                Toast.makeText(getApplicationContext(), "It doesn't work.", Toast.LENGTH_SHORT).show();
            }
        }
    }
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError)
    {
        throw databaseError.toException(); // never ignore errors.
    }
});
</code>```

A few more notes:

Any use of id needs to happen inside onDataChange, or be called from there. Outside of that, you won't have any guarantees that id will have been assigned the value you expect.

Using toasts for debugging is bound to become confusing. I highly recommend using Log.d(...) and friends, and studying the output (and its order) in the logcat output of your app.

Body:
I want to retrieve this value from this node ("id"), and the value i get is null. I have googled so many solutions that this might have to do with asynchronous way or something, i guess?

This is the database, and the highlighted node is the value i would like to get:

This is my code:

            reference = FirebaseDatabase.getInstance().getReference();
            id = null;
            Query lastQuery = reference.child("Donation Request").orderByKey().limitToLast(1);
            lastQuery.addListenerForSingleValueEvent(new ValueEventListener()
            {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot)
                {
                    if (dataSnapshot.child("id").exists())
                    {
                        id = dataSnapshot.child("id").getValue().toString();
                        int index = Integer.parseInt(id) + 1;
                        id = Integer.toString(index);
                        Toast.makeText(getApplicationContext(), "It works!!!", Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        id = "1";
                        Toast.makeText(getApplicationContext(), "It doesn't work.", Toast.LENGTH_SHORT).show();
                    }
                }
                @Override
                public void onCancelled(@NonNull DatabaseError databaseError)
                {

                }
            });

Most appreciated if someone can help me out of this!

Body:
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

Your onDataChange needs to handle this list by looping over dataSnapshot.getChildren()):

reference = FirebaseDatabase.getInstance().getReference();
id = null;
Query lastQuery = reference.child("Donation Request").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener()
{
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot)
    {
        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
            if (snapshot.hasChild("id"))
            {
                id = snapshot.child("id").getValue(String.class);
                int index = Integer.parseInt(id) + 1;
                id = Integer.toString(index);
                Toast.makeText(getApplicationContext(), "It works!!!", Toast.LENGTH_SHORT).show();
            }
            else
            {
                id = "1";
                Toast.makeText(getApplicationContext(), "It doesn't work.", Toast.LENGTH_SHORT).show();
            }
        }
    }
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError)
    {
        throw databaseError.toException(); // never ignore errors.
    }
});

A few more notes:

Any use of id needs to happen inside onDataChange, or be called from there. Outside of that, you won't have any guarantees that id will have been assigned the value you expect.

Using toasts for debugging is bound to become confusing. I highly recommend using Log.d(...) and friends, and studying the output (and its order) in the logcat output of your app.


问:
Swift: render transcription with timestamp
I'm making an app that transform from speech to text, and now I'm trying to display result on screen, and I'm wondering how to do like this one (from Otter app):

Basic idea:

1 conversation has multiple sentences

each sentence has multiple words, those words have their own timestamps and will be highlighted to match with the current audio playback time

We can click on each word to play audio at that timestamp

You can see in the end of the GIF, we can scroll the slider and words will automatically be highlighted

My thoughts:

I'm thinking of rendering UILabel (or UIButton) that represents for each word, by doing that we can click on each Label and jump to correct time, but I don't know how to append UILabel to another UILabel in same line, tried searching but can't find a solution. A sentence can be long and contains multiple words because of that it will need to break to multiline if needed

Also I'm wondering that, to make the labels auto highlight when audio playing (or when scrolling the slider) they should some how "watch" for audio playback time changes (or slider value change). 1 conversation may contains a lot of sentences and if we do "watch" in un-efficient way will cause bad performance

答:
After some researches and try figure out myself, I see that Otter uses UITextView to display each sentence, and their idea inspired me.

I ended up finish it with UITextView and Attributed text to get the result same  like them

For watching playback time changes, I use key value observer. Each sentence will observe playback time, and if the time is in the sentence's time boundary, then the sentence will find out which word inside it should be highlighted


问:
Modify external object in promise function
I have an array of objects (books) that are missing some fields, so I'm using node-isbn module to fetch the missing data. However, I'm having trouble persisting the updates to the objects. Here's some example code:

const isbn = require('node-isbn');

var books = []; // assume this is filled in elsewhere

books.forEach(function(item) {
    if (item.publication_year == '' ||
        item.num_pages == '') {
        isbn.provider(['openlibrary', 'google'])
            .resolve(item.isbn)
            .then(function (book) {
                item.num_pages = book.pageCount;
                item.publication_year = book.publishedDate.replace( /^\D+/g, '');
            }).catch(function (err) {
                console.log('Book not found', err);
            });
    }
    console.log(item)
});```

However, the console log shows that the num_pages and publication_year fields are still empty. How can I fix this?

答: Try not to use Promise inside forEach</p>

Body:
I have an array of objects (books) that are missing some fields, so I'm using node-isbn module to fetch the missing data. However, I'm having trouble persisting the updates to the objects. Here's some example code:

const isbn = require('node-isbn');

var books = []; // assume this is filled in elsewhere

books.forEach(function(item) {
    if (item.publication_year == '' ||
        item.num_pages == '') {
        isbn.provider(['openlibrary', 'google'])
            .resolve(item.isbn)
            .then(function (book) {
                item.num_pages = book.pageCount;
                item.publication_year = book.publishedDate.replace( /^\D+/g, '');
            }).catch(function (err) {
                console.log('Book not found', err);
            });
    }
    console.log(item)
});

However, the console log shows that the num_pages and publication_year fields are still empty. How can I fix this?

Body: Try not to use Promise inside forEach


问:
Firebase Firestore works with real database but not emulator
I'm using Firebase and have started trying to run a local development instance using the Firebase Emulators. I'm running v8.4.1 of Firebase Tools. When I'm running with the real Firestore database everything works fine. However there is something wrong when I'm using the emulators.

I can set a document and then get it through Javascript but nothing shows in the Firebase Emulators UI and the same in reverse, when I add data through the Firebase Emulators UI it isn't available using get in Javascript. Also, when I use the import and export function of the Firebase Tools CLI none of the data I've added through Javascript is exported and imported. I'm not getting any errors in the browser console.

I'm not sure if there is something wrong I'm doing in initializing Firebase or some other config I'm missing?

I'm running: firebase emulators:start --only functions,firestore

Firebase setup code

```<code>import * as firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/functions';

const db = firebase.initializeApp({
  apiKey: 'my_api_key',
  appId: 'my_app_id',
  authDomain: 'my_auth_domain',
  databaseURL: 'my_database_url',
  messagingSenderId: 'my_messaging_sender_id',
  projectId: 'my_project_id',
  storageBucket: 'my_storage_bucket',
}).firestore();

if (process.env.NODE_ENV === 'development') {
  firebase.setLogLevel('debug');

  db.settings({
    host: 'localhost:8000',
    ssl: false,
  });

  firebase.functions().useFunctionsEmulator('http://localhost:5001');
}

export { db };
</code>```

firebase.json

```<code>{
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "functions": {
    "source": "packages/functions"
  },
  "hosting": {
    "public": "packages/frontend/dist",
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "storage": {
    "rules": "storage.rules"
  },
  "emulators": {
    "functions": {
      "port": 5001
    },
    "firestore": {
      "port": 8000
    },
    "ui": {
      "enabled": true
    }
  }
}
</code>```

Browser console

```<code>index.esm.js?abfd:106 [2020-05-30T03:18:23.148Z]  @firebase/firestore: Firestore (7.14.5): FirestoreClient Initializing. user= Jgjhmnb23JHFDTRGEYK5Jppwed
index.esm.js?abfd:106 [2020-05-30T03:18:23.162Z]  @firebase/firestore: Firestore (7.14.5): MemoryPersistence Starting transaction: Get last stream token
index.esm.js?abfd:106 [2020-05-30T03:18:23.164Z]  @firebase/firestore: Firestore (7.14.5): MemoryPersistence Starting transaction: Get next mutation batch
index.esm.js?abfd:106 [2020-05-30T03:18:23.166Z]  @firebase/firestore: Firestore (7.14.5): MemoryPersistence Starting transaction: Allocate target
index.esm.js?abfd:106 [2020-05-30T03:18:23.167Z]  @firebase/firestore: Firestore (7.14.5): MemoryPersistence Starting transaction: Execute query
index.esm.js?abfd:106 [2020-05-30T03:18:23.168Z]  @firebase/firestore: Firestore (7.14.5): IndexFreeQueryEngine Using full collection scan to execute query: Query(target=Target(categories, orderBy: [name (asc), __name__ (asc)]); limitType=F)
index.esm.js?abfd:106 [2020-05-30T03:18:23.173Z]  @firebase/firestore: Firestore (7.14.5): Connection Creating WebChannel: http://localhost:8000/google.firestore.v1.Firestore/Listen/channel [object Object]
index.esm.js?abfd:106 [2020-05-30T03:18:23.178Z]  @firebase/firestore: Firestore (7.14.5): Connection Opening WebChannel transport.
index.esm.js?abfd:106 [2020-05-30T03:18:23.180Z]  @firebase/firestore: Firestore (7.14.5): Connection WebChannel sending: {"database":"projects/vendida-a17e6/databases/(default)","addTarget":{"query":{"structuredQuery":{"from":[{"collectionId":"categories"}],"orderBy":[{"field":{"fieldPath":"name"},"direction":"ASCENDING"},{"field":{"fieldPath":"__name__"},"direction":"ASCENDING"}]},"parent":"projects/my-project-ha47s/databases/(default)/documents"},"targetId":2}}
index.esm.js?abfd:106 [2020-05-30T03:18:23.217Z]  @firebase/firestore: Firestore (7.14.5): Connection WebChannel transport opened.
index.esm.js?abfd:106 [2020-05-30T03:18:23.241Z]  @firebase/firestore: Firestore (7.14.5): Connection WebChannel received: {"targetChange":{"targetChangeType":"ADD","targetIds":[2]}}
index.esm.js?abfd:106 [2020-05-30T03:18:23.242Z]  @firebase/firestore: Firestore (7.14.5): Connection WebChannel received: {"targetChange":{"targetChangeType":"CURRENT","targetIds":[2],"resumeToken":"HGfhjBG7dfU56Gn=","readTime":"2020-05-30T03:18:23.208926Z"}}
index.esm.js?abfd:106 [2020-05-30T03:18:23.242Z]  @firebase/firestore: Firestore (7.14.5): Connection WebChannel received: {"targetChange":{"resumeToken":"YFgT/hjfF76fWj1=","readTime":"2020-05-30T03:18:23.209597Z"}}
index.esm.js?abfd:106 [2020-05-30T03:18:23.244Z]  @firebase/firestore: Firestore (7.14.5): MemoryPersistence Starting transaction: Get last remote snapshot version
index.esm.js?abfd:106 [2020-05-30T03:18:23.246Z]  @firebase/firestore: Firestore (7.14.5): MemoryPersistence Starting transaction: Apply remote event
index.esm.js?abfd:106 [2020-05-30T03:18:23.248Z]  @firebase/firestore: Firestore (7.14.5): MemoryPersistence Starting transaction: notifyLocalViewChanges
</code>```

firestore-debug.log

```<code>May 30, 2020 1:08:25 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead
INFO: Detected non-HTTP/2 connection.
May 30, 2020 1:09:06 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead
INFO: Detected non-HTTP/2 connection.
May 30, 2020 1:09:25 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead
INFO: Detected non-HTTP/2 connection.
</code>```

firebase-debug.log

```<code>[debug] [2020-05-30T03:10:25.924Z] May 30, 2020 1:10:25 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead
INFO: Detected non-HTTP/2 connection.
 {"metadata":{"emulator":{"name":"firestore"},"message":"May 30, 2020 1:10:25 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead\nINFO: Detected non-HTTP/2 connection.\n"}}
[debug] [2020-05-30T03:11:06.713Z] May 30, 2020 1:11:06 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead
INFO: Detected non-HTTP/2 connection.
 {"metadata":{"emulator":{"name":"firestore"},"message":"May 30, 2020 1:11:06 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead\nINFO: Detected non-HTTP/2 connection.\n"}}
[debug] [2020-05-30T03:11:25.949Z] May 30, 2020 1:11:25 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead
INFO: Detected non-HTTP/2 connection.
 {"metadata":{"emulator":{"name":"firestore"},"message":"May 30, 2020 1:11:25 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead\nINFO: Detected non-HTTP/2 connection.\n"}}
</code>```

答:
Turns out the issue was due to the current status of Firebase Tools. I had previously been using Firebase Tools with another project and had to run the use command for my current project that I was trying to use the emulators with:

```<code>firebase use project_name
</code>```

Now everything works as expected.

Body:
I'm using Firebase and have started trying to run a local development instance using the Firebase Emulators. I'm running v8.4.1 of Firebase Tools. When I'm running with the real Firestore database everything works fine. However there is something wrong when I'm using the emulators.

I can set a document and then get it through Javascript but nothing shows in the Firebase Emulators UI and the same in reverse, when I add data through the Firebase Emulators UI it isn't available using get in Javascript. Also, when I use the import and export function of the Firebase Tools CLI none of the data I've added through Javascript is exported and imported. I'm not getting any errors in the browser console.

I'm not sure if there is something wrong I'm doing in initializing Firebase or some other config I'm missing?

I'm running: firebase emulators:start --only functions,firestore

Firebase setup code

import * as firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/functions';

const db = firebase.initializeApp({
  apiKey: 'my_api_key',
  appId: 'my_app_id',
  authDomain: 'my_auth_domain',
  databaseURL: 'my_database_url',
  messagingSenderId: 'my_messaging_sender_id',
  projectId: 'my_project_id',
  storageBucket: 'my_storage_bucket',
}).firestore();

if (process.env.NODE_ENV === 'development') {
  firebase.setLogLevel('debug');

  db.settings({
    host: 'localhost:8000',
    ssl: false,
  });

  firebase.functions().useFunctionsEmulator('http://localhost:5001');
}

export { db };

firebase.json

{
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "functions": {
    "source": "packages/functions"
  },
  "hosting": {
    "public": "packages/frontend/dist",
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "storage": {
    "rules": "storage.rules"
  },
  "emulators": {
    "functions": {
      "port": 5001
    },
    "firestore": {
      "port": 8000
    },
    "ui": {
      "enabled": true
    }
  }
}

Browser console

index.esm.js?abfd:106 [2020-05-30T03:18:23.148Z]  @firebase/firestore: Firestore (7.14.5): FirestoreClient Initializing. user= Jgjhmnb23JHFDTRGEYK5Jppwed
index.esm.js?abfd:106 [2020-05-30T03:18:23.162Z]  @firebase/firestore: Firestore (7.14.5): MemoryPersistence Starting transaction: Get last stream token
index.esm.js?abfd:106 [2020-05-30T03:18:23.164Z]  @firebase/firestore: Firestore (7.14.5): MemoryPersistence Starting transaction: Get next mutation batch
index.esm.js?abfd:106 [2020-05-30T03:18:23.166Z]  @firebase/firestore: Firestore (7.14.5): MemoryPersistence Starting transaction: Allocate target
index.esm.js?abfd:106 [2020-05-30T03:18:23.167Z]  @firebase/firestore: Firestore (7.14.5): MemoryPersistence Starting transaction: Execute query
index.esm.js?abfd:106 [2020-05-30T03:18:23.168Z]  @firebase/firestore: Firestore (7.14.5): IndexFreeQueryEngine Using full collection scan to execute query: Query(target=Target(categories, orderBy: [name (asc), __name__ (asc)]); limitType=F)
index.esm.js?abfd:106 [2020-05-30T03:18:23.173Z]  @firebase/firestore: Firestore (7.14.5): Connection Creating WebChannel: http://localhost:8000/google.firestore.v1.Firestore/Listen/channel [object Object]
index.esm.js?abfd:106 [2020-05-30T03:18:23.178Z]  @firebase/firestore: Firestore (7.14.5): Connection Opening WebChannel transport.
index.esm.js?abfd:106 [2020-05-30T03:18:23.180Z]  @firebase/firestore: Firestore (7.14.5): Connection WebChannel sending: {"database":"projects/vendida-a17e6/databases/(default)","addTarget":{"query":{"structuredQuery":{"from":[{"collectionId":"categories"}],"orderBy":[{"field":{"fieldPath":"name"},"direction":"ASCENDING"},{"field":{"fieldPath":"__name__"},"direction":"ASCENDING"}]},"parent":"projects/my-project-ha47s/databases/(default)/documents"},"targetId":2}}
index.esm.js?abfd:106 [2020-05-30T03:18:23.217Z]  @firebase/firestore: Firestore (7.14.5): Connection WebChannel transport opened.
index.esm.js?abfd:106 [2020-05-30T03:18:23.241Z]  @firebase/firestore: Firestore (7.14.5): Connection WebChannel received: {"targetChange":{"targetChangeType":"ADD","targetIds":[2]}}
index.esm.js?abfd:106 [2020-05-30T03:18:23.242Z]  @firebase/firestore: Firestore (7.14.5): Connection WebChannel received: {"targetChange":{"targetChangeType":"CURRENT","targetIds":[2],"resumeToken":"HGfhjBG7dfU56Gn=","readTime":"2020-05-30T03:18:23.208926Z"}}
index.esm.js?abfd:106 [2020-05-30T03:18:23.242Z]  @firebase/firestore: Firestore (7.14.5): Connection WebChannel received: {"targetChange":{"resumeToken":"YFgT/hjfF76fWj1=","readTime":"2020-05-30T03:18:23.209597Z"}}
index.esm.js?abfd:106 [2020-05-30T03:18:23.244Z]  @firebase/firestore: Firestore (7.14.5): MemoryPersistence Starting transaction: Get last remote snapshot version
index.esm.js?abfd:106 [2020-05-30T03:18:23.246Z]  @firebase/firestore: Firestore (7.14.5): MemoryPersistence Starting transaction: Apply remote event
index.esm.js?abfd:106 [2020-05-30T03:18:23.248Z]  @firebase/firestore: Firestore (7.14.5): MemoryPersistence Starting transaction: notifyLocalViewChanges

firestore-debug.log

May 30, 2020 1:08:25 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead
INFO: Detected non-HTTP/2 connection.
May 30, 2020 1:09:06 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead
INFO: Detected non-HTTP/2 connection.
May 30, 2020 1:09:25 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead
INFO: Detected non-HTTP/2 connection.

firebase-debug.log

[debug] [2020-05-30T03:10:25.924Z] May 30, 2020 1:10:25 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead
INFO: Detected non-HTTP/2 connection.
 {"metadata":{"emulator":{"name":"firestore"},"message":"May 30, 2020 1:10:25 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead\nINFO: Detected non-HTTP/2 connection.\n"}}
[debug] [2020-05-30T03:11:06.713Z] May 30, 2020 1:11:06 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead
INFO: Detected non-HTTP/2 connection.
 {"metadata":{"emulator":{"name":"firestore"},"message":"May 30, 2020 1:11:06 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead\nINFO: Detected non-HTTP/2 connection.\n"}}
[debug] [2020-05-30T03:11:25.949Z] May 30, 2020 1:11:25 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead
INFO: Detected non-HTTP/2 connection.
 {"metadata":{"emulator":{"name":"firestore"},"message":"May 30, 2020 1:11:25 PM io.gapi.emulators.netty.HttpVersionRoutingHandler channelRead\nINFO: Detected non-HTTP/2 connection.\n"}}

Body:
Turns out the issue was due to the current status of Firebase Tools. I had previously been using Firebase Tools with another project and had to run the use command for my current project that I was trying to use the emulators with:

firebase use project_name

Now everything works as expected.


问:
get data from dynamix ax xml from php
$url = "http://localhost/dss/dss.asmx/AreaCategory_list";</p>

```<code>$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36');

$xmlstr = curl_exec($ch);
curl_close($ch);

var_dump(  $xmlstr);
</code>```

答:
cannot show data

$json2 = "http://localhost/dss/dss.asmx/AreaCategory_list";

$array = json_decode($json2);
 echo $array->Remark;

Title: get data from dynamix ax xml from php

Body:
$url = "http://localhost/dss/dss.asmx/AreaCategory_list";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36');

$xmlstr = curl_exec($ch);
curl_close($ch);

var_dump(  $xmlstr);


问:
AWS Cloudformation cfn-init not installing packages
I'm trying to get a simple AWS Cloudformation cfn-init script working but not having any success. The script is shown below. When I log in to the instance created, httpd isn't even installed. I'm creating an AWS Linux2 instance in us-east-1.

```<code>Resources:
  ...
  Ec2Instance:
    Type: AWS::EC2::Instance
    Metadata:
      AWS::CloudFormation::Init:
        config:
          packages:
            yum:
              httpd: []
          files:
            /var/www/html/index.html:
              content: !Sub |
                <html><body>Hello, World</body></html>
          services:
            sysvinit:
              httpd:
                enabled: true
                ensureRunning: true
    Properties:
      InstanceType: t2.micro
      ImageId: ami-0323c3dd2da7fb37d
      KeyName: KeyPair
      SecurityGroupIds:
        - !Ref InstanceSecurityGroup
      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash -xe
            yum update -y aws-cfn-bootstrap
            /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource Ec2Instance --region ${AWS::Region}
</code>```

答:
I deployed your template, and can confirm it is correct. httpd and index.html are installed and deployed as expected.

There must be something else happening. For example, deploying to a private subnet without internet. In that case httpd want be installed. Or like @Christian mentioned, amending existing instance.

Body:
I'm trying to get a simple AWS Cloudformation cfn-init script working but not having any success. The script is shown below. When I log in to the instance created, httpd isn't even installed. I'm creating an AWS Linux2 instance in us-east-1.

Resources:
  ...
  Ec2Instance:
    Type: AWS::EC2::Instance
    Metadata:
      AWS::CloudFormation::Init:
        config:
          packages:
            yum:
              httpd: []
          files:
            /var/www/html/index.html:
              content: !Sub |
                Hello, World
          services:
            sysvinit:
              httpd:
                enabled: true
                ensureRunning: true
    Properties:
      InstanceType: t2.micro
      ImageId: ami-0323c3dd2da7fb37d
      KeyName: KeyPair
      SecurityGroupIds:
        - !Ref InstanceSecurityGroup
      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash -xe
            yum update -y aws-cfn-bootstrap
            /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource Ec2Instance --region ${AWS::Region}


问:
Cannot print correct values in Bison code
So I'm trying to declare the syntax of an array (using Bison 3.6.2) as follows:

```<code>array: '[' array_vals ']'

array_vals:
| vals array_vals

vals: STRING //String values defined in my lexer
| FLOAT //Float values defined in my lexer
| INT //Integer values defined in my lexer
</code>```

I feel like this is pretty self explanatory, but there's just one problem: Wherever I print the array_vals, using this: array: '[' array_vals ']' { cout << $2 << endl; } I get only the first value of the array in my source code, so if I have this in my source file: [10, 20, 30, 40] then it only prints 10. I've tried printing the vals in array_vals, and it's even weirder and inconsistent. I know that this isn't a bug since I went from Bison version 3.5.1 to 3.6.2 and there was no difference. Thanks in advance!

答:
A general flex+bison advice: make them print everything they do.
So the lexer would have lines like this:

```<code>">=" { cout << ">= on line: " << line << "\n"; return parser::make_GEQ(loc); }
</code>```

And the parser will have lines like this:

```<code>vals:
val      { cout << "vals -> val\n";      $$ = {$1};                  } |
val vals { cout << "vals -> val vals\n"; $2.push_front($1); $$ = $2; } ;
</code>```

Body:
So I'm trying to declare the syntax of an array (using Bison 3.6.2) as follows:

array: '[' array_vals ']'

array_vals:
| vals array_vals

vals: STRING //String values defined in my lexer
| FLOAT //Float values defined in my lexer
| INT //Integer values defined in my lexer

I feel like this is pretty self explanatory, but there's just one problem: Wherever I print the array_vals, using this: array: '[' array_vals ']' { cout << $2 << endl; } I get only the first value of the array in my source code, so if I have this in my source file: [10, 20, 30, 40] then it only prints 10. I've tried printing the vals in array_vals, and it's even weirder and inconsistent. I know that this isn't a bug since I went from Bison version 3.5.1 to 3.6.2 and there was no difference. Thanks in advance!

Body:
A general flex+bison advice: make them print everything they do.
So the lexer would have lines like this:

">=" { cout << ">= on line: " << line << "\n"; return parser::make_GEQ(loc); }

And the parser will have lines like this:

vals:
val      { cout << "vals -> val\n";      $$ = {$1};                  } |
val vals { cout << "vals -> val vals\n"; $2.push_front($1); $$ = $2; } ;


问:
Failed to render sass to css at newBuild error

I am getting below error while building my ionic project. Please help me out in resolving this issue.

答: The error you are getting implies that the value you are passing to the function is not a valid colour. Check that you are passing a valid colour first.</p>


问:
Java, moving from desktop app to web app
I'm going to write my first Java based web app, and I'm sort of lost how to begin.

Firstly, I would like a web app and a desktop app that do pretty much the same thing, without the hackish idea of embedding a web browser into the desktop app because that doesn't allow to easily make changes to the desktop without affecting the web app and vice versa.

Now, here my questions.

Right now, I have a bunch of POJOs and they communicate with a single class that, right now, uses a flat file as a "database", of course, in production, I would use a legitimate database and just change that single class. Is this a good idea? Will I be able to go from POJOs to a web app?

Should I use a framework? I would like to have this app written pretty soon, seeing that all the buisness logic is there, I just need to wrap it so its usable, so, I don't want to spend an extreme amount of time learning, say, Spring (which AFAIK is huge), but, I don't want to keep reinventing the wheel throughout my app either. I can always just use JSP and scriptlets...

If you said yes to the above, what framework(s) do you suggest? Please note that I would like a framework that I can start using in maybe 3-4 weeks of learning.

Will I have to start from scratch with the POJOs that I have written? They're well over 30k LOC, so, if it is like that, I'll be hesitant.

答:
... I a bunch of POJOs and they communicate with a single class that, right now, uses a flat file as a "database", of course, in production, I would use a legitimate database and just change that single class. Is this a good idea? Will I be able to go from POJOs to a web app?

qualified yes. if the pojo's are sane you should not have many problems. many people use hiberbate.

Should I use a framework? I would like to have this app written pretty soon, seeing that all the buisness logic is there, I just need to wrap it so its usable, so, I don't want to spend an extreme amount of time learning, say, Spring (which AFAIK is huge), but, I don't want to keep reinventing the wheel throughout my app either. I can always just use JSP and scriptlets...

probably. spring is huge, but things like grails or roo can help.

if you want to have a responsive web app, you will need to do some kind of rich client (AJAX). this may require a lot of your code to run on the client. this means writing a lot of javascript or using gwt. this will be a pain. it probably will not be so easy to just "wrap it". if you have written a swing app, then basically that code will need to run on the client.

If you said yes to the above, what framework(s) do you suggest? Please note that I would like a framework that I can start using in maybe 3-4 weeks of learning.

i like groovy and grails - grails uses spring-mvc, spring, hibernate. but there is roo, play and others.

Will I have to start from scratch with the POJOs that I have written? They're well over 30k LOC, so, if it is like that, I'll be hesitant.

the code that will run on the server can probably be mostly left alone. the code that has to run on the client needs to be rewritten in javascript or maybe you can get some reuse out of that code by using gwt,


问:
The shell variable contains ~, which was not parsed correctly
The destination is environment variable,

destination=~/Desktop

```<code>d=`date +%F-%H%M%S`

filename=${destination}/${d}.{query}

touch $filename
</code>```

when executing command，it report error. because ~ treat as a string.

the filename is ~/Desktop/2020-05-30-120306.json, ~ is not recognized.

So how to do, I need ~ to be recognized correctly

答:
Here's a link. It describes two ways this can be done. The first of which using an eval (which is dangerous):

```<code>d=`date +%F-%H%M%S`

eval destination="~/Desktop"
query="json"
filename=${destination}/${d}.${query}

touch $filename
</code>```

Second of which is safer and the recommended option.

```<code>d=`date +%F-%H%M%S`

destination="~/Desktop"
query="json"
filename=${destination/#\~/$HOME}/${d}.${query}

touch $filename
</code>```

Not sure how you are setting the $destination so you may need to play around with it, but these both worked for me.

Body:
The destination is environment variable,

destination=~/Desktop

d=`date +%F-%H%M%S`

filename=${destination}/${d}.{query}

touch $filename

when executing command，it report error. because ~ treat as a string.

the filename is ~/Desktop/2020-05-30-120306.json, ~ is not recognized.

So how to do, I need ~ to be recognized correctly

Body:
Here's a link. It describes two ways this can be done. The first of which using an eval (which is dangerous):

d=`date +%F-%H%M%S`

eval destination="~/Desktop"
query="json"
filename=${destination}/${d}.${query}

touch $filename

Second of which is safer and the recommended option.

d=`date +%F-%H%M%S`

destination="~/Desktop"
query="json"
filename=${destination/#\~/$HOME}/${d}.${query}

touch $filename

Not sure how you are setting the $destination so you may need to play around with it, but these both worked for me.