问:
How to define callbacks in separate files? (plotly dash)

Background

Dash web applications have a dash application instance, usually named app, and initiated like this:

app = dash.Dash(__name__)
```

<p>Then, callbacks are added to the application using a <code>callback</code> decorator:</p>

```@app.callback(...)
def my_function(...):
    # do stuff.
```

<p>In most of the tutorials you find, the callbacks are defined with all of the application layout in the <code>app.py</code>. This of course is just the MWE way of doing things. In a real application, separating code to modules and packages would greatly improve readability and maintainability, but naively separating the callbacks to and layouts just results into circular imports. </p>

<h3>Question</h3>

<p>What would be the correct way to separate callbacks and layouts from the <code>app.py</code> in a single page app? </p>

<h2>MWE</h2>

<p>Here is a minimal (non-)working example with the problem</p>

<h3>File structure</h3>

```.
├── my_dash_app
│   ├── app.py
│   └── views
│       ├── first_view.py
│       └── __init__.py
└── setup.py
```

<h3>setup.py</h3>

```import setuptools

setuptools.setup(
    name='dash-minimal-realworld',
    version='1.0.0',
    install_requires=['dash>=1.12.0'],
    packages=setuptools.find_packages(),
)
```

<h3>app.py</h3>

```import dash

from my_dash_app.views.first_view import make_layout

app = dash.Dash(__name__)
app.layout = make_layout()

if __name__ == '__main__':
    app.run_server(debug=True)
```

<h3>first_view.py</h3>

<pre class="lang-py prettyprint-override"><code>from dash.dependencies import Input, Output

import dash_core_components as dcc
import dash_html_components as html

from my_dash_app.app import app

def make_layout():
    return html.Div([
        dcc.Input(id='my-id', value='initial value', type='text'),
        html.Div(id='my-div')
    ])

@app.callback(Output(component_id='my-div', component_property='children'),
              [Input(component_id='my-id', component_property='value')])
def update_output_div(input_value):
    return 'You\'ve entered "{}"'.format(input_value)

</code>```

Running python ./my_dash_app/app.py results into circular dependency:

```<code>ImportError: cannot import name 'make_layout' from 'my_dash_app.views.first_view' (c:\tmp\dash_minimal_realworld\my_dash_app\views\first_view.py)
</code>```

答:
I don't think (but I might be wrong) that there's a correct way of doing it per se, but what you could do it have a central module (maindash.py) around your startup code app = dash.Dash(__name__), and have different callbacks simply import app from my_dash_app.maindash. This would set up the callbacks in their own separate modules but re-use that one central module for the app instance.

It's easiest to show an overview of it like this:

app.py being the main script called to start everything up. maindash.py is in charge of creating the main app instance. first_view.py is where the decorators are defined to set up all the callbacks.

Here's the result:

```<code>.
├── my_dash_app
│   ├── app.py
│   ├── maindash.py
│   └── views
│       ├── first_view.py
│       └── __init__.py
└── setup.py
</code>```

Since imports are re-used in Python, there's no real harm in doing from my_dash_app.maindash import app several times from different other modules, such as event handlers and the main script. They'll share the same import instance - thus re-using the dash.Dash() instance as well.

Just make sure you import the central module before setting up the handlers, and you should be good to go.

Here's the code snippets separated for testing:

app.py

from my_dash_app.maindash import app
from my_dash_app.views.first_view import make_layout

if __name__ == '__main__':
    app.layout = make_layout()
    app.run_server(debug=True)
```

<h2>maindash.py</h2>

<pre class="lang-py prettyprint-override"><code>import dash
app = dash.Dash(__name__)
</code>```

first_view.py

from my_dash_app.maindash import app
from dash.dependencies import Input, Output

import dash_core_components as dcc
import dash_html_components as html

def make_layout():
    return html.Div([
        dcc.Input(id='my-id', value='initial value', type='text'),
        html.Div(id='my-div')
    ])

@app.callback(Output(component_id='my-div', component_property='children'),
              [Input(component_id='my-id', component_property='value')])
def update_output_div(input_value):
    return 'You\'ve entered "{}"'.format(input_value)
```

Body:
Background

Dash web applications have a dash application instance, usually named app, and initiated like this:

app = dash.Dash(__name__)

Then, callbacks are added to the application using a callback decorator:

@app.callback(...)
def my_function(...):
    # do stuff.

In most of the tutorials you find, the callbacks are defined with all of the application layout in the app.py. This of course is just the MWE way of doing things. In a real application, separating code to modules and packages would greatly improve readability and maintainability, but naively separating the callbacks to and layouts just results into circular imports.

Question

What would be the correct way to separate callbacks and layouts from the app.py in a single page app?

MWE

Here is a minimal (non-)working example with the problem

File structure

.
├── my_dash_app
│   ├── app.py
│   └── views
│       ├── first_view.py
│       └── __init__.py
└── setup.py

setup.py

import setuptools

setuptools.setup(
    name='dash-minimal-realworld',
    version='1.0.0',
    install_requires=['dash>=1.12.0'],
    packages=setuptools.find_packages(),
)

app.py

import dash

from my_dash_app.views.first_view import make_layout

app = dash.Dash(__name__)
app.layout = make_layout()

if __name__ == '__main__':
    app.run_server(debug=True)

first_view.py

from dash.dependencies import Input, Output

import dash_core_components as dcc
import dash_html_components as html

from my_dash_app.app import app

def make_layout():
    return html.Div([
        dcc.Input(id='my-id', value='initial value', type='text'),
        html.Div(id='my-div')
    ])

@app.callback(Output(component_id='my-div', component_property='children'),
              [Input(component_id='my-id', component_property='value')])
def update_output_div(input_value):
    return 'You\'ve entered "{}"'.format(input_value)

Running python ./my_dash_app/app.py results into circular dependency:

ImportError: cannot import name 'make_layout' from 'my_dash_app.views.first_view' (c:\tmp\dash_minimal_realworld\my_dash_app\views\first_view.py)

Body:
I don't think (but I might be wrong) that there's a correct way of doing it per se, but what you could do it have a central module (maindash.py) around your startup code app = dash.Dash(__name__), and have different callbacks simply import app from my_dash_app.maindash. This would set up the callbacks in their own separate modules but re-use that one central module for the app instance.

It's easiest to show an overview of it like this:

app.py being the main script called to start everything up. maindash.py is in charge of creating the main app instance. first_view.py is where the decorators are defined to set up all the callbacks.

Here's the result:

.
├── my_dash_app
│   ├── app.py
│   ├── maindash.py
│   └── views
│       ├── first_view.py
│       └── __init__.py
└── setup.py

Since imports are re-used in Python, there's no real harm in doing from my_dash_app.maindash import app several times from different other modules, such as event handlers and the main script. They'll share the same import instance - thus re-using the dash.Dash() instance as well.

Just make sure you import the central module before setting up the handlers, and you should be good to go.

Here's the code snippets separated for testing:

app.py

from my_dash_app.maindash import app
from my_dash_app.views.first_view import make_layout

if __name__ == '__main__':
    app.layout = make_layout()
    app.run_server(debug=True)

maindash.py

import dash
app = dash.Dash(__name__)

first_view.py

from my_dash_app.maindash import app
from dash.dependencies import Input, Output

import dash_core_components as dcc
import dash_html_components as html

def make_layout():
    return html.Div([
        dcc.Input(id='my-id', value='initial value', type='text'),
        html.Div(id='my-div')
    ])

@app.callback(Output(component_id='my-div', component_property='children'),
              [Input(component_id='my-id', component_property='value')])
def update_output_div(input_value):
    return 'You\'ve entered "{}"'.format(input_value)


来源: stackexchange

问:
Unlimited 6 sided dice roller
Need help with a JavaScript assignment from School but don't know how I should do it and was hoping for some tips?

We're supposed to create a 6 sided dice roller program and the user will have the option to choose between how many dices should be rolled, min 1 and max 5 dices.

The sum of the amount of dices used should always be displayed on the page. But if a number 6 is thrown, then this should make the program disregard it to the sum and instead throw two new dices, there should be an error message displaying this when it happens.

When all the dices are thrown the total sum of all the dices should be displayed and how many times you threw the dices.

I've managed to create this so far but I'm not sure how I should do regarding the number 6 or even if I'm on the right path here?

JS

```<code>function rollDice() {
  var numDice = document.getElementById("diceNum").value;
  var container = document.getElementById("dieContainer");

  container.innerHTML = "";

  for (var i = 0; i < numDice; i++) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
  };

  var x, text;
  x = document.getElementById("diceNum").value;

  if (isNaN(x) || x < 1 || x > 5) {
    window.alert('Input not valid');
    document.getElementById("dieContainer").style.display = "none";
  } else {
    document.getElementById("dieContainer").style.display = "block";
  }
};
</code>```

EDIT
I updated it to this now

```<code>let diceThrows = numDice;
let sum = 0;
while(diceThrows > 0) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    if(diceRoll == 6) {
        diceThrows += 2;
        console.log("You got a 6 och two new dices were thrown");
        document.getElementById("msg").innerHTML = "You got a 6 och two new dices were thrown";
    } else {
        sum += diceRoll;
        console.log(sum);
        document.getElementById("msg").innerHTML = "Result: " + sum;
    }
    container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
    diceThrows -= 1;
}
</code>```

I managed to display the results, but wondering now if there is a way display the results without them getting reset every time you use the function?

答:
Replace loop for by loop while:

```<code>let diceThrows = 6;
let sum = 0;
while(diceThrows > 0) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    if(diceRoll == 6) {
        diceThrows += 2;
    } else {
        sum += diceRoll;
    }
    container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
    diceThrows -= 1;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Unlimited 6 sided dice roller

Body:
Need help with a JavaScript assignment from School but don't know how I should do it and was hoping for some tips?

We're supposed to create a 6 sided dice roller program and the user will have the option to choose between how many dices should be rolled, min 1 and max 5 dices.

