问:
Python3, difficulty with classes and tkinter
First of all to kick it off,

I'm not great at programming,

I have difficulty with understanding most basics,

I always try doing my uterly best to solve things like this myself.

I'm trying to create a simple gui that makes json files. Everything works fine. Fine in the sense that I'm able to create the files.
Now I wanted to get my code cleaned up and to the next level. I have added tabs to the tkinter screen and that is where the troubles starts. Because when I'm, on a differend tab, the function doesn't get the current selected items, so I added buttons to save that list and then move to different tab.

I have a function(Save_List_t), which looks at the selected items from the listbox(a_lsb1) and saves them to a list(choice_list_t). This function runs when I press button(a_button).

After doing that I got a problem, I don't want to use "global" but I need the list in a other function(Mitre_Gen_Techs) to generate the files. This function runs when I press a button on the third tab.(c.button1)

To tackel this problem, I saw a post where someone uses a class to fix it. However even after reading to the documentation about classes I still don't truely get it.

Now I'm stuck and get the error. Which I don't find that strange, it makes sense to me why it gives the error but what am I doing wrong or how do I solve this issue.

The error:

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\thans\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
TypeError: Save_List_t() missing 1 required positional argument: 'self'
</code>```

The code I wrote:

```<code>from tkinter import *
from attackcti import attack_client
from mitretemplategen import *
from tkinter import ttk

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Mitre ATT&Ck
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
ac = attack_client()
groups = ac.get_groups()
groups = ac.remove_revoked(groups)
techs = ac.get_enterprise_techniques()
techs = ac.remove_revoked(techs)

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Tkinter screen setup
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
root = Tk()

root.title("Mitre Att&ck")
root.minsize(900, 800)
root.wm_iconbitmap('')

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Functions / classes
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

class Screen(object):
    def __init__(self):
        self.choice_list_t = []
        self.choice_list_g = []

    def Save_List_t(self):
        for item in a_lsb2.curselection():
            self.choice_list_t.append(a_lsb2.get(item))
        print(self.choice_list_t)

    def Save_List_g(self):
        choice_list_g = []
        for item in b_lsb1.curselection():
            self.choice_list_g.append(b_lsb1.get(item))
        print(self.choice_list_g)

    def Mitre_Gen_Techs(self):
        # Gen the json file
        # mitre_gen_techs(self.choice_list_t, techs)

        #testing class
        print(self.choice_list_t)

    def Mitre_Gen_Groups(self):
        # Gen the json file
        # mitre_gen_groups(self.choice_list_g, groups)

        #testing class
        print(self.choice_list_g)

def main():
    # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    # First Tkinter tab
    # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    rows = 0
    while rows < 50:
        root.rowconfigure(rows, weight=1)
        root.columnconfigure(rows, weight=1)
        rows += 1

    # Notebook creating tabs
    nb = ttk.Notebook(root)
    nb.grid(row=1, column=0, columnspan=50, rowspan=50, sticky='NESW')

    # Create the differend tabs on the notebook
    tab_one = Frame(nb)
    nb.add(tab_one, text='APG')

    tab_two = Frame(nb)
    nb.add(tab_two, text='Actors')

    tab_gen = Frame(nb)
    nb.add(tab_gen, text='test')

    # =-=- First Tab -=-=
    # List box 1
    a_lsb1 = Listbox(tab_one, height=30, width=30, selectmode=MULTIPLE)
    # List with techs
    a_lsb2 = Listbox(tab_one, height=30, width=30, selectmode=MULTIPLE)
    for t in techs:
        a_lsb2.insert(END, t['name'])

    # Save list, to later use in Screen.Mitre_Gen_Techs
    a_button = Button(tab_one, text="Save selected", command=Screen.Save_List_t)

    # =-=- Second Tab -=-=
    # List with TA's
    b_lsb1 = Listbox(tab_two, height=30, width=30, selectmode=MULTIPLE)
    for g in groups:
        b_lsb1.insert(END, g['name'])

    # Save list, to later use in Screen.Mitre_Gen_Groups
    b_button = Button(tab_two, text="Save selected", command=Screen.Save_List_g)

    # =-=- Third tab -=-=
    c_button = Button(tab_gen, text="Print group json", command=Screen.Mitre_Gen_Groups)
    c_button1 = Button(tab_gen, text="Print techs json", command=Screen.Mitre_Gen_Techs)

    # Placing the items on the grid
    a_lsb1.grid(row=1, column=1)
    a_lsb2.grid(row=1, column=2)

    b_lsb1.grid(row=1, column=1)

    a_button.grid(row=2, column=1)
    b_button.grid(row=2, column=1)

    c_button.grid(row=2, column=1)
    c_button1.grid(row=2, column=2)

    root.mainloop()

# If main file then run: main()
if __name__ == "__main__":
    main()
</code>```

The application:
Image

答:
I found someone who explained what was wrong.
Credits to Scriptman ( ^ , ^ ) /

simply adding:
sc = Screen()

And changing:
Button(tab_apg, text="Save selected", command=sc.Save_List_t)

Resolved the issue.

Body:
First of all to kick it off,

I'm not great at programming,

I have difficulty with understanding most basics,

I always try doing my uterly best to solve things like this myself.

I'm trying to create a simple gui that makes json files. Everything works fine. Fine in the sense that I'm able to create the files.
Now I wanted to get my code cleaned up and to the next level. I have added tabs to the tkinter screen and that is where the troubles starts. Because when I'm, on a differend tab, the function doesn't get the current selected items, so I added buttons to save that list and then move to different tab.

I have a function(Save_List_t), which looks at the selected items from the listbox(a_lsb1) and saves them to a list(choice_list_t). This function runs when I press button(a_button).

After doing that I got a problem, I don't want to use "global" but I need the list in a other function(Mitre_Gen_Techs) to generate the files. This function runs when I press a button on the third tab.(c.button1)

To tackel this problem, I saw a post where someone uses a class to fix it. However even after reading to the documentation about classes I still don't truely get it.

Now I'm stuck and get the error. Which I don't find that strange, it makes sense to me why it gives the error but what am I doing wrong or how do I solve this issue.

The error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\thans\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
TypeError: Save_List_t() missing 1 required positional argument: 'self'

The code I wrote:

from tkinter import *
from attackcti import attack_client
from mitretemplategen import *
from tkinter import ttk

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Mitre ATT&Ck
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
ac = attack_client()
groups = ac.get_groups()
groups = ac.remove_revoked(groups)
techs = ac.get_enterprise_techniques()
techs = ac.remove_revoked(techs)

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Tkinter screen setup
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
root = Tk()

root.title("Mitre Att&ck")
root.minsize(900, 800)
root.wm_iconbitmap('')

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Functions / classes
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

class Screen(object):
    def __init__(self):
        self.choice_list_t = []
        self.choice_list_g = []

    def Save_List_t(self):
        for item in a_lsb2.curselection():
            self.choice_list_t.append(a_lsb2.get(item))
        print(self.choice_list_t)

    def Save_List_g(self):
        choice_list_g = []
        for item in b_lsb1.curselection():
            self.choice_list_g.append(b_lsb1.get(item))
        print(self.choice_list_g)

    def Mitre_Gen_Techs(self):
        # Gen the json file
        # mitre_gen_techs(self.choice_list_t, techs)

        #testing class
        print(self.choice_list_t)

    def Mitre_Gen_Groups(self):
        # Gen the json file
        # mitre_gen_groups(self.choice_list_g, groups)

        #testing class
        print(self.choice_list_g)

def main():
    # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    # First Tkinter tab
    # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    rows = 0
    while rows < 50:
        root.rowconfigure(rows, weight=1)
        root.columnconfigure(rows, weight=1)
        rows += 1

    # Notebook creating tabs
    nb = ttk.Notebook(root)
    nb.grid(row=1, column=0, columnspan=50, rowspan=50, sticky='NESW')

    # Create the differend tabs on the notebook
    tab_one = Frame(nb)
    nb.add(tab_one, text='APG')

    tab_two = Frame(nb)
    nb.add(tab_two, text='Actors')

    tab_gen = Frame(nb)
    nb.add(tab_gen, text='test')

    # =-=- First Tab -=-=
    # List box 1
    a_lsb1 = Listbox(tab_one, height=30, width=30, selectmode=MULTIPLE)
    # List with techs
    a_lsb2 = Listbox(tab_one, height=30, width=30, selectmode=MULTIPLE)
    for t in techs:
        a_lsb2.insert(END, t['name'])

    # Save list, to later use in Screen.Mitre_Gen_Techs
    a_button = Button(tab_one, text="Save selected", command=Screen.Save_List_t)

    # =-=- Second Tab -=-=
    # List with TA's
    b_lsb1 = Listbox(tab_two, height=30, width=30, selectmode=MULTIPLE)
    for g in groups:
        b_lsb1.insert(END, g['name'])

    # Save list, to later use in Screen.Mitre_Gen_Groups
    b_button = Button(tab_two, text="Save selected", command=Screen.Save_List_g)

    # =-=- Third tab -=-=
    c_button = Button(tab_gen, text="Print group json", command=Screen.Mitre_Gen_Groups)
    c_button1 = Button(tab_gen, text="Print techs json", command=Screen.Mitre_Gen_Techs)

    # Placing the items on the grid
    a_lsb1.grid(row=1, column=1)
    a_lsb2.grid(row=1, column=2)

    b_lsb1.grid(row=1, column=1)

    a_button.grid(row=2, column=1)
    b_button.grid(row=2, column=1)

    c_button.grid(row=2, column=1)
    c_button1.grid(row=2, column=2)

    root.mainloop()

# If main file then run: main()
if __name__ == "__main__":
    main()

The application:
Image


来源: stackexchange

问:
Passing parameter after query result (ExpressJS)
i am using expressjs & postgresql

How to get parameter after query result in expressJS outside function

this is my code

```<code>
const checkMail = function(regEmail){

      pool.query("SELECT * FROM tb_users where email=$1", [regEmail] ,(err, result) =>{

        console.log('inside : '+result.rowCount);
        return result.rowCount;
      });

    }

    var cekMailres = checkMail(email);

    console.log('outside : '+cekMailres);

