问:
How to show headers from QSqlTableModel on TableView(QtQuick 2)?
I set headers to model but, i can't show this in my tableview, why? Maybe there is some other parameter besides modelData, which I could use to return the names of my headers to tableview qml?

I can't provide more reproduce example, because you're haven't my sql database. This code return only data to tableview. Maybe tableview(qt quick 2) can't return headers.

In class TableModel i don't override standart methods from QSqlTableModel.

main.cpp

```<code>#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlTableModel>
#include <QFontDatabase>

#include <QDebug>
#include "TableModel.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    QSqlDatabase db;
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("172.17.110.69");
    db.setDatabaseName("usb_DB");
    db.setUserName("usb_secure");
    db.setPassword("QWer!234");
    db.setPort(3306);
    db.open();
    qDebug()<<db.isOpen();
    TableModel* model = new TableModel(&app,db);
    model->setTable("usb_devices");
    model->sort(0,Qt::SortOrder::AscendingOrder);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();
    model->setHeaderData(0,Qt::Orientation::Horizontal,"Column0");
    model->setHeaderData(1,Qt::Orientation::Horizontal,"Column1");
    model->setHeaderData(2,Qt::Orientation::Horizontal,"Column2");
    model->setHeaderData(3,Qt::Orientation::Horizontal,"Column3");

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));

    QQmlContext *context = engine.rootContext();
    context->setContextProperty("tableModel", model);

    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}
</code>```

main.qml

```<code>import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Controls.Material 2.12
import QtQuick.Window 2.11

ApplicationWindow {
    id:appWindow
    visible: true

    TableView {
        id: tableView
        boundsBehavior:Flickable.StopAtBounds
        reuseItems: true
        clip: true

        columnWidthProvider: function (column) { return 300; }
        rowHeightProvider: function () { return 48; }
        anchors.fill: parent
        topMargin: columnsHeader.implicitHeight

        model: tableModel

        delegate:ItemDelegate{
            id: delegateItem

            TextField{
                text: modelData
                horizontalAlignment: Text.AlignHCenter
            }

        }

        Row {
            id: columnsHeader
            y: tableView.contentY
            z:2

            Repeater {
                model: tableView.columns > 0 ? tableView.columns : 1

                Label {
                    id: labelRow
                    width: tableView.columnWidthProvider(index)
                    height: tableView.rowHeightProvider()
                    text: modelData
                }
            }
        }
    }
}
</code>```

TableModel.h

```<code>#ifndef TABLEMODEL_H
#define TABLEMODEL_H

#include <QtSql/QSqlRelationalTableModel>
#include <QSqlRecord>

class TableModel : public QSqlRelationalTableModel
{
    Q_OBJECT
    using QSqlRelationalTableModel::QSqlRelationalTableModel;

public slots:
    Q_INVOKABLE bool set(int, int, QString);

private:
    QSqlRecord rec;
};

#endif // TABLEMODEL_H
</code>```

Result

答:
The problem is that if the Repeater model is a number "n" the modelData are the numbers from "0" to "n-1". The solution is to be able to access headerData from QML and for this Q_INVOKABLE must be used:

class TableModel : public QSqlRelationalTableModel
{
    Q_OBJECT
public:
    using QSqlRelationalTableModel::QSqlRelationalTableModel;
    Q_INVOKABLE QVariant headerData(int section, Qt::Orientation orientation, int role=Qt::DisplayRole) const;
};
```

```// ...
QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    return QSqlRelationalTableModel::headerData(section, orientation, role);
}
// ...
```

<p><strong>*.qml</strong></p>

```// ...
Repeater {
    model: tableView.columns > 0 ? tableView.columns : 1

    Label {
        id: labelRow
        width: tableView.columnWidthProvider(index)
        height: tableView.rowHeightProvider()
        text: tableModel.headerData(modelData, Qt.Horizontal) // <---
    }
}
// ...
```

Body:
I set headers to model but, i can't show this in my tableview, why? Maybe there is some other parameter besides modelData, which I could use to return the names of my headers to tableview qml?

I can't provide more reproduce example, because you're haven't my sql database. This code return only data to tableview. Maybe tableview(qt quick 2) can't return headers.

In class TableModel i don't override standart methods from QSqlTableModel.

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlTableModel>
#include <QFontDatabase>

#include <QDebug>
#include "TableModel.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    QSqlDatabase db;
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("172.17.110.69");
    db.setDatabaseName("usb_DB");
    db.setUserName("usb_secure");
    db.setPassword("QWer!234");
    db.setPort(3306);
    db.open();
    qDebug()<<db.isOpen();
    TableModel* model = new TableModel(&app,db);
    model->setTable("usb_devices");
    model->sort(0,Qt::SortOrder::AscendingOrder);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();
    model->setHeaderData(0,Qt::Orientation::Horizontal,"Column0");
    model->setHeaderData(1,Qt::Orientation::Horizontal,"Column1");
    model->setHeaderData(2,Qt::Orientation::Horizontal,"Column2");
    model->setHeaderData(3,Qt::Orientation::Horizontal,"Column3");

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));

    QQmlContext *context = engine.rootContext();
    context->setContextProperty("tableModel", model);

    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

main.qml

import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Controls.Material 2.12
import QtQuick.Window 2.11

ApplicationWindow {
    id:appWindow
    visible: true

    TableView {
        id: tableView
        boundsBehavior:Flickable.StopAtBounds
        reuseItems: true
        clip: true

        columnWidthProvider: function (column) { return 300; }
        rowHeightProvider: function () { return 48; }
        anchors.fill: parent
        topMargin: columnsHeader.implicitHeight

        model: tableModel

        delegate:ItemDelegate{
            id: delegateItem

            TextField{
                text: modelData
                horizontalAlignment: Text.AlignHCenter
            }

        }

        Row {
            id: columnsHeader
            y: tableView.contentY
            z:2

            Repeater {
                model: tableView.columns > 0 ? tableView.columns : 1

                Label {
                    id: labelRow
                    width: tableView.columnWidthProvider(index)
                    height: tableView.rowHeightProvider()
                    text: modelData
                }
            }
        }
    }
}

TableModel.h

#ifndef TABLEMODEL_H
#define TABLEMODEL_H

#include <QtSql/QSqlRelationalTableModel>
#include <QSqlRecord>

class TableModel : public QSqlRelationalTableModel
{
    Q_OBJECT
    using QSqlRelationalTableModel::QSqlRelationalTableModel;

public slots:
    Q_INVOKABLE bool set(int, int, QString);

private:
    QSqlRecord rec;
};

#endif // TABLEMODEL_H

Result

Body:
The problem is that if the Repeater model is a number "n" the modelData are the numbers from "0" to "n-1". The solution is to be able to access headerData from QML and for this Q_INVOKABLE must be used:

class TableModel : public QSqlRelationalTableModel
{
    Q_OBJECT
public:
    using QSqlRelationalTableModel::QSqlRelationalTableModel;
    Q_INVOKABLE QVariant headerData(int section, Qt::Orientation orientation, int role=Qt::DisplayRole) const;
};

// ...
QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    return QSqlRelationalTableModel::headerData(section, orientation, role);
}
// ...

*.qml

// ...
Repeater {
    model: tableView.columns > 0 ? tableView.columns : 1

    Label {
        id: labelRow
        width: tableView.columnWidthProvider(index)
        height: tableView.rowHeightProvider()
        text: tableModel.headerData(modelData, Qt.Horizontal) // <---
    }
}
// ...


来源: stackexchange

问:
Entity Framework Core 2.1 throwing ArgumentException on left join
I recently upgraded my project from .NET Core 2.0 to 2.1. I use Entity Framework Core and have several LINQ expressions that include left joins. The following code is an example:

```<code>var tickets = (from ticket in dbContext.Tickets
               join member in dbContext.Members on ticket.MemberID equals member.ID into memberLEFT
               from member in memberLEFT.DefaultIfEmpty()
               join memberType in dbContext.MemberTypes on member.MemberTypeID equals memberType.ID into memberTypeLEFT
               from memberType in memberTypeLEFT.DefaultIfEmpty()
               select memberType)
              .ToList();
</code>```

If .NET Core 2.0, this line executed with no exceptions. In .NET Core 2.1, it's throwing the following ArgumentException:

System.ArgumentException: 'Field
  'Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Microsoft.EntityFrameworkCore.Storage.ValueBuffer,System.Collections.Generic.IEnumerable`1[Microsoft.EntityFrameworkCore.Storage.ValueBuffer]].Inner'
  is not defined for type
  'Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Microsoft.EntityFrameworkCore.Storage.ValueBuffer,Microsoft.EntityFrameworkCore.Storage.ValueBuffer]''

If I change the LINQ to perform inner joins instead of left, then it executes no problem. The joins need to be left joins though, so I can't just update all of my code to do inner joins.

Does anyone know why EF Core 2.1 is now throwing ArgumentExecptions when performing left joins, and how to get around the issue?

答: From tools > Options check Enable Just My code

ContentLicense: CC BY-SA 4.0

Body:
I recently upgraded my project from .NET Core 2.0 to 2.1. I use Entity Framework Core and have several LINQ expressions that include left joins. The following code is an example:

var tickets = (from ticket in dbContext.Tickets
               join member in dbContext.Members on ticket.MemberID equals member.ID into memberLEFT
               from member in memberLEFT.DefaultIfEmpty()
               join memberType in dbContext.MemberTypes on member.MemberTypeID equals memberType.ID into memberTypeLEFT
               from memberType in memberTypeLEFT.DefaultIfEmpty()
               select memberType)
              .ToList();

If .NET Core 2.0, this line executed with no exceptions. In .NET Core 2.1, it's throwing the following ArgumentException:

System.ArgumentException: 'Field
  'Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Microsoft.EntityFrameworkCore.Storage.ValueBuffer,System.Collections.Generic.IEnumerable`1[Microsoft.EntityFrameworkCore.Storage.ValueBuffer]].Inner'
  is not defined for type
  'Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Microsoft.EntityFrameworkCore.Storage.ValueBuffer,Microsoft.EntityFrameworkCore.Storage.ValueBuffer]''

If I change the LINQ to perform inner joins instead of left, then it executes no problem. The joins need to be left joins though, so I can't just update all of my code to do inner joins.

Does anyone know why EF Core 2.1 is now throwing ArgumentExecptions when performing left joins, and how to get around the issue?


问:
Can I use virtual tokens (tokens with identical return value) in ANTLR4 similar to c++?
In C++ I can use virtual functions to process data from similar classes that have the same parent/ancestor, does ANTLR4 support this and how would I have to set up the grammar?

I have tried to set up a grammar, using arguments that have the same return value and use that value in a token that contains the different "subclassed" tokens.

Here is some code I have tried to work with:

```<code>    amf_group
        : statements=amf_statements (GROUPSEP WS? LINE_COMMENT? EOL? | EOF)
        ;

    amf_statements returns [amf::AmfStatements stmts]
        : ( WS? ( stmt=amf_statement { stmts.emplace_back(std::move($stmt.stmtptr)); } WS? EOL) )*
        ;

    amf_statement returns [amf::AmfStatementPtr stmtptr]
        : (
            stmt = jsonparent_statement

            | stmt = jsonvalue_statement

           )
        {
            $stmtptr = std::move($stmt.stmtptr);
        }
        ;

    jsonparent_statement returns [amf::AmfStatementPtr stmtptr] locals [int lineno=0]
        :
        (T_JSONPAR      { $lineno = $T_JSONPAR.line;} )  WS (arg=integer_const)
        {
            $stmtptr = std::make_shared<amf::JSONParentStatement>($lineno, nullptr);
        }
        ;

    jsonvalue_statement returns [amf::AmfStatementPtr stmtptr] locals [int lineno=0]
        : ( T_JSONVALUE { $lineno = $T_JSONVALUE.line; } ) WS (arg=integer_const) (WS fmt=integer_const)?
        {
            $stmtptr = std::make_shared<amf::JSONValueStatement>($lineno, std::move($arg.argptr), std::move($fmt.argptr));
        }
        ;
</code>```

I receive the following error:

error(75): amf1.g4:23:10: label stmt=jsonvalue_statement type mismatch with previous definition: stmt=jsonparent_statement

This error is or course quite logical, because the tokens are indeed of a different type, but there return value types are identical. For two (virtual) tokens I can write all the code separatelty, but in my case I have some 40+ different tokens that either represent arguments or statements and writing all the combinations would be cumbersome. The above code did work in Antlr3 by the way.

Is there another way to get around these errors using ANTLR4? Does anybody have any suggestions?

答:
What's specified in a rule return value is not really a return value in a functional sense. Instead the context representing the rule will get a new member field that takes the "return" value. Given that it makes no sense trying to treat parser rules like C++ functions, they are simply not comparable.

Instead of handling all the fields in your grammar, I recommend a different approach: with ANTLR4 you will get a parse tree (if enabled), which represents the matched rules using parse rule contexts (which is super view of the previously generated AST). This context contains all the values that have been parsed out. You just need a listener in a second step after the parse run (often called the semantic phase) to walk over this tree, pick those values up and create your own data structures from them. This separation also allows to use your parser for quick syntax checks, since you don't do all the heavy work in the parse run.

Body:
In C++ I can use virtual functions to process data from similar classes that have the same parent/ancestor, does ANTLR4 support this and how would I have to set up the grammar?

I have tried to set up a grammar, using arguments that have the same return value and use that value in a token that contains the different "subclassed" tokens.

Here is some code I have tried to work with:

    amf_group
        : statements=amf_statements (GROUPSEP WS? LINE_COMMENT? EOL? | EOF)
        ;

    amf_statements returns [amf::AmfStatements stmts]
        : ( WS? ( stmt=amf_statement { stmts.emplace_back(std::move($stmt.stmtptr)); } WS? EOL) )*
        ;

    amf_statement returns [amf::AmfStatementPtr stmtptr]
        : (
            stmt = jsonparent_statement

            | stmt = jsonvalue_statement

           )
        {
            $stmtptr = std::move($stmt.stmtptr);
        }
        ;

    jsonparent_statement returns [amf::AmfStatementPtr stmtptr] locals [int lineno=0]
        :
        (T_JSONPAR      { $lineno = $T_JSONPAR.line;} )  WS (arg=integer_const)
        {
            $stmtptr = std::make_shared<amf::JSONParentStatement>($lineno, nullptr);
        }
        ;

    jsonvalue_statement returns [amf::AmfStatementPtr stmtptr] locals [int lineno=0]
        : ( T_JSONVALUE { $lineno = $T_JSONVALUE.line; } ) WS (arg=integer_const) (WS fmt=integer_const)?
        {
            $stmtptr = std::make_shared<amf::JSONValueStatement>($lineno, std::move($arg.argptr), std::move($fmt.argptr));
        }
        ;

I receive the following error:

error(75): amf1.g4:23:10: label stmt=jsonvalue_statement type mismatch with previous definition: stmt=jsonparent_statement

This error is or course quite logical, because the tokens are indeed of a different type, but there return value types are identical. For two (virtual) tokens I can write all the code separatelty, but in my case I have some 40+ different tokens that either represent arguments or statements and writing all the combinations would be cumbersome. The above code did work in Antlr3 by the way.

Is there another way to get around these errors using ANTLR4? Does anybody have any suggestions?


问:
how to focus on an input in Angular
This should be simple but I can't find a solution, the closest answer i can find on SO is this: How do I programmatically set focus to dynamically created FormControl in Angular2

However this is way more convoluted that my requirements. Mine are simple. I have an input in the template like so:

```<code><div *ngIf="someValue">
    <input class="form-control" #swiper formControlName="swipe" placeholder="Swipe">
</div>
</code>```

(Note, it's in an ngx-boostrap form-control group but I'm pretty sure this should not matter)

And I have a button that when clicked calls the following function:

```<code>onClick() {
    this.renderer.invokeElementMethod(this.swiper.nativeElement, 'focus')
}
</code>```

The goal is that when the button is clicked, my input element gets focus.  here is the rest of my component (the relevant parts):

```<code>import { Component, ElementRef, ViewChildren, Renderer } from '@angular/core';
import { MyService } from wherever/my/service/is

export class MyClass {
    @ViewChildren('swiper') input: ElementRef;
    someValue: any = false;

    constructor(private renderer: Renderer, service: MyService) {
       this.service.getSomeData().subscribe(data => {
          this.someValue = true;
       }
    }

    onClick() {
        this.renderer.invokeElementMethod(this.swiper.nativeElement, 'focus');
    }
}
</code>```

The error I get is:

```<code>ERROR TypeError: Cannot read property 'focus' of undefined
at RendererAdapter.invokeElementMethod (core.js:12032)
etc...
</code>```

Any ideas?

(Angular 5 btw)

Note, I edited the code to more accurately reflect what is actually going on, I think there may be some synchronization issue.

答:
If anyone is interested, to focus on an element which is generated dynamically, #name is not possible to keep in the field as attribute. I found a work around using native JS.

```<code><textarea [(ngModel)]="update.newComment"
          [name]="'update-' + index"
          placeholder="comment"></textarea>
</code>```

Now, a trigger to focus on above textarea could be like

```<code><span (click)="focusOn(index);">Comment</span>
</code>```

Click event will be handled in ts as

```<code>focusOn(fieldName) {
    const commmentBoxes = document.querySelectorAll(`textarea[ng-reflect-name="update-${fieldName}"]`);
    for( let i in commmentBoxes) {
        const element: any = commmentBoxes[i];
        const attributs = element.attributes;
        for(let j in attributs) {
            const attribute = attributs[j];
            if (attribute.nodeName === 'ng-reflect-name' && attribute.nodeValue === `update-${fieldName}`) {
                element.focus();
            }

        }

    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: how to focus on an input in Angular

Body:
This should be simple but I can't find a solution, the closest answer i can find on SO is this: How do I programmatically set focus to dynamically created FormControl in Angular2

However this is way more convoluted that my requirements. Mine are simple. I have an input in the template like so:

    <input class="form-control" #swiper formControlName="swipe" placeholder="Swipe">

(Note, it's in an ngx-boostrap form-control group but I'm pretty sure this should not matter)

And I have a button that when clicked calls the following function:

onClick() {
    this.renderer.invokeElementMethod(this.swiper.nativeElement, 'focus')
}

The goal is that when the button is clicked, my input element gets focus.  here is the rest of my component (the relevant parts):

import { Component, ElementRef, ViewChildren, Renderer } from '@angular/core';
import { MyService } from wherever/my/service/is

export class MyClass {
    @ViewChildren('swiper') input: ElementRef;
    someValue: any = false;

    constructor(private renderer: Renderer, service: MyService) {
       this.service.getSomeData().subscribe(data => {
          this.someValue = true;
       }
    }

    onClick() {
        this.renderer.invokeElementMethod(this.swiper.nativeElement, 'focus');
    }
}

The error I get is:

ERROR TypeError: Cannot read property 'focus' of undefined
at RendererAdapter.invokeElementMethod (core.js:12032)
etc...

Any ideas?

(Angular 5 btw)

Note, I edited the code to more accurately reflect what is actually going on, I think there may be some synchronization issue.

Body:
If anyone is interested, to focus on an element which is generated dynamically, #name is not possible to keep in the field as attribute. I found a work around using native JS.

<textarea [(ngModel)]="update.newComment"
          [name]="'update-' + index"
          placeholder="comment"></textarea>

Now, a trigger to focus on above textarea could be like

<span (click)="focusOn(index);">Comment</span>

Click event will be handled in ts as

focusOn(fieldName) {
    const commmentBoxes = document.querySelectorAll(`textarea[ng-reflect-name="update-${fieldName}"]`);
    for( let i in commmentBoxes) {
        const element: any = commmentBoxes[i];
        const attributs = element.attributes;
        for(let j in attributs) {
            const attribute = attributs[j];
            if (attribute.nodeName === 'ng-reflect-name' && attribute.nodeValue === `update-${fieldName}`) {
                element.focus();
            }

        }

    }

}


问:
Convert Venn diagram to grob?
Hi there are several ways to convert R base plots to grob object, however I can't seem to get venn diagrams from the VennDiagram package to do this. I tried two different methods but both failed.  Any ideas? thanks! </p>

```<code>library ( VennDiagram )
library(ggplotify)
library(gridGraphics)