The sum of the amount of dices used should always be displayed on the page. But if a number 6 is thrown, then this should make the program disregard it to the sum and instead throw two new dices, there should be an error message displaying this when it happens.

When all the dices are thrown the total sum of all the dices should be displayed and how many times you threw the dices.

I've managed to create this so far but I'm not sure how I should do regarding the number 6 or even if I'm on the right path here?

JS

function rollDice() {
  var numDice = document.getElementById("diceNum").value;
  var container = document.getElementById("dieContainer");

  container.innerHTML = "";

  for (var i = 0; i < numDice; i++) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    container.innerHTML += '
' + diceRoll + '
';
  };

  var x, text;
  x = document.getElementById("diceNum").value;

  if (isNaN(x) || x < 1 || x > 5) {
    window.alert('Input not valid');
    document.getElementById("dieContainer").style.display = "none";
  } else {
    document.getElementById("dieContainer").style.display = "block";
  }
};

EDIT
I updated it to this now

let diceThrows = numDice;
let sum = 0;
while(diceThrows > 0) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    if(diceRoll == 6) {
        diceThrows += 2;
        console.log("You got a 6 och two new dices were thrown");
        document.getElementById("msg").innerHTML = "You got a 6 och two new dices were thrown";
    } else {
        sum += diceRoll;
        console.log(sum);
        document.getElementById("msg").innerHTML = "Result: " + sum;
    }
    container.innerHTML += '
' + diceRoll + '
';
    diceThrows -= 1;
}

I managed to display the results, but wondering now if there is a way display the results without them getting reset every time you use the function?

Body:
Replace loop for by loop while:

let diceThrows = 6;
let sum = 0;
while(diceThrows > 0) {
    var diceRoll = Math.floor(Math.random() * 6) + 1;
    if(diceRoll == 6) {
        diceThrows += 2;
    } else {
        sum += diceRoll;
    }
    container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
    diceThrows -= 1;
}


问:
issues with Oozie and Sqoop Export
I am trying to do an Sqoop export, the sqoop command works just fine in the local Servers, however, when I try to use the same command as an Oozie action, I am getting the following error, any help would be appreciated.

```<code><<< Invocation of Main class completed <<<

Failing Oozie Launcher, Main class [org.apache.oozie.action.hadoop.SqoopMain], main() threw exception, org.apache.hadoop.hive.ql.io.AcidUtils.isTablePropertyTransactional(Ljava/util/Map;)Z
java.lang.NoSuchMethodError: org.apache.hadoop.hive.ql.io.AcidUtils.isTablePropertyTransactional(Ljava/util/Map;)Z
        at org.apache.hive.hcatalog.mapreduce.FosterStorageHandler.configureInputJobProperties(FosterStorageHandler.java:134)
        at org.apache.hive.hcatalog.common.HCatUtil.getInputJobProperties(HCatUtil.java:458)
        at org.apache.hive.hcatalog.mapreduce.InitializeInput.extractPartInfo(InitializeInput.java:161)
        at org.apache.hive.hcatalog.mapreduce.InitializeInput.getInputJobInfo(InitializeInput.java:137)
        at org.apache.hive.hcatalog.mapreduce.InitializeInput.setInput(InitializeInput.java:88)
        at org.apache.hive.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:95)
        at org.apache.hive.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:51)
        at org.apache.sqoop.mapreduce.hcat.SqoopHCatUtilities.configureHCat(SqoopHCatUtilities.java:349)
        at org.apache.sqoop.mapreduce.ExportJobBase.runExport(ExportJobBase.java:433)
        at org.apache.sqoop.manager.SQLServerManager.exportTable(SQLServerManager.java:192)
        at org.apache.sqoop.tool.ExportTool.exportTable(ExportTool.java:81)
        at org.apache.sqoop.tool.ExportTool.run(ExportTool.java:100)
        at org.apache.sqoop.Sqoop.run(Sqoop.java:147)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:76)
        at org.apache.sqoop.Sqoop.runSqoop(Sqoop.java:183)
        at org.apache.sqoop.Sqoop.runTool(Sqoop.java:225)
        at org.apache.sqoop.Sqoop.runTool(Sqoop.java:234)
        at org.apache.sqoop.Sqoop.main(Sqoop.java:243)
        at org.apache.oozie.action.hadoop.SqoopMain.runSqoopJob(SqoopMain.java:197)
        at org.apache.oozie.action.hadoop.SqoopMain.run(SqoopMain.java:179)
        at org.apache.oozie.action.hadoop.LauncherMain.run(LauncherMain.java:58)
        at org.apache.oozie.action.hadoop.SqoopMain.main(SqoopMain.java:48)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.oozie.action.hadoop.LauncherMapper.map(LauncherMapper.java:240)
        at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:54)
        at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:453)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:343)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:170)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:422)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1869)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:164)

Oozie Launcher failed, finishing Hadoop job gracefully

Oozie Launcher, uploading action data to HDFS sequence file: hdfs://EAP-DR/user/sps_hpe_ibproetl/oozie-oozi/0005868-200326034412660-oozie-oozi-W/sqoop_2--sqoop/action-data.seq
7378 [main] INFO  org.apache.hadoop.io.compress.zlib.ZlibFactory  - Successfully loaded & initialized native-zlib library
7379 [main] INFO  org.apache.hadoop.io.compress.CodecPool  - Got brand-new compressor [.deflate]
Successfully reset security manager from org.apache.oozie.action.hadoop.LauncherSecurityManager@4440750 to null
</code>```

Oozie Launcher ends

答:
When you run sqoop command from local it uses jars from /usr/lib/sqoop/lib.
And when you use oozie sqoop action it uses jars from hdfs:///user/oozie/share/lib/lib_*/sqoop/

Now looking at your error, you either are

Missing org.apache.hadoop.hive.ql.io.AcidUtils on the classpath

Have the wrong version of org.apache.hadoop.hive.ql.io.AcidUtils on the classpath

Have multiple versions of org.apache.hadoop.hive.ql.io.AcidUtils on the classpath

Title: issues with Oozie and Sqoop Export

Body:
I am trying to do an Sqoop export, the sqoop command works just fine in the local Servers, however, when I try to use the same command as an Oozie action, I am getting the following error, any help would be appreciated.

<<< Invocation of Main class completed <<<

Failing Oozie Launcher, Main class [org.apache.oozie.action.hadoop.SqoopMain], main() threw exception, org.apache.hadoop.hive.ql.io.AcidUtils.isTablePropertyTransactional(Ljava/util/Map;)Z
java.lang.NoSuchMethodError: org.apache.hadoop.hive.ql.io.AcidUtils.isTablePropertyTransactional(Ljava/util/Map;)Z
        at org.apache.hive.hcatalog.mapreduce.FosterStorageHandler.configureInputJobProperties(FosterStorageHandler.java:134)
        at org.apache.hive.hcatalog.common.HCatUtil.getInputJobProperties(HCatUtil.java:458)
        at org.apache.hive.hcatalog.mapreduce.InitializeInput.extractPartInfo(InitializeInput.java:161)
        at org.apache.hive.hcatalog.mapreduce.InitializeInput.getInputJobInfo(InitializeInput.java:137)
        at org.apache.hive.hcatalog.mapreduce.InitializeInput.setInput(InitializeInput.java:88)
        at org.apache.hive.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:95)
        at org.apache.hive.hcatalog.mapreduce.HCatInputFormat.setInput(HCatInputFormat.java:51)
        at org.apache.sqoop.mapreduce.hcat.SqoopHCatUtilities.configureHCat(SqoopHCatUtilities.java:349)
        at org.apache.sqoop.mapreduce.ExportJobBase.runExport(ExportJobBase.java:433)
        at org.apache.sqoop.manager.SQLServerManager.exportTable(SQLServerManager.java:192)
        at org.apache.sqoop.tool.ExportTool.exportTable(ExportTool.java:81)
        at org.apache.sqoop.tool.ExportTool.run(ExportTool.java:100)
        at org.apache.sqoop.Sqoop.run(Sqoop.java:147)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:76)
        at org.apache.sqoop.Sqoop.runSqoop(Sqoop.java:183)
        at org.apache.sqoop.Sqoop.runTool(Sqoop.java:225)
        at org.apache.sqoop.Sqoop.runTool(Sqoop.java:234)
        at org.apache.sqoop.Sqoop.main(Sqoop.java:243)
        at org.apache.oozie.action.hadoop.SqoopMain.runSqoopJob(SqoopMain.java:197)
        at org.apache.oozie.action.hadoop.SqoopMain.run(SqoopMain.java:179)
        at org.apache.oozie.action.hadoop.LauncherMain.run(LauncherMain.java:58)
        at org.apache.oozie.action.hadoop.SqoopMain.main(SqoopMain.java:48)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.oozie.action.hadoop.LauncherMapper.map(LauncherMapper.java:240)
        at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:54)
        at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:453)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:343)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:170)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:422)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1869)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:164)

Oozie Launcher failed, finishing Hadoop job gracefully

Oozie Launcher, uploading action data to HDFS sequence file: hdfs://EAP-DR/user/sps_hpe_ibproetl/oozie-oozi/0005868-200326034412660-oozie-oozi-W/sqoop_2--sqoop/action-data.seq
7378 [main] INFO  org.apache.hadoop.io.compress.zlib.ZlibFactory  - Successfully loaded & initialized native-zlib library
7379 [main] INFO  org.apache.hadoop.io.compress.CodecPool  - Got brand-new compressor [.deflate]
Successfully reset security manager from org.apache.oozie.action.hadoop.LauncherSecurityManager@4440750 to null

Oozie Launcher ends


问:
Chrome filter out SameSite:None secure cookie
We have web application with an iFrame, which needs a cookie to access our server.  We have set this cookie with SameSite=None;Secure value, but the Chrome browser still filter out this cookie.

Filtered out cookie list:

The third cookie in this picture is filtered out.  I thought cookies with "SameSite=None;Secure" should be send with request.  What did I miss?

