问:
Failing to install MySQL-python
I am tying to install MySQL-python in a python 2.7 virtual environment but I am getting the following error:

```<code>Installing collected packages: MySQL-python
Running setup.py install for MySQL-python ... error
ERROR: Command errored out with exit status 1:
 command: /home/jhylands/py2/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-scNGlE/MySQL-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-scNGlE/MySQL-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-FUMQGL/install-record.txt --single-version-externally-managed --compile --install-headers /home/jhylands/py2/include/site/python2.7/MySQL-python
     cwd: /tmp/pip-install-scNGlE/MySQL-python/
Complete output (30 lines):
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-2.7
copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7
creating build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb
creating build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.linux-x86_64-2.7
x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-1x6jhf/python2.7-2.7.18~rc1=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o
_mysql.c:44:10: fatal error: my_config.h: No such file or directory
   44 | #include "my_config.h"
      |          ^~~~~~~~~~~~~
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
----------------------------------------
ERROR: Command errored out with exit status 1: /home/jhylands/py2/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-scNGlE/MySQL-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-scNGlE/MySQL-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-FUMQGL/install-record.txt --single-version-externally-managed --compile --install-headers /home/jhylands/py2/include/site/python2.7/MySQL-python Check the logs for full command output.
</code>```

I have already tried installing the solutions suggested in this post
 and this post

答:
So I managed to solve the issue with the following command:

```<code>sudo wget https://raw.githubusercontent.com/paulfitz/mysql-connector-c/master/include/my_config.h -P /usr/include/mysql/
</code>```

Which I found from a comment on this answer.

Title: Failing to install MySQL-python

Body:
I am tying to install MySQL-python in a python 2.7 virtual environment but I am getting the following error:

Installing collected packages: MySQL-python
Running setup.py install for MySQL-python ... error
ERROR: Command errored out with exit status 1:
 command: /home/jhylands/py2/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-scNGlE/MySQL-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-scNGlE/MySQL-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-FUMQGL/install-record.txt --single-version-externally-managed --compile --install-headers /home/jhylands/py2/include/site/python2.7/MySQL-python
     cwd: /tmp/pip-install-scNGlE/MySQL-python/
Complete output (30 lines):
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-2.7
copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7
creating build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb
creating build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.linux-x86_64-2.7
x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-1x6jhf/python2.7-2.7.18~rc1=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o
_mysql.c:44:10: fatal error: my_config.h: No such file or directory
   44 | #include "my_config.h"
      |          ^~~~~~~~~~~~~
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
----------------------------------------
ERROR: Command errored out with exit status 1: /home/jhylands/py2/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-scNGlE/MySQL-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-scNGlE/MySQL-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-FUMQGL/install-record.txt --single-version-externally-managed --compile --install-headers /home/jhylands/py2/include/site/python2.7/MySQL-python Check the logs for full command output.

I have already tried installing the solutions suggested in this post
 and this post

Body:
So I managed to solve the issue with the following command:

sudo wget https://raw.githubusercontent.com/paulfitz/mysql-connector-c/master/include/my_config.h -P /usr/include/mysql/

Which I found from a comment on this answer.


来源: stackexchange

问:
Why is there massive white space under my image in React? What's creating this mysterious div?
I'm building a login Component in React, and trying to add the brand image. When I do this, I'm getting a huge amount of white space underneath it.

I've been working on this for a bit now, and I've discovered that, when I look in the dev tools, I can make headway by modifying this mysterious div that seems to be created by Material-UI, the front-end framework I'm using.

When I look into this in the dev tools, I find that there's a div with the attribute padding-top: calc(100%) which, when modified to something like padding-top: calc(30%), reduces the size of this whitespace underneath the image.

I've also tried some of the basic layout solutions suggested in many of the answers to similar questions here on SO, but none of them make a difference. It seems that this padding issue is at the heart of the problem.

The Problem

Because I don't know what's creating this div, I'm not able to override the padding to work towards a solution. I've tried modifying paddingTop and padding with the !important tag in the styling of both the image, and the parent element of the image.

Code Sample

```<code>          <Paper variant='outlined' style={{ width: '380px' }}>
            <Box m={4}>
              <Image
                src='../static/images/TextLogo.svg'
                imageStyle={{
                  height: 'auto',
                  width: '100%',
                }}
              />
            </Box>
          ...
</code>```

Stack

```<code>"@material-ui/core": "^4.0.0-alpha.8",
"material-ui-image": "^3.2.3",
"next": "^8.1.0",
"react": "^16.8.6",
"react-dom": "^16.8.6"
</code>```

Thanks. I'd appreciate your help!

答:
The
 with the padding-top and other styles is coming from the Image component that you are using from material-ui-image.

Below is the overall structure rendered by that Image component:

```<code>      <div
        style={styles.root}
        onClick={onClick}
      >
        {image.src && <img
          {...image}
          style={styles.image}
          onLoad={this.handleLoadImage}
          onError={this.handleImageError}
        />}
        <div style={styles.iconContainer}>
          {!disableSpinner && !this.state.imageLoaded && !this.state.imageError && loading}
          {!disableError && this.state.imageError && errorIcon}
        </div>
      </div>
</code>```

padding-top is part of the styles in styles.root.

styles.root:

```<code>    const styles = {
      root: {
        backgroundColor: color,
        paddingTop: `calc(1 / ${aspectRatio} * 100%)`,
        position: 'relative',
        ...style
      },
</code>```

When padding-top is a percentage, it is a percentage of the width, so it is important to control the width of the container in order to have predictable behavior.

You can modify the padding-top by either explicitly overriding it via the style prop or by specifying the appropriate value in the aspectRatio prop. By default, this Image component is assuming square images (aspectRatio: 1).

Here is a working example demonstrating both ways of controlling padding-top:

```<code>import React from "react";
import Image from "material-ui-image";
import Box from "@material-ui/core/Box";

export default function App() {
  return (
    <>
      <Box m={4} width={200}>
        <Image
          aspectRatio={1.5}
          src="https://www.publicdomainpictures.net/pictures/10000/velka/black-monkey-11280155875i3QV.jpg"
        />
        Something under image 1
      </Box>
      <Box m={4} width={200}>
        <Image
          style={{
            paddingTop: "calc(66.7%)"
          }}
          src="https://www.publicdomainpictures.net/pictures/10000/velka/black-monkey-11280155875i3QV.jpg"
        />
        Something under image 2
      </Box>
    </>
  );
}
</code>```

Slightly related answer (with regard to the use of padding-top): A good way to handle @material-ui Skeleton scaling within a variable height grid row?

ContentLicense: CC BY-SA 4.0

Body:
I'm building a login Component in React, and trying to add the brand image. When I do this, I'm getting a huge amount of white space underneath it.

I've been working on this for a bit now, and I've discovered that, when I look in the dev tools, I can make headway by modifying this mysterious div that seems to be created by Material-UI, the front-end framework I'm using.

When I look into this in the dev tools, I find that there's a div with the attribute padding-top: calc(100%) which, when modified to something like padding-top: calc(30%), reduces the size of this whitespace underneath the image.

I've also tried some of the basic layout solutions suggested in many of the answers to similar questions here on SO, but none of them make a difference. It seems that this padding issue is at the heart of the problem.

The Problem

Because I don't know what's creating this div, I'm not able to override the padding to work towards a solution. I've tried modifying paddingTop and padding with the !important tag in the styling of both the image, and the parent element of the image.

Code Sample

          <Paper variant='outlined' style={{ width: '380px' }}>
            <Box m={4}>
              <Image
                src='../static/images/TextLogo.svg'
                imageStyle={{
                  height: 'auto',
                  width: '100%',
                }}
              />
            </Box>
          ...

Stack

"@material-ui/core": "^4.0.0-alpha.8",
"material-ui-image": "^3.2.3",
"next": "^8.1.0",
"react": "^16.8.6",
"react-dom": "^16.8.6"

Thanks. I'd appreciate your help!

Body:
The <div> with the padding-top and other styles is coming from the Image component that you are using from material-ui-image.

Below is the overall structure rendered by that Image component:

      <div
        style={styles.root}
        onClick={onClick}
      >
        {image.src && <img
          {...image}
          style={styles.image}
          onLoad={this.handleLoadImage}
          onError={this.handleImageError}
        />}
        <div style={styles.iconContainer}>
          {!disableSpinner && !this.state.imageLoaded && !this.state.imageError && loading}
          {!disableError && this.state.imageError && errorIcon}
        </div>
      </div>

padding-top is part of the styles in styles.root.

