问:
AngularJS directive for file input not updating ngmodel
I have a directive which I want to use for file upload in my application.

But when a file is selected it doesn't update the model in the controller.

The directive is as following:

```<code>export interface IFileInputModel {
    fileName: string;
    fileContent: any;
}

export class FileInput implements ng.IDirective {
    constructor() {
    }
    restrict = "EA";
    replace = true;
    template = `<input type="file" class="form-control" accept="image/*"/>`;
    scope: {
        image: '='
    };

    link = (scope, element, attrs, ctrl) => {
        let updateModel = function () {
            let file = element[0].files[0];

            let reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onload = function (evnt: any) {
                let model: IFileInputModel = {
                    fileName: file.name,
                    fileContent: evnt.target.result
                };

                scope.$apply(function () {
                    scope.image = model;
                });
            };
        };

        element.bind('change', updateModel);
    }

    static factory(): ng.IDirectiveFactory {
        const directive = () => new FileInput();
        return directive;
    }
}
</code>```

and this how I'm using it in  the HTML

```<code><file-input ng-model="controller.img"></file-input>
</code>```

This renders the valid directive template, but when I select a file and upload it the controller.img is not updated in the controller.

What am I doing wrong?

Note - this is an AngularJS 1.X application in Typescript.

EDIT

Based on the duplicate marked question, I changed my directive to

```<code> export class FileInput implements ng.IDirective {
        constructor(private $parse) {
        }
        restrict = "EA";
        scope: {
            fileread: "="
        }

        link = (scope, element, attrs, ctrl) => {

            element.bind("change", function (changeEvent) {
                var reader = new FileReader();
                reader.onload = function (loadEvent) {
                    scope.$apply(function () {
                        scope.fileread = (loadEvent.target as any).result;
                    });
                }
                reader.readAsDataURL(changeEvent.target.files[0]);
            });

        }
}
</code>```

and tried using it as:

```<code><input type="file" fileread="controller.img" file-input/>
</code>```

but the controller.img is never updated in the controller.

答:
AngularJS does not support file inputs, you will have to manually handle it by adding an onchange event listener to the input:`

```<code>element[0].addEventListener('change', event => {
   const files = event.target.files;
   // etc...
});
</code>```

Body:
I have a directive which I want to use for file upload in my application.

But when a file is selected it doesn't update the model in the controller.

The directive is as following:

export interface IFileInputModel {
    fileName: string;
    fileContent: any;
}

export class FileInput implements ng.IDirective {
    constructor() {
    }
    restrict = "EA";
    replace = true;
    template = `<input type="file" class="form-control" accept="image/*"/>`;
    scope: {
        image: '='
    };

    link = (scope, element, attrs, ctrl) => {
        let updateModel = function () {
            let file = element[0].files[0];

            let reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onload = function (evnt: any) {
                let model: IFileInputModel = {
                    fileName: file.name,
                    fileContent: evnt.target.result
                };

                scope.$apply(function () {
                    scope.image = model;
                });
            };
        };

        element.bind('change', updateModel);
    }

    static factory(): ng.IDirectiveFactory {
        const directive = () => new FileInput();
        return directive;
    }
}

and this how I'm using it in  the HTML

<file-input ng-model="controller.img"></file-input>

This renders the valid directive template, but when I select a file and upload it the controller.img is not updated in the controller.

What am I doing wrong?

Note - this is an AngularJS 1.X application in Typescript.

EDIT

Based on the duplicate marked question, I changed my directive to

 export class FileInput implements ng.IDirective {
        constructor(private $parse) {
        }
        restrict = "EA";
        scope: {
            fileread: "="
        }

        link = (scope, element, attrs, ctrl) => {

            element.bind("change", function (changeEvent) {
                var reader = new FileReader();
                reader.onload = function (loadEvent) {
                    scope.$apply(function () {
                        scope.fileread = (loadEvent.target as any).result;
                    });
                }
                reader.readAsDataURL(changeEvent.target.files[0]);
            });

        }
}

and tried using it as:

<input type="file" fileread="controller.img" file-input/>

but the controller.img is never updated in the controller.

Body:
AngularJS does not support file inputs, you will have to manually handle it by adding an onchange event listener to the input:`

element[0].addEventListener('change', event => {
   const files = event.target.files;
   // etc...
});


来源: stackexchange

问:
Can I create a new object with the results of a query?
If there's a better way to do this, let me know, but this is kind of how i envisioned it. Can it be done?

Customer is a table in the database/datacontext. What I want is to query that table and build a new object with it.

If i were to insert a record, I would do something like this:

```<code>Customer cust = new Customer(){ FirstName = "A", LastName = "B", Age = 31 }
db.Customers.InsertOnSubmit(cust);
db.SubmitChanges();
</code>```

What I want to do is instantiate that object with a query result. Something like this:

```<code>var query =
     from a in db.Customers
     where a.FirstName == "A"
     select a;

Customer cust = new Customer(){ query };
</code>```

or maybe even

```<code>Customer cust = new Customer(){
     from a in db.Customers
     where a.FistName == "A"
     select a;
}
</code>```

is there some way to do this?

答:
There is no built in way to clone objects in the manner you want

```<code>db.Customers
    .Where(x => x.FirstName ="A")
    .Select(x => new Customer
        {
           FirstName = x.FirstName,
           LastName = x.LastName,
           ...
           Id = default(x.Id.GetType()) // or copy the Id if you want it
        })
    .First();
</code>```

Besides this method you could add a new Customer constructor that took a Customer as a parameter to do this or add a helper for cloning.

Lastly, you can consider using AutoMapper for this.

ContentLicense: CC BY-SA 3.0

Body:
If there's a better way to do this, let me know, but this is kind of how i envisioned it. Can it be done?

Customer is a table in the database/datacontext. What I want is to query that table and build a new object with it.

If i were to insert a record, I would do something like this:

Customer cust = new Customer(){ FirstName = "A", LastName = "B", Age = 31 }
db.Customers.InsertOnSubmit(cust);
db.SubmitChanges();

What I want to do is instantiate that object with a query result. Something like this:

var query =
     from a in db.Customers
     where a.FirstName == "A"
     select a;

Customer cust = new Customer(){ query };

or maybe even

Customer cust = new Customer(){
     from a in db.Customers
     where a.FistName == "A"
     select a;
}

is there some way to do this?

Body:
There is no built in way to clone objects in the manner you want

db.Customers
    .Where(x => x.FirstName ="A")
    .Select(x => new Customer
        {
           FirstName = x.FirstName,
           LastName = x.LastName,
           ...
           Id = default(x.Id.GetType()) // or copy the Id if you want it
        })
    .First();

Besides this method you could add a new Customer constructor that took a Customer as a parameter to do this or add a helper for cloning.

Lastly, you can consider using AutoMapper for this.


问:
Using MS Access as Front end to SQL Get SQL Query Data to Access
I have a Pivot Table query built in SQL

```<code>DECLARE @Columns as VARCHAR(MAX)

SELECT @Columns =
COALESCE(@Columns + ', ','') + QUOTENAME(WBName)
FROM
(SELECT DISTINCT WBName
FROM BarCodesBetweenDates
WHERE SiteID = 58
) AS B

DECLARE @SQL as VARCHAR(MAX)
SET @SQL = 'SELECT Description, ' + @Columns + '
FROM
(SELECT S.siteID, b.SiteName, B.WBName, B.PN, B.Description,
SUM(B.Quant) AS Expr1
FROM Site S INNER JOIN
BarCodesBetweenDates B ON s.SiteName = B.SiteName
WHERE S.SiteID = 58
GROUP BY B.SiteName, B.WBName, B.PN, B.Description, s.SiteID
) AS PivotData
PIVOT
(
COUNT(Expr1)
FOR WBName IN (' + @Columns + ')
) AS PivotResult
ORDER BY Description'
select @SQL
exec (@SQL)
</code>```

This is returning exactly what my ultimate client wants.

I am using Access as the front end interface to SQL.

Now in Access I want to run this SQL Query, and get the records and send out to Excel for emailing to the client, after I look it over.  I am not sure how to do this.  Do I use a command function or some other way to send this to SQL from access or do I save it as a query or view or... in SQL and then call that from Access?

答:
Put your code into a stored procedure in SQL Server. Remove select @SQL.

Run the stored procedure from Access (e.g. with a Pass-Through query with ReturnsRecords = True).

And please, please, stop calling SQL Server "SQL". SQL is a language.

ContentLicense: CC BY-SA 4.0

Body:
I have a Pivot Table query built in SQL

DECLARE @Columns as VARCHAR(MAX)

SELECT @Columns =
COALESCE(@Columns + ', ','') + QUOTENAME(WBName)
FROM
(SELECT DISTINCT WBName
FROM BarCodesBetweenDates
WHERE SiteID = 58
) AS B

DECLARE @SQL as VARCHAR(MAX)
SET @SQL = 'SELECT Description, ' + @Columns + '
FROM
(SELECT S.siteID, b.SiteName, B.WBName, B.PN, B.Description,
SUM(B.Quant) AS Expr1
FROM Site S INNER JOIN
BarCodesBetweenDates B ON s.SiteName = B.SiteName
WHERE S.SiteID = 58
GROUP BY B.SiteName, B.WBName, B.PN, B.Description, s.SiteID
) AS PivotData
PIVOT
(
COUNT(Expr1)
FOR WBName IN (' + @Columns + ')
) AS PivotResult
ORDER BY Description'
select @SQL
exec (@SQL)

This is returning exactly what my ultimate client wants.

I am using Access as the front end interface to SQL.

Now in Access I want to run this SQL Query, and get the records and send out to Excel for emailing to the client, after I look it over.  I am not sure how to do this.  Do I use a command function or some other way to send this to SQL from access or do I save it as a query or view or... in SQL and then call that from Access?


问:
How to solve the "unable to find an inherited method for function" error when converting xml to data frame?
So I have this package and function to mine data frames in the form of xml, and I've tried converting the xml to a single data frame but I'm not being able to. I used this code:

```<code>library(bold)
library(XML)
library(dplyr)
xml = bold_seqspec(taxon=c("carnivora"), format = "xml", marker="COI-5P")
df= xmlToDataFrame(xml , stringsAsFactors = FALSE,) %>%
  mutate_all(~type.convert(., as.is = T))
</code>```

However I'm getting the following error in the "xmlToDataFrame" function:

```<code>Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function ‘xmlToDataFrame’ for signature ‘"xml_document", "missing", "missing", "missing", "missing"’
</code>```

答:
The problem is that the xml is in a deeply nested list structure with variable length members, so it is not possible to automatically coerce it into a rectangular data structure (i.e. a data frame).