答:
Check https://samesite-sandbox.glitch.me to see if your browser is enforcing the new defaults. If it's all green ✔, then it is. If there is any red or orange ✘ then something is affecting how cookies are set.

Check you do not have the setting enabled to block third-party cookies, e.g. go to chrome://settings/content/cookies and ensure "Block third-party cookies" is off.

Extensions may also affect cookies. Try testing in an incognito window or a fresh Chrome profile with no extensions installed.


问:
Set ANDROID_HOME environment variable in mac
I am new in developing native app using Salesforce SDK. I tried to create android project from command line using forcedroid tool but there is problem in setting environment variable named ANDROID_HOME.

But i don't know how to set this variable.

I am attaching screenshot to describe my problem correctly.

答:
If you are setting up the ANDROID_HOME environment variable on macOS Catalina, .bash_profile is no longer Apple's default shell, and it won't persist your path variables. Use .zprofile instead and follow the environment setup instructions in react-native documentation or others. .bash_profile will keep creating new file which won't make the path permanent or persist on closing the terminal on your system path.

To create a new path just do this in macOS Big Sur:

sudo touch ~/.zshrc

sudo nano ~/.zshrc

export all the path

crtl + x and save

source ~/.zshrc

Check with echo $PATH

ContentLicense: CC BY-SA 3.0


问:
Maximum mark in Subject with Staff name
Write a query to display list of staff name, subject name handled, maximum mark scored in that subject. Give an alias to the maximum mark as max_mark. Sort the result based on maximum mark in descending.

This is the schema diagram.

This is the code I have tried.

select distinct
       staff_name,
       subject_name,
       max(value) over (partition by sb.staff_id) as max_mark
from   subject sb
       inner join staff st
       on st.staff_id=sb.staff_id
       inner join mark m
       on m.subject_id=sb.subject_id
order by max_mark desc;
```

I was abled to pass one testcase but I could not abled to pass second testcase and I don't know what second testcase is and also I am not getting what I have done wrong in my above code.Is there any way of getting solution for this problem.

答:
You can use window functions:

```<code>select staff_name, subject_name, max_mark
from (select st.staff_name, su.subject_name, ma.value as max_mark,
             row_number() over (partition by st.staff_name order by ma.value desc) as seqnum
      from subject su join
           staff st
           on st.staff_id = sb.staff_id join
           mark ma
           on ma.subject_id = su.subject_id
     ) s
order by max_mark desc;
</code>```

You can also use your method (select distinct with window functions) . . . but you have to deal with subject_name:

```<code>select distinct staff_name,
       first_value(subject_name) over (partition by sb.staff_id order by value desc) as subject_name
       max(value) over (partition by sb.staff_id) as max_mark
from   subject sb
       inner join staff st
       on st.staff_id=sb.staff_id
       inner join mark m
       on m.subject_id=sb.subject_id
order by max_mark desc;
</code>```

Title: Maximum mark in Subject with Staff name

Body:
Write a query to display list of staff name, subject name handled, maximum mark scored in that subject. Give an alias to the maximum mark as max_mark. Sort the result based on maximum mark in descending.

This is the schema diagram.

This is the code I have tried.

select distinct
       staff_name,
       subject_name,
       max(value) over (partition by sb.staff_id) as max_mark
from   subject sb
       inner join staff st
       on st.staff_id=sb.staff_id
       inner join mark m
       on m.subject_id=sb.subject_id
order by max_mark desc;

I was abled to pass one testcase but I could not abled to pass second testcase and I don't know what second testcase is and also I am not getting what I have done wrong in my above code.Is there any way of getting solution for this problem.

Body:
You can use window functions:

select staff_name, subject_name, max_mark
from (select st.staff_name, su.subject_name, ma.value as max_mark,
             row_number() over (partition by st.staff_name order by ma.value desc) as seqnum
      from subject su join
           staff st
           on st.staff_id = sb.staff_id join
           mark ma
           on ma.subject_id = su.subject_id
     ) s
order by max_mark desc;

You can also use your method (select distinct with window functions) . . . but you have to deal with subject_name:

select distinct staff_name,
       first_value(subject_name) over (partition by sb.staff_id order by value desc) as subject_name
       max(value) over (partition by sb.staff_id) as max_mark
from   subject sb
       inner join staff st
       on st.staff_id=sb.staff_id
       inner join mark m
       on m.subject_id=sb.subject_id
order by max_mark desc;


问:
Detect click on the currently active tab. ( Angular material tab )
I have a mat-tab group with different tabs. I want to detect click on the active tab header.

Eg. I have 2 tabs-  a company tab and a users tab and inside each tab there are 2 views - a list view view and a detailed view. Initially I want to load the list and on clicking on an item, want to go to the corresponding item's detailed view. But If I click on the tab header again I want to goto the list view again.

There are events like (selectedTabChange) which detects if tab is changed but since I am inside the same tab, it is not getting emitted. Any help.?

```<code><mat-tab-group class="theme-specific-tabs account-page-tabs" [(selectedIndex)]="selectedTab"  (selectedIndexChange)="accountTabOnIndexChange($event)">
</code>```

答:
Update answer of G. Tranter for Angular 8 and my case (sometimes click get into inner element):</p>

```<code><mat-tab-group (selectedIndexChange)="onTabChange($event)" (click)="tabClick($event)">
  <mat-tab label="Tab 1">Content 1</mat-tab>
  <mat-tab label="Tab 2">Content 2</mat-tab>
</mat-tab-group>

onTabChange(event: MatTabChangeEvent) {
    setTimeout(() => {
        this.selectedTabIndex = event.index;
    });
}

tabClick(event: MouseEvent) {
    let el = event.target as Element;
    let index: number;

    if (el.classList.contains("mat-tab-label")) {
        index = +el.id.substring(el.id.length - 1);
    }
    const ppEl = el.parentElement.parentElement
    if (ppEl.classList.contains("mat-tab-label")) {
        index = +ppEl.id.substring(ppEl.id.length - 1);
    }
    if (index === this.selectedTabIndex) {
        console.log("click on selected");
    }

}
</code>```

Body:
I have a mat-tab group with different tabs. I want to detect click on the active tab header.

Eg. I have 2 tabs-  a company tab and a users tab and inside each tab there are 2 views - a list view view and a detailed view. Initially I want to load the list and on clicking on an item, want to go to the corresponding item's detailed view. But If I click on the tab header again I want to goto the list view again.

There are events like (selectedTabChange) which detects if tab is changed but since I am inside the same tab, it is not getting emitted. Any help.?

<mat-tab-group class="theme-specific-tabs account-page-tabs" [(selectedIndex)]="selectedTab"  (selectedIndexChange)="accountTabOnIndexChange($event)">

Body:
Update answer of G. Tranter for Angular 8 and my case (sometimes click get into inner element):

<mat-tab-group (selectedIndexChange)="onTabChange($event)" (click)="tabClick($event)">
  <mat-tab label="Tab 1">Content 1</mat-tab>
  <mat-tab label="Tab 2">Content 2</mat-tab>
</mat-tab-group>

onTabChange(event: MatTabChangeEvent) {
    setTimeout(() => {
        this.selectedTabIndex = event.index;
    });
}

tabClick(event: MouseEvent) {
    let el = event.target as Element;
    let index: number;

    if (el.classList.contains("mat-tab-label")) {
        index = +el.id.substring(el.id.length - 1);
    }
    const ppEl = el.parentElement.parentElement
    if (ppEl.classList.contains("mat-tab-label")) {
        index = +ppEl.id.substring(ppEl.id.length - 1);
    }
    if (index === this.selectedTabIndex) {
        console.log("click on selected");
    }

}


问:
Determining binary/text file type in Java?
Namely, how would you tell an archive (jar/rar/etc.) file from a textual (xml/txt, encoding-independent) one?</p>

答: You could try the DROID tool.</p>

OwnerDisplayName: gsmd

Body: You could try the DROID tool.

OwnerDisplayName: Fabian Steeg

ContentLicense: CC BY-SA 2.5


问:
How do I fix my XSLT to correctly translate XML to HTML as expected?
I am using XSLT to translate XML to HTML.

The XML is:

```<code><PARA>
    1050
    <EMPH STYLE="min_max">
        <EMPH HL="LOW">-50</EMPH>
        <EMPH HL="HIGH">+50</EMPH>
    </EMPH>
     min
    <EMPH BOLD="0" HL="HIGH" ITAL="0" SMALLCAPS="0">-1</EMPH>
</PARA>
</code>```

How I do correctly render the output as:

1050 -50 +50 min-1

Currently I am getting 1050  min -50 +50 -1

My XSLT is:

```<code><xsl:template match="PARA">
    <xsl:value-of select="text()"/>
    <xsl:choose>
        <xsl:when test="EMPH">
            <xsl:apply-templates select="EMPH"/>
        </xsl:when>
    </xsl:choose>
</xsl:template>

<xsl:template match="EMPH">
    <xsl:choose>
        <xsl:when test="@BOLD=1"><b><xsl:value-of select="."/></b></xsl:when>
        <xsl:when test="@HL='HIGH'"><sup><xsl:value-of select="."/></sup></xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="."/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</code>```

答:
I found that this works:

```<code><xsl:template match="PARA">
    <xsl:apply-templates/>
</xsl:template>