styles.root:

    const styles = {
      root: {
        backgroundColor: color,
        paddingTop: `calc(1 / ${aspectRatio} * 100%)`,
        position: 'relative',
        ...style
      },

When padding-top is a percentage, it is a percentage of the width, so it is important to control the width of the container in order to have predictable behavior.

You can modify the padding-top by either explicitly overriding it via the style prop or by specifying the appropriate value in the aspectRatio prop. By default, this Image component is assuming square images (aspectRatio: 1).

Here is a working example demonstrating both ways of controlling padding-top:

import React from "react";
import Image from "material-ui-image";
import Box from "@material-ui/core/Box";

export default function App() {
  return (
    <>
      <Box m={4} width={200}>
        <Image
          aspectRatio={1.5}
          src="https://www.publicdomainpictures.net/pictures/10000/velka/black-monkey-11280155875i3QV.jpg"
        />
        Something under image 1
      </Box>
      <Box m={4} width={200}>
        <Image
          style={{
            paddingTop: "calc(66.7%)"
          }}
          src="https://www.publicdomainpictures.net/pictures/10000/velka/black-monkey-11280155875i3QV.jpg"
        />
        Something under image 2
      </Box>
    </>
  );
}

Slightly related answer (with regard to the use of padding-top): A good way to handle @material-ui Skeleton scaling within a variable height grid row?


问:
Reducing JVM pause time > 1 second using UseConcMarkSweepGC
I'm running a memory intensive app on a machine with 16Gb of RAM, and an 8-core processor, and Java 1.6 all running on CentOS release 5.2 (Final).  Exact JVM details are:

```<code>java version "1.6.0_10"
Java(TM) SE Runtime Environment (build 1.6.0_10-b33)
Java HotSpot(TM) 64-Bit Server VM (build 11.0-b15, mixed mode)
</code>```

I'm launching the app with the following command line options:

```<code>java -XX:+UseConcMarkSweepGC -verbose:gc -server -Xmx10g -Xms10g ...
</code>```

My application exposes a JSON-RPC API, and my goal is to respond to requests within 25ms.  Unfortunately, I'm seeing delays up to and exceeding 1 second and it appears to be caused by garbage collection.  Here are some of the longer examples:

```<code>[GC 4592788K->4462162K(10468736K), 1.3606660 secs]
[GC 5881547K->5768559K(10468736K), 1.2559860 secs]
[GC 6045823K->5914115K(10468736K), 1.3250050 secs]
</code>```

Each of these garbage collection events was accompanied by a delayed API response of very similar duration to the length of the garbage collection shown (to within a few ms).

Here are some typical examples (these were all produced within a few seconds):

```<code>[GC 3373764K->3336654K(10468736K), 0.6677560 secs]
[GC 3472974K->3427592K(10468736K), 0.5059650 secs]
[GC 3563912K->3517273K(10468736K), 0.6844440 secs]
[GC 3622292K->3589011K(10468736K), 0.4528480 secs]
</code>```

The thing is that I thought the UseConcMarkSweepGC would avoid this, or at least make it extremely rare.  On the contrary, delays exceeding 100ms are occurring almost once a minute or more (although delays of over 1 second are considerably rarer, perhaps once every 10 or 15 minutes).

The other thing is that I thought only a FULL GC would cause threads to be paused, yet these don't appear to be full GCs.

It may be relevant to note that most of the memory is occupied by a LRU memory cache that makes use of soft references.

Any assistance or advice would be greatly appreciated.

答:
Turns out that part of the heap was getting swapped out to disk, so that garbage collection had to pull a bunch of data off the disk back into memory.

I resolved this by setting Linux's "swappiness" parameter to 0 (so that it wouldn't swap data out to disk).

OwnerDisplayName: sanity

ContentLicense: CC BY-SA 3.0

Body:
I'm running a memory intensive app on a machine with 16Gb of RAM, and an 8-core processor, and Java 1.6 all running on CentOS release 5.2 (Final).  Exact JVM details are:

java version "1.6.0_10"
Java(TM) SE Runtime Environment (build 1.6.0_10-b33)
Java HotSpot(TM) 64-Bit Server VM (build 11.0-b15, mixed mode)

I'm launching the app with the following command line options:

java -XX:+UseConcMarkSweepGC -verbose:gc -server -Xmx10g -Xms10g ...

My application exposes a JSON-RPC API, and my goal is to respond to requests within 25ms.  Unfortunately, I'm seeing delays up to and exceeding 1 second and it appears to be caused by garbage collection.  Here are some of the longer examples:

[GC 4592788K->4462162K(10468736K), 1.3606660 secs]
[GC 5881547K->5768559K(10468736K), 1.2559860 secs]
[GC 6045823K->5914115K(10468736K), 1.3250050 secs]

Each of these garbage collection events was accompanied by a delayed API response of very similar duration to the length of the garbage collection shown (to within a few ms).

Here are some typical examples (these were all produced within a few seconds):

[GC 3373764K->3336654K(10468736K), 0.6677560 secs]
[GC 3472974K->3427592K(10468736K), 0.5059650 secs]
[GC 3563912K->3517273K(10468736K), 0.6844440 secs]
[GC 3622292K->3589011K(10468736K), 0.4528480 secs]

The thing is that I thought the UseConcMarkSweepGC would avoid this, or at least make it extremely rare.  On the contrary, delays exceeding 100ms are occurring almost once a minute or more (although delays of over 1 second are considerably rarer, perhaps once every 10 or 15 minutes).

The other thing is that I thought only a FULL GC would cause threads to be paused, yet these don't appear to be full GCs.

It may be relevant to note that most of the memory is occupied by a LRU memory cache that makes use of soft references.

Any assistance or advice would be greatly appreciated.

LastEditorDisplayName: sanity

ContentLicense: CC BY-SA 2.5


问:
unable to perform Iteration with R
I've been practicing with the Titanic dataset and have made steady progress. However, I have got stuck when I try to to replace the missing 'Age' variables with the median age depending upon certain conditions. Here is the dataset:

```<code>| Pclass | Name      |   Sex  | Age |
|:------:|:---------:|:------:|:---:|
|    2   |  officer  |  male  |  NA |
|    3   |  mr       |  male  |  27 |
|    3   |  miss     | female |  NA |
</code>```

Now, I want to replace the NAs with the median ages that i calculated and leave the age already present as it is. For this I used the following code for iteration:

```<code>age_fill <- function(x){

    for (i in length(x$Age)) {

      if (!is.na(x$Age[i])) {
          return(x$Age[i])

      }

      else if(is.na(x$Age[i])){

        if (x$Sex[i] == "female" && x$Pclass[i] == "3" && x$Name[i] == "miss"){
          x$Age[i] = 18
        }

        if (x$Sex[i] == "male" && x$Pclass[i] == "2" && x$Name[i] == "mr"){
          x$Age[i] = 29
        }

        if (x$Sex[i] == "male" && x$Pclass[i] == "3" && x$Name[i] == "officer"){
          x$Age[i] = 25
        }

     }

  }
  return(x)
}
</code>```

The problem here is nothing changes when i run the code as a function or in a loop. However, if I run it separately by putting in the digits of the row, it returns the results just fine.

Can someone pls tell me what I'm doing wrong?

答:
I think that the function has a parameter x and returns x, but the for cycle is aplied to a (I guess) data.frame "comb". In order to perform a call to the function
output <- age_fill(comb) you should replace comb$myVariable by x$myVariable so that all the operation within the for cycle can be applied.

Title: unable to perform Iteration with R

Body:
I've been practicing with the Titanic dataset and have made steady progress. However, I have got stuck when I try to to replace the missing 'Age' variables with the median age depending upon certain conditions. Here is the dataset:

| Pclass | Name      |   Sex  | Age |
|:------:|:---------:|:------:|:---:|
|    2   |  officer  |  male  |  NA |
|    3   |  mr       |  male  |  27 |
|    3   |  miss     | female |  NA |

Now, I want to replace the NAs with the median ages that i calculated and leave the age already present as it is. For this I used the following code for iteration:

age_fill <- function(x){

    for (i in length(x$Age)) {

      if (!is.na(x$Age[i])) {
          return(x$Age[i])

      }

      else if(is.na(x$Age[i])){

        if (x$Sex[i] == "female" && x$Pclass[i] == "3" && x$Name[i] == "miss"){
          x$Age[i] = 18
        }

        if (x$Sex[i] == "male" && x$Pclass[i] == "2" && x$Name[i] == "mr"){
          x$Age[i] = 29
        }

        if (x$Sex[i] == "male" && x$Pclass[i] == "3" && x$Name[i] == "officer"){
          x$Age[i] = 25
        }

     }

  }
  return(x)
}

The problem here is nothing changes when i run the code as a function or in a loop. However, if I run it separately by putting in the digits of the row, it returns the results just fine.

Can someone pls tell me what I'm doing wrong?


问:
How do I log a custom field in NLog to database using Microsoft.Extensions.Logging?
I am using Microsoft.Extensions.Logging together with NLog. My app is .NET Core 3.1.

I would like to extend logging with custom fields.

Is it possible or will I need to use NLog directly?

```<code>  <parameter name="@custom_guid" layout="${custom_guid}"/>

         var config = new Dictionary<string, object>();
         config.Add("custom_guid", "test");
         _logger.LogInformation("Test message", config);
</code>```

答:
You could do this:

```<code>var config = new Dictionary<string, object>();
config.Add("custom_guid", "test");

using (_logger.BeginScope(config))
{
   _logger.LogInformation("Test message");
}
</code>```

And use ${mdlc:custom_guid}

Body:
I am using Microsoft.Extensions.Logging together with NLog. My app is .NET Core 3.1.

I would like to extend logging with custom fields.

Is it possible or will I need to use NLog directly?

  <parameter name="@custom_guid" layout="${custom_guid}"/>

         var config = new Dictionary<string, object>();
         config.Add("custom_guid", "test");
         _logger.LogInformation("Test message", config);

Body:
You could do this:

var config = new Dictionary<string, object>();
config.Add("custom_guid", "test");

using (_logger.BeginScope(config))
{
   _logger.LogInformation("Test message");
}

And use ${mdlc:custom_guid}


问:
Why setState doesn't change local state?
Hello guys, so I found interesting task about React, and I a little bit don't understand how to solve it

Task: Why this code is not working? Solve this.

Code:

class Test extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      count: 1
    }
  }
  handler() {
    this.setState({count: this.state.count++})
  }
  render() {
    console.log('render')
    return (

        <button onClick={this.handler}>Add 1</button>

{this.state.count}

    );
  }
}