It is possible to extract the data you want in various ways, but you will need to decide which fields you want from each record and what to do if there are multiple entries in a single field, etc.

I would suggest you start by converting the xml to a list using xml2::as_list and exploring its contents using str to see which fields you want. You can then create a dataframe with the fields you want for each record.

For example:

library(bold)
library(XML)
library(dplyr)
xml <- bold_seqspec(taxon=c("carnivora"), format = "xml", marker="COI-5P")
df <-  xml2::as_list(xml)
df <- df$bold_records
result <- do.call(rbind, lapply(df, function(x)
{
  data.frame(specimen = x$specimen_identifiers$sampleid[[1]],
             order = x$taxonomy$order$taxon$name[[1]],
             nucleotides = x$sequences$sequence$nucleotides[[1]],
             stringsAsFactors = FALSE)
}))
```

<p>Now <code>result</code> looks like this:</p>

```tibble::as_tibble(result)
#> # A tibble: 4,577 x 3
#>    specimen   order    nucleotides
#>    <chr>      <chr>    <chr>
#>  1 T-2294     Carnivo~ ---CCTGTACCTCTTATTCGGTGCGTGAGCCGGAATGGCGGGAACCGCCCTTAGCCTACTGAT~
#>  2 HBL008245  Carnivo~ NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~
#>  3 HBL008385  Carnivo~ ACTCTTTACCTTTTATTTGGCGCATGAGCCGGAATAGTAGGCACTGCATTAAGCCTATTGATT~
#>  4 HBL008419  Carnivo~ NNTTTATATTTGCTATTCGGGGCATGAGCCGGTATAGTAGGCACTGCCCTAAGCCTCCTAATT~
#>  5 HLC-10619  Carnivo~ ACCCTTTACCTCTTATTCGGTGCATGAGCCGGAATAGTAGGAACTGCCCTCAGTCTTCTAATC~
#>  6 ROM 101864 Carnivo~ ACTCTCTACCTTCTATTCGGGGCTTGGGCTGGAATAGTGGGCACCGCTCTCAGCCTACTAATT~
#>  7 ROM 93093  Carnivo~ ACTTTGTATTTATTATTTGGAGCATGAGCCGGCATAGTAGGTACCGCCCTGAGCCTTCTTATC~
#>  8 bLpa138    Carnivo~ CCCTGCTATATCTCAATACCAAACACCCCTATTCGTCTGATCTGTTTTAATCACTGCTGTTCT~
#>  9 Fge20      Carnivo~ CCCTGCCATATCTCAATATCAAACACCTCTCTTCGTCTGATCTGTCTTAATTACTGCTGTTTT~
#> 10 bCth05     Carnivo~ TTCGCTGCCCCCTCAATAATAGGCCTTCCTATTGTAATCCTAATCATTATATTCCCATCCATT~
#> # ... with 4,567 more rows
```

Body:
So I have this package and function to mine data frames in the form of xml, and I've tried converting the xml to a single data frame but I'm not being able to. I used this code:

library(bold)
library(XML)
library(dplyr)
xml = bold_seqspec(taxon=c("carnivora"), format = "xml", marker="COI-5P")
df= xmlToDataFrame(xml , stringsAsFactors = FALSE,) %>%
  mutate_all(~type.convert(., as.is = T))

However I'm getting the following error in the "xmlToDataFrame" function:

Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function ‘xmlToDataFrame’ for signature ‘"xml_document", "missing", "missing", "missing", "missing"’

Body:
The problem is that the xml is in a deeply nested list structure with variable length members, so it is not possible to automatically coerce it into a rectangular data structure (i.e. a data frame).

It is possible to extract the data you want in various ways, but you will need to decide which fields you want from each record and what to do if there are multiple entries in a single field, etc.

I would suggest you start by converting the xml to a list using xml2::as_list and exploring its contents using str to see which fields you want. You can then create a dataframe with the fields you want for each record.

For example:

library(bold)
library(XML)
library(dplyr)
xml <- bold_seqspec(taxon=c("carnivora"), format = "xml", marker="COI-5P")
df <-  xml2::as_list(xml)
df <- df$bold_records
result <- do.call(rbind, lapply(df, function(x)
{
  data.frame(specimen = x$specimen_identifiers$sampleid[[1]],
             order = x$taxonomy$order$taxon$name[[1]],
             nucleotides = x$sequences$sequence$nucleotides[[1]],
             stringsAsFactors = FALSE)
}))

Now result looks like this:

tibble::as_tibble(result)
#> # A tibble: 4,577 x 3
#>    specimen   order    nucleotides
#>    <chr>      <chr>    <chr>
#>  1 T-2294     Carnivo~ ---CCTGTACCTCTTATTCGGTGCGTGAGCCGGAATGGCGGGAACCGCCCTTAGCCTACTGAT~
#>  2 HBL008245  Carnivo~ NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~
#>  3 HBL008385  Carnivo~ ACTCTTTACCTTTTATTTGGCGCATGAGCCGGAATAGTAGGCACTGCATTAAGCCTATTGATT~
#>  4 HBL008419  Carnivo~ NNTTTATATTTGCTATTCGGGGCATGAGCCGGTATAGTAGGCACTGCCCTAAGCCTCCTAATT~
#>  5 HLC-10619  Carnivo~ ACCCTTTACCTCTTATTCGGTGCATGAGCCGGAATAGTAGGAACTGCCCTCAGTCTTCTAATC~
#>  6 ROM 101864 Carnivo~ ACTCTCTACCTTCTATTCGGGGCTTGGGCTGGAATAGTGGGCACCGCTCTCAGCCTACTAATT~
#>  7 ROM 93093  Carnivo~ ACTTTGTATTTATTATTTGGAGCATGAGCCGGCATAGTAGGTACCGCCCTGAGCCTTCTTATC~
#>  8 bLpa138    Carnivo~ CCCTGCTATATCTCAATACCAAACACCCCTATTCGTCTGATCTGTTTTAATCACTGCTGTTCT~
#>  9 Fge20      Carnivo~ CCCTGCCATATCTCAATATCAAACACCTCTCTTCGTCTGATCTGTCTTAATTACTGCTGTTTT~
#> 10 bCth05     Carnivo~ TTCGCTGCCCCCTCAATAATAGGCCTTCCTATTGTAATCCTAATCATTATATTCCCATCCATT~
#> # ... with 4,567 more rows


问:
Can I create wheel distributions of packages containing cython for other platforms?
When I create a wheel distribution with python setup.py bdist_wheel of a package which contains cython code, then the platform tag fits to my current platform. Projects like numpy / scipy have a lot of different wheels online and I guess they use CI / CD platforms like Travis / Azure Piplelines for that. However, I wondered: Can I create wheel distributions of packages containing cython for other platforms than my own, using only my computer?

MVCE

fib.pyx

```<code>def fib_iterative_cython(int n):
        cdef long long a = 0
        cdef long long b = 1
        for i in range(n - 1):
            a, b = b, a + b
        return b
</code>```

setup.py

```<code>from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("fib.pyx")
)
</code>```

答:
Short answer: no.

Longer answer: you can distribute sdist (source distribution). This forces the users to compile the sources so they have to install developer tools. pip install mostly handles compilation except Cython: you need to teach your users to install Cython first.

Detailed answer: no. Partially it's Python fault, but mostly not. There are problems at many levels. First, cross-compilers are problematic and cross-linkers even more so. Second, setuptools doesn't know any cross-compiler.

Solution: the only way to build C-modules is to build them natively in virtual machines or Docker containers.

Body:
When I create a wheel distribution with python setup.py bdist_wheel of a package which contains cython code, then the platform tag fits to my current platform. Projects like numpy / scipy have a lot of different wheels online and I guess they use CI / CD platforms like Travis / Azure Piplelines for that. However, I wondered: Can I create wheel distributions of packages containing cython for other platforms than my own, using only my computer?

MVCE

fib.pyx

def fib_iterative_cython(int n):
        cdef long long a = 0
        cdef long long b = 1
        for i in range(n - 1):
            a, b = b, a + b
        return b

setup.py

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("fib.pyx")
)


问:
How to start two foreach loops dispatcher invoke simultaneously c# wpf
Is it possible to display strings char by char in two labels at the same time using
two different Dispatcher.BeginInvoke(new Action(() ?

I have two foreach loops like this:

```<code>        string str1 = "NUMBER OF PASSED:" + "\t\t" + passed1.ToString() + Environment.NewLine + "NUMBER OF FAILED:" + "\t" + failed1.ToString();

        foreach (var ch1 in str1)
        {
            var char_by_char1 = ch1;
            Dispatcher.BeginInvoke(new Action(() =>
            {
                first_result.Content += char_by_char1.ToString();
                System.Threading.Thread.Sleep(5);
            }), DispatcherPriority.Background);
        }

        string str2 = "NUMBER OF PASSED:" + "\t\t" + passed2.ToString() + Environment.NewLine + "NUMBER OF FAILED:" + "\t" + failed2.ToString();

        foreach (var ch2 in str2)
        {
            var char_by_char2 = ch2;
            Dispatcher.BeginInvoke(new Action(() =>
            {
                second_result.Content += char_by_char2.ToString();
                System.Threading.Thread.Sleep(5);
            }), DispatcherPriority.Background);
        }
</code>```

答:
Can you not use TPL instead, like this:

```<code>var dispatcherObj = Dispatcher.CurrentDispatcher;

string str1 = "NUMBER OF PASSED:" + "\t\t" + passed1.ToString() + Environment.NewLine + "NUMBER OF FAILED:" + "\t" + failed1.ToString();

var tsk1 = Task.Factory.StartNew(()=>
{
    foreach (var ch1 in str1)
    {
        var char_by_char1 = ch1;
        dispatcherObj.Invoke(new Action(() =>
        {
            first_result.Content += char_by_char1.ToString();
            System.Threading.Thread.Sleep(5);
        }), DispatcherPriority.Background);
    }
});

string str2 = "NUMBER OF PASSED:" + "\t\t" + passed2.ToString() + Environment.NewLine + "NUMBER OF FAILED:" + "\t" + failed2.ToString();