<xsl:template match="EMPH">
    <xsl:choose>
        <xsl:when test="@BOLD=1"><b><xsl:value-of select="text()"/></b></xsl:when>
        <xsl:when test="@HL='HIGH'"><sup><xsl:value-of select="text()"/></sup></xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="."/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</code>```

I would like to know if there is a better way to handle the multiple attributes of the EMPH element than <xsl:choose>, because this way I have to handle all combinations as unique <xsl:when> checks.

For example, I have to check for "bold", "superscript" and "bold and superscript" as three different clauses.

Body:
I am using XSLT to translate XML to HTML.

The XML is:

<PARA>
    1050
    <EMPH STYLE="min_max">
        <EMPH HL="LOW">-50</EMPH>
        <EMPH HL="HIGH">+50</EMPH>
    </EMPH>
     min
    <EMPH BOLD="0" HL="HIGH" ITAL="0" SMALLCAPS="0">-1</EMPH>
</PARA>

How I do correctly render the output as:

1050 -50 +50 min-1

Currently I am getting 1050  min -50 +50 -1

My XSLT is:

<xsl:template match="PARA">
    <xsl:value-of select="text()"/>
    <xsl:choose>
        <xsl:when test="EMPH">
            <xsl:apply-templates select="EMPH"/>
        </xsl:when>
    </xsl:choose>
</xsl:template>

<xsl:template match="EMPH">
    <xsl:choose>
        <xsl:when test="@BOLD=1"><xsl:value-of select="."/></xsl:when>
        <xsl:when test="@HL='HIGH'"><xsl:value-of select="."/></xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="."/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

Body:
I found that this works:

<xsl:template match="PARA">
    <xsl:apply-templates/>
</xsl:template>

<xsl:template match="EMPH">
    <xsl:choose>
        <xsl:when test="@BOLD=1"><b><xsl:value-of select="text()"/></b></xsl:when>
        <xsl:when test="@HL='HIGH'"><sup><xsl:value-of select="text()"/></sup></xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="."/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

I would like to know if there is a better way to handle the multiple attributes of the EMPH element than <xsl:choose>, because this way I have to handle all combinations as unique <xsl:when> checks.

For example, I have to check for "bold", "superscript" and "bold and superscript" as three different clauses.


问:
How can I use SSH remotes with GitHub Desktop?
I am using GitHub Desktop on Windows 10. I initially cloned a repo using its HTTPS URL, but now our organisation have advised that we must use the SSH URL instead. So I have changed this over.

I have also copied the contents of my public SSH key (id_rsa.pub) in to my GitHub account. My SSH key is protected by a passphrase.

Now when I try to do to a sync in GitHub Desktop I get the following error:

In Git Bash it works fine (it asks me for my passphrase before each pull/push though). Any idea what I need to do to make this work?

答:
As more recently seen in "Permission failure cloning in Git in Windows", try and launch GitHub Desktop after:

(warning: read comments first)

```<code>git config --global core.sshCommand "'C:\Windows\System32\OpenSSH\ssh.exe'"
</code>```

That will ensure GitHub Desktop to use the right OpenSSH ssh.exe, instead of an internal one, as seen in desktop/desktop issue 5641.

If Git bash does not work properly after that, you can either:

revert the configuration:

```<code>git config --global --unset core.sshCommand
</code>```

or use the Git for Windows SSH

```<code>git config --global core.sshCommand "'C:\Program Files\Git\usr\bin\ssh.exe'"
</code>```

If C:\Program Files\Git\usr\bin\ is already in your %PATH%, you don't even need that configuration: the ssh.exe from Git For Windows would be the one selected by default.

Body:
As more recently seen in "Permission failure cloning in Git in Windows", try and launch GitHub Desktop after:

(warning: read comments first)

git config --global core.sshCommand "'C:\Windows\System32\OpenSSH\ssh.exe'"

That will ensure GitHub Desktop to use the right OpenSSH ssh.exe, instead of an internal one, as seen in desktop/desktop issue 5641.

If Git bash does not work properly after that, you can either:

revert the configuration:

git config --global --unset core.sshCommand

or use the Git for Windows SSH

git config --global core.sshCommand "'C:\Program Files\Git\usr\bin\ssh.exe'"

If C:\Program Files\Git\usr\bin\ is already in your %PATH%, you don't even need that configuration: the ssh.exe from Git For Windows would be the one selected by default.


问:
How to use point column type in Ecto using PostgreSQL
I can see that Postgrex lib supports postgreSQL's point type but I can't figure out how I can use it in model. I can specify point type for column in migration but when I specify it in the model like this:

```<code>schema "something" do
  field :position, :point
end
</code>```

I get ** (ArgumentError) invalid or unknown type :point for field :position. Anything special I should do to make it work?

答:
The geo library has moved all Ecto-related code to a separate library (see related pull request here).

To use the Ecto.Type implementation of PostgreSQL point datatype, use the geo_postgis library.

Body:
I can see that Postgrex lib supports postgreSQL's point type but I can't figure out how I can use it in model. I can specify point type for column in migration but when I specify it in the model like this:

schema "something" do
  field :position, :point
end

I get ** (ArgumentError) invalid or unknown type :point for field :position. Anything special I should do to make it work?


问:
How to post a form data with array to an API with Joi array validation
I created a Hapi API which only allows multipart/form-data because I need to pass an image stream and one of the payloads is required as an array, so I use Joi.array to validate it.

```<code>  payload: {
    parse: true,
    maxBytes: 20971520,
    output: "stream",
    timeout: 300000,
    multipart: true,
  },
  validate: {
    payload: Joi.object({
      thumbnail: Joi.any().optional().meta({ swaggerType: "file" }),
      tags: Joi.array()
    }),
  }