</code>```

i need parameter result.rowCount

thank u for your help

my final solution

```<code>
var email = req.body.email;

var cekMail = new Promise(function(resolve, reject) {
      pool.query("SELECT * FROM tb_users where email=$1", [email] , function(error,result) {
      console.log("Row count: %d",result.rows.length);  // n

      if(error){
          console.log(error)
      }

      resolve(result.rows.length);
      });
  });

  cekMail.then(function (resolve, reject) {

    console.log(resolve);

    res.render('login/register',{

      layout: 'login/layout',
      mailStatus: resolve,
    });

  });

</code>```

答:
You are not returning the value from the function (you are in the query callback). I have not tested this, but it should work like that:</p>

```<code>const checkMail = async function(regEmail, fn){
  var rowCount = 0;
  await pool.query("SELECT * FROM tb_users where email=$1", [regEmail] ,(err, result) =>{

    console.log('inside : '+result.rowCount);
    fn(result.rowCount);
    return result.rowCount;
  });

}

var cekMailres = checkMail(email, function(rowCount){
    console.log('Outside: ' + rowCount);
}).then(function () {
    //do nothing
}).catch(function () {
    //do nothing
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i am using expressjs & postgresql

How to get parameter after query result in expressJS outside function

this is my code

const checkMail = function(regEmail){

      pool.query("SELECT * FROM tb_users where email=$1", [regEmail] ,(err, result) =>{

        console.log('inside : '+result.rowCount);
        return result.rowCount;
      });

    }

    var cekMailres = checkMail(email);

    console.log('outside : '+cekMailres);

i need parameter result.rowCount

thank u for your help

my final solution

var email = req.body.email;

var cekMail = new Promise(function(resolve, reject) {
      pool.query("SELECT * FROM tb_users where email=$1", [email] , function(error,result) {
      console.log("Row count: %d",result.rows.length);  // n

      if(error){
          console.log(error)
      }

      resolve(result.rows.length);
      });
  });

  cekMail.then(function (resolve, reject) {

    console.log(resolve);

    res.render('login/register',{

      layout: 'login/layout',
      mailStatus: resolve,
    });

  });

Body:
You are not returning the value from the function (you are in the query callback). I have not tested this, but it should work like that:

const checkMail = async function(regEmail, fn){
  var rowCount = 0;
  await pool.query("SELECT * FROM tb_users where email=$1", [regEmail] ,(err, result) =>{

    console.log('inside : '+result.rowCount);
    fn(result.rowCount);
    return result.rowCount;
  });

}

var cekMailres = checkMail(email, function(rowCount){
    console.log('Outside: ' + rowCount);
}).then(function () {
    //do nothing
}).catch(function () {
    //do nothing
});


问:
Is there a way to import external scripts in Flutter WebView
I'm trying to load an external script into Flutter WebView, but it doesn't seem to work. It's about tinyMCE in particular. So the intention is to open a rich text editor in an AlertDialog with WebView inside. Is that possible?

The following is my html:

```<code><html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/5.2.1/tinymce.min.js"></script>
</head>
<body>
<textarea id="test"></textarea>
<script>
  tinymce.init({
    selector: 'textarea#test',
    height: 500,
    menubar: false,
    plugins: [
      'advlist autolink lists link image charmap print preview anchor',
      'searchreplace visualblocks code fullscreen',
      'insertdatetime media table paste code help wordcount'
    ],
    toolbar: 'undo redo | formatselect | ' +
    'bold italic backcolor | alignleft aligncenter ' +
    'alignright alignjustify | bullist numlist outdent indent | ' +
    'removeformat | help',
  });
</script>
</body>
</html>
</code>```

And that's my widget:

```<code>import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class RichTextEditor extends StatefulWidget {
  final String html;

  const RichTextEditor({
    this.html: '',
  });

  @override
  RichTextEditorState createState() => RichTextEditorState();
}

class RichTextEditorState extends State<RichTextEditor> {
  WebViewController _webViewController;

  @override
  Widget build(BuildContext context) {
    final String source = Uri.dataFromString(
      widget.html,
      mimeType: 'text/html',
      encoding: Encoding.getByName('utf-8'),
    ).toString();

    return Container(
      child: Material(
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                IconButton(
                  icon: Icon(Icons.close),
                  onPressed: () => Navigator.of(context).pop(),
                ),
              ],
              mainAxisAlignment: MainAxisAlignment.end,
            ),
            Expanded(
              child: WebView(
                initialUrl: source,
                javascriptMode: JavascriptMode.unrestricted,
                onWebViewCreated: (WebViewController controller) {
                  _webViewController = controller;
                  _webViewController.loadUrl(source);
                },
              ),
            ),
          ],
        ),
      ),
      padding: EdgeInsets.all(10.0),
    );
  }

  @override
  void initState() {
    super.initState();
  }
}
</code>```

I get the following logs in the console:

```<code>D/cr_Ime  (30910): [InputMethodManagerWrapper.java:30] Constructor
W/cr_AwContents(30910): onDetachedFromWindow called when already detached. Ignoring
D/cr_Ime  (30910): [InputMethodManagerWrapper.java:59] isActive: false
I/cr_Ime  (30910): ImeThread is not enabled.
D/EGL_emulation(30910): eglMakeCurrent: 0x8a0f4ca0: ver 2 0 (tinfo 0x8976d190)
W/cr_BindingManager(30910): Cannot call determinedVisibility() - never saw a connection for the pid: 30910
D/cr_Ime  (30910): [InputMethodManagerWrapper.java:59] isActive: true
D/cr_Ime  (30910): [InputMethodManagerWrapper.java:68] hideSoftInputFromWindow
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
D/EGL_emulation(30910): eglMakeCurrent: 0xb1e05240: ver 2 0 (tinfo 0xb1e03310)
W/cr_BindingManager(30910): Cannot call determinedVisibility() - never saw a connection for the pid: 30910
D/cr_Ime  (30910): [InputMethodManagerWrapper.java:59] isActive: true
D/cr_Ime  (30910): [InputMethodManagerWrapper.java:68] hideSoftInputFromWindow
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
I/art     (30910): Background sticky concurrent mark sweep GC freed 12(424B) AllocSpace objects, 0(0B) LOS objects, 0% free, 22MB/22MB, paused 10.801ms total 19.097ms
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
I/chromium(30910): [INFO:CONSOLE(9)] "Failed to initialize the editor as the document is not in standards mode. TinyMCE requires standards mode.", source: https://cdnjs.cloudflare.com/ajax/libs/tinymce/5.2.1/tinymce.min.js (9)
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
</code>```

Any help would be much appreciated. Thanks!

答:
To make TinyMCE work, you need to add also <!DOCTYPE html> at the start of your HTML (see https://community.tiny.cloud/communityQuestion?id=9064N000000MvpyQAC).

You can also try my plugin flutter_inappwebview if it doesn't work with webview_flutter.
It's a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

Here is an example using initialData: InAppWebViewInitialData() attribute to inject an initial HTML string inside the WebView:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
              Expanded(
                  child: InAppWebView(
                    initialData: InAppWebViewInitialData(data: """
<!DOCTYPE html>

<textarea id="test"></textarea>

"""),
                    initialHeaders: {},
                    initialOptions: InAppWebViewGroupOptions(
                      crossPlatform: InAppWebViewOptions(
                        debuggingEnabled: true,
                      ),
                      android: AndroidInAppWebViewOptions(
                        builtInZoomControls: true
                      )
                    ),
                    onWebViewCreated: (InAppWebViewController controller) {
                      webView = controller;
                    },
                    onLoadStart: (InAppWebViewController controller, String url) {

                    },
                    onLoadStop: (InAppWebViewController controller, String url) {

                    }
                  ))
            ])),
      ),
    );
  }
}
```

Screenshot:

Body:
I'm trying to load an external script into Flutter WebView, but it doesn't seem to work. It's about tinyMCE in particular. So the intention is to open a rich text editor in an AlertDialog with WebView inside. Is that possible?

The following is my html:

<textarea id="test"></textarea>

And that's my widget:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class RichTextEditor extends StatefulWidget {
  final String html;

  const RichTextEditor({
    this.html: '',
  });

  @override
  RichTextEditorState createState() => RichTextEditorState();
}

class RichTextEditorState extends State<RichTextEditor> {
  WebViewController _webViewController;

  @override
  Widget build(BuildContext context) {
    final String source = Uri.dataFromString(
      widget.html,
      mimeType: 'text/html',
      encoding: Encoding.getByName('utf-8'),
    ).toString();

    return Container(
      child: Material(
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                IconButton(
                  icon: Icon(Icons.close),
                  onPressed: () => Navigator.of(context).pop(),
                ),
              ],
              mainAxisAlignment: MainAxisAlignment.end,
            ),
            Expanded(
              child: WebView(
                initialUrl: source,
                javascriptMode: JavascriptMode.unrestricted,
                onWebViewCreated: (WebViewController controller) {
                  _webViewController = controller;
                  _webViewController.loadUrl(source);
                },
              ),
            ),
          ],
        ),
      ),
      padding: EdgeInsets.all(10.0),
    );
  }

  @override
  void initState() {
    super.initState();
  }
}

I get the following logs in the console:

D/cr_Ime  (30910): [InputMethodManagerWrapper.java:30] Constructor
W/cr_AwContents(30910): onDetachedFromWindow called when already detached. Ignoring
D/cr_Ime  (30910): [InputMethodManagerWrapper.java:59] isActive: false
I/cr_Ime  (30910): ImeThread is not enabled.
D/EGL_emulation(30910): eglMakeCurrent: 0x8a0f4ca0: ver 2 0 (tinfo 0x8976d190)
W/cr_BindingManager(30910): Cannot call determinedVisibility() - never saw a connection for the pid: 30910
D/cr_Ime  (30910): [InputMethodManagerWrapper.java:59] isActive: true
D/cr_Ime  (30910): [InputMethodManagerWrapper.java:68] hideSoftInputFromWindow
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
D/EGL_emulation(30910): eglMakeCurrent: 0xb1e05240: ver 2 0 (tinfo 0xb1e03310)
W/cr_BindingManager(30910): Cannot call determinedVisibility() - never saw a connection for the pid: 30910
D/cr_Ime  (30910): [InputMethodManagerWrapper.java:59] isActive: true
D/cr_Ime  (30910): [InputMethodManagerWrapper.java:68] hideSoftInputFromWindow
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
I/art     (30910): Background sticky concurrent mark sweep GC freed 12(424B) AllocSpace objects, 0(0B) LOS objects, 0% free, 22MB/22MB, paused 10.801ms total 19.097ms
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
I/chromium(30910): [INFO:CONSOLE(9)] "Failed to initialize the editor as the document is not in standards mode. TinyMCE requires standards mode.", source: https://cdnjs.cloudflare.com/ajax/libs/tinymce/5.2.1/tinymce.min.js (9)
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread
W/art     (30910): Attempt to remove non-JNI local reference, dumping thread

Any help would be much appreciated. Thanks!

Body:
To make TinyMCE work, you need to add also <!DOCTYPE html> at the start of your HTML (see https://community.tiny.cloud/communityQuestion?id=9064N000000MvpyQAC).

You can also try my plugin flutter_inappwebview if it doesn't work with webview_flutter.
It's a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

Here is an example using initialData: InAppWebViewInitialData() attribute to inject an initial HTML string inside the WebView:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
              Expanded(
                  child: InAppWebView(
                    initialData: InAppWebViewInitialData(data: """
<!DOCTYPE html>
<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/5.2.1/tinymce.min.js"></script>
</head>
<body>
<textarea id="test"></textarea>
<script>
  tinymce.init({
    selector: 'textarea#test',
    height: 500,
    menubar: false,
    plugins: [
      'advlist autolink lists link image charmap print preview anchor',
      'searchreplace visualblocks code fullscreen',
      'insertdatetime media table paste code help wordcount'
    ],
    toolbar: 'undo redo | formatselect | ' +
    'bold italic backcolor | alignleft aligncenter ' +
    'alignright alignjustify | bullist numlist outdent indent | ' +
    'removeformat | help',
  });
</script>
</body>
</html>
"""),
                    initialHeaders: {},
                    initialOptions: InAppWebViewGroupOptions(
                      crossPlatform: InAppWebViewOptions(
                        debuggingEnabled: true,
                      ),
                      android: AndroidInAppWebViewOptions(
                        builtInZoomControls: true
                      )
                    ),
                    onWebViewCreated: (InAppWebViewController controller) {
                      webView = controller;
                    },
                    onLoadStart: (InAppWebViewController controller, String url) {

                    },
                    onLoadStop: (InAppWebViewController controller, String url) {

                    }
                  ))
            ])),
      ),
    );
  }
}

Screenshot:


问:
Anchor tag not working properly. When I open the webpage it behaves like a simple text not as a link
This link in the code is redirecting me to google instead it behaves as a plain text.

Forgot Password

<!DOCTYPE>

        <title>Messages</title>

This is a message.

This is a good message.

This is a warning message.

       /*This anchor tag is not working*/

        Forgot Password?

```