venn.plot <- draw.pairwise.venn(
    area1 = 100,
    area2 = 70,
    cross.area = 30,
    category = c("First", "Second"),
    cat.pos = c(0, 180),
    euler.d = TRUE,
    sep.dist = 0.03,
    rotation.degree = 45
);

grab_grob <- function(){
    grid.echo()
    grid.grab()
}

grid.draw(venn.plot )
g <- grab_grob()
p1 <- as.grob( venn.plot )
</code>```

答:
Your venn.plot object is a gList, a list of grobs. You can use that object directly. If you want p1 with class grob, you can substitute the last line with:

```<code>> p1 <- grobTree(venn.plot)
</code>```

Then,

```<code>> is.grob(p1)
[1] TRUE
> class(p1)
[1] "gTree" "grob"  "gDesc"
</code>```

Title: Convert Venn diagram to grob?

Body:
Hi there are several ways to convert R base plots to grob object, however I can't seem to get venn diagrams from the VennDiagram package to do this. I tried two different methods but both failed.  Any ideas? thanks!

library ( VennDiagram )
library(ggplotify)
library(gridGraphics)

venn.plot <- draw.pairwise.venn(
    area1 = 100,
    area2 = 70,
    cross.area = 30,
    category = c("First", "Second"),
    cat.pos = c(0, 180),
    euler.d = TRUE,
    sep.dist = 0.03,
    rotation.degree = 45
);

grab_grob <- function(){
    grid.echo()
    grid.grab()
}

grid.draw(venn.plot )
g <- grab_grob()
p1 <- as.grob( venn.plot )

Body:
Your venn.plot object is a gList, a list of grobs. You can use that object directly. If you want p1 with class grob, you can substitute the last line with:

> p1 <- grobTree(venn.plot)

Then,

> is.grob(p1)
[1] TRUE
> class(p1)
[1] "gTree" "grob"  "gDesc"


问:
Pdf form is null in itext7
I have created a pdf form with LibreOffice. I exported the form as pdf. I checked the option "Create  pdf form" and I choose the FDF (or PDF) submit format. .

Now I try to retrieve the fields form. I am using itext7. Here the code I am using:

```<code>PdfDocument document = new PdfDocument(new PdfReader(@"file2.pdf"), new PdfWriter("result.pdf"));
var form = iText.Forms.PdfAcroForm.GetAcroForm(document, false);

iText.Forms.Fields.PdfFormField uu = form.GetField("Category");
uu.SetValue("Auto");

document.Close();
</code>```

The problem is form is null...

Can anyone help me please?

Thank you

答:
Instead of calling the method :- form.GetField("Category");

You can use form.getFormFields() to get the list of all the form fields. Then you can check all the form fields. There could be a possibility that you might be entering the wrong form field name.

Title: Pdf form is null in itext7

Body:
I have created a pdf form with LibreOffice. I exported the form as pdf. I checked the option "Create  pdf form" and I choose the FDF (or PDF) submit format. .

Now I try to retrieve the fields form. I am using itext7. Here the code I am using:

PdfDocument document = new PdfDocument(new PdfReader(@"file2.pdf"), new PdfWriter("result.pdf"));
var form = iText.Forms.PdfAcroForm.GetAcroForm(document, false);

iText.Forms.Fields.PdfFormField uu = form.GetField("Category");
uu.SetValue("Auto");

document.Close();

The problem is form is null...

Can anyone help me please?

Thank you


问:
How can I get DetailedSpeechRecognitionResult from Microsoft.CognitiveServices.Speech
I am currently evaluating Azure CognitiveServices Speech. In the API documentation I see that there is a DetailedSpeechRecognitionResult class but I can't find a way to get it.
I create SpeechRecognizer like this:

```<code>var recognizer = factory.CreateSpeechRecognizerWithFileInput(filePath, "en-US", SpeechOutputFormat.Detailed)
</code>```

but I can't find in the documentation a function to return DetailedSpeechRecognitionResult from the SpeechRecognizer.

Am I missing something here?

答:
Ok you can use this follow. First if you use StartContinuousRecognitionAsync() process (when you try to recognized more of 15 second of speech) then you need to create an event inside of CreateSpeechRecognizerWithFileInput function:

```<code>    private async Task RecognitionStart(SpeechRecognizer recognition, TaskCompletionSource<int> breakProcess)
{
recognition.Recognized += RecognizedEventHandler;
}
</code>```

and after, in the event Handler, you can to show the answer detailed of Azure:

```<code> private void RecognizedEventHandler(object sender,SpeechRecognitionEventArgs e)
    {
        if (!string.IsNullOrEmpty(e.Result.Text))
        {
            List<DetailedSpeechRecognitionResult> theBestResult = e.Result.Best().ToList();
            resultingText = $"{string.Format(CultureInfo.InvariantCulture, e.Result.Text)} [Confidence:{theBestResult[0].Confidence}] \n";
        }
    }
</code>```

Body:
I am currently evaluating Azure CognitiveServices Speech. In the API documentation I see that there is a DetailedSpeechRecognitionResult class but I can't find a way to get it.
I create SpeechRecognizer like this:

var recognizer = factory.CreateSpeechRecognizerWithFileInput(filePath, "en-US", SpeechOutputFormat.Detailed)

but I can't find in the documentation a function to return DetailedSpeechRecognitionResult from the SpeechRecognizer.

Am I missing something here?

Body:
Ok you can use this follow. First if you use StartContinuousRecognitionAsync() process (when you try to recognized more of 15 second of speech) then you need to create an event inside of CreateSpeechRecognizerWithFileInput function:

    private async Task RecognitionStart(SpeechRecognizer recognition, TaskCompletionSource<int> breakProcess)
{
recognition.Recognized += RecognizedEventHandler;
}

and after, in the event Handler, you can to show the answer detailed of Azure:

 private void RecognizedEventHandler(object sender,SpeechRecognitionEventArgs e)
    {
        if (!string.IsNullOrEmpty(e.Result.Text))
        {
            List<DetailedSpeechRecognitionResult> theBestResult = e.Result.Best().ToList();
            resultingText = $"{string.Format(CultureInfo.InvariantCulture, e.Result.Text)} [Confidence:{theBestResult[0].Confidence}] \n";
        }
    }


问:
How to send Basic Auth with axios
I'm trying to implement the following code, but something is not working. Here is the code:

      var session_url = 'http://api_address/api/session_endpoint';
      var username = 'user';
      var password = 'password';
      var credentials = btoa(username + ':' + password);
      var basicAuth = 'Basic ' + credentials;
      axios.post(session_url, {
        headers: { 'Authorization': + basicAuth }
      }).then(function(response) {
        console.log('Authenticated');
      }).catch(function(error) {
        console.log('Error on Authentication');
      });
```

It's returning a 401 error. When I do it with Postman there is an option to set Basic Auth; if I don't fill those fields it also returns 401, but if I do, the request is successful.

Any ideas what I'm doing wrong?

Here is part of the docs of the API of how to implement this:

This service uses Basic Authentication information in the header to establish a user session. Credentials are validated against the Server. Using this web-service will create a session with the user credentials passed and return a JSESSIONID. This JSESSIONID can be used in the subsequent requests to make web-service calls.*

答:
The solution given by luschn and pillravi works fine unless you receive a Strict-Transport-Security header in the response.

Adding withCredentials: true will solve that issue.

  axios.post(session_url, {
    withCredentials: true,
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json"
    }
  },{
    auth: {
      username: "USERNAME",
      password: "PASSWORD"
  }}).then(function(response) {
    console.log('Authenticated');
  }).catch(function(error) {
    console.log('Error on Authentication');
  });