ReactDOM.render(
  <Test />,
  document.getElementById("test"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id="test"></div>
</body>
</html></code>```

答:
You sent wrong function reference.
It should be like this.

```<code><button onClick={this.handler.bind(this)}>Add 1</button>
</code>```

or

```<code><button onClick={() => this.handler()}>Add 1</button>
</code>```

Body:
Hello guys, so I found interesting task about React, and I a little bit don't understand how to solve it

Task: Why this code is not working? Solve this.

Code:

class Test extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      count: 1
    }
  }
  handler() {
    this.setState({count: this.state.count++})
  }
  render() {
    console.log('render')
    return (

        <button onClick={this.handler}>Add 1</button>

{this.state.count}

    );
  }
}

ReactDOM.render(
  <Test />,
  document.getElementById("test"));

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

Body:
You sent wrong function reference.
It should be like this.

<button onClick={this.handler.bind(this)}>Add 1</button>

or

<button onClick={() => this.handler()}>Add 1</button>


问:
Opencv module is imported in conda and VS Code but Not IDLE & Libs aren't imported in VsCode and IDLE
The OpenCV module runs without errors in Vs code, Spyder
But it runs with errors in python IDEL And doesn't import Libs
When I open The terminal of all these editors
Vscode terminal doesn't import Libs
Python IDEL doesn't import libs
Anaconda Prompt imports Libs

So My Error is
What's the problem with python IDEL and VS code terminal?
And how can I solve this?

```<code>#VS CODE
import cv2
from os import path
video = cv2.VideoCapture(0)
xml_classifier = path.join(path.dirname(cv2.__file__),
                           "data", "haarcascade_frontalface_default.xml")
while True:
    grabbed, frame = video.read()
    frame = cv2.resize(frame, (800, 500))

    def detect_faces(frame):
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        face_calssifier = cv2.CascadeClassifier(xml_classifier)
        rects = face_calssifier.detectMultiScale(gray,
                                                 scaleFactor=1.15,
                                                 minNeighbors=5,
                                                 minSize=(30, 30))
        return rects

    def draw(frame, rects, title):  # , text):
        print("=" * 30)
        print("i found {} people.".format(len(rects)).title())
        print("=" * 30)

        for x, y, w, h in rects:
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

        if title:
            cv2.imshow(title, frame)
    draw(frame, detect_faces(frame), "Video")
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video.release()
cv2.destroyAllWindows()

### In Vs code terminal ---------------------------------------------------------------------

PS C:\Users\ASUS> & C:/Users/ASUS/Anaconda3/Anaconda/python.exe c:/Users/ASUS/Computer-Vision-Projects/FDVW.py
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674) SourceReaderCB::~SourceReaderCB terminating async callback
PS C:\Users\ASUS> python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'cv2'
>>> import flask
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'flask'
>>> import numpy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'numpy'
>>> import os
>>>
</code>```

```<code># In python Idle
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import cv2
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import cv2
ModuleNotFoundError: No module named 'cv2'
>>> import numpy
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    import numpy
ModuleNotFoundError: No module named 'numpy'
>>> import flask
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import flask
ModuleNotFoundError: No module named 'flask'
>>> import os
>>>
=== RESTART: C:\Users\ASUS\Computer-Vision-Projects\#01_face_detection.py ===
Traceback (most recent call last):
  File "C:\Users\ASUS\Computer-Vision-Projects\#01_face_detection.py", line 1, in <module>
    import cv2
ModuleNotFoundError: No module named 'cv2'
>>>
</code>```

But In Anaconda prompt it runs without errors and import libs And Spyder runs without errors

```<code>(base) C:\Windows\system32>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> import flask
>>> import numpy
>>> import os
</code>```

The Same error in opencv is be in flask, numpy and etc.
  The python path in Vs code settings:
  "python.pythonPath": "C:\Users\ASUS\Anaconda3\Anaconda\python",

My VSCode settings

```<code>    {

        "editor.fontSize": 22,
        "editor.rulers": [80],
        "editor.fontWeight": "500",
        "debug.console.fontSize": 16,
        "terminal.integrated.fontSize": 16,
        "terminal.integrated.fontWeight": "100",
        // "files.autoSaveDelay": 500,
        "files.autoSave": "onFocusChange",
        "workbench.iconTheme": "material-icon-theme",

        "terminal.integrated.shell.linux": "/usr/bin/zsh",
        // "terminal.integrated.inheritEnv": false,

        //? linux
        // "python.pythonPath": "/usr/bin/python3.8",

        //? py36
        "python.pythonPath": "C:\\Users\\ASUS\\Anaconda3\\Anaconda",

        "python.formatting.provider": "autopep8",
        "[python]": {
          "editor.defaultFormatter": "ms-python.python"
        },
        "workbench.colorCustomizations": {
          "terminal.foreground": "#f0a212",
          "terminal.background": "#161C28",
          // "terminal.background": "#232F34",
          "tab.activeBorder": "#02e039",
          // "activityBar.activeBackground":"#1684b3a9",
          "activityBar.activeBorder": "#02e039",
          // "list.inactiveSelectionBackground": "#86a9fb",
          "statusBar.background": "#333",
          "statusBar.foreground": "#fff",
          "statusBar.noFolderBackground": "#333",
          "statusBar.noFolderForeground": "#fff"
        },
        "gotoNextPreviousMember.symbolKinds": ["function"],
        "editor.formatOnSave": true,
        "editor.showFoldingControls": "mouseover",
        "python.jediEnabled": false,
        // "workbench.statusBar.feedback.visible": false,
        "editor.minimap.enabled": false,
        "workbench.settings.editor": "json",

        //!READ THIS ARTICLE TO CUSTOMIZE THE TERMINAL
        //? https://pascalnaber.wordpress.com/2019/10/05/have-a-great-looking-terminal-and-a-more-effective-shell-with-oh-my-zsh-on-wsl-2-using-windows/
        "terminal.integrated.fontFamily": "Source Code Pro Semibold",
        "terminal.integrated.cursorStyle": "line",
        "terminal.integrated.cursorBlinking": true,
        "workbench.startupEditor": "newUntitledFile",
        "git.autofetch": true,
        "workbench.list.openMode": "singleClick",
        "zenMode.hideLineNumbers": false,
        "zenMode.hideTabs": false,
        "workbench.activityBar.visible": true,
        "git.enableSmartCommit": true,
        "window.zoomLevel": -1,
        "editor.defaultFormatter": "ms-python.python",
        // "terminal.integrated.rendererType": "dom",
        "sync.autoUpload": true,
        "sync.forceUpload": true,
        "sync.gist": "13d7fc3f673defc7dc0cba7f7d3dd8a5",
        "workbench.colorTheme": "Newton (rainglow)",
        "kite.showWelcomeNotificationOnStartup": false,
        "extensions.ignoreRecommendations": false,
        "python.dataScience.sendSelectionToInteractiveWindow": true,
        "vsicons.dontShowNewVersionMessage": true,
        "editor.columnSelection": false,
        "dart.debugExternalLibraries": true,
        "dart.debugSdkLibraries": false,
        "dart.previewHotReloadOnSaveWatcher": true,
        "editor.multiCursorModifier": "alt",
        "editor.formatOnPaste": true,
        "[dart]": {
          "editor.tabSize": 4,
          "editor.insertSpaces": false,
          "editor.formatOnSave": true
        },
        "python.linting.enabled": true,
        "editor.tabSize": 4,

        //!############################################################

        "window.titleBarStyle": "custom",
        "window.enableMenuBarMnemonics": false,
        "window.customMenuBarAltFocus": false,
        //!############################################################
      }
</code>```

答:
I solve this error By open anaconda prompt and open your python path likecd C:\Program Files\Python36 And write python -m pip uninstall --user opencv-contrib-python if you have this error "No module named pip.main; 'pip' is a package and cannot be directly executed" write this python get-pip.pyif you don't have get-pip.py download it from https://bootstrap.pypa.io/get-pip.py Save it in your python path .
After All this run python -m pip install --user opencv-contrib-python. Make the same thing with numpy and flask. import these libs in Vs code Terminal, Anaconda prompt and python IDLE.

Body:
The OpenCV module runs without errors in Vs code, Spyder
But it runs with errors in python IDEL And doesn't import Libs
When I open The terminal of all these editors
Vscode terminal doesn't import Libs
Python IDEL doesn't import libs
Anaconda Prompt imports Libs

So My Error is
What's the problem with python IDEL and VS code terminal?
And how can I solve this?

#VS CODE
import cv2
from os import path
video = cv2.VideoCapture(0)
xml_classifier = path.join(path.dirname(cv2.__file__),
                           "data", "haarcascade_frontalface_default.xml")
while True:
    grabbed, frame = video.read()
    frame = cv2.resize(frame, (800, 500))

    def detect_faces(frame):
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        face_calssifier = cv2.CascadeClassifier(xml_classifier)
        rects = face_calssifier.detectMultiScale(gray,
                                                 scaleFactor=1.15,
                                                 minNeighbors=5,
                                                 minSize=(30, 30))
        return rects

    def draw(frame, rects, title):  # , text):
        print("=" * 30)
        print("i found {} people.".format(len(rects)).title())
        print("=" * 30)

        for x, y, w, h in rects:
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

        if title:
            cv2.imshow(title, frame)
    draw(frame, detect_faces(frame), "Video")
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video.release()
cv2.destroyAllWindows()

### In Vs code terminal ---------------------------------------------------------------------

PS C:\Users\ASUS> & C:/Users/ASUS/Anaconda3/Anaconda/python.exe c:/Users/ASUS/Computer-Vision-Projects/FDVW.py
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674) SourceReaderCB::~SourceReaderCB terminating async callback
PS C:\Users\ASUS> python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'cv2'
>>> import flask
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'flask'
>>> import numpy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'numpy'
>>> import os
>>>

# In python Idle
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import cv2
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import cv2
ModuleNotFoundError: No module named 'cv2'
>>> import numpy
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    import numpy
ModuleNotFoundError: No module named 'numpy'
>>> import flask
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import flask
ModuleNotFoundError: No module named 'flask'
>>> import os
>>>
=== RESTART: C:\Users\ASUS\Computer-Vision-Projects\#01_face_detection.py ===
Traceback (most recent call last):
  File "C:\Users\ASUS\Computer-Vision-Projects\#01_face_detection.py", line 1, in <module>
    import cv2
ModuleNotFoundError: No module named 'cv2'
>>>

But In Anaconda prompt it runs without errors and import libs And Spyder runs without errors

(base) C:\Windows\system32>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> import flask
>>> import numpy
>>> import os

The Same error in opencv is be in flask, numpy and etc.
  The python path in Vs code settings:
  "python.pythonPath": "C:\Users\ASUS\Anaconda3\Anaconda\python",

My VSCode settings

    {

        "editor.fontSize": 22,
        "editor.rulers": [80],
        "editor.fontWeight": "500",
        "debug.console.fontSize": 16,
        "terminal.integrated.fontSize": 16,
        "terminal.integrated.fontWeight": "100",
        // "files.autoSaveDelay": 500,
        "files.autoSave": "onFocusChange",
        "workbench.iconTheme": "material-icon-theme",

        "terminal.integrated.shell.linux": "/usr/bin/zsh",
        // "terminal.integrated.inheritEnv": false,

        //? linux
        // "python.pythonPath": "/usr/bin/python3.8",

        //? py36
        "python.pythonPath": "C:\\Users\\ASUS\\Anaconda3\\Anaconda",

        "python.formatting.provider": "autopep8",
        "[python]": {
          "editor.defaultFormatter": "ms-python.python"
        },
        "workbench.colorCustomizations": {
          "terminal.foreground": "#f0a212",
          "terminal.background": "#161C28",
          // "terminal.background": "#232F34",
          "tab.activeBorder": "#02e039",
          // "activityBar.activeBackground":"#1684b3a9",
          "activityBar.activeBorder": "#02e039",
          // "list.inactiveSelectionBackground": "#86a9fb",
          "statusBar.background": "#333",
          "statusBar.foreground": "#fff",
          "statusBar.noFolderBackground": "#333",
          "statusBar.noFolderForeground": "#fff"
        },
        "gotoNextPreviousMember.symbolKinds": ["function"],
        "editor.formatOnSave": true,
        "editor.showFoldingControls": "mouseover",
        "python.jediEnabled": false,
        // "workbench.statusBar.feedback.visible": false,
        "editor.minimap.enabled": false,
        "workbench.settings.editor": "json",

        //!READ THIS ARTICLE TO CUSTOMIZE THE TERMINAL
        //? https://pascalnaber.wordpress.com/2019/10/05/have-a-great-looking-terminal-and-a-more-effective-shell-with-oh-my-zsh-on-wsl-2-using-windows/
        "terminal.integrated.fontFamily": "Source Code Pro Semibold",
        "terminal.integrated.cursorStyle": "line",
        "terminal.integrated.cursorBlinking": true,
        "workbench.startupEditor": "newUntitledFile",
        "git.autofetch": true,
        "workbench.list.openMode": "singleClick",
        "zenMode.hideLineNumbers": false,
        "zenMode.hideTabs": false,
        "workbench.activityBar.visible": true,
        "git.enableSmartCommit": true,
        "window.zoomLevel": -1,
        "editor.defaultFormatter": "ms-python.python",
        // "terminal.integrated.rendererType": "dom",
        "sync.autoUpload": true,
        "sync.forceUpload": true,
        "sync.gist": "13d7fc3f673defc7dc0cba7f7d3dd8a5",
        "workbench.colorTheme": "Newton (rainglow)",
        "kite.showWelcomeNotificationOnStartup": false,
        "extensions.ignoreRecommendations": false,
        "python.dataScience.sendSelectionToInteractiveWindow": true,
        "vsicons.dontShowNewVersionMessage": true,
        "editor.columnSelection": false,
        "dart.debugExternalLibraries": true,
        "dart.debugSdkLibraries": false,
        "dart.previewHotReloadOnSaveWatcher": true,
        "editor.multiCursorModifier": "alt",
        "editor.formatOnPaste": true,
        "[dart]": {
          "editor.tabSize": 4,
          "editor.insertSpaces": false,
          "editor.formatOnSave": true
        },
        "python.linting.enabled": true,
        "editor.tabSize": 4,

        //!############################################################

        "window.titleBarStyle": "custom",
        "window.enableMenuBarMnemonics": false,
        "window.customMenuBarAltFocus": false,
        //!############################################################
      }


问:
Why does ViewPager need to specify height manually?
I have NestedScrollView containing CardView,TabLayout and ViewPager. ViewPager is not showing the contents on Tabs if i specify android:layout_height either match_parent or wrap_content (Only tab names are visible). It only works when i specify the value in dp

My XML Layout as below.

```<code><androidx.core.widget.NestedScrollView
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
                <TextView
                    android:layout_marginTop="10dp"
                    android:id="@+id/DescriptionTv"
                    android:textStyle="bold"
                    android:text="Post description"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>
            </LinearLayout>

        </androidx.cardview.widget.CardView>

                <com.google.android.material.tabs.TabLayout
                    app:tabGravity="fill"
                    android:id="@+id/TabLayout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                </com.google.android.material.tabs.TabLayout>

            <androidx.viewpager.widget.ViewPager
                android:id="@+id/Viewpager"
                android:layout_width="match_parent"
                android:layout_height="500dp"/>  // I want to avoid specifying values but not working
        </LinearLayout>
    </androidx.core.widget.NestedScrollView>
</code>```

How do i avoid specifying android:layout_height in numbers for ViewPager to match it to screen as Normal TabLayout? Please help

I have tried to add my TabLayout inside the ViewPager but not working (Both becomes invisible)

答:
You can use match_parent and have a View inside the ViewPager with size math_parent.

Like:

<ViewPager ...layout_height="match_parent">
   <View android:layout_width="match_parent"
         android:layout_height="match_parent" />
</ViewPager>

```

Body:
I have NestedScrollView containing CardView,TabLayout and ViewPager. ViewPager is not showing the contents on Tabs if i specify android:layout_height either match_parent or wrap_content (Only tab names are visible). It only works when i specify the value in dp

My XML Layout as below.

<androidx.core.widget.NestedScrollView
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
                <TextView
                    android:layout_marginTop="10dp"
                    android:id="@+id/DescriptionTv"
                    android:textStyle="bold"
                    android:text="Post description"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>
            </LinearLayout>

        </androidx.cardview.widget.CardView>

                <com.google.android.material.tabs.TabLayout
                    app:tabGravity="fill"
                    android:id="@+id/TabLayout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                </com.google.android.material.tabs.TabLayout>

            <androidx.viewpager.widget.ViewPager
                android:id="@+id/Viewpager"
                android:layout_width="match_parent"
                android:layout_height="500dp"/>  // I want to avoid specifying values but not working
        </LinearLayout>
    </androidx.core.widget.NestedScrollView>

How do i avoid specifying android:layout_height in numbers for ViewPager to match it to screen as Normal TabLayout? Please help

I have tried to add my TabLayout inside the ViewPager but not working (Both becomes invisible)


问:
Advantages of using Fat Jars over Containers
I wanna know the difference between the two and also which one is currently used more according to industry standards. I tried finding resources online but the content about Fat Jars is very less and also almost no contrast is shown between the two anywhere.</p>

答:
Depending on your needs, you can use either standalone fat jars or fat jars inside containers. Key point I'm making is there is no standoff between the two, in fact they are complimentary.

Fat jar is a primary way to wrap java application so it could be easily containerized.

Of course, you could use fat jars in standalone ways too.

Pros of containerization:

You can take advantage of unified tooling for containers. I.e., you set up docker and you can run any container - be it java with fat jar or node.js or anything else.

You can take advantage of various container orchestration systems (docker compose, docker swarm, kubernetes, etc) - meaning you use unified tooling for healthchecks, monitoring, rolling updates, etc.

You don't need to worry about things like JRE / JDK versions on your system.

When you may still want to use standalone:

When you have java-centric architecture and established processes around that and it would be costly to change from that to modern container orchestration.

When you are using java as primary scripting (or application) platform on your instance and simply don't want any overhead of containers.


答:
Assuming that your "datetime" column is always in the format t_{int} you can use STUFF to remove the first 2 characters, and then convert that value to an int. This allows you to order them numerically, rather than lexicographically. Then you can get the MIN and MAX with a gaps and islands solution and readd the t_ prefix:

WITH YourTable AS(
    SELECT *
    FROM (VALUES('t_1',4),
                ('t_3',5),
                ('t_4',5),
                ('t_5',5),
                ('t_6',7),
                ('t_7',7),
                ('t_8',7),
                ('t_9',4),
                ('t_10',4),
                ('t_11',4))V(date_time,toolid)),
CTE AS(
    SELECT YT.date_time,
           YT.toolid,
           V.time_int,
           ROW_NUMBER() OVER (ORDER BY V.time_int) -
           ROW_NUMBER() OVER (PARTITION BY YT.toolid ORDER BY V.time_int) AS Grp
    FROM YourTable YT
         CROSS APPLY(VALUES(TRY_CONVERT(int,STUFF(date_time,1,2,''))))V(time_int))
SELECT C.toolid,
       CONCAT('t_',MIN(C.time_int)) AS From_date_time,
       CONCAT('t_',MAX(C.time_int)) AS To_date_time
FROM CTE C
GROUP BY C.toolid,
         C.Grp;
```

<p><em>Edit: Untested, but based on the OP's completely changed sample data this is now just a simple gaps and island problem:</em></p>

<pre class="lang-sql prettyprint-override"><code>WITH CTE AS(
    SELECT YT.date_time,
           YT.toolid,
           ROW_NUMBER() OVER (ORDER BY YT.date_time) -
           ROW_NUMBER() OVER (PARTITION BY YT.toolid ORDER BY YT.date_time) AS Grp
    FROM dbo.YourTable YT)
SELECT C.toolid,
       MIN(C.date_time) AS From_date_time,
       MAX(C.date_time) AS To_date_time
FROM CTE C
GROUP BY C.toolid,
         C.Grp;
</code>```

Title: Group multiple time values per id as one time period and display each time period with SQL

Body:
Is there a way to solve the following problem in a SQL query?
Assume you have the following table in a Microsoft SQL server database:

date_time                         | tool_id
----------------------------------|-----------------
2020-02-18 12:00:00.0100000       | 4
2020-02-18 12:00:00.0200000       | 5
2020-02-18 12:00:00.0300000       | 5
2020-02-18 12:00:00.0400000       | 5
2020-02-18 12:00:00.0500000       | 7
2020-02-18 12:00:00.0600000       | 7
2020-02-18 12:00:00.0700000       | 7
2020-02-18 12:00:00.0800000       | 4
2020-02-18 12:00:00.0900000       | 4
2020-02-18 12:00:00.1000000       | 4

date_time is a datetime in chronological order and tool_id is an int corresponding to a certain tool which is used in a machine at that particular timestamp. The tools are used in the machine for a certain time period (e.g. tool 7 is used from '2020-02-18 12:00:00.0500000' to '2020-02-18 12:00:00.0700000').
My goal now is to eventually get a schedule for the used tools in the following format as result table:

tool_id | from_date_time                         | to_date_time
--------|----------------------------------------|-------------------------------
4       | 2020-02-18 12:00:00.0100000            | 2020-02-18 12:00:00.0100000
5       | 2020-02-18 12:00:00.0200000            | 2020-02-18 12:00:00.0400000
7       | 2020-02-18 12:00:00.0500000            | 2020-02-18 12:00:00.0700000
4       | 2020-02-18 12:00:00.0800000            | 2020-02-18 12:00:00.1000000

The result is supposed to be displayed in a plotly dash web app so it is supposed to be used in a Python context. Even if there is a solution for this just using SQL, might there be a better solution combining SQL and Python?

Body:
Assuming that your "datetime" column is always in the format t_{int} you can use STUFF to remove the first 2 characters, and then convert that value to an int. This allows you to order them numerically, rather than lexicographically. Then you can get the MIN and MAX with a gaps and islands solution and readd the t_ prefix:

WITH YourTable AS(
    SELECT *
    FROM (VALUES('t_1',4),
                ('t_3',5),
                ('t_4',5),
                ('t_5',5),
                ('t_6',7),
                ('t_7',7),
                ('t_8',7),
                ('t_9',4),
                ('t_10',4),
                ('t_11',4))V(date_time,toolid)),
CTE AS(
    SELECT YT.date_time,
           YT.toolid,
           V.time_int,
           ROW_NUMBER() OVER (ORDER BY V.time_int) -
           ROW_NUMBER() OVER (PARTITION BY YT.toolid ORDER BY V.time_int) AS Grp
    FROM YourTable YT
         CROSS APPLY(VALUES(TRY_CONVERT(int,STUFF(date_time,1,2,''))))V(time_int))
SELECT C.toolid,
       CONCAT('t_',MIN(C.time_int)) AS From_date_time,
       CONCAT('t_',MAX(C.time_int)) AS To_date_time
FROM CTE C
GROUP BY C.toolid,
         C.Grp;

Edit: Untested, but based on the OP's completely changed sample data this is now just a simple gaps and island problem:

WITH CTE AS(
    SELECT YT.date_time,
           YT.toolid,
           ROW_NUMBER() OVER (ORDER BY YT.date_time) -
           ROW_NUMBER() OVER (PARTITION BY YT.toolid ORDER BY YT.date_time) AS Grp
    FROM dbo.YourTable YT)
SELECT C.toolid,
       MIN(C.date_time) AS From_date_time,
       MAX(C.date_time) AS To_date_time
FROM CTE C
GROUP BY C.toolid,
         C.Grp;


问:
Create FlinkSQL UDF with generic return type
I would like to define function MAX_BY that takes value of type T and ordering parameter of type Number and returns max element from window according to ordering (of type T). I've tried

```<code>public class MaxBy<T> extends AggregateFunction<T, Tuple2<T, Number>> {

    @Override
    public T getValue(Tuple2<T, Number> tuple) {
        return tuple.f0;
    }

    @Override
    public Tuple2<T, Number> createAccumulator() {
        return Tuple2.of(null, 0L);
    }

    public void accumulate(Tuple2<T, Number> acc, T value, Number order) {
        if (order.doubleValue() > acc.f1.doubleValue()) {
            acc.f0 = value;
            acc.f1 = order;
        }
    }
}
</code>```

but I cannot register such function using TableEnvironment.registerFunction. Underneath Flink uses TypeInformation to match types within SQL query and with such definition it cannot determine types (at least that's what I suppose). I saw that it is possible to provide several accumulate functions but still - I think return type must be same for each overloaded method.

Built-in aggregation functions work similarly to what I want to achieve - MAX can take arbitrary column type and return the same type. That's why I suppose I should be able to do it as well.

答:
Unfortunately, Flink doesn't support aggregation functions with flexible return types. For the MAX function, the internal implementation defines the core logic independent of the the type and then creates an implementation for every supported type (see code).

Internally, MAX is then mapped to the right implementation, depending on the type.

I don't think that's possible if you define and register a function as user-defined aggregation function.

Body:
I would like to define function MAX_BY that takes value of type T and ordering parameter of type Number and returns max element from window according to ordering (of type T). I've tried

public class MaxBy<T> extends AggregateFunction<T, Tuple2<T, Number>> {

    @Override
    public T getValue(Tuple2<T, Number> tuple) {
        return tuple.f0;
    }

    @Override
    public Tuple2<T, Number> createAccumulator() {
        return Tuple2.of(null, 0L);
    }

    public void accumulate(Tuple2<T, Number> acc, T value, Number order) {
        if (order.doubleValue() > acc.f1.doubleValue()) {
            acc.f0 = value;
            acc.f1 = order;
        }
    }
}

but I cannot register such function using TableEnvironment.registerFunction. Underneath Flink uses TypeInformation to match types within SQL query and with such definition it cannot determine types (at least that's what I suppose). I saw that it is possible to provide several accumulate functions but still - I think return type must be same for each overloaded method.

Built-in aggregation functions work similarly to what I want to achieve - MAX can take arbitrary column type and return the same type. That's why I suppose I should be able to do it as well.


问:
Between-graph replication in tensorflow: sessions and variables
Question about between-graph replication in distributed Tensorflow, because I didn't get few moments from tutorials. As I understood the current model:

We have parameter server which we just launch in separate process and make server.join().
We have workers, each of them builds the similar computational graph which contains parameter nodes linked to parameter server (through tf.train.replica_device_setter) and calculation nodes placed on workers themselves.

What I didn't find:

How sessions are working in this model? Because in examples/tutorials it is hidden behind tf.train.Supervisor.
Do we have separate sessions on each worker or just one huge session that accumulate graphs from all the workers and parameter server?

How global variables are initialized on parameter server? I wonder that I can initialize them in one of the worker processes (choose it as a "master"), if I linked these parameters on the worker through tf.train.replica_device_setter. Is that correct?

In the following gist:

https://gist.github.com/yaroslavvb/ea1b1bae0a75c4aae593df7eca72d9ca

global variables initialized just in parameter server process and all the workers consider them initialized. How is that possible, given that they even work in different sessions? I could not replicate it in simpler example.

I have main session in core program where I perform training of the model. Part of training loop is collection of data, which in turn requires calculation on the tensorflow cluster. So I need to create this cluster, put on the parameter server current state of the trained model, then collect data from calculation and continue with training loop. How can I: 1) pass current trained model to the cluster? 2) Extract collected data from cluster and pass it to main program?

Thanks in advance!

EDIT:

To q.3:
It was answered previously (In tensorflow, is variable value the only context information a session stores?) that in distributed runtime variables are shared between sessions.
Does it mean that when I create session with some "target", then all the variables will be shared between those sessions that run on the same graph?

答:
I also stumbled upon these and very similar and related questions. I tried to clarify all of this in my overview of distributed TensorFlow. Maybe that is useful for some.

More specifically, let me try to answer your questions:

You say you do between-graph replication, i.e. you build a separate computation graph for every worker. This implies that you also have a separate session everywhere, because there would be no way to use that computation graph otherwise. The server (tf.distribute.Server) will not use the local computation graph. It will just execute things when remote sessions (clients) connect to it. The session has the graph. If there would be only a single session, there would also only be a single graph, and then you have in-graph replication.

If you share the variables (e.g. they live on a parameter server), it is enough if one of the workers does the initialization (e.g. the parameter server itself). Otherwise it depends on the specific distributed strategy and how you do the synchronization of the variables. E.g. a mirrored variables has separate copies on every replica, and you would need to make sure in some way that they are synchronized.

There is only a single copy of the variable in this case, which lives on the parameter server. All read and write on this variable would be a RPC call to the parameter server.

I'm not exactly sure what you mean by main program. You would have multiple instances of your program, one for each worker. But you likely will mark one of the worker as the chief worker, which has some further responsibilities like saving the checkpoint. But otherwise, all the workers are equal and do all the same thing (this is again for between-graph replication). How your gradient accumulation or parameter update looks like depends on your strategy (e.g. whether you do sync training or async training, etc.).


问:
Need to create a table in Splunk that is a nested table or has multiple columns
I have a working Splunk search that extracts data from an xml file within a logging statement. The search creates a table with 14 columns.  Below is the query that creates this table

```<code><sourcetype and other data>..| xmlkv  | rex max_match=0 "\<ns2\:numberCode\>(?P<location>[^\<]+)"| eval Segment1_Origin =  mvindex(location, 7), Segment1_Destination = mvindex(location, 8), Segment2_Origin = mvindex(location, 10), Segment2_Destination = mvindex(location, 11), Segment3_Origin = mvindex(location, 13), Segment3_Destination = mvindex(location, 14)  |  rex max_match=0 "\<carrier\>(?P<carrier>[^\<]+)" | eval Segment1_Carrier =  mvindex(carrier, 0), Segment2_Carrier = mvindex(carrier, 1), Segment3_Carrier = mvindex(carrier, 2) |  rex max_match=0 "\<billingMethod\>(?P<billingMethod>[^\<]+)" | eval Segment1_BillingMethod =  mvindex(billingMethod, 0), Segment2_BillingMethod = mvindex(billingMethod, 1), Segment3_BillingMethod = mvindex(billingMethod, 2) | table purchCostReference, eventType, Segment1_Carrier, Segment1_BillingMethod, Segment1_Origin, Segment1_Destination, Segment2_Carrier, Segment2_BillingMethod, Segment2_Origin, Segment2_Destination, Segment3_Carrier, Segment3_BillingMethod, Segment3_Origin, Segment3_Destination | sort purchCostReference, eventType
</code>```

The table looks like this (all columns not shown because of the size):

I would like the table to have the table nested by Segments in some way.

Or like this:

Is either one of these table designs possible in Splunk?

答:
This is how I created the second instance of a table.  Added a time field. Using these commands, I parsed the values needed in the xml</p>

```<code>sourcetype... |xmlkv | rex max_match=0 "\<purchasedCostTripSegment\>(?P<segment>[^\<]+)" |eval Segments =  mvrange(1,mvcount(mvindex(segment, 0, 2))+1,1) | rex max_match=0 "\<carrier\>(?P<Carriers>[^\<]+)" | rex max_match=0 "\<billingMethod\>(?P<BillingMethod>[^\<]+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<origin>\s*<ns2:numberCode>(?P<Origin>\d+)"  | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<destination>\s*<ns2:numberCode>(?P<Destination>\d+)" | eval Time =_time | convert timeformat="%m-%d-%Y %H:%M:%S" ctime(Time) | table purchCostReference, eventType, Time, Segments, Carriers, BillingMethod, Origin, Destination | sort - Time
</code>```

Body:
I have a working Splunk search that extracts data from an xml file within a logging statement. The search creates a table with 14 columns.  Below is the query that creates this table

<sourcetype and other data>..| xmlkv  | rex max_match=0 "\<ns2\:numberCode\>(?P<location>[^\<]+)"| eval Segment1_Origin =  mvindex(location, 7), Segment1_Destination = mvindex(location, 8), Segment2_Origin = mvindex(location, 10), Segment2_Destination = mvindex(location, 11), Segment3_Origin = mvindex(location, 13), Segment3_Destination = mvindex(location, 14)  |  rex max_match=0 "\<carrier\>(?P<carrier>[^\<]+)" | eval Segment1_Carrier =  mvindex(carrier, 0), Segment2_Carrier = mvindex(carrier, 1), Segment3_Carrier = mvindex(carrier, 2) |  rex max_match=0 "\<billingMethod\>(?P<billingMethod>[^\<]+)" | eval Segment1_BillingMethod =  mvindex(billingMethod, 0), Segment2_BillingMethod = mvindex(billingMethod, 1), Segment3_BillingMethod = mvindex(billingMethod, 2) | table purchCostReference, eventType, Segment1_Carrier, Segment1_BillingMethod, Segment1_Origin, Segment1_Destination, Segment2_Carrier, Segment2_BillingMethod, Segment2_Origin, Segment2_Destination, Segment3_Carrier, Segment3_BillingMethod, Segment3_Origin, Segment3_Destination | sort purchCostReference, eventType

The table looks like this (all columns not shown because of the size):

I would like the table to have the table nested by Segments in some way.

Or like this:

Is either one of these table designs possible in Splunk?

Body:
This is how I created the second instance of a table.  Added a time field. Using these commands, I parsed the values needed in the xml

sourcetype... |xmlkv | rex max_match=0 "\<purchasedCostTripSegment\>(?P<segment>[^\<]+)" |eval Segments =  mvrange(1,mvcount(mvindex(segment, 0, 2))+1,1) | rex max_match=0 "\<carrier\>(?P<Carriers>[^\<]+)" | rex max_match=0 "\<billingMethod\>(?P<BillingMethod>[^\<]+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<origin>\s*<ns2:numberCode>(?P<Origin>\d+)"  | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<destination>\s*<ns2:numberCode>(?P<Destination>\d+)" | eval Time =_time | convert timeformat="%m-%d-%Y %H:%M:%S" ctime(Time) | table purchCostReference, eventType, Time, Segments, Carriers, BillingMethod, Origin, Destination | sort - Time


问:
TestBed.OverrideProvider() doesn't work if TestBed.inject() or TestBed.get() (deprecated) has run before
Given the example spec test below

```<code>beforeEach(function () {
        TestBed.configureTestingModule({
            providers: [
                { provide: TranslateService, useClass: TranslateServiceMock },
                { provide: StoreService, useClass: StoreServiceMock },
                {
                    provide: GLOBAL_CONFIG_TOKEN,
                    useValue: { default: true }
                }
            ],
        });
        let config = TestBed.inject(GLOBAL_CONFIG_TOKEN);
});

it('should override provider otherwise what is the point? :)', () => {
  let config = TestBed.overrideProvider(GLOBAL_CONFIG_TOKEN, { useValue: { default: false, random: 'damn' } });
expect(config).toEqual({default: false, random: 'damn'});
});
</code>```

the thing is that test failed because default is always true and random is not a property of config. This means that config still has the default value during the configure of Testing Module and the provider hasn't been overridden.

Any idea why? Is overrideProvider method just a helper that updates the moduleRef object initially passed at configureTestingModule?

答:
As it seems the fact that TestBed.inject is running before TestBed.overrideProvider causes overrideProvider to not have any effect. The overrideProvider function should be used before TestBed.inject(). Apparently it seems that is just a helper method after configurTestingModule() function run. So a solution to the example above would be:

```<code>beforeEach(function () {
        TestBed.configureTestingModule({
            providers: [
                { provide: TranslateService, useClass: TranslateServiceMock },
                { provide: StoreService, useClass: StoreServiceMock },
                {
                    provide: GLOBAL_CONFIG_TOKEN,
                    useValue: { default: true }
                }
            ],
        });
});

it('should override provider otherwise what is the point? :)', () => {
  TestBed.overrideProvider(GLOBAL_CONFIG_TOKEN, { useValue: { default: false, random: 'damn' } });

  let config = TestBed.inject(GLOBAL_CONFIG_TOKEN);
  expect(config).toEqual({default: false, random: 'damn'});
});
</code>```

Body:
Given the example spec test below

beforeEach(function () {
        TestBed.configureTestingModule({
            providers: [
                { provide: TranslateService, useClass: TranslateServiceMock },
                { provide: StoreService, useClass: StoreServiceMock },
                {
                    provide: GLOBAL_CONFIG_TOKEN,
                    useValue: { default: true }
                }
            ],
        });
        let config = TestBed.inject(GLOBAL_CONFIG_TOKEN);
});

it('should override provider otherwise what is the point? :)', () => {
  let config = TestBed.overrideProvider(GLOBAL_CONFIG_TOKEN, { useValue: { default: false, random: 'damn' } });
expect(config).toEqual({default: false, random: 'damn'});
});

the thing is that test failed because default is always true and random is not a property of config. This means that config still has the default value during the configure of Testing Module and the provider hasn't been overridden.

Any idea why? Is overrideProvider method just a helper that updates the moduleRef object initially passed at configureTestingModule?

Body:
As it seems the fact that TestBed.inject is running before TestBed.overrideProvider causes overrideProvider to not have any effect. The overrideProvider function should be used before TestBed.inject(). Apparently it seems that is just a helper method after configurTestingModule() function run. So a solution to the example above would be:

beforeEach(function () {
        TestBed.configureTestingModule({
            providers: [
                { provide: TranslateService, useClass: TranslateServiceMock },
                { provide: StoreService, useClass: StoreServiceMock },
                {
                    provide: GLOBAL_CONFIG_TOKEN,
                    useValue: { default: true }
                }
            ],
        });
});

it('should override provider otherwise what is the point? :)', () => {
  TestBed.overrideProvider(GLOBAL_CONFIG_TOKEN, { useValue: { default: false, random: 'damn' } });

  let config = TestBed.inject(GLOBAL_CONFIG_TOKEN);
  expect(config).toEqual({default: false, random: 'damn'});
});


问:
Error "TypeError: FirstForm() missing 1 required positional argument: 'request'"
Good day!

When working views.py constantly you get this kind of error:

TypeError: FirstForm() missing 1 required positional argument: 'request'

Views.py

```<code>def FirstForm(request):
if request.method == 'GET':
    form = FirstForm()
else:
    form = FirstForm(request.POST)
    if form.is_valid():
        name = form.cleaned_data['name']
        email = form.cleaned_data['email']
        date = form.cleaned_data['date']
        number = form.cleaned_data['number']
        try:
            send_mail(email, (name, date, number), settings.EMAIL_HOST_USER, ['daribian@list.ru'])
        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        return redirect('success')
return render(request, 'index.html', {'form': form})

def successView(request):
    return HttpResponse('Success!')
</code>```

Сan you tell me what the problem is?

答:
Your view has the same name as the form, hence if you call FirstForm, you will call the view, not the form.

Therefore it is better to name the view, different, for example first_view:

```<code>def <b>first_view</b>(request):
    if request.method == 'GET':
        form = FirstForm()
    else:
        form = FirstForm(request.POST, request.FILES)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            date = form.cleaned_data['date']
            number = form.cleaned_data['number']
            try:
                send_mail(email, (name, date, number), settings.EMAIL_HOST_USER, ['daribian@list.ru'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('success')
    return render(request, 'index.html', {'form': form})</code>```

Note: according to PEP-8, you should write the functions in snake_case, not camelCase, so success_view, instead of <s>successView</s>.

Body:
Good day!

When working views.py constantly you get this kind of error:

TypeError: FirstForm() missing 1 required positional argument: 'request'

Views.py

def FirstForm(request):
if request.method == 'GET':
    form = FirstForm()
else:
    form = FirstForm(request.POST)
    if form.is_valid():
        name = form.cleaned_data['name']
        email = form.cleaned_data['email']
        date = form.cleaned_data['date']
        number = form.cleaned_data['number']
        try:
            send_mail(email, (name, date, number), settings.EMAIL_HOST_USER, ['daribian@list.ru'])
        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        return redirect('success')
return render(request, 'index.html', {'form': form})

def successView(request):
    return HttpResponse('Success!')

Сan you tell me what the problem is?

Body:
Your view has the same name as the form, hence if you call FirstForm, you will call the view, not the form.

Therefore it is better to name the view, different, for example first_view:

def first_view(request):
    if request.method == 'GET':
        form = FirstForm()
    else:
        form = FirstForm(request.POST, request.FILES)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            date = form.cleaned_data['date']
            number = form.cleaned_data['number']
            try:
                send_mail(email, (name, date, number), settings.EMAIL_HOST_USER, ['daribian@list.ru'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('success')
    return render(request, 'index.html', {'form': form})

Note: according to PEP-8, you should write the functions in snake_case, not camelCase, so success_view, instead of <s>successView</s>.


问:
webmatrix c# and razor
I wanted to give a try to razor but there are not many tutorials on web;  I've already tried this one, so better ask here. Can anyone please tell me how razor works? I mean are there any code behind pages or controls? and what is done in code behind pages if they exist? Also, how can I reference code behind pages? Generally speaking, what type of code fits in the cshtml page, I mean, for the sake of a clear design how should be the structure etc etc. finally, any good tutorial is highly appreciated. Thanks! </p>

<p>Please note: I'm not using visual studio, I'm using webmatrix. </p>

答:
I can't speak a whole lot to WebMatrix.  But...are you familiar with ASP.NET MVC?  Given what you're asking, it sounds like maybe you aren't.  I would start with learning the basics of MVC first.  I learned on the NerdDinner example

http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx

To answer your question more directly, no there are no code behind files (though a code behind is technically possibly through some hackery).  The paradigm is completely different from web forms.  Essentially you have classes called controllers that accumulate the data for a page.  The "data" for the page is referred to as a model and closely resembles what your problem domain is.  Models are classes intended to represent objects in the system (customers, users, orders, widgets, etc...).  The controller passes models to the view.  The view renders the page.  So the code you'd expect to find in each of these is:

Model: object representing the problem domain like Blog, Person, User, etc...
Controller: Gets data from database using services that return Model objects (or calls into entity framework, NHibernate, whatever)
View: displays that using cshtml, aspx or whatever the ViewRenderer is

So, in your view (cshtml), you're really just going to have straightforward programming for displaying UI elements and performing UI logic. You'll have mostly HTML and then some bits scattered around to pull data from the model and display it like

```<code><td>@Model.Name</td>
<td>@Model.Description</td>
</code>```

Hope that helps

EDIT: After reading a bit more, sounds like WebMatrix is kind of a RAD tool for web apps.  Looking at the tutorial that you posted, looks like they're showing you go treat it like classic ASP and put everything right on the cshtml page.  This is an option.  I wouldn't recommend it though.  It'll make life tough, but I'm unsure if there are better ways in WebMatrix.

Title: webmatrix c# and razor

Body:
I wanted to give a try to razor but there are not many tutorials on web;  I've already tried this one, so better ask here. Can anyone please tell me how razor works? I mean are there any code behind pages or controls? and what is done in code behind pages if they exist? Also, how can I reference code behind pages? Generally speaking, what type of code fits in the cshtml page, I mean, for the sake of a clear design how should be the structure etc etc. finally, any good tutorial is highly appreciated. Thanks!

Please note: I'm not using visual studio, I'm using webmatrix.

Body:
I can't speak a whole lot to WebMatrix.  But...are you familiar with ASP.NET MVC?  Given what you're asking, it sounds like maybe you aren't.  I would start with learning the basics of MVC first.  I learned on the NerdDinner example

http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx

To answer your question more directly, no there are no code behind files (though a code behind is technically possibly through some hackery).  The paradigm is completely different from web forms.  Essentially you have classes called controllers that accumulate the data for a page.  The "data" for the page is referred to as a model and closely resembles what your problem domain is.  Models are classes intended to represent objects in the system (customers, users, orders, widgets, etc...).  The controller passes models to the view.  The view renders the page.  So the code you'd expect to find in each of these is:

Model: object representing the problem domain like Blog, Person, User, etc...
Controller: Gets data from database using services that return Model objects (or calls into entity framework, NHibernate, whatever)
View: displays that using cshtml, aspx or whatever the ViewRenderer is

So, in your view (cshtml), you're really just going to have straightforward programming for displaying UI elements and performing UI logic. You'll have mostly HTML and then some bits scattered around to pull data from the model and display it like

<td>@Model.Name</td>
<td>@Model.Description</td>

Hope that helps

EDIT: After reading a bit more, sounds like WebMatrix is kind of a RAD tool for web apps.  Looking at the tutorial that you posted, looks like they're showing you go treat it like classic ASP and put everything right on the cshtml page.  This is an option.  I wouldn't recommend it though.  It'll make life tough, but I'm unsure if there are better ways in WebMatrix.


问:
How to check if an specific Grakn instance already exists before trying to insert it into the KG?
Let's assume that a Grakn KG contains entities of type 'product' and that they are uniquely identified by the key 'id_prod'. As I understand it, the attempt to insert an instance of product with a repeated id_prod will generate an error.

Assuming that the insertion is being done through a console script, how could the previous existence of the instance be checked with graql during the insertion? And via the python client, are there any special recommendations or patterns to follow?

答:
Your assertion is correct. At present Graql doesn't have a PUT behaviour built-in that would check for existence and insert only if not present. This is a feature that should be included in the future (I work at Grakn).

Instead, you have broadly two options:

You match for concepts by their keys. If there are no results then you insert them. Then you can match insert for the keyed concepts to add relations to them etc.

You first ensure that you've inserted all of the keyed concepts into the KB (may not be possible). You then make the match insert queries directly, matching for the keyed concepts, with no need for checking the keys exist


问:
Header html errors
I have been creating the menu for the main page of my website. First I made it in a drawing I wanted to pass it to html with figma it did not go well.

Now I want to create it pure code. But it doesn't turn out the way I want either.
link:
https://codepen.io/R3DW0LF/pen/ExVqYbo?

```<code>        <div class="page-header">
            <div class="page-content-wrap">
                <div class="page-header-content">
                    <div class="dyna_logo img kfuwufhd">
                        <span>Dynamo</span>
                    </div>
                    <div class="search__box">
                        <div class="srch_inpt" style="display: block;">
                            <input class="search_input efh473e" type="text" placeholder="Search">
                        </div>
                    </div>
                    <div class="inpts-tpbar">
                        <div class="tpbar login-top jfhejdyd" style="display: inline-flex;">
                            <div class="control-input login">
                                <a href="/signin">Hello</a>
                            </div>
                            <div class="control-input register">
                                <a href="/singup">Hello 2</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>`
</code>```

I want something like this:
Design of what i want

答:
You can use flex to separate your page-content, you can try with justify-content:

```<code>.separate{
display: flex;
justify-content: space-between;
}
</code>```

Title: Header html errors

Body:
I have been creating the menu for the main page of my website. First I made it in a drawing I wanted to pass it to html with figma it did not go well.

Now I want to create it pure code. But it doesn't turn out the way I want either.
link:
https://codepen.io/R3DW0LF/pen/ExVqYbo?

                        Dynamo

                            <input class="search_input efh473e" type="text" placeholder="Search">

                                Hello

                                Hello 2

`

I want something like this:
Design of what i want

Body:
You can use flex to separate your page-content, you can try with justify-content:

.separate{
display: flex;
justify-content: space-between;
}


问:
Performance across folds in random forest
I'm trying to get sensitivity, specificity, ppv, and npv (or a confusion matrix can also work) across all of my folds when I train a random forest using caret, but specifically if I change the threshold. I know normally with the default threshold you can use model$resample to give you the metrics for all of the folds but how do I do this at a new threshold?

Here is my model:

```<code>ctrl <- trainControl(method = "cv",
                 number = 5,
                 savePredictions = TRUE,
                 summaryFunction = TwoClassSummary,
                 classProbs = TRUE)

model <- train(outcome ~ ., data=df,
  trControl = ctrl, method= "rf", preProc=c("center","scale"), metric="ROC",importance=TRUE)
</code>```

Here is how to generate a confusion matrix at a new threshold:

```<code> label <- ifelse(model$pred$affirmatory > 0.75, 'affirmatory', 'negatory')
 confusionMatrix(label, model$pred$obs, positive = 'affirmatory')
</code>```

But this only gives me the average values across all the folds. How do I see the metrics for all folds?

答:
I figured out the answer to my question and wanted to post it in case it benefits anyone in the future.

Here's a reproducible example using iris. Say you're interested in the performance in each fold where the threshold=0.2.

```<code>set.seed(3949)
attach(iris)
#create a binary outcome on Sepal.Length
iris <- iris %>% mutate(Sepal.Length=ifelse(Sepal.Length>5.0,"aff","neg"))

practice <- train(Sepal.Length ~ ., data = iris, trControl = ctrl, method=
"rf", preProc=c("center","scale"), metric="ROC",importance=TRUE, tuneGrid =
data.frame(mtry = 2)) #must specify a single mtry

#examine outcome at every fold
print(practice$pred)
</code>```

You can see that the default threshold is 0.5. If threshold>0.5, then pred will be aff and vice versa. If I want threshold=0.2, then I will get aff when threshold>0.2. So now you just need to create a new column with a new prediction based off of that threshold and then you can generate a confusion matrix from that.

```<code>f1 <- practice$pred %>% filter(Resample=="Fold1")
f1 <- f1 %>% mutate(new_pred=ifelse(aff>0.2,"positive","negative"))
f1 %>% group_by(obs, new_pred) %>% summarize(n=n())
</code>```

Repeat the above for each of the folds. The last line gives you a broken down confusion matrix. Using that, you can manually figure out sen/spec/ppv/npv. If you want to confirm if this method actually works, you can generate the confusion matrix for the entire model evaluated at a new threshold using:

```<code>label <- ifelse(practice$pred$aff > 0.2, 'aff', 'neg')
confusionMatrix(label, practice$pred$obs, positive = 'aff')
</code>```

Count the individual combinations in each fold and it will add up to the total in the above confusion matrix. Also if you take any performance metric, say specificity, across each folds and average it, you'll also get the specificity from the above line. Just another check to make sure you're doing everything right if you needed confirmation.

Body:
I'm trying to get sensitivity, specificity, ppv, and npv (or a confusion matrix can also work) across all of my folds when I train a random forest using caret, but specifically if I change the threshold. I know normally with the default threshold you can use model$resample to give you the metrics for all of the folds but how do I do this at a new threshold?

Here is my model:

ctrl <- trainControl(method = "cv",
                 number = 5,
                 savePredictions = TRUE,
                 summaryFunction = TwoClassSummary,
                 classProbs = TRUE)

model <- train(outcome ~ ., data=df,
  trControl = ctrl, method= "rf", preProc=c("center","scale"), metric="ROC",importance=TRUE)

Here is how to generate a confusion matrix at a new threshold:

 label <- ifelse(model$pred$affirmatory > 0.75, 'affirmatory', 'negatory')
 confusionMatrix(label, model$pred$obs, positive = 'affirmatory')

But this only gives me the average values across all the folds. How do I see the metrics for all folds?

Body:
I figured out the answer to my question and wanted to post it in case it benefits anyone in the future.

Here's a reproducible example using iris. Say you're interested in the performance in each fold where the threshold=0.2.

set.seed(3949)
attach(iris)
#create a binary outcome on Sepal.Length
iris <- iris %>% mutate(Sepal.Length=ifelse(Sepal.Length>5.0,"aff","neg"))

practice <- train(Sepal.Length ~ ., data = iris, trControl = ctrl, method=
"rf", preProc=c("center","scale"), metric="ROC",importance=TRUE, tuneGrid =
data.frame(mtry = 2)) #must specify a single mtry

#examine outcome at every fold
print(practice$pred)

You can see that the default threshold is 0.5. If threshold>0.5, then pred will be aff and vice versa. If I want threshold=0.2, then I will get aff when threshold>0.2. So now you just need to create a new column with a new prediction based off of that threshold and then you can generate a confusion matrix from that.

f1 <- practice$pred %>% filter(Resample=="Fold1")
f1 <- f1 %>% mutate(new_pred=ifelse(aff>0.2,"positive","negative"))
f1 %>% group_by(obs, new_pred) %>% summarize(n=n())

Repeat the above for each of the folds. The last line gives you a broken down confusion matrix. Using that, you can manually figure out sen/spec/ppv/npv. If you want to confirm if this method actually works, you can generate the confusion matrix for the entire model evaluated at a new threshold using:

label <- ifelse(practice$pred$aff > 0.2, 'aff', 'neg')
confusionMatrix(label, practice$pred$obs, positive = 'aff')

Count the individual combinations in each fold and it will add up to the total in the above confusion matrix. Also if you take any performance metric, say specificity, across each folds and average it, you'll also get the specificity from the above line. Just another check to make sure you're doing everything right if you needed confirmation.


问:
Which one is better for efficient free text search, Hibernate Search or Lucene?
We are developing a web application using Spring MVC, Spring and Hibernate.

We need to add efficient free text search capabilities to our applications. For this we are thinking of using either Hibernate Search (it uses Lucene under the hood) or directly lucene.

What is the best option for us as we are already using hibernate in our application? What are the pros and cons of one over the other?

Thanks.

答:
disclaimer: I'm one of the developers of Hibernate Search.

The goal of the project is not to compete with Lucene nor Solr, but to facilitate as much as possible integration with Hibernate applications, to avoid having to maintain the two worlds in sync and duplicate all mapping and CRUD operations.

While we provide some common helpers and a nice encapsulation, Hibernate Search can also hand you over a direct reference to the Lucene API, so in case you find yourself needing to use the "raw" Lucene API you will never be stuck. Also for writing to the index Hibernate Search provides a common pattern which will solve most of known requirements, but in case you have very non-standard requirements you can get full control of the written Documents.

Solr is a good alternative, but as it is a separate server you have to interact with it via REST APIs which is quite different, with it's pros and cons. Having a second service to manage is not always wanted, and of course the remote invocations will never be as efficient as direct references to Lucene and to all it's internal filters and caches.
Not all functionality of Lucene can be exposed via a remote API, and if you need to do some "low level" operation, if this is not implemented in Solr you won't be able to do it (without patching Solr). Still Solr is very cute, especially when you want to share the index with other non-Java applications, and so we might add a Solr backend for Hibernate Search to eventually keep a Solr server in synch (especially if there's interest for it, and possibly some help).

Finally, the Lucene API is really hard core stuff. We spend a lot of effort to make the best use of it to provide top performance while exposing a stable API to people using Hibernate Search, basically until now all releases have been backwards compatible to provide a "drop-in" performance boost to use latest greatest tricks from Lucene - which actually changes API quite often; these changes are always exciting, but be prepared to maintain that in your application if you don't use a proper abstraction.


问:
Group row id for all unique rows in SQL Server
I would like to generate group row id for each unique rows. Any hint or suggestion would be helpful. I am using SQL Server 2017.

答:
For your Case ROW NUMBER Function and use PARTITION by Column Names

```<code>SELECT *,ROW_NUMBER () OVER (Partition By COL1 ORDER BY COL1)  from @T
</code>```

Body:
For your Case ROW NUMBER Function and use PARTITION by Column Names

SELECT *,ROW_NUMBER () OVER (Partition By COL1 ORDER BY COL1)  from @T


问:
javascript map and join on an array
```<code>d = [
    ["a", "Adobe"]
    ["b", "Boston"]
    ["c", "Cars"]
    ["d", "Dominos"]
    ["e", "Microsoft"]
]
const asString = d.map(function(x){
        x[0],'=',x[1]
    }).join('&');
  console.log(asString);
</code>```

I'm trying to generate a query string from the above array, but seem to be getting only &&&&. The original solution used Template Literals and was like this:

```<code>const asString = d
      .map(x => `${encodeURIComponent(x[0])}=${encodeURIComponent(x[1])}`)
      .join('&');
  console.log(asString);
</code>```

This works fine, but I don't want to use Template Literals.

The end result is a querystring like this: a=Adobe&b=Boston&c=Cars&d=Dominos&e=Microsoft

答:
Just using map and join:

const d = [
    ["a", "Adobe"],
    ["b", "Boston"],
    ["c", "Cars"],
    ["d", "Dominos"],
    ["e", "Microsoft"]
]
let queryString = d.map(x=>x.map(encodeURIComponent).join("=")).join("&")
console.log(queryString)

// Without arrow function
queryString = d.map(function(x){
  return x.map(encodeURIComponent).join("=")
}).join("&");

console.log(queryString)```

Title: javascript map and join on an array

Body:
d = [
    ["a", "Adobe"]
    ["b", "Boston"]
    ["c", "Cars"]
    ["d", "Dominos"]
    ["e", "Microsoft"]
]
const asString = d.map(function(x){
        x[0],'=',x[1]
    }).join('&');
  console.log(asString);

I'm trying to generate a query string from the above array, but seem to be getting only &&&&. The original solution used Template Literals and was like this:

const asString = d
      .map(x => `${encodeURIComponent(x[0])}=${encodeURIComponent(x[1])}`)
      .join('&');
  console.log(asString);

This works fine, but I don't want to use Template Literals.

The end result is a querystring like this: a=Adobe&b=Boston&c=Cars&d=Dominos&e=Microsoft