答:
There is a typo.
Change herf to href.

<!DOCTYPE>

        <title>Messages</title>

This is a message.

This is a good message.

This is a warning message.

       /*This anchor tag is not working*/

        Forgot Password?

```

Body:
There is a typo.
Change herf to href.

<!DOCTYPE>
<html>
    <head>

        <title>Messages</title>
        <!-- <link rel="stylesheet" href="mystyle1.css" type="text/css"> -->

    </head>
    <body>

        <div class = message id = neutral>This is a message.</div>
        <div class = message id = good>This is a good message.</div>
        <div class = message id = warning>This is a warning message.</div>
        <hr />
       /*This anchor tag is not working*/<br>
        <a href = "https://www.google.com">Forgot Password?</a>
    </body>

</html>


问:
using XPath to find node under a context node does not work (firefox/firebug/javascript)
I want to extract information from a web page.

The page has m nodes, which can be found by .evaluate("//div[@class='news']", document, ....).

For each of the above nodes, there are 3 nodes inside them. Each of them has different @class selector. And I want to extract these m 3-tuple records.

I tried to use .evaluate() function as instructed in

https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript

by using this code

```<code>parentNodes = document.evaluate("//div[@class='news']", document, ....).
while (true){
   var node = parentNodes.iterateNext();
   var child = document.evaluate("//div[@class='title']", node, ....).
   ...
}
</code>```

However, "child" is always assigned to the first node in the document, instead of the first node within "node".

I ran this in firebug console.

Does any one know what's wrong?

答:
Use .// instead of //.

Explanation from the XML Path Language specification (XPath), Version 1.0:

//para selects all the para descendants of the document root and thus selects all para elements in the same document as the context
  node

. selects the context node

.//para selects the para element descendants of the context node

The current top answer is wrong in that there is no way to call .evaluate on any other object, but document. document.evaluate is correct.

ContentLicense: CC BY-SA 2.5

Body:
I want to extract information from a web page.

The page has m nodes, which can be found by .evaluate("//div[@class='news']", document, ....).

For each of the above nodes, there are 3 nodes inside them. Each of them has different @class selector. And I want to extract these m 3-tuple records.

I tried to use .evaluate() function as instructed in

https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript

by using this code

parentNodes = document.evaluate("//div[@class='news']", document, ....).
while (true){
   var node = parentNodes.iterateNext();
   var child = document.evaluate("//div[@class='title']", node, ....).
   ...
}

However, "child" is always assigned to the first node in the document, instead of the first node within "node".

I ran this in firebug console.

Does any one know what's wrong?


问:
I wrote x86-64 Assembly. But it's not working under Windows, only on OnlineGDB (Linux)
I wrote a x86-64 code in Assembly Language. The output is 17.

```<code>    .text
.LC0:
    .string "%d\n"
printint:
    pushq   %rbp
    movq    %rsp, %rbp
    subq    $16, %rsp
    movl    %edi, -4(%rbp)
    movl    -4(%rbp), %eax
    movl    %eax, %esi
    leaq    .LC0(%rip), %rdi
    movl    $0, %eax
    call    printf@PLT
    nop
    leave
    ret

    .globl  main
    .type   main, @function
main:
    pushq   %rbp
    movq    %rsp, %rbp
    movq    $2, %r8
    movq    $3, %r9
    movq    $5, %r10
    imulq   %r9, %r10
    addq    %r8, %r10
    movq    $8, %r8
    movq    $3, %r9
    movq    %r8,%rax
    cqo
    idivq   %r9
    movq    %rax,%r8
    subq    %r10, %r8
    movq    %r10, %rdi
    call    printint
    movl    $0, %eax
    popq    %rbp
    ret

</code>```

When i Compile this wth GCC, I got this errors.

```<code>out.s: Assembler messages:
out.s:5: Error: bad register name `%rbp'
out.s:6: Error: bad register name `%rsp'
out.s:7: Error: bad register name `%rsp'
out.s:8: Error: bad register name `%rbp)'
out.s:9: Error: bad register name `%rbp)'
out.s:11: Error: bad register name `%rip)'
out.s:19: Warning: .type pseudo-op used outside of .def/.endef: ignored.
out.s:19: Error: junk at end of line, first unrecognized character is `m'
out.s:21: Error: bad register name `%rbp'
out.s:22: Error: bad register name `%rsp'
out.s:23: Error: bad register name `%r8'
out.s:24: Error: bad register name `%r9'
out.s:25: Error: bad register name `%r10'
out.s:26: Error: bad register name `%r9'
out.s:27: Error: bad register name `%r8'
out.s:28: Error: bad register name `%r8'
out.s:29: Error: bad register name `%r9'
out.s:30: Error: bad register name `%r8'
out.s:31: Error: `cqo' is only supported in 64-bit mode
out.s:32: Error: bad register name `%r9'
out.s:33: Error: bad register name `%rax'
out.s:34: Error: bad register name `%r10'
out.s:35: Error: bad register name `%r10'
out.s:38: Error: bad register name `%rbp'
</code>```

Similarly when I did this in NASM, I got the following errors.

```<code>out.s:1: warning: label alone on a line without a colon might be in error [-w+orphan-labels]
out.s:3: error: parser: instruction expected
out.s:5: error: parser: instruction expected
out.s:6: error: expression syntax error
out.s:7: error: parser: instruction expected
out.s:8: error: parser: instruction expected
out.s:9: error: parser: instruction expected
out.s:10: error: parser: instruction expected
out.s:11: error: parser: instruction expected
out.s:12: error: parser: instruction expected
out.s:18: error: parser: instruction expected
out.s:19: error: parser: instruction expected
out.s:21: error: label `pushq' inconsistently redefined
out.s:5: note: label `pushq' originally defined here
out.s:21: error: parser: instruction expected
out.s:22: error: expression syntax error
out.s:23: error: expression syntax error
out.s:24: error: expression syntax error
out.s:25: error: expression syntax error
out.s:26: error: parser: instruction expected
out.s:27: error: parser: instruction expected
out.s:28: error: expression syntax error
out.s:29: error: expression syntax error
out.s:30: error: expression syntax error
out.s:32: error: parser: instruction expected
out.s:33: error: expression syntax error
out.s:34: error: label `subq' inconsistently redefined
out.s:7: note: label `subq' originally defined here
out.s:34: error: parser: instruction expected
out.s:35: error: expression syntax error
out.s:37: error: label `movl' inconsistently redefined
out.s:8: note: label `movl' originally defined here
out.s:37: error: parser: instruction expected
out.s:38: error: parser: instruction expected
</code>```