</code>```

In Front End side, I try to append FormData by stringify it as below:

```<code>  const formData = new FormData();

  formData.append("tags", JSON.stringify(values[val]);
</code>```

But, it still showing ""tags" must be an array" error message.
Is there any other way to pass an array into a form data?

答:
I've had the exact same issue. I'm using express, but I suppose you will find the answer helpful in Hapi as well.

You cannot directly pass the tags input to Joi validation, because it is a string representation of an array. You can first parse it -

```<code>let parsedTags = [];
if (tags) {
  parsedTags = JSON.parse(tags);
}
</code>```

(this logic can be wrapped inside a try-catch to catch any parsing issue)

Then, pass parsedTags into the validation function (keeping the key as 'tags').

I don't know of any other way to do this, and this solution worked for me.

Body:
I created a Hapi API which only allows multipart/form-data because I need to pass an image stream and one of the payloads is required as an array, so I use Joi.array to validate it.

  payload: {
    parse: true,
    maxBytes: 20971520,
    output: "stream",
    timeout: 300000,
    multipart: true,
  },
  validate: {
    payload: Joi.object({
      thumbnail: Joi.any().optional().meta({ swaggerType: "file" }),
      tags: Joi.array()
    }),
  }

In Front End side, I try to append FormData by stringify it as below:

  const formData = new FormData();

  formData.append("tags", JSON.stringify(values[val]);

But, it still showing ""tags" must be an array" error message.
Is there any other way to pass an array into a form data?

Body:
I've had the exact same issue. I'm using express, but I suppose you will find the answer helpful in Hapi as well.

You cannot directly pass the tags input to Joi validation, because it is a string representation of an array. You can first parse it -

let parsedTags = [];
if (tags) {
  parsedTags = JSON.parse(tags);
}

(this logic can be wrapped inside a try-catch to catch any parsing issue)

Then, pass parsedTags into the validation function (keeping the key as 'tags').

I don't know of any other way to do this, and this solution worked for me.


问:
Interop: Cannot call get_Range, and cannot use two-dimensional object array returned by Range().Value2?
Trying to replace Cells(RowIndex,ColumnIndex).Value() calls by row-wise references for performance, I permanently fail at referencing the result.

Starting with Excel Interop - Efficiency and performance, which contains the tip to use get_range, i.e.

```<code>//get values
object[,] objectArray = shtName.get_Range("A1:Z100").Value2;
iFace = Convert.ToInt32(objectArray[1,1]);

//set values
object[,] objectArray = new object[3,1] {{"A"}{"B"}{"C"}};
rngName.Value2 = objectArray;
</code>```

I figured I cannot use get_Range since that method is not callable for me, says VB at run-time (not a visible member).

Now I came up with stuff like:

```<code>Dim Values As Object(,)
Values = Sheet.Range(Sheet.Cells(RowIndex, 1), Sheet.Cells(2, 17)).Value2
For Index As Integer = 0 To 16
  MsgBox(Values(0, Index))
Next
</code>```

However, referencing Values with two dimension indices always returns an "index was outside the bounds of the array" exception. Inspecting the array with the debugger shows a nice 2-dimensional array which should has 17 elements on the second dimension, so Value (0,0) should indeed be a valid reference -- but it isn't:

The debugger lets me inspect Value, I can also drill down to Value(0,0) and see the correct value, but re-evaluating just that element, i.e. inspecting "Value (0,0)" returns above message.

How can I reference what my Value2 call returns?

答:
Perhaps something like this?  Note that if you want the array to have the column as the first element you'd use change the line below as noted:</p>

```<code>Imports Microsoft.Office.Interop
    Module Module1
        Sub main()
            Dim appExcel As Excel.Application
            Dim wb As Excel.Workbook
            Dim ws As Excel.Worksheet
            Dim values As Object

            appExcel = GetObject(, "Excel.Application")
            wb = appExcel.Workbooks(1)
            ws = wb.Worksheets(1)
            With ws
                values = .Range(.Cells(1, 1), .Cells(2, 5)).Value2
                'if column is first element use appExcel.Worksheetfunction.Transpose(.Range(.Cells(1, 1), .Cells(2, 5)).Value2)
                For i As Int32 = LBound(values, 1) To UBound(values, 1)
                    For j As Int32 = LBound(values, 2) To UBound(values, 2)
                        System.Windows.Forms.MessageBox.Show(values(i, j))
                    Next j
                Next
            End With
        End Sub
    End Module
</code>```

Body:
Trying to replace Cells(RowIndex,ColumnIndex).Value() calls by row-wise references for performance, I permanently fail at referencing the result.

Starting with Excel Interop - Efficiency and performance, which contains the tip to use get_range, i.e.

//get values
object[,] objectArray = shtName.get_Range("A1:Z100").Value2;
iFace = Convert.ToInt32(objectArray[1,1]);

//set values
object[,] objectArray = new object[3,1] {{"A"}{"B"}{"C"}};
rngName.Value2 = objectArray;

I figured I cannot use get_Range since that method is not callable for me, says VB at run-time (not a visible member).

Now I came up with stuff like:

Dim Values As Object(,)
Values = Sheet.Range(Sheet.Cells(RowIndex, 1), Sheet.Cells(2, 17)).Value2
For Index As Integer = 0 To 16
  MsgBox(Values(0, Index))
Next

However, referencing Values with two dimension indices always returns an "index was outside the bounds of the array" exception. Inspecting the array with the debugger shows a nice 2-dimensional array which should has 17 elements on the second dimension, so Value (0,0) should indeed be a valid reference -- but it isn't:

The debugger lets me inspect Value, I can also drill down to Value(0,0) and see the correct value, but re-evaluating just that element, i.e. inspecting "Value (0,0)" returns above message.

How can I reference what my Value2 call returns?

Body:
Perhaps something like this?  Note that if you want the array to have the column as the first element you'd use change the line below as noted:

Imports Microsoft.Office.Interop
    Module Module1
        Sub main()
            Dim appExcel As Excel.Application
            Dim wb As Excel.Workbook
            Dim ws As Excel.Worksheet
            Dim values As Object

            appExcel = GetObject(, "Excel.Application")
            wb = appExcel.Workbooks(1)
            ws = wb.Worksheets(1)
            With ws
                values = .Range(.Cells(1, 1), .Cells(2, 5)).Value2
                'if column is first element use appExcel.Worksheetfunction.Transpose(.Range(.Cells(1, 1), .Cells(2, 5)).Value2)
                For i As Int32 = LBound(values, 1) To UBound(values, 1)
                    For j As Int32 = LBound(values, 2) To UBound(values, 2)
                        System.Windows.Forms.MessageBox.Show(values(i, j))
                    Next j
                Next
            End With
        End Sub
    End Module


问:
Ionic 5 - how to modify ion-button expand="block" width
I have this line

```<code><ion-button expand="block" id="create" shape="round">Create Account</ion-button>
</code>```

I would like to increase the width of this button.
I can't find any way to increase the button height and width.
I have tried to use an id. That didn't do anything.

```<code>#create {
    --width: 250px;
    --height: 120px;
}
</code>```

答:
You are using invalid css properties ( --widthand --heigth ). I think you are looking for height  and width.

```<code>#create {
    width: 250px;
    height: 120px;
}
</code>```

Body:
I have this line

<ion-button expand="block" id="create" shape="round">Create Account</ion-button>

I would like to increase the width of this button.
I can't find any way to increase the button height and width.
I have tried to use an id. That didn't do anything.

#create {
    --width: 250px;
    --height: 120px;
}

Body:
You are using invalid css properties ( --widthand --heigth ). I think you are looking for height  and width.

#create {
    width: 250px;
    height: 120px;
}


答:
You have an array full of arrays filled with dictionaries, so tickGroups[0][0]['price'] should give you the price from the first one for example.
If you want the correct dimensions you should work again on the creation, nevertheless, there are dictionaries at the end, not lists.</p>

Title: Selection issue in big ndimension numpy array

Body:
I have a big multidimension numpy array, that I created by converting lists, and when I try to select one specific entry I get this error :

tickGroups[0, 0, 0]

IndexError                                Traceback (most recent call last)
<ipython-input-108-e8d1dd9db3ac> in <module>
----> 1 tickGroups[0, 0, 0]

IndexError: too many indices for array

When I do tickGroups[0]

array([{'price': 239.99, 'size': 1, 'tick': 0, 'sizeInBTC': 0.004166840285011875},
       {'price': 237.43, 'size': 1500, 'tick': -1, 'sizeInBTC': 6.317651518342248},
       {'price': 237.41, 'size': 1500, 'tick': -1, 'sizeInBTC': 6.318183732782949},
       ...,
       {'price': 238.55, 'size': 800, 'tick': -1, 'sizeInBTC': 3.353594634248585},
       {'price': 237.69, 'size': 5000, 'tick': -1, 'sizeInBTC': 21.035802936598092},
       {'price': 237.98, 'size': 22774, 'tick': 1, 'sizeInBTC': 95.69711740482394}],
      dtype=object)

and tickGroups[0][0]

{'price': 239.99, 'size': 1, 'tick': 0, 'sizeInBTC': 0.004166840285011875}

tickGroups[:] returns the whole thing

array([array([{'price': 239.99, 'size': 1, 'tick': 0, 'sizeInBTC': 0.004166840285011875},
       {'price': 237.43, 'size': 1500, 'tick': -1, 'sizeInBTC': 6.317651518342248},
       {'price': 237.41, 'size': 1500, 'tick': -1, 'sizeInBTC': 6.318183732782949},
       ...,
       {'price': 238.55, 'size': 800, 'tick': -1, 'sizeInBTC': 3.353594634248585},
       {'price': 237.69, 'size': 5000, 'tick': -1, 'sizeInBTC': 21.035802936598092},
       {'price': 237.98, 'size': 22774, 'tick': 1, 'sizeInBTC': 95.69711740482394}],
      dtype=object),
       array([{'price': 237.78, 'size': 1111, 'tick': -1, 'sizeInBTC': 4.67238623938094},
       {'price': 237.81, 'size': 5000, 'tick': 1, 'sizeInBTC': 21.02518817543417},
       {'price': 237.81, 'size': 5000, 'tick': 0, 'sizeInBTC': 21.02518817543417},
       ...,
       {'price': 244.48, 'size': 1400, 'tick': -1, 'sizeInBTC': 5.726439790575917},
       {'price': 244.33, 'size': 2000, 'tick': -1, 'sizeInBTC': 8.185650554577824},
       {'price': 244.21, 'size': 7500, 'tick': -1, 'sizeInBTC': 30.71127308464027}],
      dtype=object),
       array([{'price': 244.08, 'size': 10000, 'tick': -1, 'sizeInBTC': 40.970173713536546},
       {'price': 244.05, 'size': 7500, 'tick': -1, 'sizeInBTC': 30.73140749846343},
       {'price': 244.25, 'size': 20, 'tick': 1, 'sizeInBTC': 0.08188331627430911},
       ...,
       {'price': 254.0, 'size': 2000, 'tick': -1, 'sizeInBTC': 7.874015748031496},
       {'price': 253.83, 'size': 6, 'tick': -1, 'sizeInBTC': 0.023637867864318637},
       {'price': 253.82, 'size': 6, 'tick': -1, 'sizeInBTC': 0.023638799149003232}],
      dtype=object),
       ...,
       array([{'price': 17519.5, 'size': 10, 'tick': -1, 'sizeInBTC': 0.0005707925454493565},
       {'price': 17519.5, 'size': 10066, 'tick': 0, 'sizeInBTC': 0.5745597762493222},
       {'price': 17529.5, 'size': 100, 'tick': 1, 'sizeInBTC': 0.005704669271798968},
       ...,
       {'price': 17429.5, 'size': 9905, 'tick': -1, 'sizeInBTC': 0.5682893944175106},
       {'price': 17430.5, 'size': 4800, 'tick': 1, 'sizeInBTC': 0.2753793637589283},
       {'price': 17431.0, 'size': 500, 'tick': 1, 'sizeInBTC': 0.02868452756583099}],
      dtype=object),
       array([{'price': 17431.0, 'size': 1000, 'tick': 0, 'sizeInBTC': 0.05736905513166198},
       {'price': 17430.5, 'size': 2975, 'tick': -1, 'sizeInBTC': 0.17067783482975243},
       {'price': 17431.0, 'size': 1278, 'tick': 1, 'sizeInBTC': 0.07331765245826401},
       ...,
       {'price': 17450.0, 'size': 1000, 'tick': -1, 'sizeInBTC': 0.05730659025787966},
       {'price': 17458.0, 'size': 6000, 'tick': 1, 'sizeInBTC': 0.34368197960820257},
       {'price': 17460.0, 'size': 12549, 'tick': 1, 'sizeInBTC': 0.7187285223367698}],
      dtype=object),
       array([{'price': 17460.0, 'size': 145, 'tick': 0, 'sizeInBTC': 0.008304696449026346},
       {'price': 17460.0, 'size': 500, 'tick': 0, 'sizeInBTC': 0.0286368843069874},
       {'price': 17462.0, 'size': 100, 'tick': 1, 'sizeInBTC': 0.005726720879624327},
       ...,
       {'price': 17550.0, 'size': 197, 'tick': 0, 'sizeInBTC': 0.011225071225071225},
       {'price': 17549.0, 'size': 525, 'tick': -1, 'sizeInBTC': 0.029916234543278818},
       {'price': 17544.5, 'size': 50, 'tick': -1, 'sizeInBTC': 0.002849895978796774}],
      dtype=object)], dtype=object)

So if I'm trying to select the first price 239.99 for example, I thought that tickGroups [0, 0, 0] would work, but I get the error above.
np.shape(tickGroups) returns

(16130,)


问:
Keras loss function value error: ValueError: An operation has `None` for gradient. on LSTM network
So I'm trying to train my LSTM network language model, and use a perplexity function as my loss function but i get the following error:

```<code>ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.
</code>```

My loss function looks as follows:

```<code>from keras import backend as K
def perplexity_raw(y_true, y_pred):
    """
    The perplexity metric. Why isn't this part of Keras yet?!
    https://stackoverflow.com/questions/41881308/how-to-calculate-perplexity-of-rnn-in-tensorflow
    https://github.com/keras-team/keras/issues/8267
    """
#     cross_entropy = K.sparse_categorical_crossentropy(y_true, y_pred)
    cross_entropy = K.cast(K.equal(K.max(y_true, axis=-1),
                          K.cast(K.argmax(y_pred, axis=-1), K.floatx())),
                  K.floatx())
    perplexity = K.exp(cross_entropy)
    return perplexity