```

Title: How to send Basic Auth with axios

Body:
I'm trying to implement the following code, but something is not working. Here is the code:

      var session_url = 'http://api_address/api/session_endpoint';
      var username = 'user';
      var password = 'password';
      var credentials = btoa(username + ':' + password);
      var basicAuth = 'Basic ' + credentials;
      axios.post(session_url, {
        headers: { 'Authorization': + basicAuth }
      }).then(function(response) {
        console.log('Authenticated');
      }).catch(function(error) {
        console.log('Error on Authentication');
      });

It's returning a 401 error. When I do it with Postman there is an option to set Basic Auth; if I don't fill those fields it also returns 401, but if I do, the request is successful.

Any ideas what I'm doing wrong?

Here is part of the docs of the API of how to implement this:

This service uses Basic Authentication information in the header to establish a user session. Credentials are validated against the Server. Using this web-service will create a session with the user credentials passed and return a JSESSIONID. This JSESSIONID can be used in the subsequent requests to make web-service calls.*


问:
Permissions policy that will limit which apps are allowed to request Call Log and SMS permissions
Today I got a mail like this, according to this I’m not able to use RECEIVE_SMS READ_SMS anymore in my app. In my app I’m using auto read OTP. Is there any solution for this?

Hello Google Play Developer,

In October, we announced updates to our Permissions policy that will
  limit which apps are allowed to request Call Log and SMS permissions.
  This policy will impact one or more of your apps.

Only an app that has been selected as a user's default app for making
  calls or text messages, or whose core functionality is approved for
  one of the exception use cases, will be able to request access to Call
  Log or SMS permissions.

Action required

Below, we've listed apps from your catalog which do not meet the
  requirements for permission requests. Please remove any disallowed or
  unused permissions from your app's manifest (specified below), migrate
  to an alternative implementation (e.g. SMS Retriever API for most
  cases of OTP verification), or evaluate if your app qualifies for an
  exception.

Next steps

Read through the Permissions policy and the Play Console Help Center
  article, which describes intended uses, exceptions, invalid uses, and
  alternative implementation options for usage of Call Log or SMS
  permissions.

Update your app or submit a Permissions Declaration Form.

Option 1) If your app does not require access to Call Log or SMS
  permissions: Make appropriate changes to your app by removing the
  specified permissions from your app's manifest or migrating to an
  available alternative implementation by January 9, 2019.

Option 2) If your app is a default handler or you believe your app
  qualifies for an exception: Please submit a request via the
  Permissions Declaration Form. You do not need to have implemented APK
  changes in order to submit a form. Declaration Forms received by
  January 9, 2019 may be eligible for additional time to make changes to
  bring their app(s) into compliance. If you have recently submitted a
  Permissions Declaration Form, we are in the process of reviewing your
  information and will respond to your application.

Make sure that your app is otherwise compliant with all other
  Developer Program Policies to prevent your app from being removed.

Alternatively, you can choose to unpublish the app.

Our Developer Program Policies are designed to provide a safe and
  secure experience for our users while also giving developers the tools
  they need to succeed. That is why we will remove apps that violate our
  policies. In cases of repeated or serious violations of our policies,
  we may also terminate your developer account and any related developer
  accounts.

We appreciate your willingness to partner with us as we make these
  improvements to better protect users.

Affected apps

Affected apps and permissions are listed below, up to 20; if you have
  additional apps, please ensure that they are also compliant with the
  Permissions policy.

答:
If your app not using those permissions and the third-party library using some kind of those permission use below code for avoiding those permissions. it may affect those library smooth functioning

```<code> <uses-permission
        android:name="android.permission.RECEIVE_SMS"
        tools:node="remove" />
    <uses-permission
        android:name="android.permission.READ_SMS"
        tools:node="remove" />
    <uses-permission
        android:name="android.permission.SEND_SMS"
        tools:node="remove" />
</code>```

or else you can use alternate methods in the answers, example

SMS Retriever Api

Body:
If your app not using those permissions and the third-party library using some kind of those permission use below code for avoiding those permissions. it may affect those library smooth functioning

 <uses-permission
        android:name="android.permission.RECEIVE_SMS"
        tools:node="remove" />
    <uses-permission
        android:name="android.permission.READ_SMS"
        tools:node="remove" />
    <uses-permission
        android:name="android.permission.SEND_SMS"
        tools:node="remove" />

or else you can use alternate methods in the answers, example

SMS Retriever Api


问:
React - Expected an assignment or function call and instead saw an expression
Binding the firebase data to Dropdown with condition.
getting the following error
'  Line 424:  Expected an assignment or function call and instead saw an expression  no-unused-expressions
'</p>

```<code>  <TextField
                        id="sp_Role"
                        select
                        label="Select Role"
                        fullWidth
                        required
                        className={classes.textField}
                        value={this.state.sp_Role}
                        helperText={this.state.sp_RoleError}
                        error={!!this.state.sp_RoleError}
                        onChange={this.handleChangedropdown('sp_Role')}
                        SelectProps={{
                          MenuProps: {
                            className: classes.menu,
                          },
                        }}
                        margin="normal"
                      >
                        {role && role.map(option =>
                         {option.role_ActiveFlag==="1" ?        ---424 line
                          (<MenuItem key={option.id} value={option.role_Name}>
                            {option.role_Name}
                          </MenuItem>)
                          :null
                        })}
                      </TextField>
</code>```

答: Move first bracket ( from line 425 to the end of line 424. And I think u should add return on the beginning of 424 or change brackets to ().

Body:
Binding the firebase data to Dropdown with condition.
getting the following error
'  Line 424:  Expected an assignment or function call and instead saw an expression  no-unused-expressions
'

  <TextField
                        id="sp_Role"
                        select
                        label="Select Role"
                        fullWidth
                        required
                        className={classes.textField}
                        value={this.state.sp_Role}
                        helperText={this.state.sp_RoleError}
                        error={!!this.state.sp_RoleError}
                        onChange={this.handleChangedropdown('sp_Role')}
                        SelectProps={{
                          MenuProps: {
                            className: classes.menu,
                          },
                        }}
                        margin="normal"
                      >
                        {role && role.map(option =>
                         {option.role_ActiveFlag==="1" ?        ---424 line
                          (<MenuItem key={option.id} value={option.role_Name}>
                            {option.role_Name}
                          </MenuItem>)
                          :null
                        })}
                      </TextField>


问:
Gulp Error: watch ENOSPC
Hi i'm getting this error while running gulp watch. im using vueify in laravel project.  why is this happening. it was working fine all these days and this came in today.

```<code>$ gulp watch
[12:56:01] Using gulpfile ~/Documents/web_projects/next-home/gulpfile.js
[12:56:01] Starting 'watch'...
[12:56:01] Starting 'browserify'...
Fetching Browserify Source Files...
    - resources/assets/js/app.js
Saving To...
   - public/js/app.js
[12:56:02] Finished 'browserify' after 707 ms
[12:56:02] 'watch' errored after 722 ms
[12:56:02] Error: watch /home/bazi/Documents/web_projects/next-home/resources/assets/less/ ENOSPC
    at exports._errnoException (util.js:893:11)
    at FSWatcher.start (fs.js:1313:19)
    at Object.fs.watch (fs.js:1341:11)
    at Gaze._watchDir (/home/bazi/Documents/web_projects/next-home/node_modules/gaze/lib/gaze.js:289:30)
    at /home/bazi/Documents/web_projects/next-home/node_modules/gaze/lib/gaze.js:358:10
    at iterate (/home/bazi/Documents/web_projects/next-home/node_modules/gaze/lib/helper.js:52:5)
    at Object.forEachSeries (/home/bazi/Documents/web_projects/next-home/node_modules/gaze/lib/helper.js:66:3)
    at Gaze._initWatched (/home/bazi/Documents/web_projects/next-home/node_modules/gaze/lib/gaze.js:354:10)
    at Gaze.add (/home/bazi/Documents/web_projects/next-home/node_modules/gaze/lib/gaze.js:177:8)
    at new Gaze (/home/bazi/Documents/web_projects/next-home/node_modules/gaze/lib/gaze.js:74:10)
events.js:154
      throw er; // Unhandled 'error' event
      ^
Error: watch /home/bazi/Documents/web_projects/next-home/package.json ENOSPC
    at exports._errnoException (util.js:893:11)
    at FSWatcher.start (fs.js:1313:19)
    at Object.fs.watch (fs.js:1341:11)
    at createFsWatchInstance (/home/bazi/Documents/web_projects/next-home/node_modules/chokidar/lib/nodefs-handler.js:37:15)
    at setFsWatchListener (/home/bazi/Documents/web_projects/next-home/node_modules/chokidar/lib/nodefs-handler.js:80:15)
    at FSWatcher.NodeFsHandler._watchWithNodeFs (/home/bazi/Documents/web_projects/next-home/node_modules/chokidar/lib/nodefs-handler.js:228:14)
    at FSWatcher.NodeFsHandler._handleFile (/home/bazi/Documents/web_projects/next-home/node_modules/chokidar/lib/nodefs-handler.js:255:21)
    at FSWatcher.<anonymous> (/home/bazi/Documents/web_projects/next-home/node_modules/chokidar/lib/nodefs-handler.js:473:21)
    at FSReqWrap.oncomplete (fs.js:82:15)