But when i went to https://www.onlinegdb.com/online_gcc_assembler and compiled it, I got the correct answer (17).

I'm still learning assembly language. I searched for an answer, but could not found one. Can you explain the reason for this ?

Details about my Laptop

AMD RYZEN 5 Processor ( x64 Based )

64bit Windows 10

答:
out.s:31: Error: 'cqo' is only supported in 64-bit mode tells you that you tried to assemble this 64-bit code in 32-bit mode.  Perhaps you tried to use mingw32 under Windows, instead of 64-bit mingw?

This code is for x86-64 GNU/Linux: note the calling convention passing args in RDI, RSI, and use of @plt.  DLLs don't use a PLT, that's a GNU/Linux thing (traditional dynamic linking, not new style gcc -fno-plt with early instead of lazy binding).  That's why it works in OnlineGDB, which uses x86-64 GNU/Linux.

It won't work under 64-bit Windows, except inside WSL.  Even Cygwin 64 is a source compatiblity layer, not binary / ABI / calling convention.

Also, it's written in AT&T syntax with GAS directives.  NASM uses Intel syntax with different directives; no wonder nearly every single line is an error when you try to assemble it with nasm -fwin64.

Body:
I wrote a x86-64 code in Assembly Language. The output is 17.

    .text
.LC0:
    .string "%d\n"
printint:
    pushq   %rbp
    movq    %rsp, %rbp
    subq    $16, %rsp
    movl    %edi, -4(%rbp)
    movl    -4(%rbp), %eax
    movl    %eax, %esi
    leaq    .LC0(%rip), %rdi
    movl    $0, %eax
    call    printf@PLT
    nop
    leave
    ret

    .globl  main
    .type   main, @function
main:
    pushq   %rbp
    movq    %rsp, %rbp
    movq    $2, %r8
    movq    $3, %r9
    movq    $5, %r10
    imulq   %r9, %r10
    addq    %r8, %r10
    movq    $8, %r8
    movq    $3, %r9
    movq    %r8,%rax
    cqo
    idivq   %r9
    movq    %rax,%r8
    subq    %r10, %r8
    movq    %r10, %rdi
    call    printint
    movl    $0, %eax
    popq    %rbp
    ret

When i Compile this wth GCC, I got this errors.

out.s: Assembler messages:
out.s:5: Error: bad register name `%rbp'
out.s:6: Error: bad register name `%rsp'
out.s:7: Error: bad register name `%rsp'
out.s:8: Error: bad register name `%rbp)'
out.s:9: Error: bad register name `%rbp)'
out.s:11: Error: bad register name `%rip)'
out.s:19: Warning: .type pseudo-op used outside of .def/.endef: ignored.
out.s:19: Error: junk at end of line, first unrecognized character is `m'
out.s:21: Error: bad register name `%rbp'
out.s:22: Error: bad register name `%rsp'
out.s:23: Error: bad register name `%r8'
out.s:24: Error: bad register name `%r9'
out.s:25: Error: bad register name `%r10'
out.s:26: Error: bad register name `%r9'
out.s:27: Error: bad register name `%r8'
out.s:28: Error: bad register name `%r8'
out.s:29: Error: bad register name `%r9'
out.s:30: Error: bad register name `%r8'
out.s:31: Error: `cqo' is only supported in 64-bit mode
out.s:32: Error: bad register name `%r9'
out.s:33: Error: bad register name `%rax'
out.s:34: Error: bad register name `%r10'
out.s:35: Error: bad register name `%r10'
out.s:38: Error: bad register name `%rbp'

Similarly when I did this in NASM, I got the following errors.

out.s:1: warning: label alone on a line without a colon might be in error [-w+orphan-labels]
out.s:3: error: parser: instruction expected
out.s:5: error: parser: instruction expected
out.s:6: error: expression syntax error
out.s:7: error: parser: instruction expected
out.s:8: error: parser: instruction expected
out.s:9: error: parser: instruction expected
out.s:10: error: parser: instruction expected
out.s:11: error: parser: instruction expected
out.s:12: error: parser: instruction expected
out.s:18: error: parser: instruction expected
out.s:19: error: parser: instruction expected
out.s:21: error: label `pushq' inconsistently redefined
out.s:5: note: label `pushq' originally defined here
out.s:21: error: parser: instruction expected
out.s:22: error: expression syntax error
out.s:23: error: expression syntax error
out.s:24: error: expression syntax error
out.s:25: error: expression syntax error
out.s:26: error: parser: instruction expected
out.s:27: error: parser: instruction expected
out.s:28: error: expression syntax error
out.s:29: error: expression syntax error
out.s:30: error: expression syntax error
out.s:32: error: parser: instruction expected
out.s:33: error: expression syntax error
out.s:34: error: label `subq' inconsistently redefined
out.s:7: note: label `subq' originally defined here
out.s:34: error: parser: instruction expected
out.s:35: error: expression syntax error
out.s:37: error: label `movl' inconsistently redefined
out.s:8: note: label `movl' originally defined here
out.s:37: error: parser: instruction expected
out.s:38: error: parser: instruction expected

But when i went to https://www.onlinegdb.com/online_gcc_assembler and compiled it, I got the correct answer (17).

I'm still learning assembly language. I searched for an answer, but could not found one. Can you explain the reason for this ?

Details about my Laptop

AMD RYZEN 5 Processor ( x64 Based )

64bit Windows 10


问:
Troubles extract data from json with PostgreSQL
I have a text column like this:

```<code>{
   "addFee":0,
   "addFeeTotal":0,
   "addFeeType":0,
   "addFeeUsers":0,
   "addFeeVat":0,
   "addFeeYears":0,
   "priceTotal":0,
   "unit1":"db",
   "unit1Value":5,
   "unit2":null,
   "unit2Value":0
}
</code>```

I'd like list the priceTotal values, but

I got "cannot extract elements from a scalar" for this:

```<code>select p
from web.order_details,
   jsonb_array_elements_text(calculatedproductprice::jsonb -> 'priceTotal') as p
</code>```

And got "function jsonb_array_elements_text(text) does not exist" for this:

```<code>select js ->> 'priceTotal' as p
from web.order_details,
   jsonb_array_elements_text(calculatedproductprice) as js
</code>```

I ran out of ideas, but maybe this is not a valid json data?

答:
Well, your JSON isn't an array, so obviously jsonb_array_elements isn't the right function to use.

As the key you are interested in, is a top-level key, you don't need anything else than just the ->> operator:

```<code>select calculatedproductprice::jsonb -> 'priceTotal' as price_total
from web.order_details
</code>```

Body:
I have a text column like this:

{
   "addFee":0,
   "addFeeTotal":0,
   "addFeeType":0,
   "addFeeUsers":0,
   "addFeeVat":0,
   "addFeeYears":0,
   "priceTotal":0,
   "unit1":"db",
   "unit1Value":5,
   "unit2":null,
   "unit2Value":0
}

I'd like list the priceTotal values, but

I got "cannot extract elements from a scalar" for this:

select p
from web.order_details,
   jsonb_array_elements_text(calculatedproductprice::jsonb -> 'priceTotal') as p

And got "function jsonb_array_elements_text(text) does not exist" for this:

select js ->> 'priceTotal' as p
from web.order_details,
   jsonb_array_elements_text(calculatedproductprice) as js

I ran out of ideas, but maybe this is not a valid json data?

Body:
Well, your JSON isn't an array, so obviously jsonb_array_elements isn't the right function to use.

As the key you are interested in, is a top-level key, you don't need anything else than just the ->> operator:

select calculatedproductprice::jsonb -> 'priceTotal' as price_total
from web.order_details


问:
reading content of .aspx using javascript
i am using javascript to read the content of .aspx page. but i am not able to read it. i am using javascript as:

```<code>function edit(headtext,totext, bodytext, footertext){
        alert('lll');
         //var xmlDoc=new ActiveXObject("MSXML.DOMDocument");
         xmlDoc.async="false";
         xmlDoc.load("theme3ex.aspx");
         var students = xmlDoc.documentElement;
         alert('0000');
         var student = students.childNodes(0);
         document.getElementById('txtareahead').innerHTML = headtext;
         document.getElementById('txtareato').innerHTML = totext;
         document.getElementById('txtareabody').innerHTML = bodytext;
         document.getElementById('txtareafooter').innerHTML = footertext;
         location.href = "MailSender.aspx";
         }
</code>```

is there any problem eith my javascript..

答:
First problem is that you've commented out the line which creates the AJAX object, so none of the subsequent code will work because they're trying to access an object which doesn't exist.

Second problem is that even if you uncomment that line, it's using Activex/MSXML which will only work with IE (and even then only older versions of IE).

In short, your code isn't good, and needs to be entirely redone rather than being fixed.

My recommendation is that you find a more up-to-date example of how to do AJAX code. Possibly even just use a good quality Javascript library like JQuery.

ContentLicense: CC BY-SA 3.0

Body:
i am using javascript to read the content of .aspx page. but i am not able to read it. i am using javascript as:

function edit(headtext,totext, bodytext, footertext){
        alert('lll');
         //var xmlDoc=new ActiveXObject("MSXML.DOMDocument");
         xmlDoc.async="false";
         xmlDoc.load("theme3ex.aspx");
         var students = xmlDoc.documentElement;
         alert('0000');
         var student = students.childNodes(0);
         document.getElementById('txtareahead').innerHTML = headtext;
         document.getElementById('txtareato').innerHTML = totext;
         document.getElementById('txtareabody').innerHTML = bodytext;
         document.getElementById('txtareafooter').innerHTML = footertext;
         location.href = "MailSender.aspx";
         }

is there any problem eith my javascript..


问:
Tkinter flush buttons next to each other
This has been asked before but I cant seem to figure out how to use the previous answers for my solution as it isn't working. I want to get 2 buttons flushed to the north west, and one RUN button flushed at the south west.

However, I get but buttons very spaced out, possibly because of the row size of the text field beside it. How do I fix this? I've attached current result as well as intended outcome

Code Result

Intended Outcome

Bad photo edit, the run button is supposed to be 2x bigger than the other buttons

Current Code

```<code>from tkinter import scrolledtext
import sys
from tkinter import filedialog
import tkinter
import datetime