</code>```

and I create my model as follows:

```<code># define model
model = Sequential()
model.add(Embedding(vocab_size, 500, input_length=max_length-1))
model.add(LSTM(750))
model.add(Dense(vocab_size, activation='softmax'))
print(model.summary())
# compile network
model.compile(loss=perplexity_raw, optimizer='adam', metrics=['accuracy'])
# fit network
model.fit(X, y, epochs=150, verbose=2)

</code>```

The error occurs  when I try to fit my model. Does anyone know what causes the error and how to fix it?

答:
These are the culprits: K.argmax and K.max. They don't have a gradient. I also think you just straight up don't need them in your loss metric! That's because maxing and argmaxing something removes the information on how much the prediction is wrong.

I don't know what kind of loss you want to measure, but I think you are looking for something like tf.exp(tf.nn.sigmoid_cross_entropy_with_logits(y_true, y_pred)) or tf.exp(tf.softmax_cross_entopy_with_logits(y_true, y_pred)). You might need to convert your logits to one hot encodings using tf.one_hot.

Body:
So I'm trying to train my LSTM network language model, and use a perplexity function as my loss function but i get the following error:

ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.

My loss function looks as follows:

from keras import backend as K
def perplexity_raw(y_true, y_pred):
    """
    The perplexity metric. Why isn't this part of Keras yet?!
    https://stackoverflow.com/questions/41881308/how-to-calculate-perplexity-of-rnn-in-tensorflow
    https://github.com/keras-team/keras/issues/8267
    """
#     cross_entropy = K.sparse_categorical_crossentropy(y_true, y_pred)
    cross_entropy = K.cast(K.equal(K.max(y_true, axis=-1),
                          K.cast(K.argmax(y_pred, axis=-1), K.floatx())),
                  K.floatx())
    perplexity = K.exp(cross_entropy)
    return perplexity

and I create my model as follows:

# define model
model = Sequential()
model.add(Embedding(vocab_size, 500, input_length=max_length-1))
model.add(LSTM(750))
model.add(Dense(vocab_size, activation='softmax'))
print(model.summary())
# compile network
model.compile(loss=perplexity_raw, optimizer='adam', metrics=['accuracy'])
# fit network
model.fit(X, y, epochs=150, verbose=2)

The error occurs  when I try to fit my model. Does anyone know what causes the error and how to fix it?


问:
How to set useEffect dependency when the calculation that uses stateB should be triggered by the change of stateA
```<code>function Example() {
  const [stateA, stateA] = useState(0);
  const [stateB, stateB] = useState(0);

  useEffect(() => {
    // this calculation should only be trigged by the change of stateA
    // but it somehow uses the stateB for calculation

    const calculation = () => {
      console.log(stateB);
    };
    calculation();
  }, [stateA]);

  return null;
}
</code>```

According to the guide from https://overreacted.io/a-complete-guide-to-useeffect/, I am wondering what is the correct way to set dependency in this case

答:
If you're using the result of the calculation in your component, this sounds like a good use case for the useCallback hook.

const someResult = useCallback(() => {
  return doSomething(stateB);
}, [stateA])
```

<p>If you want to just run some random effect, then <code>useEffect</code> is correct. You just need to specify <code>stateA</code> in the dependency array.</p>

<pre class="lang-js prettyprint-override"><code>useEffect(() => {
  doSomething(stateB);
}, [stateA])
</code>```

If you're using the exhaustive-deps linting rule, you'll get a waring in both cases. This is because your memoized calculation is relying on stateB but will not be recomputed when stateB updates, meaning your calculations could be stale. You have a couple options:

Add stateB to the dependency array (your calculation will then happen when stateA or stateB are updated.

Ignore the linting rule. You can suppress the warning by placing this comment on the line before your dependency array: // eslint-disable-next-line react-hooks/exhaustive-deps

Conventional wisdom is that suppressing this warning will come back to bite you, so it might be worth trying to figure out if you can accomplish what you need without this stale computation.

Body:
function Example() {
  const [stateA, stateA] = useState(0);
  const [stateB, stateB] = useState(0);

  useEffect(() => {
    // this calculation should only be trigged by the change of stateA
    // but it somehow uses the stateB for calculation

    const calculation = () => {
      console.log(stateB);
    };
    calculation();
  }, [stateA]);

  return null;
}

According to the guide from https://overreacted.io/a-complete-guide-to-useeffect/, I am wondering what is the correct way to set dependency in this case

Body:
If you're using the result of the calculation in your component, this sounds like a good use case for the useCallback hook.

const someResult = useCallback(() => {
  return doSomething(stateB);
}, [stateA])

If you want to just run some random effect, then useEffect is correct. You just need to specify stateA in the dependency array.

useEffect(() => {
  doSomething(stateB);
}, [stateA])

If you're using the exhaustive-deps linting rule, you'll get a waring in both cases. This is because your memoized calculation is relying on stateB but will not be recomputed when stateB updates, meaning your calculations could be stale. You have a couple options:

Add stateB to the dependency array (your calculation will then happen when stateA or stateB are updated.

Ignore the linting rule. You can suppress the warning by placing this comment on the line before your dependency array: // eslint-disable-next-line react-hooks/exhaustive-deps

Conventional wisdom is that suppressing this warning will come back to bite you, so it might be worth trying to figure out if you can accomplish what you need without this stale computation.


问:
C++ twoSum. Optimize memory usage
I am solving a twoSum problem.
Steps:

Read an input file with a following template:

```<code>   7
   1 7 3 4 7 9
</code>```

First line is the target number, second line is a number sequence.

Numbers can be in range 0 < N < 999999999

If the sum of two numbers from the number sequence equals the target number, I write "1" to the output file.

If there are no numbers the sum of which equals the target number then I write "0" to the output file.

I need to optimize memory usage in my code. How can I do that?

```<code>#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <unordered_map>
#include <string>
#include <algorithm>

using namespace std;

int main() {

ifstream f1;
vector<int> nums;
string line;
string source;
//Open input file and read it to a string
f1.open("input.txt");
while (getline(f1, line, '\n')) {
    source+=line + " ";
    } f1.close();

//Parse the string into an int vector
stringstream parser(source);
int num;
while (parser >> num) { nums.push_back(num); }

//Clear used strings
line = "";
source = "";

//Get target number
int target = nums.at(0);

//Get number sequence
nums.erase(nums.begin());
bool flag = false;

//Check number sequence for two numbers sum of which equals the target number

unordered_map<int, int> mp;

for(int i=0;i<nums.size();i++){
  if(mp.count(nums[i])==1){
    flag = true;
    break;}
  mp[target-nums[i]]=i;
  }

//Write the result into the output file
ofstream f2;
f2.open("output.txt");
f2 << flag;
f2.close();
}

</code>```

答:
There are a couple of things you can do to minimise memory usage here. First up, you don't need to read entire contents of the file into std::string. You can read directly into std::vector, or better still read the file contents into a single int variable and process the numbers as you go. Another thing: you do not need to use a std::unordered_map, because presence of the key is the only thing you are really interested in, so std::unordered_set is sufficient. Below a simple solution making use of that suggestions:

```<code>#include <fstream>
#include <unordered_set>

int main() {
    std::ifstream input {"input.txt"};

    int target;
    input >> target;
    int current_number;
    bool found = false;
    std::unordered_set<int> observed_numbers;
    while (input >> current_number) {
        if (observed_numbers.count(target - current_number) > 0) {
            found = true;
            break;
        }
        observed_numbers.insert(current_number);
    }
    std::ofstream output {"output.txt"};
    output << found;
}
</code>```

Title: C++ twoSum. Optimize memory usage

Body:
I am solving a twoSum problem.
Steps:

Read an input file with a following template:

   7
   1 7 3 4 7 9

First line is the target number, second line is a number sequence.

Numbers can be in range 0 < N < 999999999

If the sum of two numbers from the number sequence equals the target number, I write "1" to the output file.

If there are no numbers the sum of which equals the target number then I write "0" to the output file.

I need to optimize memory usage in my code. How can I do that?

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <unordered_map>
#include <string>
#include <algorithm>

using namespace std;

int main() {

ifstream f1;
vector<int> nums;
string line;
string source;
//Open input file and read it to a string
f1.open("input.txt");
while (getline(f1, line, '\n')) {
    source+=line + " ";
    } f1.close();

//Parse the string into an int vector
stringstream parser(source);
int num;
while (parser >> num) { nums.push_back(num); }

//Clear used strings
line = "";
source = "";

//Get target number
int target = nums.at(0);

//Get number sequence
nums.erase(nums.begin());
bool flag = false;

//Check number sequence for two numbers sum of which equals the target number

unordered_map<int, int> mp;

for(int i=0;i<nums.size();i++){
  if(mp.count(nums[i])==1){
    flag = true;
    break;}
  mp[target-nums[i]]=i;
  }

//Write the result into the output file
ofstream f2;
f2.open("output.txt");
f2 << flag;
f2.close();
}

Body:
There are a couple of things you can do to minimise memory usage here. First up, you don't need to read entire contents of the file into std::string. You can read directly into std::vector, or better still read the file contents into a single int variable and process the numbers as you go. Another thing: you do not need to use a std::unordered_map, because presence of the key is the only thing you are really interested in, so std::unordered_set is sufficient. Below a simple solution making use of that suggestions:

#include <fstream>
#include <unordered_set>

int main() {
    std::ifstream input {"input.txt"};

    int target;
    input >> target;
    int current_number;
    bool found = false;
    std::unordered_set<int> observed_numbers;
    while (input >> current_number) {
        if (observed_numbers.count(target - current_number) > 0) {
            found = true;
            break;
        }
        observed_numbers.insert(current_number);
    }
    std::ofstream output {"output.txt"};
    output << found;
}


问:
Jquery $(this) node and its use
I am trying to understand some jquery code that uses a $(this) node.  What is it used for and when can it be used?

```<code>$("li").hover(border, noBorder);
function border()
{
    $(this).css("border", "1px solid black");
}
</code>```

答:
Please read jQuery's this:demystified by Remy Sharp

There are really two main contexts of
  'this' in jQuery. The first refers to
  a to a DOM element, and the second to
  a jQuery object.

As a DOM Element

```<code>$('a.newTarget').each(function () { // <- our anonymous callback
    // check the DOM attribute 'host' on this
    if (this.host != window.location.host) {
        // create a jQuery object using the current DOM element
        $(this).attr('target', '_new');
    }
});
</code>```

As a jQuery Object

```<code>jQuery.fn.newTarget = function () {
    // 'this' is a jQuery object at this point - with all the jQuery functions

    return this.each(function () { // return so we don't break the chain
        // now we are inside of a jQuery function, the DOM element is the context
        // so 'this' has changed to become a DOM element.

        if (this.host != window.location.host) {
            $(this).attr('target', '_new');
        }
    });
};
</code>```

Hope this helps.

Title: Jquery $(this) node and its use

Body:
I am trying to understand some jquery code that uses a $(this) node.  What is it used for and when can it be used?

$("li").hover(border, noBorder);
function border()
{
    $(this).css("border", "1px solid black");
}

Body:
Please read jQuery's this:demystified by Remy Sharp

There are really two main contexts of
  'this' in jQuery. The first refers to
  a to a DOM element, and the second to
  a jQuery object.

As a DOM Element

$('a.newTarget').each(function () { // <- our anonymous callback
    // check the DOM attribute 'host' on this
    if (this.host != window.location.host) {
        // create a jQuery object using the current DOM element
        $(this).attr('target', '_new');
    }
});

As a jQuery Object

jQuery.fn.newTarget = function () {
    // 'this' is a jQuery object at this point - with all the jQuery functions

    return this.each(function () { // return so we don't break the chain
        // now we are inside of a jQuery function, the DOM element is the context
        // so 'this' has changed to become a DOM element.

        if (this.host != window.location.host) {
            $(this).attr('target', '_new');
        }
    });
};

Hope this helps.


问:
Cocoa: How do I change the download destination? Swift
I’m trying to download a file from a URL, I managed to do that however, the it will download to ~Libray directory. How do I change the directory to the downloads folder? or out of the library directory.

Here is my file downloader…

```<code>import Foundation