var tsk2 = Task.Factory.StartNew(()=>
{
    foreach (var ch2 in str2)
    {
        var char_by_char2 = ch2;
        dispatcherObj.Invoke(new Action(() =>
        {
            second_result.Content += char_by_char2.ToString();
            System.Threading.Thread.Sleep(5);
        }), DispatcherPriority.Background);
    }
});
</code>```

I am running the Loops on a Task/non UI thread, and posting the UI changes using Dispatcher.Invoke

Body:
Is it possible to display strings char by char in two labels at the same time using
two different Dispatcher.BeginInvoke(new Action(() ?

I have two foreach loops like this:

        string str1 = "NUMBER OF PASSED:" + "\t\t" + passed1.ToString() + Environment.NewLine + "NUMBER OF FAILED:" + "\t" + failed1.ToString();

        foreach (var ch1 in str1)
        {
            var char_by_char1 = ch1;
            Dispatcher.BeginInvoke(new Action(() =>
            {
                first_result.Content += char_by_char1.ToString();
                System.Threading.Thread.Sleep(5);
            }), DispatcherPriority.Background);
        }

        string str2 = "NUMBER OF PASSED:" + "\t\t" + passed2.ToString() + Environment.NewLine + "NUMBER OF FAILED:" + "\t" + failed2.ToString();

        foreach (var ch2 in str2)
        {
            var char_by_char2 = ch2;
            Dispatcher.BeginInvoke(new Action(() =>
            {
                second_result.Content += char_by_char2.ToString();
                System.Threading.Thread.Sleep(5);
            }), DispatcherPriority.Background);
        }

Body:
Can you not use TPL instead, like this:

var dispatcherObj = Dispatcher.CurrentDispatcher;

string str1 = "NUMBER OF PASSED:" + "\t\t" + passed1.ToString() + Environment.NewLine + "NUMBER OF FAILED:" + "\t" + failed1.ToString();

var tsk1 = Task.Factory.StartNew(()=>
{
    foreach (var ch1 in str1)
    {
        var char_by_char1 = ch1;
        dispatcherObj.Invoke(new Action(() =>
        {
            first_result.Content += char_by_char1.ToString();
            System.Threading.Thread.Sleep(5);
        }), DispatcherPriority.Background);
    }
});

string str2 = "NUMBER OF PASSED:" + "\t\t" + passed2.ToString() + Environment.NewLine + "NUMBER OF FAILED:" + "\t" + failed2.ToString();

var tsk2 = Task.Factory.StartNew(()=>
{
    foreach (var ch2 in str2)
    {
        var char_by_char2 = ch2;
        dispatcherObj.Invoke(new Action(() =>
        {
            second_result.Content += char_by_char2.ToString();
            System.Threading.Thread.Sleep(5);
        }), DispatcherPriority.Background);
    }
});

I am running the Loops on a Task/non UI thread, and posting the UI changes using Dispatcher.Invoke


问:
How to show bottom sheet on map in flutter mobile application?
I see a lot of tutorials for implementing bottom sheet in my flutter application, but i am facing problem in implementing that, all of them showing bottom sheet after onPressed/onTap and i do not want that. I had implemented google map in my application but now i want to show persistent bottom sheet after i got response from API on map screen and color of that bottom sheet must be transparent so that map can be visible through bottom sheet.

Can you share some code that how can i show bottomsheet without onpressed on google map screen in flutter mobile application?

答:
after getting your data :</p>

```<code>return showModalBottomSheet(

        isDismissible: false,

        isScrollControlled: true,
        context: context,
        builder: (BuildContext context) => SingleChildScrollView(
          child: Container(
            padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom),
            child: ?,
          ),
        ),
      );
</code>```

Body:
after getting your data :

return showModalBottomSheet(

        isDismissible: false,

        isScrollControlled: true,
        context: context,
        builder: (BuildContext context) => SingleChildScrollView(
          child: Container(
            padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom),
            child: ?,
          ),
        ),
      );


问:
Sumo Simulator, VEINS
need your help
I am new to SUMO. I am using SUMO OMNET++, VEINS and Prext. How to know the boundary of the road on which vehicle moves, is there any function defined which gives the road boundaries.
How to send multiple messages from the same vehicle at given timestamp.??

I am able to manipulate the Vehicle position by adding some random values to it, but the problem is that , the new modified Vehicle position comes out of the road (lane).

Please help this.

Regards
Pradeep

答:
I do not know why but I feel you are trying to broadcast the safety message (BSMs) of vehicles with falsified locations (of course to confuse the tracker) but it is against the requirements of road-safety, you will confuse other vehicles (except if you have a mechanism to filter the wrong locations by the other legitimate vehicles).

Anyways, I do not know such a function that returns the road's extremities, but, how about creating a grid model? this why you can determine if a point is inside the road or not (it is up to you to create the function for that, it will be feasible at least and accurate to some extent).

Title: Sumo Simulator, VEINS


问:
Count if current row and next row meet the criteria
For example, I have a table in with thousands of row:

```<code>      | col
row 1 | NN
row 2 | NNP
row 3 | VB
row 4 | NNP
row 5 | NN
row 6 | NNP
row 7 | JJ
row 8 | NUM
row 9 | CW
.....
row 10000 | NNP
</code>```

Can I count with condition :
IF (row 1 = NN AND row 2= NNP) AND (row 2 = NN AND row 3= NNP) AND ... AND (row 9999 = NN and row 10000 = NNP) THEN count?

答:
This should also work:</p>

```<code>=COUNTIFS(A1:A999,"NN",A2:A1000,"NNP")
</code>```

Body:
For example, I have a table in with thousands of row:

      | col
row 1 | NN
row 2 | NNP
row 3 | VB
row 4 | NNP
row 5 | NN
row 6 | NNP
row 7 | JJ
row 8 | NUM
row 9 | CW
.....
row 10000 | NNP

Can I count with condition :
IF (row 1 = NN AND row 2= NNP) AND (row 2 = NN AND row 3= NNP) AND ... AND (row 9999 = NN and row 10000 = NNP) THEN count?

Body:
This should also work:

=COUNTIFS(A1:A999,"NN",A2:A1000,"NNP")


问:
Vue CLI quesar plugin q-image not showing image
I am using quasar as a plugin in my vue. I am having trouble using the q-image component. When I use the  the code and image displayed ok but when i use it on

```<code><q-img
    :src="'../../statics/infocom.png'"
    spinner-color="white"
    style="height: 140px; max-width: 150px"
    />
</code>```

the image does not show

答:
It should work fine if and only if your relative path is correct.

Or try:

```<code>  <q-img
    :src="require('../statics/infocom.png')"
    spinner-color="white"
    style="height: 140px; max-width: 150px"
    />
</code>```

Body:
I am using quasar as a plugin in my vue. I am having trouble using the q-image component. When I use the  the code and image displayed ok but when i use it on

<q-img
    :src="'../../statics/infocom.png'"
    spinner-color="white"
    style="height: 140px; max-width: 150px"
    />

the image does not show

Body:
It should work fine if and only if your relative path is correct.

Or try:

  <q-img
    :src="require('../statics/infocom.png')"
    spinner-color="white"
    style="height: 140px; max-width: 150px"
    />


问:
Sorting, grouping, and counting dates using the java Stream API
How to solve the following examples using the Stream API.

```<code>/*
 * Calculate the total number of Mondays for the specified years grouped by month
 */
EnumMap<Month, Long> totalMondaysByMonth(int yearSince, int yearUntilInclusive);

/*
 * Issue a list of Fridays on the 13th for the specified years,
 * sorted in ascending order first by year, and second by name of the month
 */