class MyApp(object):
    """"""
    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        self.root = parent
        self.root.title("test program")

        self.frame = tkinter.Frame(parent)
        #self.frame.pack()

        self.frame.grid(column=0,row=0)
        enforcement_btn = tkinter.Button(self.frame,
                             text="File 1")
        icare_btn = tkinter.Button(self.frame,
                             text="File 2")
        run_btn = tkinter.Button(self.frame,
                             text="RUN")

        enforcement_btn.grid(column=1,row=0, sticky='NW')
        icare_btn.grid(column=1,row=1, sticky='NW')
        run_btn.grid(column=1,row=2,sticky='SW')

        self.text = scrolledtext.ScrolledText(self.frame)
        self.text.grid(column=2,row=0,sticky='WENS',columnspan=2,rowspan=2)
        self.init_text()
    #----------------------------------------------------------------------

    def init_text(self):
        print("Console Test")

#----------------------------------------------------------------------
if __name__ == "__main__":
    root = tkinter.Tk()
    root.geometry("600x300")
    app = MyApp(root)
    root.mainloop()
</code>```

All help is much appreciated, thank you! :)

答:
make row 2 to expand:

```<code>self.frame.rowconfigure(2, weight=1)
</code>```

change rowspan of self.text from 2 to 3:

```<code>self.text.grid(column=2, row=0, sticky='WENS', columnspan=2, rowspan=3)
</code>```

Body:
This has been asked before but I cant seem to figure out how to use the previous answers for my solution as it isn't working. I want to get 2 buttons flushed to the north west, and one RUN button flushed at the south west.

However, I get but buttons very spaced out, possibly because of the row size of the text field beside it. How do I fix this? I've attached current result as well as intended outcome

Code Result

Intended Outcome

Bad photo edit, the run button is supposed to be 2x bigger than the other buttons

Current Code

from tkinter import scrolledtext
import sys
from tkinter import filedialog
import tkinter
import datetime

class MyApp(object):
    """"""
    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        self.root = parent
        self.root.title("test program")

        self.frame = tkinter.Frame(parent)
        #self.frame.pack()

        self.frame.grid(column=0,row=0)
        enforcement_btn = tkinter.Button(self.frame,
                             text="File 1")
        icare_btn = tkinter.Button(self.frame,
                             text="File 2")
        run_btn = tkinter.Button(self.frame,
                             text="RUN")

        enforcement_btn.grid(column=1,row=0, sticky='NW')
        icare_btn.grid(column=1,row=1, sticky='NW')
        run_btn.grid(column=1,row=2,sticky='SW')

        self.text = scrolledtext.ScrolledText(self.frame)
        self.text.grid(column=2,row=0,sticky='WENS',columnspan=2,rowspan=2)
        self.init_text()
    #----------------------------------------------------------------------

    def init_text(self):
        print("Console Test")

#----------------------------------------------------------------------
if __name__ == "__main__":
    root = tkinter.Tk()
    root.geometry("600x300")
    app = MyApp(root)
    root.mainloop()

All help is much appreciated, thank you! :)

Body:
make row 2 to expand:

self.frame.rowconfigure(2, weight=1)

change rowspan of self.text from 2 to 3:

self.text.grid(column=2, row=0, sticky='WENS', columnspan=2, rowspan=3)


问:
mat-icon is not a known element in angular
I am trying to use an angular material icon for add but I get this error
 'mat-icon' is not a known element:
    1. If 'mat-icon' is an Angular component, then verify that it is part of this module.
    2. If 'mat-icon' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

the structure of my project is like this I have a modules folder that contains a dashboard folder and I have a folder named shared that it has it owns module.
this is my dashboard code

```<code><div class="search-div">
  <button mat-raised-button  (click)="onCreate()">
    <mat-icon>add</mat-icon> Create
  </button>
</div>
</code>```

this is my app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DefaultModule } from './layouts/default/default.module';
import { MatTableModule } from '@angular/material/table';
import { HttpClientModule } from '@angular/common/http';
import {UserInfoService} from './services/user-info.service'
import {MatCardModule} from '@angular/material/card';
import {MatDialogModule} from '@angular/material/dialog';
import { PostsComponent } from './modules/posts/posts.component';
import {  MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { NewuserComponent } from './modules/newuser/newuser.component';
import { DashboardComponent } from './modules/dashboard/dashboard.component';

@NgModule({
  declarations: [
    AppComponent,
    NewuserComponent,

  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    DefaultModule,
    MatTableModule,
    HttpClientModule,
    MatCardModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    MatIconModule,
    FormsModule,
    ReactiveFormsModule
  ],

  providers: [UserInfoService],
  bootstrap: [AppComponent],
  entryComponents:[NewuserComponent]
})
export class AppModule { }
</code>```

how can i fix that error?

答:
I think the problem is with your folder structure.
In app folder, create both components newuser and dashboard. no need to create any module for newuser or dashboard otherwise if you create any module for both of them, then you have to import the things in their particular module. You have a working code, just structured it properly.</p>

Body:
I am trying to use an angular material icon for add but I get this error
 'mat-icon' is not a known element:
    1. If 'mat-icon' is an Angular component, then verify that it is part of this module.
    2. If 'mat-icon' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

the structure of my project is like this I have a modules folder that contains a dashboard folder and I have a folder named shared that it has it owns module.
this is my dashboard code

  <button mat-raised-button  (click)="onCreate()">
    <mat-icon>add</mat-icon> Create
  </button>