class FileDownloader {

    static func loadFileSync(url: URL, completion: @escaping (String?, Error?) -> Void)
    {
        let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask).first!

        let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)

        if FileManager().fileExists(atPath: destinationUrl.path)
        {
            print("File already exists [\(destinationUrl.path)]")
            completion(destinationUrl.path, nil)
        }
        else if let dataFromURL = NSData(contentsOf: url)
        {
            if dataFromURL.write(to: destinationUrl, atomically: true)
            {
                print("file saved [\(destinationUrl.path)]")
                completion(destinationUrl.path, nil)
            }
            else
            {
                print("error saving file")
                let error = NSError(domain:"Error saving file", code:1001, userInfo:nil)
                completion(destinationUrl.path, error)
            }
        }
        else
        {
            let error = NSError(domain:"Error downloading file", code:1002, userInfo:nil)
            completion(destinationUrl.path, error)
        }
    }

    static func loadFileAsync(url: URL, completion: @escaping (String?, Error?) -> Void)
    {
        let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

        let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)

        if FileManager().fileExists(atPath: destinationUrl.path)
        {
            print("File already exists [\(destinationUrl.path)]")
            completion(destinationUrl.path, nil)
        }
        else
        {
            let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
            var request = URLRequest(url: url)
            request.httpMethod = "GET"
            let task = session.dataTask(with: request, completionHandler:
            {
                data, response, error in
                if error == nil
                {
                    if let response = response as? HTTPURLResponse
                    {
                        if response.statusCode == 200
                        {
                            if let data = data
                            {
                                if let _ = try? data.write(to: destinationUrl, options: Data.WritingOptions.atomic)
                                {
                                    completion(destinationUrl.path, error)
                                }
                                else
                                {
                                    completion(destinationUrl.path, error)
                                }
                            }
                            else
                            {
                                completion(destinationUrl.path, error)
                            }
                        }
                    }
                }
                else
                {
                    completion(destinationUrl.path, error)
                }
            })
            task.resume()
        }
    }
}
</code>```

I took a look at the code and I think it has to do something with this

```<code> let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask).first!

        let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)
</code>```

I have tried chinging the code from documentDirectory to desktopDirectory but that still puts it in the library directory. How do I change it from the library directory to the downloads directory?

答:
You are running a sandboxed app. The Appname/Data/... directories are aliases of the real directories.

Also, you should use userDomainMask instead of allDomainsMask to search for the path in user's home directory. The correct directory you are looking for is downloadsDirectory.

```<code>let downloadsUrl = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first!
let destinationUrl = downloadsUrl.appendingPathComponent(url.lastPathComponent)
</code>```

There is another SO thread about sandboxed directories:

how to get /Users/username/Downloads path in a sandboxed app?

Body:
I’m trying to download a file from a URL, I managed to do that however, the it will download to ~Libray directory. How do I change the directory to the downloads folder? or out of the library directory.

Here is my file downloader…

import Foundation

class FileDownloader {

    static func loadFileSync(url: URL, completion: @escaping (String?, Error?) -> Void)
    {
        let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask).first!

        let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)

        if FileManager().fileExists(atPath: destinationUrl.path)
        {
            print("File already exists [\(destinationUrl.path)]")
            completion(destinationUrl.path, nil)
        }
        else if let dataFromURL = NSData(contentsOf: url)
        {
            if dataFromURL.write(to: destinationUrl, atomically: true)
            {
                print("file saved [\(destinationUrl.path)]")
                completion(destinationUrl.path, nil)
            }
            else
            {
                print("error saving file")
                let error = NSError(domain:"Error saving file", code:1001, userInfo:nil)
                completion(destinationUrl.path, error)
            }
        }
        else
        {
            let error = NSError(domain:"Error downloading file", code:1002, userInfo:nil)
            completion(destinationUrl.path, error)
        }
    }

    static func loadFileAsync(url: URL, completion: @escaping (String?, Error?) -> Void)
    {
        let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

        let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)

        if FileManager().fileExists(atPath: destinationUrl.path)
        {
            print("File already exists [\(destinationUrl.path)]")
            completion(destinationUrl.path, nil)
        }
        else
        {
            let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
            var request = URLRequest(url: url)
            request.httpMethod = "GET"
            let task = session.dataTask(with: request, completionHandler:
            {
                data, response, error in
                if error == nil
                {
                    if let response = response as? HTTPURLResponse
                    {
                        if response.statusCode == 200
                        {
                            if let data = data
                            {
                                if let _ = try? data.write(to: destinationUrl, options: Data.WritingOptions.atomic)
                                {
                                    completion(destinationUrl.path, error)
                                }
                                else
                                {
                                    completion(destinationUrl.path, error)
                                }
                            }
                            else
                            {
                                completion(destinationUrl.path, error)
                            }
                        }
                    }
                }
                else
                {
                    completion(destinationUrl.path, error)
                }
            })
            task.resume()
        }
    }
}

I took a look at the code and I think it has to do something with this

 let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask).first!

        let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)

I have tried chinging the code from documentDirectory to desktopDirectory but that still puts it in the library directory. How do I change it from the library directory to the downloads directory?

Body:
You are running a sandboxed app. The Appname/Data/... directories are aliases of the real directories.

Also, you should use userDomainMask instead of allDomainsMask to search for the path in user's home directory. The correct directory you are looking for is downloadsDirectory.

let downloadsUrl = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first!
let destinationUrl = downloadsUrl.appendingPathComponent(url.lastPathComponent)

There is another SO thread about sandboxed directories:

how to get /Users/username/Downloads path in a sandboxed app?


问:
Flutter FutureBuilder not building with data from sqlite
I'm very new in flutter, and are trying to write the app that will take value from sqlite. From what I tried, it needs to use FutureBuilder widget.

But the following code I wrote, the FutureBuilder widget seems to get data from sqlite, but the "builder" property was never called:

```<code>import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutterapp/dbHelper.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes:{
        "/": (context) =>Test()
      }
    );
  }
}

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {

  bool nameCheck = false; // Use to check name textfield has correctly be inputed
  TextEditingController nameController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body:Column(
          children: <Widget>[
            SizedBox(height:300),
            Row(
              children: <Widget>[
                Expanded(
                    child: TextField(
                      controller: nameController,
                    )
                ),
                IconButton(
                  icon: Icon(Icons.check_circle),
                    onPressed:(){
                      return FutureBuilder(
                          future: getData(nameController.text),
                          builder: (BuildContext context, AsyncSnapshot<List<Map>>snapshot) {
                            print("Start future"); // never get printed
                            List<Widget> children;
                            if (snapshot.hasData) {
                              children = <Widget>[
                                Builder(
                                    builder: (BuildContext context) {
                                      print("got data");
                                      final result = snapshot.data;
                                      print(result) ; // never get printed
                                      setState(() {
                                        nameCheck = true;
                                      });
                                      return Container();
                                    })
                              ];
                            } else {
                              children = <Widget>[
                                AlertDialog(
                                    content: SpinKitCircle(
                                      color: Colors.white,
                                      size: 80.0,
                                    ))
                              ];
                            }
                            return Center(
                                child: Container(
                                    color: Colors.blue,
                                    child: Column(
                                      mainAxisAlignment:
                                      MainAxisAlignment
                                          .center,
                                      crossAxisAlignment:
                                      CrossAxisAlignment
                                          .center,
                                      children: children,
                                    )));
                          });}
                )
              ],
            ),
            Builder(
              builder: (BuildContext context){
                if (nameCheck == true){
                  return Text("test");
                }
                return Container();
              }
            )
          ],
        )
    );
  }
}

Future<List<Map>> getData(String input_name) async{
  final dbHelper = DBHelper.instance;
  await dbHelper.database;
  final result = await dbHelper.query("SELECT * FROM Guest WHERE Name = \"$input_name\"");
  print(result); // This get printed
  return result;
}
</code>```

The DBHelper code is as follow, basically it just set up a sqlite database and some database operation:

```<code>import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';