List<LocalDate> friday13s(int yearFrom, int yearUntilInclusive);
</code>```

My example solution:

```<code>public EnumMap<Month, Long> totalMondaysByMonth(int yearSince, int yearUntilInclusive) {
           return Stream.iterate(LocalDate.of(yearSince, 0, 0), date -> date.plusYears(1))
                   .limit(yearUntilInclusive)
                   .filter(x -> x.getDayOfWeek() == DayOfWeek.MONDAY)
                   .collect(Collectors.groupingBy(LocalDate::getMonth, Collectors.summingLong(???));

}
</code>```

What code should I insert in (Collectors.summingLong(???))) to count the number of Mondays?

```<code>public List<LocalDate> friday13s(int yearFrom, int yearUntilInclusive) {
    return Stream.iterate(LocalDate.of(yearFrom, 0, 0), date -> date.plusYears(1))
            .limit(yearUntilInclusive)
            .filter(x -> x.getDayOfWeek() == DayOfWeek.FRIDAY || x.getDayOfMonth() == 13)
            .sorted(Comparator.comparing(LocalDate::getYear).thenComparing(LocalDate::getMonth))
            .collect(Collectors.toList());
}
</code>```

Tell me how to write correctly.

答:
I will only help you fix the first one, you can understand this and fix your second one too (it is almost the same).

You first say :

```<code>Stream.iterate(LocalDate.of(yearSince, 0, 0), date -> date.plusYears(1))
</code>```

But do you really need to iterate years here? You need to find out Mondays (which are days, no?) That is the main problem here, since your "loop" is going to happen only as many times as that difference of years is. Let's say you want 2018-2020 interval - how many times are you going to iterate with what you have right now?

But now you need to think when to "stop" this loop - and this why you were using limit:

```<code> .limit(yearUntilInclusive)
</code>```

The problem is that if you would correctly iterate days, you do not really know when to stop, do you? Ideally, you want to stop by using a Predicate, like: I want to start on the first day of 2018 and stop on the last day of 2020. limit can't really do that (you could via a difference of days from that last to that first - I'll let you figure out how). Or, I find easier to use a Predicate with takeWhile (requires at least java-9).

Then that Collectors.summingLong can be made as an Collectors.summingInt (you would need a lot of years to jump from 32 bits integer to 64 bits long). And what do you need to do there? For each days that you have a match, simply add one. Simply "adding one" is also called counting and there is a collector for that Collectors.counting() that you can use also.

And the last point is that EnumMap can take a Map as a parameter to its constructor; as such:

```<code>public static EnumMap<Month, Integer> totalMondaysByMonth(int yearSince, int yearUntilInclusive) {

    return Stream.iterate(LocalDate.of(yearSince, 1, 1), date -> date.plusDays(1))
                 .takeWhile(date -> date.getYear() <= yearUntilInclusive)
                 .filter(x -> x.getDayOfWeek() == DayOfWeek.MONDAY)
                 .collect(
                     Collectors.collectingAndThen(
                         Collectors.groupingBy(LocalDate::getMonth, Collectors.summingInt(x -> 1)),
                         EnumMap::new
                     )
                 );
}
</code>```

But can you be more effective here? You could find the first Monday in the year you start from and iterate weeks from that, not days:

```<code> LocalDate firstMonday = LocalDate.of(yearSince, 1, 1).with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
 EnumMap<Month, Integer> right =
        Stream.iterate(firstMonday, date -> date.plusWeeks(1))
              .takeWhile(date -> date.getYear() <= yearUntilInclusive)
              .collect(
                  Collectors.collectingAndThen(
                      Collectors.groupingBy(LocalDate::getMonth, Collectors.summingInt(x -> 1)),
                      EnumMap::new
                  )
              );
</code>```

Body:
How to solve the following examples using the Stream API.

/*
 * Calculate the total number of Mondays for the specified years grouped by month
 */
EnumMap<Month, Long> totalMondaysByMonth(int yearSince, int yearUntilInclusive);

/*
 * Issue a list of Fridays on the 13th for the specified years,
 * sorted in ascending order first by year, and second by name of the month
 */
List<LocalDate> friday13s(int yearFrom, int yearUntilInclusive);

My example solution:

public EnumMap<Month, Long> totalMondaysByMonth(int yearSince, int yearUntilInclusive) {
           return Stream.iterate(LocalDate.of(yearSince, 0, 0), date -> date.plusYears(1))
                   .limit(yearUntilInclusive)
                   .filter(x -> x.getDayOfWeek() == DayOfWeek.MONDAY)
                   .collect(Collectors.groupingBy(LocalDate::getMonth, Collectors.summingLong(???));

}

What code should I insert in (Collectors.summingLong(???))) to count the number of Mondays?

public List<LocalDate> friday13s(int yearFrom, int yearUntilInclusive) {
    return Stream.iterate(LocalDate.of(yearFrom, 0, 0), date -> date.plusYears(1))
            .limit(yearUntilInclusive)
            .filter(x -> x.getDayOfWeek() == DayOfWeek.FRIDAY || x.getDayOfMonth() == 13)
            .sorted(Comparator.comparing(LocalDate::getYear).thenComparing(LocalDate::getMonth))
            .collect(Collectors.toList());
}

Tell me how to write correctly.

Body:
I will only help you fix the first one, you can understand this and fix your second one too (it is almost the same).

You first say :

Stream.iterate(LocalDate.of(yearSince, 0, 0), date -> date.plusYears(1))

But do you really need to iterate years here? You need to find out Mondays (which are days, no?) That is the main problem here, since your "loop" is going to happen only as many times as that difference of years is. Let's say you want 2018-2020 interval - how many times are you going to iterate with what you have right now?

But now you need to think when to "stop" this loop - and this why you were using limit:

 .limit(yearUntilInclusive)

The problem is that if you would correctly iterate days, you do not really know when to stop, do you? Ideally, you want to stop by using a Predicate, like: I want to start on the first day of 2018 and stop on the last day of 2020. limit can't really do that (you could via a difference of days from that last to that first - I'll let you figure out how). Or, I find easier to use a Predicate with takeWhile (requires at least java-9).

Then that Collectors.summingLong can be made as an Collectors.summingInt (you would need a lot of years to jump from 32 bits integer to 64 bits long). And what do you need to do there? For each days that you have a match, simply add one. Simply "adding one" is also called counting and there is a collector for that Collectors.counting() that you can use also.

And the last point is that EnumMap can take a Map as a parameter to its constructor; as such:

public static EnumMap<Month, Integer> totalMondaysByMonth(int yearSince, int yearUntilInclusive) {

    return Stream.iterate(LocalDate.of(yearSince, 1, 1), date -> date.plusDays(1))
                 .takeWhile(date -> date.getYear() <= yearUntilInclusive)
                 .filter(x -> x.getDayOfWeek() == DayOfWeek.MONDAY)
                 .collect(
                     Collectors.collectingAndThen(
                         Collectors.groupingBy(LocalDate::getMonth, Collectors.summingInt(x -> 1)),
                         EnumMap::new
                     )
                 );
}

But can you be more effective here? You could find the first Monday in the year you start from and iterate weeks from that, not days:

 LocalDate firstMonday = LocalDate.of(yearSince, 1, 1).with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
 EnumMap<Month, Integer> right =
        Stream.iterate(firstMonday, date -> date.plusWeeks(1))
              .takeWhile(date -> date.getYear() <= yearUntilInclusive)
              .collect(
                  Collectors.collectingAndThen(
                      Collectors.groupingBy(LocalDate::getMonth, Collectors.summingInt(x -> 1)),
                      EnumMap::new
                  )
              );


问:
Datastructures where Add, Get kth largest are O(log n) and O(1)
Give a data structure that stores comparable objects and supports add() and get(k) operations [get(k) returns the kth smallest element in the data structure (1 <= k <= n)]. get(k) must be O(1) and add() must be O(log n) where n is the number of objects added to the data structure. Give another structure where get(k) is O(log n) and add is O(1)

答:
I defer to the answer of @btilly , but I'm going to try another way to describe a data structure that has constant addition and constant get(k). This will use a lot of memory though.

Any feedback appreciated, I'm only just making this up as I go along ...

Imagine we're talking about a set of 8-bit integers. Therefore, there are 256 integers that can be members of the set.

Now, imagine a balanced binary tree containing all 256 integers as leaves, and 255 other non-leaf nodes, giving us 9 levels altogether. The shape of this tree is fixed, but we will store a count at each node. The count on each leaf node will simply be a 1 or 0 depending on whether that integer is currently a member of our set. The count at each non-leaf node will be the total of the leaves below it.

This will give us O(1) addition (and removal). Each time an element is added (or removed), exactly 9 nodes (the root node, the relevant leaf node, and 7 nodes in between) will have to have their count incremented(decremented).

I think this will also give us constant time lookup. If you want to find the kth-smallest element, simply start at the root node and work you way down towards the relevant leaf, moving to the left or right as necessary.

LastEditorDisplayName: Aryabhatta


问:
Trying to use fit with SelectKBest variable and keep getting a TypeError
I'm trying to use .fit() on my SelectKBest variable and I keep getting an error once my program hits skb.fit(X, y). Not sure why.

Error I'm getting:
fit % (self.score_func, type(self.score_func)) TypeError: The score function should be a callable, 26.48914983923762 (< class 'numpy.float64' >) was passed.

My Code:

```<code>X = df.loc[:, features].astype(float)
y = df.iloc[:, 0].astype(float)

model = LogisticRegression()
classifier = LogisticRegression()
skb = SelectKBest(score_func = chi2, k = 3)

skb.fit(X, y) # Error happens here
</code>```

What my Dataframe looks like:

```<code>         col1  col2   col3      col4   col5 col6    col7
0           0  22.0   7.2500       3      1  1.0      0
1           1  38.0  71.2833       1      1  0.0      0
2           1  26.0   7.9250       3      0  0.0      0
3           1  35.0  53.1000       1      1  0.0      0
4           0  35.0   8.0500       3      0  1.0      0
..        ...   ...      ...     ...    ...  ...    ...
885         0  39.0  29.1250       3      0  0.0      5
886         0  27.0  13.0000       2      0  1.0      0
887         1  19.0  30.0000       1      0  0.0      0
889         1  26.0  30.0000       1      0  1.0      0
890         0  32.0   7.7500       3      0  1.0      0
</code>```

I tried changing each col to a float

Edit: I added a comment on the line where the error happens

答: I had the same problem. To fix it by move the import statement further down in the code. The problem is that it is getting confused with an earlier chi2 squared function you called.</p>

Body:
I'm trying to use .fit() on my SelectKBest variable and I keep getting an error once my program hits skb.fit(X, y). Not sure why.

Error I'm getting:
fit % (self.score_func, type(self.score_func)) TypeError: The score function should be a callable, 26.48914983923762 (< class 'numpy.float64' >) was passed.

My Code:

X = df.loc[:, features].astype(float)
y = df.iloc[:, 0].astype(float)

model = LogisticRegression()
classifier = LogisticRegression()
skb = SelectKBest(score_func = chi2, k = 3)

skb.fit(X, y) # Error happens here

What my Dataframe looks like:

         col1  col2   col3      col4   col5 col6    col7
0           0  22.0   7.2500       3      1  1.0      0
1           1  38.0  71.2833       1      1  0.0      0
2           1  26.0   7.9250       3      0  0.0      0
3           1  35.0  53.1000       1      1  0.0      0
4           0  35.0   8.0500       3      0  1.0      0
..        ...   ...      ...     ...    ...  ...    ...
885         0  39.0  29.1250       3      0  0.0      5
886         0  27.0  13.0000       2      0  1.0      0
887         1  19.0  30.0000       1      0  0.0      0
889         1  26.0  30.0000       1      0  1.0      0
890         0  32.0   7.7500       3      0  1.0      0

I tried changing each col to a float

Edit: I added a comment on the line where the error happens


问:
How to use ESC/POS command 'GS v 0'
please can someone explain the 'GS v 0' command? I want to print some Bitmap on my thermal printer. I can't understand the parameters xL xH yL ...

The following is in the programming guide, but until now I can't see solution.

ASCII: Gs v 0
Decimal: 29 118 48 m xL xH yL yH [d]k
Hexadecimal: 1D 76 30 m xL xH yL yH [d]k

0 ≤ m ≤ 3, 48 ≤ m ≤ 51
0 ≤ xL ≤ 255
0 ≤ xH ≤ 255
0 ≤ yL ≤ 255
0 ≤ d ≤ 255
k = ( xL + xH × 256) × ( yL + yH × 256) ( k ≠ 0)

xL, xH specifies (xL + xH × 256) bytes in horizontal direction for
the bit image.
yL, yH specifies (yL + yH × 256) dots in vertical direction for the
bit image.
[d]k specifies the bit image data (raster format).

答:
First let me say that I know the question is old and this command is considered obsolete, but there is still a huge market out there with thermal printers that accept this command.

Don't have enough points on this account to write a comment on @Fewl 's answer.

He is right about yL and yH, but not about xL and xH.

xL, xH specifies (xL + xH × 256) bytes in horizontal direction for the bit image.

yL, yH specifies (yL + yH × 256) dots in vertical direction for the bit image.

Ref: https://www.epson-biz.com/modules/ref_escpos/index.php?content_id=94

So let's say that your bitmap is 384 pixels wide and 260 pixels tall, then:

```<code>xL = width % 2048 / 8;
xH = width / 2048;
// width = 384
// xL = 48
// xH = 0
// (xL + xH × 256) = 48 + 0 x 256 = 48 **bytes** in horizontal direction.

yL = height % 256;
yH = height / 256;
//height = 260
// yL = 4
// yH = 1
// (yL + yH × 256) = 4 + 1 x 256 = 260 **dots** in vertical direction
</code>```

Explanation, example bit image has 384 / 8 = 48 bytes in the horizontal direction, since 48 < 256 you don't need to calculate xH (High byte) it will be 0. You would only need to calculate xH if your bitmap is wider than 8 * 256 = 2048 dots... Which is highly unlikely to happen with thermal pos printers but I've included even that scenario in the code above.

Important note! My example width (384) is divisible by 8. If it isn't you will have to account for that by rounding up the division and pad the bit data with zeroes... or simply resize the bitmap beforehand to have its width divisible by 8.

Title: How to use ESC/POS command 'GS v 0'

Body:
First let me say that I know the question is old and this command is considered obsolete, but there is still a huge market out there with thermal printers that accept this command.

Don't have enough points on this account to write a comment on @Fewl 's answer.

He is right about yL and yH, but not about xL and xH.

xL, xH specifies (xL + xH × 256) bytes in horizontal direction for the bit image.

yL, yH specifies (yL + yH × 256) dots in vertical direction for the bit image.

Ref: https://www.epson-biz.com/modules/ref_escpos/index.php?content_id=94

So let's say that your bitmap is 384 pixels wide and 260 pixels tall, then:

xL = width % 2048 / 8;
xH = width / 2048;
// width = 384
// xL = 48
// xH = 0
// (xL + xH × 256) = 48 + 0 x 256 = 48 **bytes** in horizontal direction.

yL = height % 256;
yH = height / 256;
//height = 260
// yL = 4
// yH = 1
// (yL + yH × 256) = 4 + 1 x 256 = 260 **dots** in vertical direction

Explanation, example bit image has 384 / 8 = 48 bytes in the horizontal direction, since 48 < 256 you don't need to calculate xH (High byte) it will be 0. You would only need to calculate xH if your bitmap is wider than 8 * 256 = 2048 dots... Which is highly unlikely to happen with thermal pos printers but I've included even that scenario in the code above.

Important note! My example width (384) is divisible by 8. If it isn't you will have to account for that by rounding up the division and pad the bit data with zeroes... or simply resize the bitmap beforehand to have its width divisible by 8.


问:
What should I know about C# before walking into an interview for a .NET job?
Sure, we all have written tons of C# code. So walking into an interview for a .NET job should be a no-brainer, right? And then you read some stackoverflow posts and it hits you: You don't know squat!

Remember that site with the cram sessions to go through, before taking an exam? I think stackoverflow could be used to make a sorted (voting) list of topics to know about.

Please only put one topic per post.
Please also add some information about the topic. Links, reference material etc.

EDIT: I guess some of you misunderstood the reason for the post - I'm hoping to generate a list of stuff to know about .NET, a sort of cram session that can be reviewed by everyone on the planet to regularly review. This should help us all remember arcane stuff we never really use.

答:
ScottHa has two great lists of interview questions:

ASP.NET Interview Questions

What Great .NET Developers Ought To Know

OwnerDisplayName: Daren Thomas

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Daren Thomas

OwnerDisplayName: Portman


问:
Insert data into table and get ID from increased primary key
In my ASP.NET application I have a need to do something like this: First, get data from a user, second insert this data into SQL Server database table, then get the ID value from that table (which is autoincremented) and then use it in another insert into another table.

Now, I already found out that in order to do this, I need to use T-SQL OUTPUT clause. However, when I try to do this I get this error:

I tried to follow the advice from those posts:
Get output parameter value in ADO.NET and Use SQL Server Stored procedure output in asp.net c#
but I couldn't make it work.

I'm not using stored procedure, but the single SQL statement instead. Here it is:

```<code>INSERT INTO BS_product_sets (User_id, Set_name, Set_id, Products_count)
OUTPUT inserted.ID INTO @NEWID
VALUES (@UID, @SNAME, @SPREFIX, @PCOUNT)
</code>```

I also tried this:

```<code>DECLARE @NEWID int;

INSERT INTO BS_product_sets (User_id, Set_name, Set_id, Products_count)
OUTPUT inserted.ID INTO @NEWID
VALUES (@UID, @SNAME, @SPREFIX, @PCOUNT)
</code>```

But then it gets even weirder because the error I get is:

Does anyone of you know how to resolve it? Here is the rest of my code in C#:

```<code>public void InsertProductAutoBinds(int user_id, int parameters_count, List<int> cat_ids, List<string> names, List<string> values, string set_name, string set_id)
{
    SqlConnection connection = new SqlConnection(DatabaseConstants.ConnectionString);

    // Adding set to database
    SqlCommand command = new SqlCommand(DatabaseConstants.InsertSet, connection);
    command.Parameters.AddWithValue("@UID", user_id);
    command.Parameters.AddWithValue("@SNAME", set_name);
    command.Parameters.AddWithValue("@SPREFIX", set_id);
    command.Parameters.AddWithValue("@PCOUNT", 0);
    command.Parameters.Add("@NEWID", SqlDbType.Int).Direction = ParameterDirection.Output;

    connection.Open();
    command.ExecuteNonQuery();

    int new_inserted_id = Convert.ToInt32(command.Parameters["@NEWID"].Value);

    connection.Close();

    // Adding binds
    command = new SqlCommand(DatabaseConstants.InsertAutoBinds1, connection);
    command.Parameters.AddWithValue("@UID", user_id);
    command.Parameters.AddWithValue("@SID", new_inserted_id);
    command.Parameters.AddWithValue("@P1ID", cat_ids[0]);
    command.Parameters.AddWithValue("@VN1", names[0]);
    command.Parameters.AddWithValue("@VS1", values[0]);

    if (parameters_count > 1)
    {
        command.CommandText = DatabaseConstants.InsertAutoBinds2;
        command.Parameters.AddWithValue("@P2ID", cat_ids[1]);
        command.Parameters.AddWithValue("@VN2", names[1]);
        command.Parameters.AddWithValue("@VS2", values[1]);
    }

    if (parameters_count > 2)
    {
        command.CommandText = DatabaseConstants.InsertAutoBinds3;
        command.Parameters.AddWithValue("@P3ID", cat_ids[2]);
        command.Parameters.AddWithValue("@VN3", names[2]);
        command.Parameters.AddWithValue("@VS3", values[2]);
    }

    connection.Open();
    command.ExecuteNonQuery();
    connection.Close();
}
</code>```

答:
If you have:</p>

```<code>CREATE TABLE tab (Id Int IDENTITY, User_Id Int, ...)

DECLARE @NewID Int

INSERT INTO tab (User_Id,...) VALUES (123, ...)

SET @NewId = @@Identity
</code>```

Body:
In my ASP.NET application I have a need to do something like this: First, get data from a user, second insert this data into SQL Server database table, then get the ID value from that table (which is autoincremented) and then use it in another insert into another table.

Now, I already found out that in order to do this, I need to use T-SQL OUTPUT clause. However, when I try to do this I get this error:

I tried to follow the advice from those posts:
Get output parameter value in ADO.NET and Use SQL Server Stored procedure output in asp.net c#
but I couldn't make it work.

I'm not using stored procedure, but the single SQL statement instead. Here it is:

INSERT INTO BS_product_sets (User_id, Set_name, Set_id, Products_count)
OUTPUT inserted.ID INTO @NEWID
VALUES (@UID, @SNAME, @SPREFIX, @PCOUNT)

I also tried this:

DECLARE @NEWID int;

INSERT INTO BS_product_sets (User_id, Set_name, Set_id, Products_count)
OUTPUT inserted.ID INTO @NEWID
VALUES (@UID, @SNAME, @SPREFIX, @PCOUNT)

But then it gets even weirder because the error I get is:

Does anyone of you know how to resolve it? Here is the rest of my code in C#:

public void InsertProductAutoBinds(int user_id, int parameters_count, List<int> cat_ids, List<string> names, List<string> values, string set_name, string set_id)
{
    SqlConnection connection = new SqlConnection(DatabaseConstants.ConnectionString);

    // Adding set to database
    SqlCommand command = new SqlCommand(DatabaseConstants.InsertSet, connection);
    command.Parameters.AddWithValue("@UID", user_id);
    command.Parameters.AddWithValue("@SNAME", set_name);
    command.Parameters.AddWithValue("@SPREFIX", set_id);
    command.Parameters.AddWithValue("@PCOUNT", 0);
    command.Parameters.Add("@NEWID", SqlDbType.Int).Direction = ParameterDirection.Output;

    connection.Open();
    command.ExecuteNonQuery();

    int new_inserted_id = Convert.ToInt32(command.Parameters["@NEWID"].Value);

    connection.Close();

    // Adding binds
    command = new SqlCommand(DatabaseConstants.InsertAutoBinds1, connection);
    command.Parameters.AddWithValue("@UID", user_id);
    command.Parameters.AddWithValue("@SID", new_inserted_id);
    command.Parameters.AddWithValue("@P1ID", cat_ids[0]);
    command.Parameters.AddWithValue("@VN1", names[0]);
    command.Parameters.AddWithValue("@VS1", values[0]);

    if (parameters_count > 1)
    {
        command.CommandText = DatabaseConstants.InsertAutoBinds2;
        command.Parameters.AddWithValue("@P2ID", cat_ids[1]);
        command.Parameters.AddWithValue("@VN2", names[1]);
        command.Parameters.AddWithValue("@VS2", values[1]);
    }

    if (parameters_count > 2)
    {
        command.CommandText = DatabaseConstants.InsertAutoBinds3;
        command.Parameters.AddWithValue("@P3ID", cat_ids[2]);
        command.Parameters.AddWithValue("@VN3", names[2]);
        command.Parameters.AddWithValue("@VS3", values[2]);
    }

    connection.Open();
    command.ExecuteNonQuery();
    connection.Close();
}

Body:
If you have:

CREATE TABLE tab (Id Int IDENTITY, User_Id Int, ...)

DECLARE @NewID Int

INSERT INTO tab (User_Id,...) VALUES (123, ...)

SET @NewId = @@Identity


问:
Why cant I start a JavaFX program?
I have a little problem with my program.
I can run the program normally until i give my elements tags and actions like "onClick"...
There is some kind of exception that i can't fix so I'm asking for your help.
Is the problem just in my computer or it's the code fault ?

Here's all you need :

Exception :

```<code>Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:473)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:372)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:941)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:973)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:198)
    at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: javafx.fxml.LoadException:
/E:/programovanie/netgame/out/production/netgame/sample/sample.fxml:26

    at javafx.fxml/javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2625)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2603)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3253)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3210)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3179)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3152)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3129)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3122)
    at sample.Main.start(Main.java:13)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:919)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$11(PlatformImpl.java:449)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$9(PlatformImpl.java:418)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:417)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:175)
    ... 1 more
Caused by: java.lang.IllegalArgumentException: Can not set org.w3c.dom.Text field sample.Controller.minuty to javafx.scene.text.Text
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at java.base/jdk.internal.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
    at java.base/java.lang.reflect.Field.set(Field.java:780)
    at javafx.fxml/javafx.fxml.FXMLLoader.injectFields(FXMLLoader.java:1174)
    at javafx.fxml/javafx.fxml.FXMLLoader.access$1600(FXMLLoader.java:105)
    at javafx.fxml/javafx.fxml.FXMLLoader$ValueElement.processValue(FXMLLoader.java:865)
    at javafx.fxml/javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:759)
    at javafx.fxml/javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2722)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2552)
    ... 17 more
Exception running application sample.Main
</code>```

sample.fxml :

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="600.0" prefWidth="900.0" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
    <children>
        <GridPane minHeight="100.0" minWidth="900.0" style="-fx-background-color: #CDE8C8; -fx-border-color: black;">
            <columnConstraints>
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
            </columnConstraints>
            <rowConstraints>
                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            </rowConstraints>
            <children>
                <Text fx:id="minuty" strokeType="OUTSIDE" strokeWidth="0.0" text="00" wrappingWidth="225.125">
                    <font>
                        <Font size="40.0" />
                    </font>
                    <GridPane.margin>
                        <Insets left="50.0" />
                    </GridPane.margin>
                </Text>
                <Text strokeType="OUTSIDE" strokeWidth="0.0" text=":" textAlignment="CENTER" wrappingWidth="224.671875">
                    <font>
                        <Font size="40.0" />
                    </font>
                </Text>
                <Text fx:id="sekundy" strokeType="OUTSIDE" strokeWidth="0.0" text="00" textAlignment="RIGHT" wrappingWidth="176.9375">
                    <font>
                        <Font size="40.0" />
                    </font>
                    <GridPane.margin>
                        <Insets />
                    </GridPane.margin>
                </Text>
                <Text fx:id="stavcerveny" fill="RED" strokeType="OUTSIDE" strokeWidth="0.0" text="0" wrappingWidth="225.5625" GridPane.columnIndex="1">
                    <font>
                        <Font size="40.0" />
                    </font>
                    <GridPane.margin>
                        <Insets left="50.0" />
                    </GridPane.margin>
                </Text>
                <Text strokeType="OUTSIDE" strokeWidth="0.0" text=":" textAlignment="CENTER" wrappingWidth="225.671875" GridPane.columnIndex="1">
                    <font>
                        <Font size="40.0" />
                    </font>
                </Text>
                <Text fx:id="stavmodry" fill="#0073ff" strokeType="OUTSIDE" strokeWidth="0.0" text="0" textAlignment="RIGHT" wrappingWidth="157.5625" GridPane.columnIndex="1">
                    <font>
                        <Font size="40.0" />
                    </font>
                </Text>
                <Button alignment="CENTER" mnemonicParsing="false" onMouseClicked="#zapnutie" prefHeight="25.0" prefWidth="226.0" text="PLAY" GridPane.columnIndex="2">
                    <GridPane.margin>
                        <Insets bottom="40.0" left="40.0" right="40.0" />
                    </GridPane.margin>
                </Button>
                <Button mnemonicParsing="false" onMouseClicked="#restart" prefHeight="25.0" prefWidth="227.0" text="RESTART" textAlignment="CENTER" GridPane.columnIndex="2">
                    <opaqueInsets>
                        <Insets />
                    </opaqueInsets>
                    <GridPane.margin>
                        <Insets left="40.0" right="40.0" top="50.0" />
                    </GridPane.margin>
                </Button>
                <Slider fx:id="obtiazne" prefHeight="14.0" prefWidth="126.0" GridPane.columnIndex="3">
                    <GridPane.margin>
                        <Insets left="20.0" right="20.0" />
                    </GridPane.margin>
                </Slider>
            </children>
        </GridPane>
      <AnchorPane fx:id="hra" layoutY="100.0" prefHeight="500.0" prefWidth="900.0" />
    </children>
</AnchorPane>

</code>```