this is my app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DefaultModule } from './layouts/default/default.module';
import { MatTableModule } from '@angular/material/table';
import { HttpClientModule } from '@angular/common/http';
import {UserInfoService} from './services/user-info.service'
import {MatCardModule} from '@angular/material/card';
import {MatDialogModule} from '@angular/material/dialog';
import { PostsComponent } from './modules/posts/posts.component';
import {  MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { NewuserComponent } from './modules/newuser/newuser.component';
import { DashboardComponent } from './modules/dashboard/dashboard.component';

@NgModule({
  declarations: [
    AppComponent,
    NewuserComponent,

  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    DefaultModule,
    MatTableModule,
    HttpClientModule,
    MatCardModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    MatIconModule,
    FormsModule,
    ReactiveFormsModule
  ],

  providers: [UserInfoService],
  bootstrap: [AppComponent],
  entryComponents:[NewuserComponent]
})
export class AppModule { }

how can i fix that error?


问:
vectorized method to count number of special instances in numpy array
Let's say I have an array that is

test = np.array([0,2,1,5,3,6,10,0,0,3,2,3,0,0,7,3,6,2,0,0,3,5,4,6])

What I want to know is the number of times when the next value is non-zero when the previous value is zero; so for the above array I should have 4.

I wrote a function that does that but it is performing very slow. Is there any vectorized function that I should re-write it into?

```<code>def count_instance(array):
    return int(array[0] > 0) + sum(int(array[i] > 0 and array[i-1] == 0) for i in range(1,array.shape[0]))
</code>```

答:
One-liner with slicing -

```<code>((test[:-1]==0) & (test[1:]!=0)).sum()
</code>```

Another way with re-usage of the same mask -

```<code>m = test==0
((m[:-1]) & (~m[1:])).sum()
</code>```

Body:
Let's say I have an array that is

test = np.array([0,2,1,5,3,6,10,0,0,3,2,3,0,0,7,3,6,2,0,0,3,5,4,6])

What I want to know is the number of times when the next value is non-zero when the previous value is zero; so for the above array I should have 4.

I wrote a function that does that but it is performing very slow. Is there any vectorized function that I should re-write it into?

def count_instance(array):
    return int(array[0] > 0) + sum(int(array[i] > 0 and array[i-1] == 0) for i in range(1,array.shape[0]))

Body:
One-liner with slicing -

((test[:-1]==0) & (test[1:]!=0)).sum()

Another way with re-usage of the same mask -

m = test==0
((m[:-1]) & (~m[1:])).sum()


问:
Variable in Jupyter Notebook only works within the cell
I have a variable that I use in one cell of the jupyter but when I call it in the next cell it says the variable cannot be found

I've tried creating an instance of the variable before reading the data from the son file. I've tried creating another variable the same as the first and using that one in the next cell.

```<code>if os.path.isfile("cointegration.json"):
    with open("cointegration.json", "r") as f:
        cointegration_mv = json.load(f)
else:
    cointegration_mv = {}
    for i in range(0, len(usd_pairs)):
        pair_i = usd_pairs[i]
        print(pair_i)
        for j in range(0, i):
            pair_j = usd_pairs[j]
            print("\t+",pair_j)
            if pair_i != pair_j:
                code = pair_i + '_' + pair_j
                print("\t\t=",code)
                cointegration_mv[code] =  get_cointegration(pair_i, pair_j)

    json = json.dumps(cointegration_mv)
    f = open("cointegration.json","w")
    f.write(json)
    f.close()

print(cointegration_mv.keys())

#This does print the keys

#The next cell
print(cointegration_mv.keys())
</code>```

The error is:

```<code>NameError                                 Traceback (most recent call last)
<ipython-input-15-7abb854e8cc9> in <module>
----> 1 print(cointegration_mv.keys())

NameError: name 'cointegration_mv' is not defined
</code>```

This happens even when I create an instance of the variable before reading in the data (so I'd expect the keys to just be empty), and when I try duplicating the variable and passing the duplicate.

答:
May be that variable declared in first cell is in local scope.Thats why when calling in second cell giving not defined as error.
try putting your code in function in first cell and then  call that function in second cell</p>

Body:
I have a variable that I use in one cell of the jupyter but when I call it in the next cell it says the variable cannot be found

I've tried creating an instance of the variable before reading the data from the son file. I've tried creating another variable the same as the first and using that one in the next cell.

if os.path.isfile("cointegration.json"):
    with open("cointegration.json", "r") as f:
        cointegration_mv = json.load(f)
else:
    cointegration_mv = {}
    for i in range(0, len(usd_pairs)):
        pair_i = usd_pairs[i]
        print(pair_i)
        for j in range(0, i):
            pair_j = usd_pairs[j]
            print("\t+",pair_j)
            if pair_i != pair_j:
                code = pair_i + '_' + pair_j
                print("\t\t=",code)
                cointegration_mv[code] =  get_cointegration(pair_i, pair_j)

    json = json.dumps(cointegration_mv)
    f = open("cointegration.json","w")
    f.write(json)
    f.close()

print(cointegration_mv.keys())

#This does print the keys

#The next cell
print(cointegration_mv.keys())

The error is:

NameError                                 Traceback (most recent call last)
<ipython-input-15-7abb854e8cc9> in <module>
----> 1 print(cointegration_mv.keys())

NameError: name 'cointegration_mv' is not defined

This happens even when I create an instance of the variable before reading in the data (so I'd expect the keys to just be empty), and when I try duplicating the variable and passing the duplicate.


问:
How to fill column based on value of other column in dataframe?
I am trying to fill the column based on some condition. Can you please help me how to do this?

Example:

df:

```<code>   Name  Age
0   Tom   20
1  nick   21
2  nick   19
3  jack   18
4  shiv   21
5  shiv   22
6  jim    23
</code>```

I have created the dataframe with one more column:
df['New'] = df['Name'].shift()

```<code>   Name  Age  New
0   Tom   20  NaN
1  nick   21  Tom
2  nick   19  nick
3  jack   18  nick
4  shiv   21  jack
5  shiv   22  shiv
6  jim    23  shiv
</code>```

Expected Output:

```<code>   Name  Age  New  order
0   Tom   20  NaN   1
1  nick   21  Tom   2
2  nick   19  nick  2
3  jack   18  nick  3
4  shiv   21  jack  4
5  shiv   22  shiv  4
6  jim    23  shiv  5
</code>```

condition :
if Name is matching the New column then check the previous row number and fill the number same number else fill the next number.
It is quiet similar like dense_rank() but I don't want to use dense_rank concept here. So is there any way to fill this column?

答:
Using .cumsum() over boolean Series:

```<code>df['order'] = (df['Name'] != df['Name'].shift()).cumsum()

print(df)
</code>```

Prints:

```<code>   Name  Age  order
0   Tom   20      1
1  nick   21      2
2  nick   19      2
3  jack   18      3
4  shiv   21      4
5  shiv   22      4
6   jim   23      5
</code>```

Body:
I am trying to fill the column based on some condition. Can you please help me how to do this?

Example:

df:

   Name  Age
0   Tom   20
1  nick   21
2  nick   19
3  jack   18
4  shiv   21
5  shiv   22
6  jim    23

I have created the dataframe with one more column:
df['New'] = df['Name'].shift()

   Name  Age  New
0   Tom   20  NaN
1  nick   21  Tom
2  nick   19  nick
3  jack   18  nick
4  shiv   21  jack
5  shiv   22  shiv
6  jim    23  shiv

Expected Output:

   Name  Age  New  order
0   Tom   20  NaN   1
1  nick   21  Tom   2
2  nick   19  nick  2
3  jack   18  nick  3
4  shiv   21  jack  4
5  shiv   22  shiv  4
6  jim    23  shiv  5

condition :
if Name is matching the New column then check the previous row number and fill the number same number else fill the next number.
It is quiet similar like dense_rank() but I don't want to use dense_rank concept here. So is there any way to fill this column?

Body:
Using .cumsum() over boolean Series:

df['order'] = (df['Name'] != df['Name'].shift()).cumsum()

print(df)

Prints:

   Name  Age  order
0   Tom   20      1
1  nick   21      2
2  nick   19      2
3  jack   18      3
4  shiv   21      4
5  shiv   22      4
6   jim   23      5


问:
Total Collections, rejecting collections of types that do not include all possibilities
Let's say we have the following types:

sealed trait T
case object Goat extends T
case object Monk extends T
case object Tiger extends T
```

<p>Now, how do you construct a collection of <code>T</code> such that <em>at least one</em> of each sub-<code>T</code> appears in the collection, this constraint being enforced at compile time? A collection where, contrary to this:</p>

```val s:Seq[T] = Seq(Goat)
```

<p>which compiles, this:</p>

```val ts:TotalSeq[T] = TotalSeq(Goat, Goat, Tiger)
```

does not. I've used Scala above, but I would be happy to see solutions in other languages as well.

(Forgive me if my words are a bit off; I have a cold and am amusing myself today with puzzles.)

答:
It looks like the builder pattern with generalized type constraints: http://www.tikalk.com/java/blog/type-safe-builder-scala-using-type-constraints

Something like:

```<code>sealed trait TBoolean
sealed trait TTrue extends TBoolean
sealed trait TFalse extends TBoolean

class SeqBuilder[HasGoat <: TBoolean, HasMonk <: TBoolean, HasTiger <: TBoolean] private (seq: Seq[T]) {

  def +=(g: Goat.type) = new SeqBuilder[TTrue, HasMonk, HasTiger](g +: seq)

  def +=(m: Monk.type) = new SeqBuilder[HasGoat, TTrue, HasTiger](m +: seq)

  def +=(t: Tiger.type) = new SeqBuilder[HasGoat, HasMonk, TTrue](t +: seq)

  def build()(implicit evg: HasGoat =:= TTrue, evm: HasMonk =:= TTrue, evt: HasTiger =:= TTrue) = seq
}

object SeqBuilder {
  def apply = new SeqBuilder(Seq())
}
</code>```

Usage:

```<code>scala> SeqBuilder() + Goat + Tiger + Monk build()
res21: Seq[T] = List(Monk, Tiger, Goat)

scala> SeqBuilder() + Goat + Goat + Monk build()
<console>:34: error: Cannot prove that Nothing =:= TTrue.
       SeqBuilder() + Goat + Goat + Monk build()
                                         ^
</code>```

If the number of instances you want grows you can try using an HMap

Other similar approaches: phantom types: http://james-iry.blogspot.com/2010/10/phantom-types-in-haskell-and-scala.html

Another approach is to ask why you need all 3 objects. Say you want to carry an operation when the seq has all three, then you can do something like:

```<code>object SeqBuilder {
  val all = Seq(Goat, Monk, Tiger)

  def apply(t: T*)(onAll: Seq[T] => Unit)(onViolation: => Unit) = {
     val seq = Seq(t:_*)
     if(all forall seq.contains) onAll(seq)
     else onViolation
  }
}
</code>```

That way, the function onAll is not called if not all required Ts have been supplied and otherwise the violation function is called

Body:
Let's say we have the following types:

sealed trait T
case object Goat extends T
case object Monk extends T
case object Tiger extends T

Now, how do you construct a collection of T such that at least one of each sub-T appears in the collection, this constraint being enforced at compile time? A collection where, contrary to this:

val s:Seq[T] = Seq(Goat)

which compiles, this:

val ts:TotalSeq[T] = TotalSeq(Goat, Goat, Tiger)

does not. I've used Scala above, but I would be happy to see solutions in other languages as well.

(Forgive me if my words are a bit off; I have a cold and am amusing myself today with puzzles.)

Body:
It looks like the builder pattern with generalized type constraints: http://www.tikalk.com/java/blog/type-safe-builder-scala-using-type-constraints

Something like:

sealed trait TBoolean
sealed trait TTrue extends TBoolean
sealed trait TFalse extends TBoolean

class SeqBuilder[HasGoat <: TBoolean, HasMonk <: TBoolean, HasTiger <: TBoolean] private (seq: Seq[T]) {

  def +=(g: Goat.type) = new SeqBuilder[TTrue, HasMonk, HasTiger](g +: seq)

  def +=(m: Monk.type) = new SeqBuilder[HasGoat, TTrue, HasTiger](m +: seq)

  def +=(t: Tiger.type) = new SeqBuilder[HasGoat, HasMonk, TTrue](t +: seq)

  def build()(implicit evg: HasGoat =:= TTrue, evm: HasMonk =:= TTrue, evt: HasTiger =:= TTrue) = seq
}

object SeqBuilder {
  def apply = new SeqBuilder(Seq())
}

Usage:

scala> SeqBuilder() + Goat + Tiger + Monk build()
res21: Seq[T] = List(Monk, Tiger, Goat)

scala> SeqBuilder() + Goat + Goat + Monk build()
<console>:34: error: Cannot prove that Nothing =:= TTrue.
       SeqBuilder() + Goat + Goat + Monk build()
                                         ^

If the number of instances you want grows you can try using an HMap

Other similar approaches: phantom types: http://james-iry.blogspot.com/2010/10/phantom-types-in-haskell-and-scala.html

Another approach is to ask why you need all 3 objects. Say you want to carry an operation when the seq has all three, then you can do something like:

object SeqBuilder {
  val all = Seq(Goat, Monk, Tiger)

  def apply(t: T*)(onAll: Seq[T] => Unit)(onViolation: => Unit) = {
     val seq = Seq(t:_*)
     if(all forall seq.contains) onAll(seq)
     else onViolation
  }
}

That way, the function onAll is not called if not all required Ts have been supplied and otherwise the violation function is called


问:
Traffic Incident API - How do the START_TIME, END_TIME and ENTRY_TIME parameters work?
How exactly do the START_TIME, END_TIME and ENTRY_TIME parameters work and how are they affected when an incident is updated?

I would assume that START_TIME is the time the incident is reported (or due to start in the case of roadworks), END_TIME is the when the incident is expected to be over and ENTRY_TIME when the incident was registered with HERE? Is this correct? I have not been able to find any documentation for this.

答:
An array of  elements that contain the incident location, time, duration, severity, description and other details. The keys are the logical named keys. You can refer more details at our documentation for Traffic Incident API :

developer.here.com/documentation/traffic/dev_guide/topics/incident-data.html


问:
How does exshuffle works in cloze questions (package `exams`)?
I would like to understand how does exsuffle works on cloze questions. Does it work with various schoice questions with a different number of possible answers?

I expect to have the possible answers shuffled when presenting the exercises in Moodle. With the observed behavior, the order is always the same.

答:
or you can use (for future reference) "MULTICHOICE_VS" as in:

```<code>
    exams2moodle(questions,
             name = "exameXPTO",
             cloze = list(cloze_mchoice_display = "MULTICHOICE_VS"),
             envir =.GlobalEnv)

</code>```

:-)

Body:
or you can use (for future reference) "MULTICHOICE_VS" as in:

    exams2moodle(questions,
             name = "exameXPTO",
             cloze = list(cloze_mchoice_display = "MULTICHOICE_VS"),
             envir =.GlobalEnv)

:-)


问:
How to input a 2-D array directly in C with negative values, spaces and newline
I want to directly input a 2-D Array in C, separated just by single spaces and newlines. At the same time I also want to verify whether the user is entering a valid single digit integer (either positive or negative).
I tried the following.

```<code>int A[3][3];
    int i,j;
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
            scanf("%d",&A[i][j]);
    }
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
            printf("%d ",A[i][j]);
        printf("\n");
    }
</code>```

But I want 2 things in this:-

Input that is first verified whether its a single digit integer or not.

Not works merely for positive integers and 0 but also for negative integers.

eg.
input such as the following should be accepted and stored in 2-d array

1 2 -3 4
-5 1 2 -6
1 1 2 3
```
<p>I'm sorry if I wasn't clear. An important component is that the input should be confirmed whether its integer or not i.e. the input should be either as char or string and if it is an integer  (which can be ascertained by functions such as isdigit() , then it should be converted to an integer value.
This following code chunk works for single positive values</p>
```char c = getchar();
  if (isdigit(c))
     int value = c - '0';
```

However, I don't know how to enable this functionality for negative integers in a complete 2D array input.

答:
So first, tell the user to enter values row-wise or column-wise. In this case, ask like this

printf("Enter integers row-wise");

Now the user will enter values.

After scanning those values put an if statement to verify that value is greater than or equal to -9 and less than 9. If value is within the range continue; else put a exit(1); statement and tell the user that entered value is incorrect. Like this:

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
    int A[3][3];
    int i, j;
    for( i = 0; i < 3; i++ )
    {
        for( j = 0; j < 3; j++)
        {
            scanf("%d", &A[i][j]);
            if(A[i][j] >= -9 && A[i][j] <= 9)
                continue;
            else
            {
                printf("Enter correct values.\n");
                exit(1);
            }
        }
    }

    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
            printf("%d ",A[i][j]);
        printf("\n");
    }
    return 0;
}