</code>```

and this is my gulpfile.js

```<code>var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');
elixir(function(mix) {
    mix.less('app.less');
    mix.browserify('app.js');
});
</code>```

答:
You have to increase your number of watched files in your system config. Run this command and it will work for you</p>

```<code>echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
</code>```

Title: Gulp Error: watch ENOSPC

Body:
Hi i'm getting this error while running gulp watch. im using vueify in laravel project.  why is this happening. it was working fine all these days and this came in today.

$ gulp watch
[12:56:01] Using gulpfile ~/Documents/web_projects/next-home/gulpfile.js
[12:56:01] Starting 'watch'...
[12:56:01] Starting 'browserify'...
Fetching Browserify Source Files...
    - resources/assets/js/app.js
Saving To...
   - public/js/app.js
[12:56:02] Finished 'browserify' after 707 ms
[12:56:02] 'watch' errored after 722 ms
[12:56:02] Error: watch /home/bazi/Documents/web_projects/next-home/resources/assets/less/ ENOSPC
    at exports._errnoException (util.js:893:11)
    at FSWatcher.start (fs.js:1313:19)
    at Object.fs.watch (fs.js:1341:11)
    at Gaze._watchDir (/home/bazi/Documents/web_projects/next-home/node_modules/gaze/lib/gaze.js:289:30)
    at /home/bazi/Documents/web_projects/next-home/node_modules/gaze/lib/gaze.js:358:10
    at iterate (/home/bazi/Documents/web_projects/next-home/node_modules/gaze/lib/helper.js:52:5)
    at Object.forEachSeries (/home/bazi/Documents/web_projects/next-home/node_modules/gaze/lib/helper.js:66:3)
    at Gaze._initWatched (/home/bazi/Documents/web_projects/next-home/node_modules/gaze/lib/gaze.js:354:10)
    at Gaze.add (/home/bazi/Documents/web_projects/next-home/node_modules/gaze/lib/gaze.js:177:8)
    at new Gaze (/home/bazi/Documents/web_projects/next-home/node_modules/gaze/lib/gaze.js:74:10)
events.js:154
      throw er; // Unhandled 'error' event
      ^
Error: watch /home/bazi/Documents/web_projects/next-home/package.json ENOSPC
    at exports._errnoException (util.js:893:11)
    at FSWatcher.start (fs.js:1313:19)
    at Object.fs.watch (fs.js:1341:11)
    at createFsWatchInstance (/home/bazi/Documents/web_projects/next-home/node_modules/chokidar/lib/nodefs-handler.js:37:15)
    at setFsWatchListener (/home/bazi/Documents/web_projects/next-home/node_modules/chokidar/lib/nodefs-handler.js:80:15)
    at FSWatcher.NodeFsHandler._watchWithNodeFs (/home/bazi/Documents/web_projects/next-home/node_modules/chokidar/lib/nodefs-handler.js:228:14)
    at FSWatcher.NodeFsHandler._handleFile (/home/bazi/Documents/web_projects/next-home/node_modules/chokidar/lib/nodefs-handler.js:255:21)
    at FSWatcher.<anonymous> (/home/bazi/Documents/web_projects/next-home/node_modules/chokidar/lib/nodefs-handler.js:473:21)
    at FSReqWrap.oncomplete (fs.js:82:15)

and this is my gulpfile.js

var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');
elixir(function(mix) {
    mix.less('app.less');
    mix.browserify('app.js');
});

Body:
You have to increase your number of watched files in your system config. Run this command and it will work for you

echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p


问:
Numbering row in order by ID
Sorry if this post is not well organized, first time stack overflower...

I am trying to create a column to create a order within each IDs, but the twist is that if there is a gap year, order needs to start from the beginning.
Please check example and expected result below.

I wasn't able to find appropriate code for it.. I cannot think of anything :( Please help me! I appreciate alot!

答:
One option is to create a new group variable when difference between the year is greater than 1 and create a sequence in each group using row_number().

```<code>library(dplyr)
df %>%
  group_by(ID, group = cumsum(c(1, diff(Year) > 1))) %>%
  mutate(order = row_number()) %>%
  ungroup() %>%
  select(-group)

#    ID     Year order
#   <fct>  <int> <int>
# 1  A      2007     1
# 2  A      2008     2
# 3  A      2009     3
# 4  A      2013     1
# 5  A      2014     2
# 6  A      2015     3
# 7  A      2016     4
# 8  B      2010     1
# 9  B      2012     1
#10  B      2013     2
</code>```

Using base R ave that would be

```<code>as.integer(with(df, ave(ID, ID, cumsum(c(1, diff(Year) > 1)), FUN = seq_along)))
#[1] 1 2 3 1 2 3 4 1 1 2
</code>```

data

```<code>df <- data.frame(ID = c(rep("A", 7), rep("B", 3)),
       Year = c(2007:2009, 2013:2016, 2010, 2012, 2013), stringsAsFactors = FALSE)
</code>```

Title: Numbering row in order by ID

Body:
One option is to create a new group variable when difference between the year is greater than 1 and create a sequence in each group using row_number().

library(dplyr)
df %>%
  group_by(ID, group = cumsum(c(1, diff(Year) > 1))) %>%
  mutate(order = row_number()) %>%
  ungroup() %>%
  select(-group)

#    ID     Year order
#   <fct>  <int> <int>
# 1  A      2007     1
# 2  A      2008     2
# 3  A      2009     3
# 4  A      2013     1
# 5  A      2014     2
# 6  A      2015     3
# 7  A      2016     4
# 8  B      2010     1
# 9  B      2012     1
#10  B      2013     2

Using base R ave that would be

as.integer(with(df, ave(ID, ID, cumsum(c(1, diff(Year) > 1)), FUN = seq_along)))
#[1] 1 2 3 1 2 3 4 1 1 2

data

df <- data.frame(ID = c(rep("A", 7), rep("B", 3)),
       Year = c(2007:2009, 2013:2016, 2010, 2012, 2013), stringsAsFactors = FALSE)


问:
Disable pointer-event when hovering router button if disabled
Is it possible to turn off pointer-events on disabled Routerbuttons? My state on the Route is set to disabled due to some criterias not fulfilled that early, but it's still possible to point on it and click, even tho its not doing anything than trigger a message. Do I need to add css class on the route? Was hoping I didn't need to do that.

<Route
      disabled={saving || ableToWork === false}
      requiresValidation
      key={`${match.url}/receipt`}
      label={formatMessage(GeneralMessages.verify)}
      loc={`${match.url}/receipt`}
      path={`${match.path}receipt`}
      render={() => (
        <Receipt
          {...rest}
          match={match}
          onCancel={this.onCancel}
          onBack={this.handleOnBack}
        />
      )}
    />,
```

答:
Yes you have to use CSS for this.

The Route component doesn't handle this : docs


问:
How extend task provided by plugin?
I have kotlin2js plugin with task compileKotlin2Js. I configure it like this:

```<code>val compileKotlin2Js: Kotlin2JsCompile by tasks
compileKotlin2Js.kotlinOptions {
    main = "call"
    outputFile = "${projectDir}/build/app.js"
}
</code>```

Now I want to create similar task, but with other kotlinOptions. For example:

```<code>.kotlinOptions {
    main = "noCall"
    outputFile = "${projectDir}/build/lib.js"
}
</code>```

How to do it?

UPDATE: I also tried to do some thing like this:

```<code>tasks.register<Kotlin2JsCompile>("myCompile2Js") {
    kotlinOptions {
        main = "noCall"
        outputFile = "${projectDir}/build/lib.js"
    }
}
</code>```

But it produce error:

```<code>Execution failed for task ':myCompile2Js'.
> lateinit property destinationDirProvider has not been initialized
</code>```

I also tried to specify destinationDir. Error disappear, but such task does not produce any build.

答:
I haven't tested it, but I believe something like the following should do the trick:

```<code>tasks.register<Kotlin2JsCompile>("myCompile2Js") {
    kotlinOptions {
        main = "noCall"
        outputFile = "${projectDir}/build/lib.js"
    }
}
</code>```

Or if you need a reference to the task later on:

```<code>val myCompile2Js by tasks.creating(Kotlin2JsCompile::class)
myCompile2Js.kotlinOptions {
    main = "noCall"
    outputFile = "${projectDir}/build/lib.js"
}
</code>```

Title: How extend task provided by plugin?

Body:
I have kotlin2js plugin with task compileKotlin2Js. I configure it like this:

val compileKotlin2Js: Kotlin2JsCompile by tasks
compileKotlin2Js.kotlinOptions {
    main = "call"
    outputFile = "${projectDir}/build/app.js"
}

Now I want to create similar task, but with other kotlinOptions. For example:

.kotlinOptions {
    main = "noCall"
    outputFile = "${projectDir}/build/lib.js"
}

How to do it?

UPDATE: I also tried to do some thing like this:

tasks.register<Kotlin2JsCompile>("myCompile2Js") {
    kotlinOptions {
        main = "noCall"
        outputFile = "${projectDir}/build/lib.js"
    }
}

But it produce error:

Execution failed for task ':myCompile2Js'.
> lateinit property destinationDirProvider has not been initialized

I also tried to specify destinationDir. Error disappear, but such task does not produce any build.

Body:
I haven't tested it, but I believe something like the following should do the trick:

tasks.register<Kotlin2JsCompile>("myCompile2Js") {
    kotlinOptions {
        main = "noCall"
        outputFile = "${projectDir}/build/lib.js"
    }
}

Or if you need a reference to the task later on:

val myCompile2Js by tasks.creating(Kotlin2JsCompile::class)
myCompile2Js.kotlinOptions {
    main = "noCall"
    outputFile = "${projectDir}/build/lib.js"
}


问:
dynamically map array items to java.reflect.Field objects
I need to write code that simulates having a user-defined number of fields available in a class at runtime. The idea being to be able to return java.reflect.Field objects pointing to those "dynamic" fields to client-code.

```<code>class DynamicFieldClass {
 /**
  * fieldNames is the list of names of the fields we want to "exist" in the class
  * they will all be of the same type (say String)
  */
 public DynamicFieldClass(List<String> fieldNames) {
 // ... what do we do here
 }
 public Field getFieldObjectFor(String desiredFieldName) {
 // ... what do we do here
 }
}
</code>```

Is there something similar to DynamicProxy (but for fields)?
Thanks

答:
I ended up using Javassist to :
- create a new class definition at runtime that inherits from my original class
- inject the fields I needed into the new class definition

I also replaced the public constructor by a static factory method that makes and returns an instance of the new class definition. All in all, the code looks like this:

```<code>class DynamicFieldClass {
protected DynamicFieldClass()   {
}
public Field getFieldObjectFor(String desiredFieldName) {
    return null;
}

/**
* fieldNames is the list of names of the fields we want to "exist" in the class
* they will all be of the same type (say String)
*/
public static createInstance (List<String> fieldNames)  {
    ClassPool defaultClassPool = ClassPool.getDefault();
    CtClass originalClass = defaultClassPool.get("DynamicFieldClass");
    CtClass newClass = defaultClassPool.makeClass("modified_DynamicFieldClass", originalClass);

    StringBuilder getterCore = new StringBuilder();
    for (String item : fieldNames)  {
        CtField addedField = CtField.make(String.format("private String %s;", item), newClass);
        newClass.addField(addedField);
        getterCore.append(String.format("if \"%s\".equals(%1) { return this.class.getDeclaredField(%s);}", item, item));
    }
    getterCore.append("throw new IllegalArgumentException(\"Unknown field name: \" + $1);");
    final String sourceGeneralGetter = String.format("{%s}", getterCore.toString());
    CtMethod mold = originalClass.getDeclaredMethod("getFieldObjectFor");
    CtMethod copiedMeth = CtNewMethod.copy(mold, newClass, null);
    newClass.addMethod(copiedMeth);
    CtMethod getMeth = newClass.getDeclaredMethod("getFieldObjectFor");
    getMeth.setBody(sourceGeneralGetter);
    CtConstructor defaultCtor = new CtConstructor(new CtClass[0], newClass);
    defaultCtor.setBody("{}");
    newClass.addConstructor(defaultCtor);
    Class modifiedClass = newClass.toClass();
    return modifiedClass.newInstance();
}
</code>```

}

ContentLicense: CC BY-SA 2.5

Body:
I need to write code that simulates having a user-defined number of fields available in a class at runtime. The idea being to be able to return java.reflect.Field objects pointing to those "dynamic" fields to client-code.

class DynamicFieldClass {
 /**
  * fieldNames is the list of names of the fields we want to "exist" in the class
  * they will all be of the same type (say String)
  */
 public DynamicFieldClass(List<String> fieldNames) {
 // ... what do we do here
 }
 public Field getFieldObjectFor(String desiredFieldName) {
 // ... what do we do here
 }
}

Is there something similar to DynamicProxy (but for fields)?
Thanks

Body:
I ended up using Javassist to :
- create a new class definition at runtime that inherits from my original class
- inject the fields I needed into the new class definition

I also replaced the public constructor by a static factory method that makes and returns an instance of the new class definition. All in all, the code looks like this:

class DynamicFieldClass {
protected DynamicFieldClass()   {
}
public Field getFieldObjectFor(String desiredFieldName) {
    return null;
}

/**
* fieldNames is the list of names of the fields we want to "exist" in the class
* they will all be of the same type (say String)
*/
public static createInstance (List<String> fieldNames)  {
    ClassPool defaultClassPool = ClassPool.getDefault();
    CtClass originalClass = defaultClassPool.get("DynamicFieldClass");
    CtClass newClass = defaultClassPool.makeClass("modified_DynamicFieldClass", originalClass);

    StringBuilder getterCore = new StringBuilder();
    for (String item : fieldNames)  {
        CtField addedField = CtField.make(String.format("private String %s;", item), newClass);
        newClass.addField(addedField);
        getterCore.append(String.format("if \"%s\".equals(%1) { return this.class.getDeclaredField(%s);}", item, item));
    }
    getterCore.append("throw new IllegalArgumentException(\"Unknown field name: \" + $1);");
    final String sourceGeneralGetter = String.format("{%s}", getterCore.toString());
    CtMethod mold = originalClass.getDeclaredMethod("getFieldObjectFor");
    CtMethod copiedMeth = CtNewMethod.copy(mold, newClass, null);
    newClass.addMethod(copiedMeth);
    CtMethod getMeth = newClass.getDeclaredMethod("getFieldObjectFor");
    getMeth.setBody(sourceGeneralGetter);
    CtConstructor defaultCtor = new CtConstructor(new CtClass[0], newClass);
    defaultCtor.setBody("{}");
    newClass.addConstructor(defaultCtor);
    Class modifiedClass = newClass.toClass();
    return modifiedClass.newInstance();
}

}


问:
Error installing nuget package Swashbuckle
I'm trying to install nuget package Swashbuckle to a new project that will get me swagger things. I created the project and then tried to add project but I'm getting the error:

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   NU1107  Version conflict detected for Microsoft.AspNet.WebApi.Client. Install/reference Microsoft.AspNet.WebApi.Client 5.2.6 directly to project TestAPI to resolve this issue.
 TestAPI -> Microsoft.AspNetCore.App 2.1.1 -> Microsoft.AspNet.WebApi.Client (>= 5.2.6 && < 5.3.0)
 TestAPI -> Swashbuckle 5.6.0 -> Microsoft.AspNet.WebApi.WebHost 4.0.20710 -> Microsoft.AspNet.WebApi.Core 4.0.20710 -> Microsoft.AspNet.WebApi.Client (>= 4.0.20710 && < 4.1.0).   TestAPI
</code>```

How do I resolve this error? I have upgraded all packages and things I could find...

答:
Try this:

```<code>PM> Install-Package Swashbuckle.AspNetCore --version 4.0.1
</code>```

Reference : Get started with Swashbuckle and ASP.NET Core

Body:
I'm trying to install nuget package Swashbuckle to a new project that will get me swagger things. I created the project and then tried to add project but I'm getting the error:

Severity    Code    Description Project File    Line    Suppression State
Error   NU1107  Version conflict detected for Microsoft.AspNet.WebApi.Client. Install/reference Microsoft.AspNet.WebApi.Client 5.2.6 directly to project TestAPI to resolve this issue.
 TestAPI -> Microsoft.AspNetCore.App 2.1.1 -> Microsoft.AspNet.WebApi.Client (>= 5.2.6 && < 5.3.0)
 TestAPI -> Swashbuckle 5.6.0 -> Microsoft.AspNet.WebApi.WebHost 4.0.20710 -> Microsoft.AspNet.WebApi.Core 4.0.20710 -> Microsoft.AspNet.WebApi.Client (>= 4.0.20710 && < 4.1.0).   TestAPI

How do I resolve this error? I have upgraded all packages and things I could find...

Body:
Try this:

PM> Install-Package Swashbuckle.AspNetCore --version 4.0.1

Reference : Get started with Swashbuckle and ASP.NET Core


问:
How to use authlib without https
I would like to know if there is a way to tell authlib to ignore the lack of HTTPS in my dev environment instead of throwing an InsecureTransportError.

答:
As mentionned here you can set an environment variable :

```<code>export AUTHLIB_INSECURE_TRANSPORT=1
</code>```

Or if you want to set it programmatically

```<code># Somewhere in webapp_example.py, before the app.run for example
import os
os.environ['AUTHLIB_INSECURE_TRANSPORT'] = '1'
</code>```

Title: How to use authlib without https

Body:
As mentionned here you can set an environment variable :

export AUTHLIB_INSECURE_TRANSPORT=1

Or if you want to set it programmatically

# Somewhere in webapp_example.py, before the app.run for example
import os
os.environ['AUTHLIB_INSECURE_TRANSPORT'] = '1'


问:
How to fix: 'Error in strwidth' when plotting legend
I am trying to plot a line chart with points with a legend based on the colour of the points. The chart plots correctly but the legend does not display.

The data behind the chart is a format of a dataframe with 4 columns - Month, variable (e.g. specific users), value (a numeric value representing a score) and colour (a red/amber/green value based on the numeric score).

The chart code is as follows:

```<code>ggplot(data = meltdf2, aes(x = Month, y = variable, group = variable)) +
  geom_line(linetype = "dashed", colour = "grey") +
  geom_point(colour = meltdf2$colour, size = 3) +
  scale_x_date(date_breaks = "1 month" , date_labels = "%b-%y") +
  theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(),
        axis.line.x = element_line(colour = "darkgrey"),
        panel.background = element_rect(fill = "white"),
        panel.grid.major = element_blank(), panel.grid.minor = element_blank())

legend("topleft", legend = c("High", "Mid", "Low"), pch = 1,  col= c("red2","gold","limegreen"))
</code>```

Regardless of whether I run the plot and legend code separately or together and if I include them in the same paraentheses or not, I get the error:
Error in strwidth(legend, units = "user", cex = cex, font = text.font) : plot.new has not been called yet

Any advice on how to get the legend to display would be much appreciated.

答:
Answer based on @r2evans comment above:

The issue was indeed trying to use base graphics commands with a ggplot graphic.

To solve this and display the required legend I created a palette vector (pal), with names based on the values of the melt2df$colour variable in the source dataframe. This vector was included in the plot code as part of ascale_colour_manual function. An aes function was used within the geom_point function to wrap the various aesthetic requirements for the series.

Completed code shown below:

```<code>pal <- c("High"="red2","Mid"="gold","Low" = "limegreen","NA"= "NA")

#create plot with line and points.
#colour of points based on colour column of meltdf2
ggplot(data = meltdf2, aes(x = Month, y = variable, group = variable)) +
  geom_line(linetype = "dashed", colour = "grey") +
  geom_point(aes(colour = meltdf2$colour, size = 3)) +
  scale_colour_manual(values = pal, limits = names(pal)) +
  scale_x_date(date_breaks = "1 month" , date_labels = "%b-%y") +
  theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(),
        axis.line.x = element_line(colour = "darkgrey"),
        panel.background = element_rect(fill = "white"),
        panel.grid.major = element_blank(), panel.grid.minor = element_blank())