Controller.java :

```<code>package sample;

import javafx.fxml.FXML;
import javafx.scene.control.Slider;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import org.w3c.dom.Text;

public class Controller {
    @FXML
    Slider obtiazne;
    @FXML
    Text minuty;
    @FXML
    Text sekundy;
    @FXML
    Text stavcerveny;
    @FXML
    Text stavmodry;
    @FXML
    AnchorPane hra;

    public void zapnutie(MouseEvent mouseEvent) {
        System.out.println(obtiazne.getValue());
    }

    public void restart(MouseEvent mouseEvent) {
    }
}

</code>```

Main.java :

```<code>package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

</code>```

I think the right rows are :

"at sample.Main.start(Main.java:13)"

and that's : " Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); "

I don't understand the rest of it so I hope, that you can easily get through the problem :)

答:
The part of the stack trace that's relevant is

Can not set org.w3c.dom.Text field sample.Controller.minuty to
  javafx.scene.text.Text

Which means your imports are wrong in the controller class

Change import org.w3c.dom.Text; to import javafx.scene.text.Text;

Title: Why cant I start a JavaFX program?

Body:
I have a little problem with my program.
I can run the program normally until i give my elements tags and actions like "onClick"...
There is some kind of exception that i can't fix so I'm asking for your help.
Is the problem just in my computer or it's the code fault ?

Here's all you need :

Exception :

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:473)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:372)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:941)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:973)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:198)
    at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: javafx.fxml.LoadException:
/E:/programovanie/netgame/out/production/netgame/sample/sample.fxml:26

    at javafx.fxml/javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2625)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2603)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3253)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3210)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3179)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3152)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3129)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3122)
    at sample.Main.start(Main.java:13)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:919)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$11(PlatformImpl.java:449)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$9(PlatformImpl.java:418)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:417)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:175)
    ... 1 more
Caused by: java.lang.IllegalArgumentException: Can not set org.w3c.dom.Text field sample.Controller.minuty to javafx.scene.text.Text
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at java.base/jdk.internal.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
    at java.base/java.lang.reflect.Field.set(Field.java:780)
    at javafx.fxml/javafx.fxml.FXMLLoader.injectFields(FXMLLoader.java:1174)
    at javafx.fxml/javafx.fxml.FXMLLoader.access$1600(FXMLLoader.java:105)
    at javafx.fxml/javafx.fxml.FXMLLoader$ValueElement.processValue(FXMLLoader.java:865)
    at javafx.fxml/javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:759)
    at javafx.fxml/javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2722)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2552)
    ... 17 more
Exception running application sample.Main

sample.fxml :

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="600.0" prefWidth="900.0" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
    <children>
        <GridPane minHeight="100.0" minWidth="900.0" style="-fx-background-color: #CDE8C8; -fx-border-color: black;">
            <columnConstraints>
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
            </columnConstraints>
            <rowConstraints>
                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            </rowConstraints>
            <children>
                <Text fx:id="minuty" strokeType="OUTSIDE" strokeWidth="0.0" text="00" wrappingWidth="225.125">

                    <GridPane.margin>
                        <Insets left="50.0" />
                    </GridPane.margin>
                </Text>
                <Text strokeType="OUTSIDE" strokeWidth="0.0" text=":" textAlignment="CENTER" wrappingWidth="224.671875">

                </Text>
                <Text fx:id="sekundy" strokeType="OUTSIDE" strokeWidth="0.0" text="00" textAlignment="RIGHT" wrappingWidth="176.9375">

                    <GridPane.margin>
                        <Insets />
                    </GridPane.margin>
                </Text>
                <Text fx:id="stavcerveny" fill="RED" strokeType="OUTSIDE" strokeWidth="0.0" text="0" wrappingWidth="225.5625" GridPane.columnIndex="1">

                    <GridPane.margin>
                        <Insets left="50.0" />
                    </GridPane.margin>
                </Text>
                <Text strokeType="OUTSIDE" strokeWidth="0.0" text=":" textAlignment="CENTER" wrappingWidth="225.671875" GridPane.columnIndex="1">

                </Text>
                <Text fx:id="stavmodry" fill="#0073ff" strokeType="OUTSIDE" strokeWidth="0.0" text="0" textAlignment="RIGHT" wrappingWidth="157.5625" GridPane.columnIndex="1">

                </Text>
                <Button alignment="CENTER" mnemonicParsing="false" onMouseClicked="#zapnutie" prefHeight="25.0" prefWidth="226.0" text="PLAY" GridPane.columnIndex="2">
                    <GridPane.margin>
                        <Insets bottom="40.0" left="40.0" right="40.0" />
                    </GridPane.margin>
                </Button>
                <Button mnemonicParsing="false" onMouseClicked="#restart" prefHeight="25.0" prefWidth="227.0" text="RESTART" textAlignment="CENTER" GridPane.columnIndex="2">
                    <opaqueInsets>
                        <Insets />
                    </opaqueInsets>
                    <GridPane.margin>
                        <Insets left="40.0" right="40.0" top="50.0" />
                    </GridPane.margin>
                </Button>
                <Slider fx:id="obtiazne" prefHeight="14.0" prefWidth="126.0" GridPane.columnIndex="3">
                    <GridPane.margin>
                        <Insets left="20.0" right="20.0" />
                    </GridPane.margin>
                </Slider>
            </children>
        </GridPane>
      <AnchorPane fx:id="hra" layoutY="100.0" prefHeight="500.0" prefWidth="900.0" />
    </children>
</AnchorPane>

Controller.java :

package sample;

import javafx.fxml.FXML;
import javafx.scene.control.Slider;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import org.w3c.dom.Text;

public class Controller {
    @FXML
    Slider obtiazne;
    @FXML
    Text minuty;
    @FXML
    Text sekundy;
    @FXML
    Text stavcerveny;
    @FXML
    Text stavmodry;
    @FXML
    AnchorPane hra;

    public void zapnutie(MouseEvent mouseEvent) {
        System.out.println(obtiazne.getValue());
    }

    public void restart(MouseEvent mouseEvent) {
    }
}

Main.java :

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

I think the right rows are :

"at sample.Main.start(Main.java:13)"

and that's : " Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); "

I don't understand the rest of it so I hope, that you can easily get through the problem :)