</code>```

Body:
I want to directly input a 2-D Array in C, separated just by single spaces and newlines. At the same time I also want to verify whether the user is entering a valid single digit integer (either positive or negative).
I tried the following.

int A[3][3];
    int i,j;
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
            scanf("%d",&A[i][j]);
    }
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
            printf("%d ",A[i][j]);
        printf("\n");
    }

But I want 2 things in this:-

Input that is first verified whether its a single digit integer or not.

Not works merely for positive integers and 0 but also for negative integers.

eg.
input such as the following should be accepted and stored in 2-d array

1 2 -3 4
-5 1 2 -6
1 1 2 3

I'm sorry if I wasn't clear. An important component is that the input should be confirmed whether its integer or not i.e. the input should be either as char or string and if it is an integer  (which can be ascertained by functions such as isdigit() , then it should be converted to an integer value.
This following code chunk works for single positive values

char c = getchar();
  if (isdigit(c))
     int value = c - '0';

However, I don't know how to enable this functionality for negative integers in a complete 2D array input.

Body:
So first, tell the user to enter values row-wise or column-wise. In this case, ask like this

printf("Enter integers row-wise");

Now the user will enter values.

After scanning those values put an if statement to verify that value is greater than or equal to -9 and less than 9. If value is within the range continue; else put a exit(1); statement and tell the user that entered value is incorrect. Like this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int A[3][3];
    int i, j;
    for( i = 0; i < 3; i++ )
    {
        for( j = 0; j < 3; j++)
        {
            scanf("%d", &A[i][j]);
            if(A[i][j] >= -9 && A[i][j] <= 9)
                continue;
            else
            {
                printf("Enter correct values.\n");
                exit(1);
            }
        }
    }

    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
            printf("%d ",A[i][j]);
        printf("\n");
    }
    return 0;
}


问:
Dapper INSERT AccessViolationException
I'm currently trying out Dapper and am really surprised how easy it can be to make "All-Day" statements in just a short amount of time.

I'm working on a Blazor WebAssembly project and am trying to make simple SELECT and INSERT statements.

I'll try to lay out everything as clear as possible to speed up the answering-process.

I have 2 projects, one a simple .Net Standard 2.0 class library with 4 classes which are used for the background-work like SQL and the BlazorWebAssembly. Now an overview over the classes in the ClassLibrary:

ProjektData.cs (the Blazor App calls the methods):

```<code>using System.Collections.Generic;

namespace BlazorBoardcardsAppData
{
    using System.Threading.Tasks;

    using BlazorBoardcardsAppData.Models;

    public class ProjektData
    {
        private readonly AccessDataAccess db;

        public ProjektData(AccessDataAccess db)
        {
            this.db = db;
        }

        public Task<List<ProjektModel>> GetProjekte()
        {
            string sql = "SELECT * FROM Projekte";

            return this.db.LoadData<ProjektModel, dynamic>(sql, new { });
        }

        public void SaveProjekte<I>()
        {
            string sql = "INSERT INTO Projekte (sName, sBeschreibung) " +
                         "VALUES (@sName, @sBeschreibung);";

            this.db.SaveData(sql, new { });
        }
    }
}
</code>```

and AccessDataAccess.cs (where I already played around with different approaches to fix this problem)

```<code>namespace BlazorBoardcardsAppData
{
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using System.Data.OleDb;
    using System.Linq;

    using BlazorBoardcardsAppData.Models;

    using Dapper;

    using Microsoft.Extensions.Configuration;

    public class AccessDataAccess
    {
        private readonly IConfiguration config;

        public string ConnectionString { get; set; } = "Default";

        public AccessDataAccess(IConfiguration config)
        {
            this.config = config;
        }

        public async Task<List<T>> LoadData<T, U>(string sql, U parameters)
        {
            string connectionString = this.config.GetConnectionString(ConnectionString);
            using (OleDbConnection con = new OleDbConnection(connectionString))
            {
                var data = await con.QueryAsync<T>(sql, parameters);
                return data.ToList();
            }
        }

        public void SaveData<U>(string sql, U parameters)
        {
            string connectionString = this.config.GetConnectionString(ConnectionString);
            //ProjektModel t = new ProjektModel
            //{
            //    sName = "test",
            //    sBeschreibung = "test",
            //    bAbgeschlossen = false,
            //    bDokuVorhanden = true,
            //    dAusstehendFte = 1,
            //    dGesamtFte = 2,
            //    lKanbanProjekt = 2314,
            //    sAbrechnungsmethode = "test",
            //    sErforderlicheLizenzen = "test",
            //    sExterneKontakte = "test",
            //    sGeplanteErweiterung = "test",
            //    sRaciqA = "test",
            //    sRaciqC = "test",
            //    sRaciqQ = "test",
            //    sRaciqR = "test",
            //    sRaciqI = "test",
            //    sZielgruppe = "test"
            //};
            //List<ProjektModel> u = new List<ProjektModel>();
            //u.Add(t);
            using (OleDbConnection con = new OleDbConnection(connectionString))
            {
                con.Execute(sql, new {
                    sName = "test",
                    sBeschreibung = "test",
                    bAbgeschlossen = false,
                    bDokuVorhanden = true,
                    dAusstehendFte = 1,
                    dGesamtFte = 2,
                    lKanbanProjekt = 2314,
                    sAbrechnungsmethode = "test",
                    sErforderlicheLizenzen = "test",
                    sExterneKontakte = "test",
                    sGeplanteErweiterung = "test",
                    sRaciqA = "test",
                    sRaciqC = "test",
                    sRaciqQ = "test",
                    sRaciqR = "test",
                    sRaciqI = "test",
                    sZielgruppe = "test"
                });
            }
        }
    }
}
</code>```

The goal is to INSERT into the SQL-Database using the "ProjektModel" as a model for the parameters.
I tried several approaches, the commented code being one of them.
The SELECT statement works like a charm so I can exclude a connection problem or something like that.
I tried the ExecuteAsync but no difference, the exception always appears at the same position:

@EDIT: This screenshot is from the SQLMapper partial class from Dapper

And just for completion the call from the other project (Blazor project which uses the DLL with the Dapper methods)

```<code>@page "/"
@page "/boardcards"

@using BlazorBoardcardsAppData
@using BlazorBoardcardsAppData.Models

@inject ProjektData PjData
@inject IJSRuntime jsRuntime
@inject ProjektModel TProjektModel
@inject ProjektDataDictionary ProjektDataDictionary