</code>```

Body:
I am trying to plot a line chart with points with a legend based on the colour of the points. The chart plots correctly but the legend does not display.

The data behind the chart is a format of a dataframe with 4 columns - Month, variable (e.g. specific users), value (a numeric value representing a score) and colour (a red/amber/green value based on the numeric score).

The chart code is as follows:

ggplot(data = meltdf2, aes(x = Month, y = variable, group = variable)) +
  geom_line(linetype = "dashed", colour = "grey") +
  geom_point(colour = meltdf2$colour, size = 3) +
  scale_x_date(date_breaks = "1 month" , date_labels = "%b-%y") +
  theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(),
        axis.line.x = element_line(colour = "darkgrey"),
        panel.background = element_rect(fill = "white"),
        panel.grid.major = element_blank(), panel.grid.minor = element_blank())

legend("topleft", legend = c("High", "Mid", "Low"), pch = 1,  col= c("red2","gold","limegreen"))

Regardless of whether I run the plot and legend code separately or together and if I include them in the same paraentheses or not, I get the error:
Error in strwidth(legend, units = "user", cex = cex, font = text.font) : plot.new has not been called yet

Any advice on how to get the legend to display would be much appreciated.

Body:
Answer based on @r2evans comment above:

The issue was indeed trying to use base graphics commands with a ggplot graphic.

To solve this and display the required legend I created a palette vector (pal), with names based on the values of the melt2df$colour variable in the source dataframe. This vector was included in the plot code as part of ascale_colour_manual function. An aes function was used within the geom_point function to wrap the various aesthetic requirements for the series.

Completed code shown below:

pal <- c("High"="red2","Mid"="gold","Low" = "limegreen","NA"= "NA")

#create plot with line and points.
#colour of points based on colour column of meltdf2
ggplot(data = meltdf2, aes(x = Month, y = variable, group = variable)) +
  geom_line(linetype = "dashed", colour = "grey") +
  geom_point(aes(colour = meltdf2$colour, size = 3)) +
  scale_colour_manual(values = pal, limits = names(pal)) +
  scale_x_date(date_breaks = "1 month" , date_labels = "%b-%y") +
  theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(),
        axis.line.x = element_line(colour = "darkgrey"),
        panel.background = element_rect(fill = "white"),
        panel.grid.major = element_blank(), panel.grid.minor = element_blank())


问:
How to get JSON data from an API in flutter
I'm facing the same issue since i start coding yesterday on my project which has a part of getting some of json data from a given api.

My api link is: http://alkadhum-col.edu.iq/wp-json/wp/v2/posts?_embed

I'm working on flutter SDK and i'm confused why it is not working with me!, my job is to get only link, title, and source_url objects but i cannot get it.

I tried the following code in flutter documentation

https://flutter.dev/docs/cookbook/networking/fetch-data
and after some of modification according to my needs didn't got any data.

```<code>import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Post> fetchPost() async {
  final response =
      await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

class Post {

  final int id;
  String title;
  String link;

  Post({this.id, this.title, this.link});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title'].toString(),
      link: json['link'].toString()
    );
  }
}

void main() => runApp(MyApp(post: fetchPost()));

class MyApp extends StatelessWidget {
  final Future<Post> post;

  MyApp({Key key, this.post}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Post>(
            future: post,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.link);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}
</code>```

I only got the meesage below:

Type List dynamic is not a subtype of type Map String, dynamic

Any help will be appreciated.

Thanks in advance.

答:
You need to change your class. you need to create your class structure as per the JSON response.

```<code>class Post {
  int id;
  String title;
  String link;

  Post({this.id, this.title, this.link});

  factory Post.fromJson(Map<String, dynamic> json) {
     return Post(
         id: json['id'],
         title: title = json['title'] != null ? new Title.fromJson(json['title']) : null;
         link: json['link'].toString()
        );
    }
 }

class Title {
    String rendered;

    Title({this.rendered});

     Title.fromJson(Map<String, dynamic> json) {
          rendered = json['rendered'];
      }

       Map<String, dynamic> toJson() {
          final Map<String, dynamic> data = new Map<String, dynamic>();
          data['rendered'] = this.rendered;
          return data;
        }
  }
</code>```

Then, in your API method. As the response, you are getting is a JSON array. So, take that in a list and cast the response into your JSON class.

```<code>Future<List<Post>> fetchPost() async {
  final response =
        await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

     if (response.statusCode == 200) {
       // If the call to the server was successful, parse the JSON
        var lst = response.body as List;
        return lst.map((d) => Post.fromJson(d)).toList();
      } else {
        // If that call was not successful, throw an error.
          throw Exception('Failed to load post');
      }
 }
</code>```

You can always use tools like https://javiercbk.github.io/json_to_dart/ to create Dart classes from complex JSON. Which saves a lot of time.

Body:
I'm facing the same issue since i start coding yesterday on my project which has a part of getting some of json data from a given api.

My api link is: http://alkadhum-col.edu.iq/wp-json/wp/v2/posts?_embed

I'm working on flutter SDK and i'm confused why it is not working with me!, my job is to get only link, title, and source_url objects but i cannot get it.

I tried the following code in flutter documentation

https://flutter.dev/docs/cookbook/networking/fetch-data
and after some of modification according to my needs didn't got any data.

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Post> fetchPost() async {
  final response =
      await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

class Post {

  final int id;
  String title;
  String link;

  Post({this.id, this.title, this.link});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title'].toString(),
      link: json['link'].toString()
    );
  }
}

void main() => runApp(MyApp(post: fetchPost()));

class MyApp extends StatelessWidget {
  final Future<Post> post;

  MyApp({Key key, this.post}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Post>(
            future: post,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.link);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

I only got the meesage below:

Type List dynamic is not a subtype of type Map String, dynamic

Any help will be appreciated.

Thanks in advance.

Body:
You need to change your class. you need to create your class structure as per the JSON response.

class Post {
  int id;
  String title;
  String link;

  Post({this.id, this.title, this.link});

  factory Post.fromJson(Map<String, dynamic> json) {
     return Post(
         id: json['id'],
         title: title = json['title'] != null ? new Title.fromJson(json['title']) : null;
         link: json['link'].toString()
        );
    }
 }

class Title {
    String rendered;

    Title({this.rendered});

     Title.fromJson(Map<String, dynamic> json) {
          rendered = json['rendered'];
      }

       Map<String, dynamic> toJson() {
          final Map<String, dynamic> data = new Map<String, dynamic>();
          data['rendered'] = this.rendered;
          return data;
        }
  }

Then, in your API method. As the response, you are getting is a JSON array. So, take that in a list and cast the response into your JSON class.

Future<List<Post>> fetchPost() async {
  final response =
        await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

     if (response.statusCode == 200) {
       // If the call to the server was successful, parse the JSON
        var lst = response.body as List;
        return lst.map((d) => Post.fromJson(d)).toList();
      } else {
        // If that call was not successful, throw an error.
          throw Exception('Failed to load post');
      }
 }

You can always use tools like https://javiercbk.github.io/json_to_dart/ to create Dart classes from complex JSON. Which saves a lot of time.


问:
Using Mongoid query syntax vs Activerecord
I'm having a little conundrum that I am confused by.

In rails console if I use

```<code>@o = ObjName.where(o_id: "VAL")
</code>```

I don't get an object returned.  I get this though:

```<code> => #<Mongoid::Criteria
  selector: {:conditions=>{:site_id=>"PST"}},
  options:  {},
  class:    Site,
  embedded: false>
</code>```

But if I use:

```<code>@o = ObjName.first(:conditions => {:o_id => "VAL"})
</code>```

I do.  There where function is used within Mongoid, and my model includes Mongoid.  So I don't understand why this doesn't work.

答:
Mongoid is very lazy in its loading. It will only execute the query and load the results into objects when you iterate over the results.

So Model.find will execute the mongodb findOne method and load into results.

```<code>@o = ObjName.where(o_id=>"VAL").first #will push into an object

@o = ObjName.where(:status=>"whoknows").all
#query has not been loaded
@o.each do |o|
  #now the query has been executed
  puts o
end
</code>```

Body:
I'm having a little conundrum that I am confused by.

In rails console if I use

@o = ObjName.where(o_id: "VAL")

I don't get an object returned.  I get this though:

 => #<Mongoid::Criteria
  selector: {:conditions=>{:site_id=>"PST"}},
  options:  {},
  class:    Site,
  embedded: false>

But if I use:

@o = ObjName.first(:conditions => {:o_id => "VAL"})

I do.  There where function is used within Mongoid, and my model includes Mongoid.  So I don't understand why this doesn't work.

Body:
Mongoid is very lazy in its loading. It will only execute the query and load the results into objects when you iterate over the results.

So Model.find will execute the mongodb findOne method and load into results.

@o = ObjName.where(o_id=>"VAL").first #will push into an object

@o = ObjName.where(:status=>"whoknows").all
#query has not been loaded
@o.each do |o|
  #now the query has been executed
  puts o
end


问:
C# WPF - Tasks vs Multithreading, and updating UI components from them
So basically I'm using C# to write a port scanning WPF application, that will scan over a thousand combinations of ports and IPs (x.x.x.x:xx). As a result, I have to split this process up into multiple threads to quicken the process and avoid making the UI freeze. Shown below is my code for the MainWindow:

```<code>namespace PortScannerTool
{
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
            tb_portstatus.Text = "Click the button to query ports";
            dns_info.Text = tb_portstatus.Text;
        }