问:
How to add multiple "AND" conditions in a JOIN
I'm trying to add a "AND" condition to the join query but haven't been able to figure it out (not sure if it's even possible via Doctrine/Symfony). I'd appreciate any help with this.

```<code>->select('c, p')
->from(Customer::class, 'c')
->leftJoin('c.phones', 'p')
</code>```

Example:-

```<code>SELECT c.*, p.*
FROM customer c
LEFT JOIN phone p ON c.id = p.customer_id AND p.is_main = 1 AND p.category = 0
</code>```

答:
You can use conditionType of the leftJoin function in queryBuilder check the documentation </p>

```<code>    public function leftJoin($join, $alias, $conditionType = null, $condition = null, $indexBy = null);

    Example:
    $qb->leftJoin('c.phones', 'p', 'WITH', 'p.is_main = 1 AND p.category = 0', 'p.id')
</code>```

Body:
I'm trying to add a "AND" condition to the join query but haven't been able to figure it out (not sure if it's even possible via Doctrine/Symfony). I'd appreciate any help with this.

->select('c, p')
->from(Customer::class, 'c')
->leftJoin('c.phones', 'p')

Example:-

SELECT c.*, p.*
FROM customer c
LEFT JOIN phone p ON c.id = p.customer_id AND p.is_main = 1 AND p.category = 0

Body:
You can use conditionType of the leftJoin function in queryBuilder check the documentation

    public function leftJoin($join, $alias, $conditionType = null, $condition = null, $indexBy = null);

    Example:
    $qb->leftJoin('c.phones', 'p', 'WITH', 'p.is_main = 1 AND p.category = 0', 'p.id')


问:
Matplotlib showing blank figures in all Jupyter notebooks (no errors)
All Matplotlib figures are showing up blank or empty in my Jupyter notebooks.

Code works (for other people); produces no errors.

Reviewed questions here and here.

Restarted Kernels (in multiple notebooks).

Confirmed that Matplotlib is installed via command prompt in Python:

```<code>>>> import matplotlib
>>> matplotlib.__version__
'3.1.1'
</code>```

For reference, I am also running:

Python (3.7.4)

Windows 10 Home (Version 10.0.18362, Build 18362)

Chrome (Version 79.0.3945.130, Official Build, 64-bit)

JupyterLab extension loaded from Anaconda3 installation

This is happening in all my jupyter notebooks, and saving any figs to .png also saves blank .png files.

Created a simple test bar chart with the following code, which produces a blank interactive figure:

```<code>%matplotlib notebook

import matplotlib.pyplot as plt
import numpy as np

users = [1000, 2000, 3000, 4000, 5000]
x_axis = np.arange(len(users))
x_axis

fig, ax = plt.subplots()
ax.bar(x_axis, users, color='r', alpha=0.5, align="edge")
</code>```

The resulting interactive fig does show a "Figure 1" gray interactive bar at the top, and also states the following string at the bottom (since there is no ; at the end of the code):

```<code><BarContainer object of 5 artists>
</code>```

Not interested in switching to matplotlib inline (wish to keep interactive notebooks).

Any thoughts on how to resolve this blank figures issue please? TIA!

答:
...aaaand turns out someone else (who had recently used my computer) had adjusted a setting in Chrome to block (i.e., not show) images.  Yikes!  So simple.  And so frustrating to have not checked the following setting, which I'm sharing here in case someone else has this same issue:

Chrome-->Settings-->Advanced-->Privacy and security-->Site Settings-->Images-->Show all (slider should be turned ON)

Issue resolved.  Figs are now showing (e.g., on test code above).  Cheers!

Body:
All Matplotlib figures are showing up blank or empty in my Jupyter notebooks.

Code works (for other people); produces no errors.

Reviewed questions here and here.

Restarted Kernels (in multiple notebooks).

Confirmed that Matplotlib is installed via command prompt in Python:

>>> import matplotlib
>>> matplotlib.__version__
'3.1.1'

For reference, I am also running:

Python (3.7.4)

Windows 10 Home (Version 10.0.18362, Build 18362)

Chrome (Version 79.0.3945.130, Official Build, 64-bit)

JupyterLab extension loaded from Anaconda3 installation

This is happening in all my jupyter notebooks, and saving any figs to .png also saves blank .png files.

Created a simple test bar chart with the following code, which produces a blank interactive figure:

%matplotlib notebook

import matplotlib.pyplot as plt
import numpy as np

users = [1000, 2000, 3000, 4000, 5000]
x_axis = np.arange(len(users))
x_axis

fig, ax = plt.subplots()
ax.bar(x_axis, users, color='r', alpha=0.5, align="edge")

The resulting interactive fig does show a "Figure 1" gray interactive bar at the top, and also states the following string at the bottom (since there is no ; at the end of the code):

<BarContainer object of 5 artists>

Not interested in switching to matplotlib inline (wish to keep interactive notebooks).

Any thoughts on how to resolve this blank figures issue please? TIA!


问:
How to generate a list with only two 1s and other 0s of the given length?
I have to generate lists that consist of 2 '1's and other elements are '0's. I tried the following code but it does not work:

```<code>count([], _, 0).
count([X|T], X, Y) :- count(T, X, Z), Y is 1+Z.
count([X1|T],X,Z):- X1\=X,count(T,X,Z).

two(X) :- count(X, 1, Counter), Counter =:= 2.
</code>```

Querying length(Vs, 4), Vs ins 0..1, two(Vs). gives nothing.

How to generate such lists properly?
I expect to get something like [1, 1, 0, 0], [1, 0, 1, 0] ... [0, 0, 1, 1].

答:
A grammar is quite a natural way of specifying a list pattern:

```<code>two --> [1], one ; [0], two.
one --> [1], zeros ; [0], one.
zeros --> [] ; [0], zeros.
</code>```

Example call:

```<code>?- length(Xs, 3), phrase(two, Xs, []).
Xs = [1, 1, 0]
Yes (0.00s cpu, solution 1, maybe more)
Xs = [1, 0, 1]
Yes (0.00s cpu, solution 2, maybe more)
Xs = [0, 1, 1]
Yes (0.00s cpu, solution 3, maybe more)
No (0.00s cpu)
</code>```

Body:
I have to generate lists that consist of 2 '1's and other elements are '0's. I tried the following code but it does not work:

count([], _, 0).
count([X|T], X, Y) :- count(T, X, Z), Y is 1+Z.
count([X1|T],X,Z):- X1\=X,count(T,X,Z).

two(X) :- count(X, 1, Counter), Counter =:= 2.

Querying length(Vs, 4), Vs ins 0..1, two(Vs). gives nothing.

How to generate such lists properly?
I expect to get something like [1, 1, 0, 0], [1, 0, 1, 0] ... [0, 0, 1, 1].

Body:
A grammar is quite a natural way of specifying a list pattern:

two --> [1], one ; [0], two.
one --> [1], zeros ; [0], one.
zeros --> [] ; [0], zeros.

Example call:

?- length(Xs, 3), phrase(two, Xs, []).
Xs = [1, 1, 0]
Yes (0.00s cpu, solution 1, maybe more)
Xs = [1, 0, 1]
Yes (0.00s cpu, solution 2, maybe more)
Xs = [0, 1, 1]
Yes (0.00s cpu, solution 3, maybe more)
No (0.00s cpu)


答:
Use the WITH option like this:

```<code>$qb->leftJoin('c.phones', 'p', 'WITH', 'p.is_main = 1 AND p.category = 0', 'p.id')
</code>```

Docs

Title: How to add multiple "AND" conditions in a JOIN

Body:
Use the WITH option like this:

$qb->leftJoin('c.phones', 'p', 'WITH', 'p.is_main = 1 AND p.category = 0', 'p.id')

Docs


问:
How do I create a new list of dictionaries based on a key-value result?
I have a list of dictionaries. For example, something like [{'sex':'male'}, {'sex':'male'}, {'sex':'male'}, {'sex':'female'}, {'sex':'female'}. Imagine this, but way bigger.

How would I be able to go though and make a new list with just the male dictionaries? It would look like [{'sex':'male'}, {'sex':'male'}, {'sex':'male'}

答:
This is trivial with a list comprehension:</p>

```<code>list_of_data = [{'sex':'male'}, {'sex':'male'}, {'sex':'male'}, {'sex':'female'}, {'sex':'female'}]

only_males = [x for x in list_of_data if x['sex'] == 'male']
</code>```

Body:
This is trivial with a list comprehension:

list_of_data = [{'sex':'male'}, {'sex':'male'}, {'sex':'male'}, {'sex':'female'}, {'sex':'female'}]

only_males = [x for x in list_of_data if x['sex'] == 'male']


答:
There's no way to build a deterministic comparison-based data structure with amortized O(1)-time adds and worst-case O(log n)-time gets. The other configuration cannot be ruled out by an information-theoretic lower bound, but I seriously doubt that anyone knows how to do it.

For the experts: the adversary first adds n items, answering the algorithm's O(n) comparisons in such a way as to leave an antichain of size at least log2 n. It then chooses k in such a way that computing get(k) forces the algorithm to do selection on the antichain, incurring a cost of Ω(log2 n).

Why can the adversary force such a large antichain? Suppose that the algorithm always left no antichain of more than log2 n elements. By Dilworth's theorem, the elements can be partitioned into at most log2 n chains, which can be merged using O(n log log n) comparisons, giving a sorting algorithm that uses o(n log n) comparisons and thus a contradiction.

What could your interviewer have meant? It's conceivable to me that if both operations are amortized, then there's a solution. This is a non-canonical relaxation of the requirements, however.

Title: Datastructures where Add, Get kth largest are O(log n) and O(1)

Body: Give a data structure that stores comparable objects and supports add() and get(k) operations [get(k) returns the kth smallest element in the data structure (1 <= k <= n)]. get(k) must be O(1) and add() must be O(log n) where n is the number of objects added to the data structure. Give another structure where get(k) is O(log n) and add is O(1)


答:
dict_list_1 = [{'sex':'male'}, {'sex':'male'}, {'sex':'male'}, {'sex':'female'}, {'sex':'female'}]
dict_list_2 = [dic for dic in dict_list_1 if dic['sex'] == 'male']
```

Title: How do I create a new list of dictionaries based on a key-value result?

Body:
I have a list of dictionaries. For example, something like [{'sex':'male'}, {'sex':'male'}, {'sex':'male'}, {'sex':'female'}, {'sex':'female'}. Imagine this, but way bigger.

How would I be able to go though and make a new list with just the male dictionaries? It would look like [{'sex':'male'}, {'sex':'male'}, {'sex':'male'}


问:
How do I disable the touch of a child element in Touchable Component
I have following code

```<code><BlurView blurType={'light'} blurAmount={10} style={{flex: 1}}>
    <TouchableOpacity style={{flex: 1, justifyContent: 'center', alignItems: 'center'}} onPress={() => this.setState({displayVideoModal: false})}>
        <View style={{width: moderateScale(300), height: moderateScale(300), backgroundColor: '#333333', borderRadius: moderateScale(24)}}>

        </View>
    </TouchableOpacity>
</BlurView>
</code>```

Which result in following

I have TouchableOpacity covering the BlurView area because I want the full blur view screen to respond to touch event and hide it. except the view in the center. It will contain the video and must not receive the touch event of its parent component and it must have touch event of its own.

How do I do this? Or I am willing to know if there are alternatives to achieve the similar result.

答:
Nested touchables were not working for me because I also had buttons in the floating view. On the background overlay view (BlurView in this case), add the following props:

```<code>onStartShouldSetResponder={(event) => {
    return event.nativeEvent.touches.length == 1;
}}
onResponderRelease={(event) => {
    if (event.target == event.currentTarget) {
        this.props.onCancel()
    }
}}
</code>```

This works because event.currentTarget is the view that has the prop onResponderRelease and target is the view that the touch was released upon.

React Native Gesture Responder System documentation: https://facebook.github.io/react-native/docs/gesture-responder-system

Body:
I have following code

<BlurView blurType={'light'} blurAmount={10} style={{flex: 1}}>
    <TouchableOpacity style={{flex: 1, justifyContent: 'center', alignItems: 'center'}} onPress={() => this.setState({displayVideoModal: false})}>
        <View style={{width: moderateScale(300), height: moderateScale(300), backgroundColor: '#333333', borderRadius: moderateScale(24)}}>

        </View>
    </TouchableOpacity>
</BlurView>

Which result in following

I have TouchableOpacity covering the BlurView area because I want the full blur view screen to respond to touch event and hide it. except the view in the center. It will contain the video and must not receive the touch event of its parent component and it must have touch event of its own.

How do I do this? Or I am willing to know if there are alternatives to achieve the similar result.

Body:
Nested touchables were not working for me because I also had buttons in the floating view. On the background overlay view (BlurView in this case), add the following props:

onStartShouldSetResponder={(event) => {
    return event.nativeEvent.touches.length == 1;
}}
onResponderRelease={(event) => {
    if (event.target == event.currentTarget) {
        this.props.onCancel()
    }
}}

This works because event.currentTarget is the view that has the prop onResponderRelease and target is the view that the touch was released upon.

React Native Gesture Responder System documentation: https://facebook.github.io/react-native/docs/gesture-responder-system


问:
How to asynchronously write to a JSON file from an array?
I'm scraping some data and pushing it to any array from which it is written to a JSON file. Currently it writes to the JSON file after every push to th array...

```<code>    const myArray = [];
    const htmlString = await rp(url);
    $('a','#atozindex', htmlString).map(async (index, element) => {
        let link = $(element).attr('href');
        if (link) {
            //Do something
            myArray.push({ item1, item2, item3 });
            fs.writeFile("./arrayContents.json", JSON.stringify(myArray), function(err) {
                if(err) {
                    console.log(err);
                }
                console.log("Some Message");
            });
        }
    });
    return myArray;
</code>```

I want to have it push only once at the very end when all the data is already in the array. So something like this:

```<code>    const myArray = [];
    const htmlString = await rp(url);
    $('a','#atozindex', htmlString).map(async (index, element) => {
        let link = $(element).attr('href');
        if (link) {
            //Do something
            myArray.push({ item1, item2, item3 });
        }
    });
    fs.writeFile("./arrayContents.json", JSON.stringify(myArray), function(err) {
        if(err) {
            console.log(err);
        }
        console.log("Some Message");
    return myArray;
</code>```

But I'm having some trouble figuring it out.

答:
i think that you can do that like this

```<code>$.when(mapping()).then(function( ) { // mapping is a function for your map and until it finish then do that ...

});
</code>```

OR

```<code>$.when(mapping()).done(function( ) { // mapping is a function for your map and until it finish then do that ...

    });
</code>```

until map finish then or done do somting , thant's it

you can see learn more about when/then or done here

Body:
I'm scraping some data and pushing it to any array from which it is written to a JSON file. Currently it writes to the JSON file after every push to th array...

    const myArray = [];
    const htmlString = await rp(url);
    $('a','#atozindex', htmlString).map(async (index, element) => {
        let link = $(element).attr('href');
        if (link) {
            //Do something
            myArray.push({ item1, item2, item3 });
            fs.writeFile("./arrayContents.json", JSON.stringify(myArray), function(err) {
                if(err) {
                    console.log(err);
                }
                console.log("Some Message");
            });
        }
    });
    return myArray;

I want to have it push only once at the very end when all the data is already in the array. So something like this:

    const myArray = [];
    const htmlString = await rp(url);
    $('a','#atozindex', htmlString).map(async (index, element) => {
        let link = $(element).attr('href');
        if (link) {
            //Do something
            myArray.push({ item1, item2, item3 });
        }
    });
    fs.writeFile("./arrayContents.json", JSON.stringify(myArray), function(err) {
        if(err) {
            console.log(err);
        }
        console.log("Some Message");
    return myArray;

But I'm having some trouble figuring it out.

Body:
i think that you can do that like this

$.when(mapping()).then(function( ) { // mapping is a function for your map and until it finish then do that ...

});

OR

$.when(mapping()).done(function( ) { // mapping is a function for your map and until it finish then do that ...

    });

until map finish then or done do somting , thant's it

you can see learn more about when/then or done here


问:
error: consider creating fewer actors or increase the resources available to this Ray cluster
I had this problem when I try to run on virtual box: python examples/train.py singleagent_traffic_light_grid.
I appreciate your time to help to fix it.

答: It looks like you only have 1 CPU available on that machine. Try using the stable baseline examples instead, they can run if only 1 CPU is available.</p>


问:
How to increment values at the same time rather than mapping through them in order?
I am making a racing game in ReactJS and I need to increment the values of four race entities (divs in my case) at the same time, rather than mapping through them and incrementing them one by one. Right now they all increment on button click at random speed.

```<code>changePlayerArr.map(player => {
  console.log(player)
  player.speed = player.speed - Math.floor(Math.random() * 11 + 5)
});
</code>```

They move by VW in CSS and the goal is to get them to -100vw which is the end of the screen. However, I can't know which one is the real winner if I increment their speeds from the first div to last div or vice versa. Any suggestions?

答:
Javascript is single-threaded, not much in the way of concurrency. I think about the best you can do is to keep a structure of some metric that matters to the racing players (displacement for example) and apply a displacement accumulator (displacementDelta = rate * time) upon each render cycle to determine a new sorted order.

The winner could be the element in first place (index 0 maybe?) after accumulating displacement and sorting the structure after at least one element achieves the racing distance.

Body:
I am making a racing game in ReactJS and I need to increment the values of four race entities (divs in my case) at the same time, rather than mapping through them and incrementing them one by one. Right now they all increment on button click at random speed.

changePlayerArr.map(player => {
  console.log(player)
  player.speed = player.speed - Math.floor(Math.random() * 11 + 5)
});

They move by VW in CSS and the goal is to get them to -100vw which is the end of the screen. However, I can't know which one is the real winner if I increment their speeds from the first div to last div or vice versa. Any suggestions?


问:
Dict column output to standard pandas column
I have a situation where my output from a previous code step has been stored as a dictionary but as a pandas column after the use of zip function.
Now I want to store the results of this dict column as a standard pandas column.

The code that I have used which has created the dict column using the zip function :

```<code>a=pd.DataFrame(zip(tf_lst,results),columns=['A','B'])
</code>```

The output from this code looks like this :

```<code>A             B
Uni.      {'architecture': 0.665, 'software': 0.614}
School    {'Science': 0.665, 'C++': 0.614}
</code>```

Now I want to store the COL B which is currently in the form of a dict to a standard pandas column in the following way:
I want to remove the values from each of the keys and store it separated by commas

```<code> A          B
Uni        architecture,software
School     Science,C++
</code>```

答:
You could use transform: I used assign just in case you want to maintain your original column. You can overwrite it, or even drop it. etc</p>

```<code>df.assign(C = df.B.transform(','.join))
        A                                           B                      C
0    Uni.  {'architecture': 0.665, 'software': 0.614}  architecture,software
1  School            {'Science': 0.665, 'C++': 0.614}            Science,C++
</code>```

Body:
I have a situation where my output from a previous code step has been stored as a dictionary but as a pandas column after the use of zip function.
Now I want to store the results of this dict column as a standard pandas column.

The code that I have used which has created the dict column using the zip function :

a=pd.DataFrame(zip(tf_lst,results),columns=['A','B'])

The output from this code looks like this :

A             B
Uni.      {'architecture': 0.665, 'software': 0.614}
School    {'Science': 0.665, 'C++': 0.614}

Now I want to store the COL B which is currently in the form of a dict to a standard pandas column in the following way:
I want to remove the values from each of the keys and store it separated by commas

 A          B
Uni        architecture,software
School     Science,C++

Body:
You could use transform: I used assign just in case you want to maintain your original column. You can overwrite it, or even drop it. etc

df.assign(C = df.B.transform(','.join))
        A                                           B                      C
0    Uni.  {'architecture': 0.665, 'software': 0.614}  architecture,software
1  School            {'Science': 0.665, 'C++': 0.614}            Science,C++


问:
How to deal with large ICS files?
My application (php/laravel, but irrelevant here) holds calendar entries for its users (comparable to a car logbook), and some users want to sync those events to their calendar app of choice. I started looking into the ics standard (RFC 5545 etc.) and created an endpoint that generates those files.

Problem: The files are getting huge. Some users have their entire driving history with hundreds and thousands of entries in the application, generating and transfering those MBs of ICS files will take ages (using php, anyways), let alone doing that everytime the calendar app tries to sync.

Question(s): What is the preferred way of dealing with huge ICS documents? HTTP headers and caching is one thing, but how do other people solve this problem? Just send events of the last year? Is there a (pagination?) spec that I haven't found yet?

答:
This is historical data,  so it is not going to change.  You could offer batches by time period and cache the historical batches.  Last years, or anything before the last 4 weeks,  never gets updated for example.  They do a one-off import of each historical batch into a separate 'driving history' calendar.  No more subscribing? Or maybe they can only subscribe for the last month say? </p>

<p>One cannot import & subscribe into the same calendar, so it does mean they would have at least 2 calendars - 1 historical calendar used for imports, and 1 'current' that will update with yesterday's ride.  Of course there is then manual effort for anyone who wants to always have the old data as when events fall off the 'current' calendar, at some point they'd have to go import the latest 'old' events.  </p>

Title: How to deal with large ICS files?

Body:
This is historical data,  so it is not going to change.  You could offer batches by time period and cache the historical batches.  Last years, or anything before the last 4 weeks,  never gets updated for example.  They do a one-off import of each historical batch into a separate 'driving history' calendar.  No more subscribing? Or maybe they can only subscribe for the last month say?

One cannot import & subscribe into the same calendar, so it does mean they would have at least 2 calendars - 1 historical calendar used for imports, and 1 'current' that will update with yesterday's ride.  Of course there is then manual effort for anyone who wants to always have the old data as when events fall off the 'current' calendar, at some point they'd have to go import the latest 'old' events.