<header>
    <link href="css/BoardcardsSite.css" rel="stylesheet" type="text/css" />
</header>
<body>
    <h1>Projekt Boardkarten</h1>

    <div class="row align-items-center">
        <button @onclick="@AddProjektToTable">Add</button>
        <p id="TextPaddingSpacer" class="col mb-0">Alle Stundenzettel der ** Komponenten</p>
        <input class="form-control mr-sm-2 col-2" type="search" placeholder="Suchen" aria-label="Suchen"
               @bind-value="SearchTerms" @bind-value:event="oninput" />
    </div>

    @if (filteredProjects == null)
    {
        <p><em>Loading...</em></p>
    }
    else
    {
        <table class="table table-hover">
            <thead>
                <tr>
                    <th id="BoardcardsNameColumnWidth">Name</th>
                    <th>Beschreibung</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var projects in filteredProjects)
                {
                    <tr class="TableRows" @onclick="@(e => OpenNewTab(projects))">
                        <td>@projects.sName</td>
                        @if (string.IsNullOrEmpty(projects.sBeschreibung) || projects.sBeschreibung.Equals("?"))
                        {
                            <td>(Keine Informationen)</td>
                        }
                        else
                        {
                            <td>@projects.sBeschreibung</td>
                        }
                    </tr>
                }
            </tbody>
        </table>
    }
</body>

@code {
    private List<ProjektModel> projects;

    private string SearchTerms { get; set; } = string.Empty;

    protected override async Task OnInitializedAsync()
    {
        projects = await PjData.GetProjekte();
        if (ProjektDataDictionary.AllProjekt.Count == 0)
        {
            foreach (ProjektModel projektModel in projects)
            {
                ProjektDataDictionary.AllProjekt[projektModel.gID] = projektModel;
            }
        }
    }

    private List<ProjektModel> filteredProjects => projects.Where(x => x.sName.ToLower().Contains(SearchTerms.ToLower())
                                                                    || (x.sBeschreibung?.ToLower().Contains(SearchTerms.ToLower()) ?? false)).ToList();
    private async Task OpenNewTab(ProjektModel pj)
    {
        await jsRuntime.InvokeVoidAsync("Open", $"/BoardcardViewer/{pj.gID}");
    }

    private void AddProjektToTable()
    {
        PjData.SaveProjekte<ProjektModel>();
    }
}
</code>```

Where AddProjectToTable is the call.

What am I doing wrong?

答:
First of all, you should create command in opened connection. Now, you create command and then open connection (if it is closed). Try to change this (first open connection, and then create a command).

The next thing that you should be aware of is:

```<code>await cmd.ExecuteNonQueryAsync(command.CancellationToken).ConfigureAwait(false);
</code>```

Try to remove ConfigureAwait and see what happens. If it works, try then to change it to:

```<code>await (cmd.ExecuteNonQueryAsync(command.CancellationToken).ConfigureAwait(false));
</code>```

Title: Dapper INSERT AccessViolationException

Body:
I'm currently trying out Dapper and am really surprised how easy it can be to make "All-Day" statements in just a short amount of time.

I'm working on a Blazor WebAssembly project and am trying to make simple SELECT and INSERT statements.

I'll try to lay out everything as clear as possible to speed up the answering-process.

I have 2 projects, one a simple .Net Standard 2.0 class library with 4 classes which are used for the background-work like SQL and the BlazorWebAssembly. Now an overview over the classes in the ClassLibrary:

ProjektData.cs (the Blazor App calls the methods):

using System.Collections.Generic;

namespace BlazorBoardcardsAppData
{
    using System.Threading.Tasks;

    using BlazorBoardcardsAppData.Models;

    public class ProjektData
    {
        private readonly AccessDataAccess db;

        public ProjektData(AccessDataAccess db)
        {
            this.db = db;
        }

        public Task<List<ProjektModel>> GetProjekte()
        {
            string sql = "SELECT * FROM Projekte";

            return this.db.LoadData<ProjektModel, dynamic>(sql, new { });
        }

        public void SaveProjekte()
        {
            string sql = "INSERT INTO Projekte (sName, sBeschreibung) " +
                         "VALUES (@sName, @sBeschreibung);";

            this.db.SaveData(sql, new { });
        }
    }
}

and AccessDataAccess.cs (where I already played around with different approaches to fix this problem)

namespace BlazorBoardcardsAppData
{
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using System.Data.OleDb;
    using System.Linq;

    using BlazorBoardcardsAppData.Models;

    using Dapper;

    using Microsoft.Extensions.Configuration;

    public class AccessDataAccess
    {
        private readonly IConfiguration config;

        public string ConnectionString { get; set; } = "Default";

        public AccessDataAccess(IConfiguration config)
        {
            this.config = config;
        }

        public async Task<List<T>> LoadData<T, U>(string sql, U parameters)
        {
            string connectionString = this.config.GetConnectionString(ConnectionString);
            using (OleDbConnection con = new OleDbConnection(connectionString))
            {
                var data = await con.QueryAsync<T>(sql, parameters);
                return data.ToList();
            }
        }

        public void SaveData(string sql, U parameters)
        {
            string connectionString = this.config.GetConnectionString(ConnectionString);
            //ProjektModel t = new ProjektModel
            //{
            //    sName = "test",
            //    sBeschreibung = "test",
            //    bAbgeschlossen = false,
            //    bDokuVorhanden = true,
            //    dAusstehendFte = 1,
            //    dGesamtFte = 2,
            //    lKanbanProjekt = 2314,
            //    sAbrechnungsmethode = "test",
            //    sErforderlicheLizenzen = "test",
            //    sExterneKontakte = "test",
            //    sGeplanteErweiterung = "test",
            //    sRaciqA = "test",
            //    sRaciqC = "test",
            //    sRaciqQ = "test",
            //    sRaciqR = "test",
            //    sRaciqI = "test",
            //    sZielgruppe = "test"
            //};
            //List<ProjektModel> u = new List<ProjektModel>();
            //u.Add(t);
            using (OleDbConnection con = new OleDbConnection(connectionString))
            {
                con.Execute(sql, new {
                    sName = "test",
                    sBeschreibung = "test",
                    bAbgeschlossen = false,
                    bDokuVorhanden = true,
                    dAusstehendFte = 1,
                    dGesamtFte = 2,
                    lKanbanProjekt = 2314,
                    sAbrechnungsmethode = "test",
                    sErforderlicheLizenzen = "test",
                    sExterneKontakte = "test",
                    sGeplanteErweiterung = "test",
                    sRaciqA = "test",
                    sRaciqC = "test",
                    sRaciqQ = "test",
                    sRaciqR = "test",
                    sRaciqI = "test",
                    sZielgruppe = "test"
                });
            }
        }
    }
}

The goal is to INSERT into the SQL-Database using the "ProjektModel" as a model for the parameters.
I tried several approaches, the commented code being one of them.
The SELECT statement works like a charm so I can exclude a connection problem or something like that.
I tried the ExecuteAsync but no difference, the exception always appears at the same position:

@EDIT: This screenshot is from the SQLMapper partial class from Dapper

And just for completion the call from the other project (Blazor project which uses the DLL with the Dapper methods)

@page "/"
@page "/boardcards"

@using BlazorBoardcardsAppData
@using BlazorBoardcardsAppData.Models

@inject ProjektData PjData
@inject IJSRuntime jsRuntime
@inject ProjektModel TProjektModel
@inject ProjektDataDictionary ProjektDataDictionary

    <link href="css/BoardcardsSite.css" rel="stylesheet" type="text/css" />

Projekt Boardkarten

        <button @onclick="@AddProjektToTable">Add</button>

Alle Stundenzettel der ** Komponenten

        <input class="form-control mr-sm-2 col-2" type="search" placeholder="Suchen" aria-label="Suchen"
               @bind-value="SearchTerms" @bind-value:event="oninput" />

    @if (filteredProjects == null)
    {

Loading...

    }
    else
    {

                    Name
                    Beschreibung

                @foreach (var projects in filteredProjects)
                {

 OpenNewTab(projects))">
                        @projects.sName
                        @if (string.IsNullOrEmpty(projects.sBeschreibung) || projects.sBeschreibung.Equals("?"))
                        {
                            (Keine Informationen)
                        }
                        else
                        {
                            @projects.sBeschreibung
                        }

                }

    }

@code {
    private List<ProjektModel> projects;

    private string SearchTerms { get; set; } = string.Empty;

    protected override async Task OnInitializedAsync()
    {
        projects = await PjData.GetProjekte();
        if (ProjektDataDictionary.AllProjekt.Count == 0)
        {
            foreach (ProjektModel projektModel in projects)
            {
                ProjektDataDictionary.AllProjekt[projektModel.gID] = projektModel;
            }
        }
    }

    private List<ProjektModel> filteredProjects => projects.Where(x => x.sName.ToLower().Contains(SearchTerms.ToLower())
                                                                    || (x.sBeschreibung?.ToLower().Contains(SearchTerms.ToLower()) ?? false)).ToList();
    private async Task OpenNewTab(ProjektModel pj)
    {
        await jsRuntime.InvokeVoidAsync("Open", $"/BoardcardViewer/{pj.gID}");
    }

    private void AddProjektToTable()
    {
        PjData.SaveProjekte<ProjektModel>();
    }
}

Where AddProjectToTable is the call.

What am I doing wrong?

Body:
First of all, you should create command in opened connection. Now, you create command and then open connection (if it is closed). Try to change this (first open connection, and then create a command).

The next thing that you should be aware of is:

await cmd.ExecuteNonQueryAsync(command.CancellationToken).ConfigureAwait(false);

Try to remove ConfigureAwait and see what happens. If it works, try then to change it to:

await (cmd.ExecuteNonQueryAsync(command.CancellationToken).ConfigureAwait(false));