class DBHelper {
  static final _databaseName = "MonetaryDB.db";
  static final _databaseVersion = 1;

  static final create_table_Test = "CREATE TABLE \"Guest\" (\"Name\"    TEXT NOT NULL PRIMARY KEY, \"Money\" INTEGER, \"Person\" INTEGER)";

  static final String insert_guest = "INSERT INTO Guest (Name, Money, Person) VALUES (\"testname\", 1000, 1)";

  DBHelper._privateConstructor();

  static final DBHelper instance = DBHelper._privateConstructor();

  static Database _database;
  Future<Database> get database async {
    if (_database != null) {
      return _database;}
    else{
      _database = await _initDatabase();
    return _database;}
  }

  _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path,
      version: _databaseVersion,
      onCreate: _onCreate,
    );
  }

  Future _onCreate(Database db, int version) async {
    await db.execute(create_table_Test);
    await db.rawInsert(insert_guest);
  }

  Future<int> insert(String statement) async {
    Database db = await instance.database;
    return await db.rawInsert(statement);
  }

  Future<List<Map>> query(String statement) async {
    Database db = await instance.database;
    return await db.rawQuery(statement);
  }

  Future<int> update(String statement) async{
    Database db = await instance.database;
    return await db.rawUpdate(statement);
  }

  Future<int> delete(String statement) async{
    Database db = await instance.database;
    return db.rawDelete(statement);
  }
}
</code>```

If I simply change the IconButton onPressed function into setState((){nameCheck = true}), The Text("test") widget will show, so the problem must be the FutureBuilder. Also, the getData() function can get the correct result from the sqlite database

I have no idea why the FutureBuilder doesn't get build, did someone have any idea of it?
Thanks!

答:
So with the help in the comment section, I change the code and it worked:

```<code>...
  Widget build(BuildContext context) {
    return Scaffold(
        body:Column(
          children: <Widget>[
            SizedBox(height:300),
            Row(
              children: <Widget>[
                Expanded(
                    child: TextField(
                      controller: nameController,
                    )
                ),
                IconButton(
                  icon: Icon(Icons.check_circle),
                    onPressed:(){
                    return showDialog(
                      context: context,
                      builder: (BuildContext context){
                        return AlertDialog(
                          actions: <Widget>[
                            SizedBox(
                              width: 300,
                              height: 300,
                              child: FutureBuilder(
                                  future: getData(nameController.text),
                                  builder: (BuildContext context, AsyncSnapshot<List<Map>>snapshot) {
                                    if (snapshot.hasData) {
                                      final result = snapshot.data;
                                      SchedulerBinding.instance.addPostFrameCallback((_) => setState(() {
                                        nameCheck = true;
                                      }));
                                      Navigator.pop(context, true);
                                    }
                                    else {
                                      return Container(
                                          child: SpinKitCircle(
                                            color: Colors.white,
                                            size: 80.0,
                                          ));
                                    }
                                    return Container(color: Colors.blue);
                                  })
                            ),
                          ],
                        );
                      }
                    );
                  }
                )
              ],
            ),
            Builder(
              builder: (BuildContext context){
                if (nameCheck == true){
                  return Text("test");
                }
                return Container();
              }
            )
          ],
        )
    );
  }
...
</code>```

The other codes are still the same.

Like the comment section above had suggested, the main problem is that there will be no place to build for the widget the FutureBuilder that is going to built. To solve this problem, I place the FutureBuilder widget into the AlertDialog widget, since that I still want to keep the SpinKitCircle widget when loading.

I also gave up the Column widget at the end of the FutureBuilder widget, and deleted the Builder widget at the beginning of the FutureBuilder widget, which it was no longer needed when there was no Column.

The above codes still throw an acceptable exception:"setState() or markNeedsBuild() called during build." But the whole things still can run, so I will try to fix that the other day.

Thanks for the suggestion in the comment section.

Body:
I'm very new in flutter, and are trying to write the app that will take value from sqlite. From what I tried, it needs to use FutureBuilder widget.

But the following code I wrote, the FutureBuilder widget seems to get data from sqlite, but the "builder" property was never called:

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutterapp/dbHelper.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes:{
        "/": (context) =>Test()
      }
    );
  }
}

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {

  bool nameCheck = false; // Use to check name textfield has correctly be inputed
  TextEditingController nameController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body:Column(
          children: <Widget>[
            SizedBox(height:300),
            Row(
              children: <Widget>[
                Expanded(
                    child: TextField(
                      controller: nameController,
                    )
                ),
                IconButton(
                  icon: Icon(Icons.check_circle),
                    onPressed:(){
                      return FutureBuilder(
                          future: getData(nameController.text),
                          builder: (BuildContext context, AsyncSnapshot<List<Map>>snapshot) {
                            print("Start future"); // never get printed
                            List<Widget> children;
                            if (snapshot.hasData) {
                              children = <Widget>[
                                Builder(
                                    builder: (BuildContext context) {
                                      print("got data");
                                      final result = snapshot.data;
                                      print(result) ; // never get printed
                                      setState(() {
                                        nameCheck = true;
                                      });
                                      return Container();
                                    })
                              ];
                            } else {
                              children = <Widget>[
                                AlertDialog(
                                    content: SpinKitCircle(
                                      color: Colors.white,
                                      size: 80.0,
                                    ))
                              ];
                            }
                            return Center(
                                child: Container(
                                    color: Colors.blue,
                                    child: Column(
                                      mainAxisAlignment:
                                      MainAxisAlignment
                                          .center,
                                      crossAxisAlignment:
                                      CrossAxisAlignment
                                          .center,
                                      children: children,
                                    )));
                          });}
                )
              ],
            ),
            Builder(
              builder: (BuildContext context){
                if (nameCheck == true){
                  return Text("test");
                }
                return Container();
              }
            )
          ],
        )
    );
  }
}

Future<List<Map>> getData(String input_name) async{
  final dbHelper = DBHelper.instance;
  await dbHelper.database;
  final result = await dbHelper.query("SELECT * FROM Guest WHERE Name = \"$input_name\"");
  print(result); // This get printed
  return result;
}

The DBHelper code is as follow, basically it just set up a sqlite database and some database operation:

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';

class DBHelper {
  static final _databaseName = "MonetaryDB.db";
  static final _databaseVersion = 1;

  static final create_table_Test = "CREATE TABLE \"Guest\" (\"Name\"    TEXT NOT NULL PRIMARY KEY, \"Money\" INTEGER, \"Person\" INTEGER)";

  static final String insert_guest = "INSERT INTO Guest (Name, Money, Person) VALUES (\"testname\", 1000, 1)";

  DBHelper._privateConstructor();

  static final DBHelper instance = DBHelper._privateConstructor();

  static Database _database;
  Future<Database> get database async {
    if (_database != null) {
      return _database;}
    else{
      _database = await _initDatabase();
    return _database;}
  }

  _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path,
      version: _databaseVersion,
      onCreate: _onCreate,
    );
  }

  Future _onCreate(Database db, int version) async {
    await db.execute(create_table_Test);
    await db.rawInsert(insert_guest);
  }

  Future<int> insert(String statement) async {
    Database db = await instance.database;
    return await db.rawInsert(statement);
  }

  Future<List<Map>> query(String statement) async {
    Database db = await instance.database;
    return await db.rawQuery(statement);
  }

  Future<int> update(String statement) async{
    Database db = await instance.database;
    return await db.rawUpdate(statement);
  }

  Future<int> delete(String statement) async{
    Database db = await instance.database;
    return db.rawDelete(statement);
  }
}

If I simply change the IconButton onPressed function into setState((){nameCheck = true}), The Text("test") widget will show, so the problem must be the FutureBuilder. Also, the getData() function can get the correct result from the sqlite database

I have no idea why the FutureBuilder doesn't get build, did someone have any idea of it?
Thanks!

Body:
So with the help in the comment section, I change the code and it worked:

...
  Widget build(BuildContext context) {
    return Scaffold(
        body:Column(
          children: <Widget>[
            SizedBox(height:300),
            Row(
              children: <Widget>[
                Expanded(
                    child: TextField(
                      controller: nameController,
                    )
                ),
                IconButton(
                  icon: Icon(Icons.check_circle),
                    onPressed:(){
                    return showDialog(
                      context: context,
                      builder: (BuildContext context){
                        return AlertDialog(
                          actions: <Widget>[
                            SizedBox(
                              width: 300,
                              height: 300,
                              child: FutureBuilder(
                                  future: getData(nameController.text),
                                  builder: (BuildContext context, AsyncSnapshot<List<Map>>snapshot) {
                                    if (snapshot.hasData) {
                                      final result = snapshot.data;
                                      SchedulerBinding.instance.addPostFrameCallback((_) => setState(() {
                                        nameCheck = true;
                                      }));
                                      Navigator.pop(context, true);
                                    }
                                    else {
                                      return Container(
                                          child: SpinKitCircle(
                                            color: Colors.white,
                                            size: 80.0,
                                          ));
                                    }
                                    return Container(color: Colors.blue);
                                  })
                            ),
                          ],
                        );
                      }
                    );
                  }
                )
              ],
            ),
            Builder(
              builder: (BuildContext context){
                if (nameCheck == true){
                  return Text("test");
                }
                return Container();
              }
            )
          ],
        )
    );
  }
...

The other codes are still the same.

Like the comment section above had suggested, the main problem is that there will be no place to build for the widget the FutureBuilder that is going to built. To solve this problem, I place the FutureBuilder widget into the AlertDialog widget, since that I still want to keep the SpinKitCircle widget when loading.

I also gave up the Column widget at the end of the FutureBuilder widget, and deleted the Builder widget at the beginning of the FutureBuilder widget, which it was no longer needed when there was no Column.

The above codes still throw an acceptable exception:"setState() or markNeedsBuild() called during build." But the whole things still can run, so I will try to fix that the other day.

Thanks for the suggestion in the comment section.