        private void Btn1_Click(object sender, RoutedEventArgs e)
        {

            CmdExec cmdobj = new CmdExec("127.0.0.0","8080");
            Thread query_status = new Thread(cmdobj.Runcmd);
            query_status.Start();
            tb_portstatus.Text = "Done!";
        }
    }
}
</code>```

```<code>namespace PortQueryApp
{
    class CmdExec
    {

        string command;
        public string dnsText;
        public string querystatusText;

        public CmdExec(string ip, string port)
        {
           this.command = $"-n {ip} -o {port}";
        }

        public void Runcmd()
        {
            Process proc = new Process();
            proc.StartInfo.FileName = "PortQry.exe";
            proc.StartInfo.Arguments = this.command;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.Start();
            string query_output = proc.StandardOutput.ReadToEnd();
            proc.WaitForExit();

            string resolve_pass = "Name resolved";
            string resolve_fail = "Failed to resolve IP address to name";

            if (query_output.Contains(resolve_pass))
            {
                this.dnsText = "Resolved!";
            }
            if (query_output.Contains(resolve_fail))
            {
                this.dnsText = "Resolve Failed!";
            }

            this.querystatusText = "Done!";

        }
    }
}
</code>```

dns_info and tb_portstatus are XAML Textboxes. CmdExec.Rumcmd is the method that does the actual port scanning itself. If you look at the CmdExec class, PortQry.exe is the microsoft port query tool.

So I want to get the cmdobj.Runcmd method to update the UI once it's done running. But I don't know how to do so, I've Googled this extensively, and I'm getting some people suggesting using delegates, Tasks and BackgroundWorkers, not sure which method would be best for my case.

Could anyone give some suggestions or point me to any guides? That'd be awesome! Thanks!

Edit: Most examples have their Multithreaded method within the same class as well. I'm not sure if this is required, but should I use:

```<code> class CmdExec : MainWindow
{
   //Do stuff
}
</code>```

instead?

答:
What you SHOULD do is:
Give some events CmdExec so that they can be fired when something changes, for example:

```<code>public delegate void CombinationFoundDelegate(object sender, int port, string ip);
//note that it would be better to create class derived from EventArgs instead of passing bare arguments in this delegate
public class CmdExec
{
    public event CombinationFoundDelegate CombinationFound;

    public void Runcmd()
    {
       //do your work and call event when necessary:
       if(CanConnect(ip, port))
         CombinationFound?.Invoke(this, port, ip);
    }
}
</code>```

And then on your form just listen to this event:

```<code>cmdobj.CombinationFound += new CombinationFoundCallback;
</code>```

And all the GUI updates may happen in this callback. But, you have to be aware that this callback is called from different thread (as CmdExec runs on different thread), so you need to synchronize your controls. You can use it Dispatcher for that case:

```<code>Action a = new Action(() => textBox.Text = ip);

if(!Dispatcher.CheckAccess())
   Dispatcher.Invoke(a);
else
   a();
</code>```

So, note that CheckAccess is for some reason hidden in Intellisense, but it's really there. CheckAccess just cheks wheter synchronization is required or not (in Winforms it would be InvokeRequired).

Next, if synchronization is required, you can run your UI update code inside dispatcher invoke method. However, if not synchronization is required, you can just run your ui code here. That's why I have created Action for this - not to duplicate the code.

And that's simply it.
(Code written from head, so there can be some difference with real code, but this is how it should look and work).

Body:
So basically I'm using C# to write a port scanning WPF application, that will scan over a thousand combinations of ports and IPs (x.x.x.x:xx). As a result, I have to split this process up into multiple threads to quicken the process and avoid making the UI freeze. Shown below is my code for the MainWindow:

namespace PortScannerTool
{
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
            tb_portstatus.Text = "Click the button to query ports";
            dns_info.Text = tb_portstatus.Text;
        }

        private void Btn1_Click(object sender, RoutedEventArgs e)
        {

            CmdExec cmdobj = new CmdExec("127.0.0.0","8080");
            Thread query_status = new Thread(cmdobj.Runcmd);
            query_status.Start();
            tb_portstatus.Text = "Done!";
        }
    }
}

namespace PortQueryApp
{
    class CmdExec
    {

        string command;
        public string dnsText;
        public string querystatusText;

        public CmdExec(string ip, string port)
        {
           this.command = $"-n {ip} -o {port}";
        }

        public void Runcmd()
        {
            Process proc = new Process();
            proc.StartInfo.FileName = "PortQry.exe";
            proc.StartInfo.Arguments = this.command;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.Start();
            string query_output = proc.StandardOutput.ReadToEnd();
            proc.WaitForExit();

            string resolve_pass = "Name resolved";
            string resolve_fail = "Failed to resolve IP address to name";

            if (query_output.Contains(resolve_pass))
            {
                this.dnsText = "Resolved!";
            }
            if (query_output.Contains(resolve_fail))
            {
                this.dnsText = "Resolve Failed!";
            }

            this.querystatusText = "Done!";

        }
    }
}

dns_info and tb_portstatus are XAML Textboxes. CmdExec.Rumcmd is the method that does the actual port scanning itself. If you look at the CmdExec class, PortQry.exe is the microsoft port query tool.

So I want to get the cmdobj.Runcmd method to update the UI once it's done running. But I don't know how to do so, I've Googled this extensively, and I'm getting some people suggesting using delegates, Tasks and BackgroundWorkers, not sure which method would be best for my case.

Could anyone give some suggestions or point me to any guides? That'd be awesome! Thanks!

Edit: Most examples have their Multithreaded method within the same class as well. I'm not sure if this is required, but should I use:

 class CmdExec : MainWindow
{
   //Do stuff
}

instead?

Body:
What you SHOULD do is:
Give some events CmdExec so that they can be fired when something changes, for example:

public delegate void CombinationFoundDelegate(object sender, int port, string ip);
//note that it would be better to create class derived from EventArgs instead of passing bare arguments in this delegate
public class CmdExec
{
    public event CombinationFoundDelegate CombinationFound;

    public void Runcmd()
    {
       //do your work and call event when necessary:
       if(CanConnect(ip, port))
         CombinationFound?.Invoke(this, port, ip);
    }
}

And then on your form just listen to this event:

cmdobj.CombinationFound += new CombinationFoundCallback;

And all the GUI updates may happen in this callback. But, you have to be aware that this callback is called from different thread (as CmdExec runs on different thread), so you need to synchronize your controls. You can use it Dispatcher for that case:

Action a = new Action(() => textBox.Text = ip);

if(!Dispatcher.CheckAccess())
   Dispatcher.Invoke(a);
else
   a();

So, note that CheckAccess is for some reason hidden in Intellisense, but it's really there. CheckAccess just cheks wheter synchronization is required or not (in Winforms it would be InvokeRequired).

Next, if synchronization is required, you can run your UI update code inside dispatcher invoke method. However, if not synchronization is required, you can just run your ui code here. That's why I have created Action for this - not to duplicate the code.

And that's simply it.
(Code written from head, so there can be some difference with real code, but this is how it should look and work).


问:
jsPDF Big table, headers overlap in second page
I'm using jsPDF and svg_to_pdf to export both an SVG and a table to a PDF. This is my code:

```<code>function svg_to_pdf(svg, callback) {

console.log("svgtopdf.js");
svgAsDataUri(svg, {}, function(svg_uri) {
var image = document.createElement('img');

image.src = svg_uri;
image.onload = function() {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');
  var doc = new jsPDF('portrait', 'pt', 'a4', true);
  var dataUrl;

  source = $('#datos_alumnos')[0];
  specialElementHandlers = {
      '#bypassme' : function(element, renderer){
          return true;
      }
  };

  margins = {
            top: 40,
            bottom: 60,
            left: 40,
            width: 270
        };

  canvas.width = image.width;
  canvas.height = image.height;
  context.drawImage(image, 0, 0, image.width, image.height);
  dataUrl = canvas.toDataURL('image/jpeg');
  doc.addImage(dataUrl, 'JPEG', 0, 0, 500, 263);

  doc.fromHTML(
    source,
    40,
    270, {
        'width': 550,
        'elementHandlers': specialElementHandlers
    },

    function(dispose){
        //doc.save('SVG.pdf');
    }
    , margins);

callback(doc);
}
});
}
</code>```

The result is a PDF with the image at the top and the table next. The problem comes when it enters the second page as the headers of the table overlap with the first row and it looks like this.

http://i.imgur.com/vlfm4Fv.png

Is it possible to remove the headers on the second page?

答:
When you draw table, just use: </p>

```<code>startY: doc.internal.getNumberOfPages() > 1 ? doc.autoTableEndPosY() + 20 : 200,
</code>```

Body:
I'm using jsPDF and svg_to_pdf to export both an SVG and a table to a PDF. This is my code:

function svg_to_pdf(svg, callback) {

console.log("svgtopdf.js");
svgAsDataUri(svg, {}, function(svg_uri) {
var image = document.createElement('img');

image.src = svg_uri;
image.onload = function() {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');
  var doc = new jsPDF('portrait', 'pt', 'a4', true);
  var dataUrl;

  source = $('#datos_alumnos')[0];
  specialElementHandlers = {
      '#bypassme' : function(element, renderer){
          return true;
      }
  };

  margins = {
            top: 40,
            bottom: 60,
            left: 40,
            width: 270
        };

  canvas.width = image.width;
  canvas.height = image.height;
  context.drawImage(image, 0, 0, image.width, image.height);
  dataUrl = canvas.toDataURL('image/jpeg');
  doc.addImage(dataUrl, 'JPEG', 0, 0, 500, 263);

  doc.fromHTML(
    source,
    40,
    270, {
        'width': 550,
        'elementHandlers': specialElementHandlers
    },

    function(dispose){
        //doc.save('SVG.pdf');
    }
    , margins);

callback(doc);
}
});
}

The result is a PDF with the image at the top and the table next. The problem comes when it enters the second page as the headers of the table overlap with the first row and it looks like this.

http://i.imgur.com/vlfm4Fv.png

Is it possible to remove the headers on the second page?

Body:
When you draw table, just use:

startY: doc.internal.getNumberOfPages() > 1 ? doc.autoTableEndPosY() + 20 : 200,