问:
Using NetBeans and Command Line Arguments
I am new to java and I know this isn't for homework but I need help. I've typed a program in java and I need to have the values passed in the command line arguments and that is where I am getting stuck I quite understand how to do that. Here is the question that I needed to answer.

(Write an application that uses an enhanced for a statement to sum the double values passed by the command-line arguments. [Hint: Use the static method parseDouble of class Double to convert a String to a double value .])

here is my code

```<code>public class Enhanced {

   public static void main(String[] args) {

   Double total = 0.0;
   for (String number : args) {

   total += Double.parseDouble(number);
   }
   //print total
   System.out.printf("Total of array elements: %f%n", total);
   }
}
</code>```

答:
First thing you would need to compile your code using below command.

```<code>javac Enhanced.java
</code>```

It will compile your program and prepare a class file for it, then you need to run that class as specified in other answers.

```<code>java Enhanced 3.2 2.12 5.83
</code>```

Body:
I am new to java and I know this isn't for homework but I need help. I've typed a program in java and I need to have the values passed in the command line arguments and that is where I am getting stuck I quite understand how to do that. Here is the question that I needed to answer.

(Write an application that uses an enhanced for a statement to sum the double values passed by the command-line arguments. [Hint: Use the static method parseDouble of class Double to convert a String to a double value .])

here is my code

public class Enhanced {

   public static void main(String[] args) {

   Double total = 0.0;
   for (String number : args) {

   total += Double.parseDouble(number);
   }
   //print total
   System.out.printf("Total of array elements: %f%n", total);
   }
}

Body:
First thing you would need to compile your code using below command.

javac Enhanced.java

It will compile your program and prepare a class file for it, then you need to run that class as specified in other answers.

java Enhanced 3.2 2.12 5.83


来源: stackexchange

问:
Why doesn't build_runner generate files when serializing JSON in dart/flutter
I'm just trying to generate my files with the same command i stored like 3 months ago (i'm not very good with backend and devops) and now it doesn't generate the files anymore.
It tells me to use the delete command which i don't remember but even using that one my files still won't be generated.
This is what my log looks like, and below you can find the code for a simple class.

One of my guesses would be this has something to do with me changing my github account, since there's the permission issue mentioned.

Im using vs code in windows 10.

log file:

```<code>E:\1 Work\flutter_pilot> flutter pub run build_runner build
[INFO] Generating build script...
[INFO] Generating build script completed, took 336ms

[WARNING] Deleted previous snapshot due to missing asset graph.
[INFO] Creating build script snapshot......
[INFO] Creating build script snapshot... completed, took 12.5s

[INFO] Initializing inputs
[INFO] Building new asset graph...
[INFO] Building new asset graph completed, took 787ms

[INFO] Checking for unexpected pre-existing outputs....
[INFO] Found 13 declared outputs which already exist on disk. This is likely because the`.dart_tool/build` folder was deleted, or you are submitting generated files to your source repository.
[SEVERE] Conflicting outputs were detected and the build is unable to prompt for permission to remove them. These outputs must be removed manually or the build can be run with `--delete-conflicting-outputs`. The outputs are: lib/models/advisory-service-item.g.dart
lib/models/advisory-service.g.dart
lib/models/auth.g.dart
lib/models/contract.g.dart
lib/models/contributor.g.dart
lib/models/exact-cost-values.g.dart
lib/models/exact-cost.g.dart
lib/models/expert.g.dart
lib/models/paginator-info.g.dart
lib/models/person.g.dart
lib/models/project.g.dart
lib/models/system-country.g.dart
lib/models/user.g.dart
pub failed (78)
</code>```

class file:

```<code>import 'package:json_annotation/json_annotation.dart';
part 'organisation.g.dart';

@JsonSerializable()
class Organisation {
  final String name;
  Organisation({this.name});

  factory Organisation.fromJson(Map<String, dynamic> json) => _$OrganisationFromJson(json);

  Map<String, dynamic> toJson() => _$OrganisationToJson(this);
}
</code>```

答: Delete .dart_tool folder and run flutter pub get. After this, run the build runner command

ContentLicense: CC BY-SA 4.0

Body:
I'm just trying to generate my files with the same command i stored like 3 months ago (i'm not very good with backend and devops) and now it doesn't generate the files anymore.
It tells me to use the delete command which i don't remember but even using that one my files still won't be generated.
This is what my log looks like, and below you can find the code for a simple class.

One of my guesses would be this has something to do with me changing my github account, since there's the permission issue mentioned.

Im using vs code in windows 10.

log file:

E:\1 Work\flutter_pilot> flutter pub run build_runner build
[INFO] Generating build script...
[INFO] Generating build script completed, took 336ms

[WARNING] Deleted previous snapshot due to missing asset graph.
[INFO] Creating build script snapshot......
[INFO] Creating build script snapshot... completed, took 12.5s

[INFO] Initializing inputs
[INFO] Building new asset graph...
[INFO] Building new asset graph completed, took 787ms

[INFO] Checking for unexpected pre-existing outputs....
[INFO] Found 13 declared outputs which already exist on disk. This is likely because the`.dart_tool/build` folder was deleted, or you are submitting generated files to your source repository.
[SEVERE] Conflicting outputs were detected and the build is unable to prompt for permission to remove them. These outputs must be removed manually or the build can be run with `--delete-conflicting-outputs`. The outputs are: lib/models/advisory-service-item.g.dart
lib/models/advisory-service.g.dart
lib/models/auth.g.dart
lib/models/contract.g.dart
lib/models/contributor.g.dart
lib/models/exact-cost-values.g.dart
lib/models/exact-cost.g.dart
lib/models/expert.g.dart
lib/models/paginator-info.g.dart
lib/models/person.g.dart
lib/models/project.g.dart
lib/models/system-country.g.dart
lib/models/user.g.dart
pub failed (78)

class file:

import 'package:json_annotation/json_annotation.dart';
part 'organisation.g.dart';

@JsonSerializable()
class Organisation {
  final String name;
  Organisation({this.name});

  factory Organisation.fromJson(Map<String, dynamic> json) => _$OrganisationFromJson(json);

  Map<String, dynamic> toJson() => _$OrganisationToJson(this);
}


问:
input value same as predefined list but getting a different output
Ive written a program which takes in the name and age of multiple entries seperated by a comma and then sepearates  the aplhabets from the numerics and then compares the name with a pre defined set/list.
If the entry doesnt match with the pre defined data, the program sends a message"incorrect entry" along with the element which didnt match.
heres the code:

```<code>from string import digits

print("enter name and age")
order=input("Seperate entries using a comma ',':")
order1=order.strip()
order2=order1.replace(" ","")
order_sep=order2.split()
removed_digits=str.maketrans('','',digits)
names=order.translate(removed_digits)
print(names)
names1=names.split(',')
names_list=['abby','chris','john','cena']

names_list=set(names_list)

for name in names1:
    if name not in names_list:
        print(f"{name}:doesnt match with predefined data")
</code>```

the problem im having is even when i enter chris or john, the program treats them as they dont belong to the pre defined list

```<code>sample input : ravi 19,chris 20
output:ravi ,chris
ravi :doesnt match with predefined data
chris :doesnt match with predefined data
</code>```

also i have another issue , ive written a part to eliminate whitespace but i dont know why, it doesnt elimintae them

```<code>sample input:ravi , chris
ravi :doesnt match with predefined data
()chris :doesnt match with predefined data
</code>```

theres a space where ive put parenthesis.

any suggestion to tackle this problem and/or improve this code is appreciated!

答:
I think some of the parts can be simplified, especially when removing the digits. As long as the input is entered with a space between the name and age, you can use split() twice. First to separate the entries with split(',') and next to separate out the ages with split(). It makes comparisons easier later if you store the names by themselves with no punctuation or whitespace around them. To print the names out from an iterable, you can use the str.join() function. Here is an example:

```<code>print("enter name and age")
order = input("Seperate entries using a comma ',': ")
names1 = [x.split()[0] for x in order.split(',')]
print(', '.join(names1))

names_list=['abby', 'chris', 'john', 'cena']
for name in names1:
    if name not in names_list:
        print(f"{name}:doesnt match with predefined data")
</code>```

This will give the desired output:

```<code>enter name and age
Seperate entries using a comma ',': ravi 19, chris 20
ravi, chris
ravi:doesnt match with predefined data
</code>```

Body:
Ive written a program which takes in the name and age of multiple entries seperated by a comma and then sepearates  the aplhabets from the numerics and then compares the name with a pre defined set/list.
If the entry doesnt match with the pre defined data, the program sends a message"incorrect entry" along with the element which didnt match.
heres the code:

from string import digits

print("enter name and age")
order=input("Seperate entries using a comma ',':")
order1=order.strip()
order2=order1.replace(" ","")
order_sep=order2.split()
removed_digits=str.maketrans('','',digits)
names=order.translate(removed_digits)
print(names)
names1=names.split(',')
names_list=['abby','chris','john','cena']

names_list=set(names_list)

for name in names1:
    if name not in names_list:
        print(f"{name}:doesnt match with predefined data")

the problem im having is even when i enter chris or john, the program treats them as they dont belong to the pre defined list

sample input : ravi 19,chris 20
output:ravi ,chris
ravi :doesnt match with predefined data
chris :doesnt match with predefined data

also i have another issue , ive written a part to eliminate whitespace but i dont know why, it doesnt elimintae them

sample input:ravi , chris
ravi :doesnt match with predefined data
()chris :doesnt match with predefined data

theres a space where ive put parenthesis.

any suggestion to tackle this problem and/or improve this code is appreciated!

Body:
I think some of the parts can be simplified, especially when removing the digits. As long as the input is entered with a space between the name and age, you can use split() twice. First to separate the entries with split(',') and next to separate out the ages with split(). It makes comparisons easier later if you store the names by themselves with no punctuation or whitespace around them. To print the names out from an iterable, you can use the str.join() function. Here is an example:

print("enter name and age")
order = input("Seperate entries using a comma ',': ")
names1 = [x.split()[0] for x in order.split(',')]
print(', '.join(names1))

names_list=['abby', 'chris', 'john', 'cena']
for name in names1:
    if name not in names_list:
        print(f"{name}:doesnt match with predefined data")

This will give the desired output:

enter name and age
Seperate entries using a comma ',': ravi 19, chris 20
ravi, chris
ravi:doesnt match with predefined data


问:
Is flask required for a discord bot?
I am writing a discord bot, but flask is doing some annoying stuff such as forcing me to use kill -9 on it. Is it ok to write a discord bot without flask? Some tutorials I've read use flask, but I am confused as to if it is required or not.

答: No you don't need flask for a discord bot. Please look into creating a discord bot using python here.</p>

Title: Is flask required for a discord bot?


问:
Cannot resolve symbol 'AndroidSchedulers ' on AndroidSchedulers.mainThread() using implementation 'androidx.room:room-rxjava2:2.1.0'
I am trying to follow a few code examples to pull a single record from the database to display, because it seems somewhat complicated to do so with LiveData. However, I am getting an error in the IDE.

Cannot resolve symbol 'AndroidSchedulers'

on the line:

```<code>AndroidSchedulers.mainThread()
</code>```

in this call:

```<code>        viewModel.getScenario(scenarioId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DisposableSingleObserver<Scenario>() {
                    @Override
                    public void onSuccess(Scenario scenario) {

                    }
                });
</code>```

My grade has this:

```<code>implementation 'androidx.room:room-rxjava2:2.1.0'
</code>```

答: You have missing implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' in your gradle. AndroidSchedulers.mainThread() is part of rxandroid not a   rxjava2

Body:
I am trying to follow a few code examples to pull a single record from the database to display, because it seems somewhat complicated to do so with LiveData. However, I am getting an error in the IDE.

Cannot resolve symbol 'AndroidSchedulers'

on the line:

AndroidSchedulers.mainThread()

in this call:

        viewModel.getScenario(scenarioId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DisposableSingleObserver<Scenario>() {
                    @Override
                    public void onSuccess(Scenario scenario) {

                    }
                });

My grade has this:

implementation 'androidx.room:room-rxjava2:2.1.0'


问:
Python trick in finding leading zeros in string
I have a binary string say '01110000', and I want to return the number of leading zeros in front without writing a forloop. Does anyone have any idea on how to do that? Preferably a way that also returns 0 if the string immediately starts with a '1'</p>

答: I'm using has_leading_zero = re.match(r'0\d+', str(data)) as a solution that accepts any number and treats 0 as a valid number without a leading zero

ContentLicense: CC BY-SA 3.0


问:
Define an API that accepts multiple types each of which has its own range of possible values
I want to define an API that accepts a (type, value) pair and performs some operation on them.

```<code>typedef enum {
    TTL_ENTRY = 1,
    ACCESS_ENTRY = 2
}type_t;

typedef struct {
    type_t type;
    uint32 value;
}type_val_t;

int entries_add(size_t count, type_val_t *type_val);
</code>```

Each type has it's own range of possible values.

TTL_ENTRY's value can be a uint32 with any value.

ACCESS_ENTRY's value should accept only values from the enum:

```<code>typedef enum {
    STATE_NONE = 0,
    STATE_DROP,
    STATE_PATH
    /* ... */
}state_t;
</code>```

Is there a way to make this API more clear about which value should pair with which type?
Or somehow bind a value type for each type from type_t?

I thought converting value type from a uint32 into a union of possible values, like so:

```<code>typedef union {
    uint32 ttl_bitmap;
    state_t state;
}value_t;

typedef struct {
    type_t type;
    value_t value;
}type_val_t;
</code>```

But even when using this kind of type it is not 100% clear which value should be coupled with which type.

答:
I think based on your limited example that using a union for value_t is probably a good idea.

About the best you can do beyond that, in C, is to name the fields in the union directly after the enums which select those fields so the correspondence is clear to any user of these data structures.

For your example this might mean you should make value_t look more like this:

```<code>typedef union {
    uint32 ttl_entry;
    state_t access_entry;
} value_t;
</code>```

So when choosing your type selector enum identifiers you might consider how they could also be used as field names.

You may then also want to write a macro or set of macros for accessing each field based on the enum value.

There may be other ways to design your API and data structures in a more C-friendly way, but you would have to describe your larger problem (probably in another question) to get more guidance.

Body:
I want to define an API that accepts a (type, value) pair and performs some operation on them.

typedef enum {
    TTL_ENTRY = 1,
    ACCESS_ENTRY = 2
}type_t;

typedef struct {
    type_t type;
    uint32 value;
}type_val_t;

int entries_add(size_t count, type_val_t *type_val);

Each type has it's own range of possible values.

TTL_ENTRY's value can be a uint32 with any value.

ACCESS_ENTRY's value should accept only values from the enum:

typedef enum {
    STATE_NONE = 0,
    STATE_DROP,
    STATE_PATH
    /* ... */
}state_t;

Is there a way to make this API more clear about which value should pair with which type?
Or somehow bind a value type for each type from type_t?

I thought converting value type from a uint32 into a union of possible values, like so:

typedef union {
    uint32 ttl_bitmap;
    state_t state;
}value_t;

typedef struct {
    type_t type;
    value_t value;
}type_val_t;

But even when using this kind of type it is not 100% clear which value should be coupled with which type.

Body:
I think based on your limited example that using a union for value_t is probably a good idea.

About the best you can do beyond that, in C, is to name the fields in the union directly after the enums which select those fields so the correspondence is clear to any user of these data structures.

For your example this might mean you should make value_t look more like this:

typedef union {
    uint32 ttl_entry;
    state_t access_entry;
} value_t;

So when choosing your type selector enum identifiers you might consider how they could also be used as field names.

You may then also want to write a macro or set of macros for accessing each field based on the enum value.

There may be other ways to design your API and data structures in a more C-friendly way, but you would have to describe your larger problem (probably in another question) to get more guidance.


问:
jQuery not firing when clicking item in drop down menu
I'm updating the UI of my project that has two download buttons for PDF and CSV. I'm trying to put them now in a drop down menu to save some space and a cleaner UI. My problem now is, the jQuery are not working anymore after putting them in drop-down menu. Here's what I have:

```<code><div class="col-sm-8">
    <div class="btn-group float-right">
        <button type="button" class="btn btn-success" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-download"></i>Download
            <div class="dropdown-menu" role="menu" x-placement="top-start" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(-1px, -3px, 0px);">
                <a type="button" href="#" data-href="{{route('csv')}}"
                    class="dropdown-item download-csv">CSV</a>
                <div class="dropdown-divider"></div>
                <a type="button" href="#" data-href="{{ route('pdf') }}"
                    class="dropdown-item download-pdf">PDF</a>
            </div>
        </button>
    </div>
</div>
</code>```

js

```<code>$(document).on('click','.download-csv', function(){
    console.log('just here');
});
</code>```

BUTTON ONLY

```<code><div class="col-sm-4">
    <a type="button" href="#" data-href="{{route('csv')}}"
        class="btn btn-block btn-secondary btn-download custom-font-button download-csv"><i class="fa fa-download"></i>@lang('guest.csv')</a>
</div>
</code>```

It's as the same as before codes, but when I'm just using buttons, it's working well. What could be the possible cause for this one?

答:
Hope this help you. try this

$(document).on('click', '.download-csv', function() {
  console.log('just here');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.open .dropdown-menu {
  display: block !important;
}</code>```

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

    <button type="button" class="btn btn-success" data-toggle="dropdown" aria-expanded="false">Download

                CSV

                PDF

        </button>

  @lang('guest.csv')

```

Body:
I'm updating the UI of my project that has two download buttons for PDF and CSV. I'm trying to put them now in a drop down menu to save some space and a cleaner UI. My problem now is, the jQuery are not working anymore after putting them in drop-down menu. Here's what I have:

        <button type="button" class="btn btn-success" data-toggle="dropdown" aria-expanded="false">Download

                CSV

                PDF

        </button>

js

$(document).on('click','.download-csv', function(){
    console.log('just here');
});

BUTTON ONLY

    @lang('guest.csv')

It's as the same as before codes, but when I'm just using buttons, it's working well. What could be the possible cause for this one?

Body:
Hope this help you. try this

$(document).on('click', '.download-csv', function() {
  console.log('just here');
});

.open .dropdown-menu {
  display: block !important;
}

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="col-sm-8">
  <div class="btn-group float-right">
    <button type="button" class="btn btn-success" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-download"></i>Download
            <div class="dropdown dropdown-menu" role="menu" x-placement="top-start" style="position: absolute; will-change: transform; left: 0px; transform: translate3d(-1px, -3px, 0px);">
                <a type="button" href="#" data-href="{{route('csv')}}"
                    class="dropdown-item download-csv">CSV</a>
                <div class="dropdown-divider"></div>
                <a type="button" href="#" data-href="{{ route('pdf') }}"
                    class="dropdown-item download-pdf">PDF</a>
            </div>
        </button>
  </div>
</div>

<div class="col-sm-4">
  <a type="button" href="#" data-href="{{route('csv')}}" class="btn btn-block btn-secondary btn-download custom-font-button download-csv"><i class="fa fa-download"></i>@lang('guest.csv')</a>
</div>


问:
mysql in clause vs multiple delete with one commit
I have about 100K records that I have to run for the following query:

```<code>delete from users where name in #{String}
</code>```

where the string could be 100K strings of this form: Joe,Kate etc.

For performance is it better to run the above statement or delete one record in a loop with one session.commit(); in the end?

EDITED

There could be only one record for each value

答:
It would be better not to use such statements!
The query optimizer will have a field day parsing such a query. I suggest using some temporary table to join against, or some other WHERE-clause that the records to be deleted have in common?</p>

Body:
I have about 100K records that I have to run for the following query:

delete from users where name in #{String}

where the string could be 100K strings of this form: Joe,Kate etc.

For performance is it better to run the above statement or delete one record in a loop with one session.commit(); in the end?

EDITED

There could be only one record for each value


问:
KStream leftJoin KStream with the same Key
I have the problem taht i try to leftjoin 2 Streams. mergedKey has 100+
listings with the same key and DataStream has just 1 listing with the same key as mergedKey. I want in the endStream Value from mergedKey Merged with DataStream.

```<code>      //get DataStream
        final KStream<String, GenericRecord> DataStream = builder.stream("Datastreams");
        // Transform merged to Equals Keys to DataStream.Iot
        final KStream<String, GenericRecord> mergedKey = mergedFoIObs
                .map((key, value) -> KeyValue.pair(value.get("Datastream").toString(), value));
        // Join the DataStream with MergedStream

        final KStream<String, String> mergedFoIObsData = mergedKey.leftJoin(
                DataStream,
            (value, data) -> {
                try {
                    if(data != null{
                        value.put("Datastream", data.toString());
                        JSONObject jo = (JSONObject) new JSONParser().parse(value.toString());
                        return jo.toJSONString();}
                      return null

                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;

            }, JoinWindows.of(10000));
</code>```

But My problem is that in the Endstream I get just 1 listing with the right values and the other listings has null as values.

Taht means that data is null after the first "round".

When i transfrom DataStream to a KTable I have the problem taht i get right listing but just 37 listings so 60 are Misssing.

I hope you can help me out.

答:
"Furthermore, for each input record of this KStream that does not satisfy the join predicate the provided ValueJoiner will be called with a null value for the other stream."

So you should not return null when the data (right value) is null, you should return value (left value).

kafka docs link on leftJoin

Body:
I have the problem taht i try to leftjoin 2 Streams. mergedKey has 100+
listings with the same key and DataStream has just 1 listing with the same key as mergedKey. I want in the endStream Value from mergedKey Merged with DataStream.

      //get DataStream
        final KStream<String, GenericRecord> DataStream = builder.stream("Datastreams");
        // Transform merged to Equals Keys to DataStream.Iot
        final KStream<String, GenericRecord> mergedKey = mergedFoIObs
                .map((key, value) -> KeyValue.pair(value.get("Datastream").toString(), value));
        // Join the DataStream with MergedStream

        final KStream<String, String> mergedFoIObsData = mergedKey.leftJoin(
                DataStream,
            (value, data) -> {
                try {
                    if(data != null{
                        value.put("Datastream", data.toString());
                        JSONObject jo = (JSONObject) new JSONParser().parse(value.toString());
                        return jo.toJSONString();}
                      return null

                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;

            }, JoinWindows.of(10000));

But My problem is that in the Endstream I get just 1 listing with the right values and the other listings has null as values.

Taht means that data is null after the first "round".

When i transfrom DataStream to a KTable I have the problem taht i get right listing but just 37 listings so 60 are Misssing.

I hope you can help me out.


问:
After update Eclipse I can not generate reports in JasperStudio
I have little problem. In previous version of Eclipse (2019-06) I created many reports with JasperSoft (plug-in in eclipse). Yesterday I updated to new version (big mistake?) and I can not create reports. I do everything as always and this is my result:

```<code>Exception in thread "main" java.lang.NullPointerException
at net.sf.jasperreports.components.table.fill.TableReport.createCell(TableReport.java:1600)
at net.sf.jasperreports.components.table.fill.TableReport$ReportBandCreator.createColumnCell(TableReport.java:497)
at net.sf.jasperreports.components.table.fill.TableReport$ColumnHeaderCreator.createColumnCell(TableReport.java:709)
at net.sf.jasperreports.components.table.fill.TableReport$ColumnHeaderCreator.createColumnCell(TableReport.java:686)
at net.sf.jasperreports.components.table.fill.TableReport$ReportBandCreator.visitColumn(TableReport.java:476)
at net.sf.jasperreports.components.table.fill.TableReport$ReportBandCreator.visitColumn(TableReport.java:442)
at net.sf.jasperreports.components.table.StandardColumn.visitColumn(StandardColumn.java:74)
at net.sf.jasperreports.components.table.fill.TableReport$ReportBandCreator.visit(TableReport.java:555)
at net.sf.jasperreports.components.table.fill.TableReport.createColumnHeader(TableReport.java:1112)
at net.sf.jasperreports.components.table.fill.TableReport.<init>(TableReport.java:300)
at net.sf.jasperreports.components.table.fill.FillTable.createFillTableSubreportFactory(FillTable.java:335)
at net.sf.jasperreports.components.table.fill.FillTable.createFillSubreport(FillTable.java:309)
at net.sf.jasperreports.components.table.fill.FillTable.evaluate(FillTable.java:131)
at net.sf.jasperreports.engine.fill.JRFillComponentElement.evaluate(JRFillComponentElement.java:110)
at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:381)
at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:500)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnBand(JRVerticalFiller.java:2022)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:748)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:255)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:115)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:580)
at net.sf.jasperreports.engine.fill.BaseReportFiller.fill(BaseReportFiller.java:414)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:121)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:583)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:929)
at com.baeldung.jasperreports.Main.main(Main.java:242)
</code>```

This is my code (shorter version):

```<code>String outputFile = File.separatorChar + "D:\\eclipse\\JasperTableExample2.pdf";

Collection<Person> osoba = new ArrayList<Person>();

Person john = new Person();
john.setName("John");
john.setSurname("Doe");
john.setEmail("john@gmail.com");
john.setAge(22);
john.setX(5);
john.setY(5);
john.setZ(1);
john.setDateTime(LocalDateTime.of(2019,12,12,9,25));
osoba.add(john);

JRBeanCollectionDataSource personJRBean = new JRBeanCollectionDataSource(osoba);
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("ItemDataSource", personJRBean);
JasperPrint jasperPrint = JasperFillManager.fillReport("D://path//NewReport.jasper", parameters, new JREmptyDataSource()); // this is #242 line at Main.java
OutputStream outputStream = new FileOutputStream(new File(outputFile));
JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
</code>```

I do not put here a Person class. Java code works well.

In JasperStudio I create new report, new parameter (name as in code - ItemDataSource, set class to net.sf.jasperreports.engine.data.JRBeanCollectionDataSource). Then I create a table with the new dataset and choose this:

Then I just launched Main and the report was generated.

Before update, this process worked perfectly, but after "update step" I am getting this error.

答:
I had the exact same problem with the same stacktrace.
It was not about eclipse but about the Jaspersoft Studio version.

I was using Jaspersoft Studio 6.11.0 in eclipse and version 6.4.3 of jasperreports.jar at runtime.
I had to upgrade my pom.xml (I'm using maven) to both 6.11.0 and it fixed it.

Body:
I have little problem. In previous version of Eclipse (2019-06) I created many reports with JasperSoft (plug-in in eclipse). Yesterday I updated to new version (big mistake?) and I can not create reports. I do everything as always and this is my result:

Exception in thread "main" java.lang.NullPointerException
at net.sf.jasperreports.components.table.fill.TableReport.createCell(TableReport.java:1600)
at net.sf.jasperreports.components.table.fill.TableReport$ReportBandCreator.createColumnCell(TableReport.java:497)
at net.sf.jasperreports.components.table.fill.TableReport$ColumnHeaderCreator.createColumnCell(TableReport.java:709)
at net.sf.jasperreports.components.table.fill.TableReport$ColumnHeaderCreator.createColumnCell(TableReport.java:686)
at net.sf.jasperreports.components.table.fill.TableReport$ReportBandCreator.visitColumn(TableReport.java:476)
at net.sf.jasperreports.components.table.fill.TableReport$ReportBandCreator.visitColumn(TableReport.java:442)
at net.sf.jasperreports.components.table.StandardColumn.visitColumn(StandardColumn.java:74)
at net.sf.jasperreports.components.table.fill.TableReport$ReportBandCreator.visit(TableReport.java:555)
at net.sf.jasperreports.components.table.fill.TableReport.createColumnHeader(TableReport.java:1112)
at net.sf.jasperreports.components.table.fill.TableReport.<init>(TableReport.java:300)
at net.sf.jasperreports.components.table.fill.FillTable.createFillTableSubreportFactory(FillTable.java:335)
at net.sf.jasperreports.components.table.fill.FillTable.createFillSubreport(FillTable.java:309)
at net.sf.jasperreports.components.table.fill.FillTable.evaluate(FillTable.java:131)
at net.sf.jasperreports.engine.fill.JRFillComponentElement.evaluate(JRFillComponentElement.java:110)
at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:381)
at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:500)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnBand(JRVerticalFiller.java:2022)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:748)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:255)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:115)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:580)
at net.sf.jasperreports.engine.fill.BaseReportFiller.fill(BaseReportFiller.java:414)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:121)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:583)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:929)
at com.baeldung.jasperreports.Main.main(Main.java:242)

This is my code (shorter version):

String outputFile = File.separatorChar + "D:\\eclipse\\JasperTableExample2.pdf";

Collection<Person> osoba = new ArrayList<Person>();

Person john = new Person();
john.setName("John");
john.setSurname("Doe");
john.setEmail("john@gmail.com");
john.setAge(22);
john.setX(5);
john.setY(5);
john.setZ(1);
john.setDateTime(LocalDateTime.of(2019,12,12,9,25));
osoba.add(john);

JRBeanCollectionDataSource personJRBean = new JRBeanCollectionDataSource(osoba);
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("ItemDataSource", personJRBean);
JasperPrint jasperPrint = JasperFillManager.fillReport("D://path//NewReport.jasper", parameters, new JREmptyDataSource()); // this is #242 line at Main.java
OutputStream outputStream = new FileOutputStream(new File(outputFile));
JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);

I do not put here a Person class. Java code works well.

In JasperStudio I create new report, new parameter (name as in code - ItemDataSource, set class to net.sf.jasperreports.engine.data.JRBeanCollectionDataSource). Then I create a table with the new dataset and choose this:

Then I just launched Main and the report was generated.

Before update, this process worked perfectly, but after "update step" I am getting this error.


问:
React Router v4 - How to get current route?
I'd like to display a title in <AppBar /> that is somehow passed in from the current route.

In React Router v4, how would <AppBar /> be able to get the current route passed into it's title prop?

```<code>  <Router basename='/app'>
    <main>
      <Menu active={menu} close={this.closeMenu} />
      <Overlay active={menu} onClick={this.closeMenu} />
      <AppBar handleMenuIcon={this.handleMenuIcon} title='Test' />
      <Route path='/customers' component={Customers} />
    </main>
  </Router>
</code>```

Is there a way to pass a custom title from a custom prop on <Route />?

答:
There's a hook called useLocation in react-router v5, no need for HOC or other stuff, it's very succinctly and convenient.</p>

```<code>import { useLocation } from 'react-router-dom';

const ExampleComponent: React.FC = () => {
  const location = useLocation();

  return (
    <Router basename='/app'>
      <main>
        <AppBar handleMenuIcon={this.handleMenuIcon} title={location.pathname} />
      </main>
    </Router>
  );
}
</code>```

Body:
I'd like to display a title in <AppBar /> that is somehow passed in from the current route.

In React Router v4, how would <AppBar /> be able to get the current route passed into it's title prop?

  <Router basename='/app'>

      <Menu active={menu} close={this.closeMenu} />
      <Overlay active={menu} onClick={this.closeMenu} />
      <AppBar handleMenuIcon={this.handleMenuIcon} title='Test' />
      <Route path='/customers' component={Customers} />

  </Router>

Is there a way to pass a custom title from a custom prop on <Route />?

Body:
There's a hook called useLocation in react-router v5, no need for HOC or other stuff, it's very succinctly and convenient.

import { useLocation } from 'react-router-dom';

const ExampleComponent: React.FC = () => {
  const location = useLocation();

  return (
    <Router basename='/app'>
      <main>
        <AppBar handleMenuIcon={this.handleMenuIcon} title={location.pathname} />
      </main>
    </Router>
  );
}


问:
Count integer partitions with k parts when partition elements given
I want to count the integer partitions of n with k partition elements. The possible partition elements are defined through a given vector v with distinct elements. Partition elements can be choosen more than once.  How Can i do this? Optimal without iterating through all integer partitions of n.

Example:

n := 10

k := 3

v := 1,2,6,7,8

=> 3

答:
One way is to have the recurrence consider each element in order.

Unmemoised JavaScript:

function f(n, k, v, i=0){
  if (k == 0)
    return n == 0;

  if (i == v.length)
    return false;

  let total = 0

  while (k >= 0 && n >= 0){
    total = total + f(n, k, v, i+1);
    k = k - 1;
    n = n - v[i];
  }

  return total;
}

console.log(f(10, 3, [1,2,6,7,8]));```


问:
Truth tables in code? How to structure state machine?
I have a (somewhat) large truth table / state machine that I need to implement in my code (embedded C). I anticipate the behavior specification of this state machine to change in the future, and so I'd like to keep this easily modifiable in the future.

My truth table has 4 inputs and 4 outputs. I have it all in an Excel spreadsheet, and if I could just paste that into my code with a little formatting, that would be ideal.

I was thinking I would like to access my truth table like so:

```<code>u8 newState[] = decisionTable[input1][input2][input3][input4];
</code>```

And then I could access the output values with:

```<code>setOutputPin( LINE_0, newState[0] );
setOutputPin( LINE_1, newState[1] );
setOutputPin( LINE_2, newState[2] );
setOutputPin( LINE_3, newState[3] );
</code>```

But in order to get that, it looks like I would have to do a fairly confusing table like so:

```<code>static u8 decisionTable[][][][][] =
 {{{{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }},
   {{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }}},
  {{{ 0, 0, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}},
 {{{{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}},
  {{{ 0, 1, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}};
</code>```

Those nested brackets can be somewhat confusing -- does anyone have a better idea for how I can keep a pretty looking table in my code?

Thanks!

Edit based on HUAGHAGUAH's answer:

Using an amalgamation of everyone's input (thanks -- I wish I could "accept" 3 or 4 of these answers), I think I'm going to try it as a two dimensional array. I'll index into my array using a small bit-shifting macro:

```<code>#define SM_INPUTS( in0, in1, in2, in3 ) ((in0 << 0) | (in1 << 1) | (in2 << 2) | (in3 << 3))
</code>```

And that will let my truth table array look like this:

```<code>static u8 decisionTable[][] = {
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 }};
</code>```

And I can then access my truth table like so:

```<code>decisionTable[ SM_INPUTS( line1, line2, line3, line4 ) ]
</code>```

I'll give that a shot and see how it works out. I'll also be replacing the 0's and 1's with more helpful #defines that express what each state means, along with /**/ comments that explain the inputs for each line of outputs. Thanks for the help, everyone!

答: I don't see any reference to the current state in order to get your output state.  This means it is not a state machine, but only a truth table.  There are four inputs, so there are only 16 possible input combinations.  So, a table with 16 positions ought to do it.</p>

OwnerDisplayName: HanClinto

ContentLicense: CC BY-SA 2.5

Body:
I have a (somewhat) large truth table / state machine that I need to implement in my code (embedded C). I anticipate the behavior specification of this state machine to change in the future, and so I'd like to keep this easily modifiable in the future.

My truth table has 4 inputs and 4 outputs. I have it all in an Excel spreadsheet, and if I could just paste that into my code with a little formatting, that would be ideal.

I was thinking I would like to access my truth table like so:

u8 newState[] = decisionTable[input1][input2][input3][input4];

And then I could access the output values with:

setOutputPin( LINE_0, newState[0] );
setOutputPin( LINE_1, newState[1] );
setOutputPin( LINE_2, newState[2] );
setOutputPin( LINE_3, newState[3] );

But in order to get that, it looks like I would have to do a fairly confusing table like so:

static u8 decisionTable[][][][][] =
 {{{{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }},
   {{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }}},
  {{{ 0, 0, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}},
 {{{{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}},
  {{{ 0, 1, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}};

Those nested brackets can be somewhat confusing -- does anyone have a better idea for how I can keep a pretty looking table in my code?

Thanks!

Edit based on HUAGHAGUAH's answer:

Using an amalgamation of everyone's input (thanks -- I wish I could "accept" 3 or 4 of these answers), I think I'm going to try it as a two dimensional array. I'll index into my array using a small bit-shifting macro:

#define SM_INPUTS( in0, in1, in2, in3 ) ((in0 << 0) | (in1 << 1) | (in2 << 2) | (in3 << 3))

And that will let my truth table array look like this:

static u8 decisionTable[][] = {
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 }};

And I can then access my truth table like so:

decisionTable[ SM_INPUTS( line1, line2, line3, line4 ) ]

I'll give that a shot and see how it works out. I'll also be replacing the 0's and 1's with more helpful #defines that express what each state means, along with /**/ comments that explain the inputs for each line of outputs. Thanks for the help, everyone!

LastEditorDisplayName: Im safe against SQL injection

OwnerDisplayName: gbarry


问:
Import Excel with HTML Format to DataTable
I've been searching in the net with no answers
How do you import a .xls file that is made of
,,
, tags to DataTable?

答:
if the HTML is well formed you can try to load it as XML. Expanding a bit with a very simple example: </p>

```<code>        System.Xml.Linq.XDocument html = System.Xml.Linq.XDocument.Load (@"[xls doc]");
        //this will pull all the Table Headers.
        var q = from th in html.Descendants ("th") select (string)th.Value;
</code>```

Body:
if the HTML is well formed you can try to load it as XML. Expanding a bit with a very simple example:

        System.Xml.Linq.XDocument html = System.Xml.Linq.XDocument.Load (@"[xls doc]");
        //this will pull all the Table Headers.
        var q = from th in html.Descendants ("th") select (string)th.Value;


问:
react-bootstrap component Switches not working
The bootstrap switches not seems to be working. Even the documentation version not workng

```<code><Form>
  <Form.Check
    type="switch"
    id="custom-switch"
    label="Check this switch"
  />
  <Form.Check
    disabled
    type="switch"
    label="disabled switch"
    id="disabled-custom-switch"
  />
</Form>
</code>```

答:
Unfortunately documentation for the switch isn't the greatest. Nevertheless, the following should help with setting up the switch for your use.</p>

```<code>const [isSwitchOn, setIsSwitchOn] = useState(false);

const onSwitchAction = () => {
  setIsSwitchOn(!isSwitchOn);
};

...
<Form>
  <Form.Switch
    onChange={onSwitchAction}
    id="custom-switch"
    label="anything you want to put here"
    checked={isSwitchOn}
    disabled // apply if you want the switch disabled
  />
</Form>
...
</code>```

Body:
The bootstrap switches not seems to be working. Even the documentation version not workng

<Form>
  <Form.Check
    type="switch"
    id="custom-switch"
    label="Check this switch"
  />
  <Form.Check
    disabled
    type="switch"
    label="disabled switch"
    id="disabled-custom-switch"
  />
</Form>

Body:
Unfortunately documentation for the switch isn't the greatest. Nevertheless, the following should help with setting up the switch for your use.

const [isSwitchOn, setIsSwitchOn] = useState(false);

const onSwitchAction = () => {
  setIsSwitchOn(!isSwitchOn);
};

...
<Form>
  <Form.Switch
    onChange={onSwitchAction}
    id="custom-switch"
    label="anything you want to put here"
    checked={isSwitchOn}
    disabled // apply if you want the switch disabled
  />
</Form>
...


问:
Are Spring/Micronaut repository tests necessary
Hello stackoverflow community.

I had an argument at work regarding if repository tests for spring-data JPA (or the Micronaut version) are necessary at all.

This would be my setup of the application:

@Controller ➡ @Service/@Sigleton ➡ Repository<Entity>

in my service tests I'd use the @ExtendWith(SpringExtension::class) extension (Junit5)

when creating the test setup, I'd @MockBean away other systems I need to call (like REST-APIs) but @Autowire my Repository's.
When setting up my test data I'd simply save my required entities into an H2 in-memory database by using the injected repositories.

This will test my database logic and business logic as well. In case of 100% test coverage I've tested all the database calls which can happen in production.

However what I usually see in projects is that the Repository is mocked away.
To test the custom repository calls there are separate Tests to make sure the repository functions work as expected.

What are your comments on this. Do you prefer the approach without repository mocks or with and why?

答:
If you are not mocking your Repository in service junits, then it is an Integration test and not a Unit test. And it is fine if you want to keep it this way.

But if you want to write unit tests, which tests your individual layers then you should mock your Repository and write separate integration tests for Repository.


问:
Regex pattern not printing matches from text
I tested my code to make sure my pattern matches a test case test but for some reason it's not finding matches in a string of text text_to_search. Can anyone help me out here? At first I thought I fixed it because I forgot about using the .group(0) to print the full match but it's still not working.

Here is my code:

```<code>test = 'E000.1'
text_to_search = '''

237.0-237.2 is the range for the ICD-9 codes for neoplasm of uncertain behavior of\
endocrine glands and nervous system. On the hand, the ICD-9 code for Type II Diabetes\
with other manifestations is 250.8x where x is 0 or 2 depending on controlled or\
uncontrolled.

'''
pattern = re.compile(r'^(V\d{2}(\.\w{1,3})?|\d{3}(\.\w{1,2})?|E\d{3}(\.\w{1,2})?)-?(V\d{2}(\.\w{1,3})?|\d{3}(\.\w{1,2})?|E\d{3}(\.\w{1,2})?)?$')

matches = pattern.finditer(text_to_search)

for match in matches:
    print(matches.group(0))
</code>```

答:
You have anchors in your regular expression ^...$ which assert that the match needs to be the entirety of the string (from its beginning to its end). The entirety of the string is obviously not a match candidate (and you know it, or you wouldn't be trying to find multiple matches with finditer).

Remove those anchors.

```<code>pattern = re.compile(r'(V\d{2}(\.\w{1,3})?|\d{3}(\.\w{1,2})?|E\d{3}(\.\w{1,2})?)-?(V\d{2}(\.\w{1,3})?|\d{3}(\.\w{1,2})?|E\d{3}(\.\w{1,2})?)?')
</code>```

Body:
I tested my code to make sure my pattern matches a test case test but for some reason it's not finding matches in a string of text text_to_search. Can anyone help me out here? At first I thought I fixed it because I forgot about using the .group(0) to print the full match but it's still not working.

Here is my code:

test = 'E000.1'
text_to_search = '''

237.0-237.2 is the range for the ICD-9 codes for neoplasm of uncertain behavior of\
endocrine glands and nervous system. On the hand, the ICD-9 code for Type II Diabetes\
with other manifestations is 250.8x where x is 0 or 2 depending on controlled or\
uncontrolled.

'''
pattern = re.compile(r'^(V\d{2}(\.\w{1,3})?|\d{3}(\.\w{1,2})?|E\d{3}(\.\w{1,2})?)-?(V\d{2}(\.\w{1,3})?|\d{3}(\.\w{1,2})?|E\d{3}(\.\w{1,2})?)?$')

matches = pattern.finditer(text_to_search)

for match in matches:
    print(matches.group(0))

Body:
You have anchors in your regular expression ^...$ which assert that the match needs to be the entirety of the string (from its beginning to its end). The entirety of the string is obviously not a match candidate (and you know it, or you wouldn't be trying to find multiple matches with finditer).

Remove those anchors.

pattern = re.compile(r'(V\d{2}(\.\w{1,3})?|\d{3}(\.\w{1,2})?|E\d{3}(\.\w{1,2})?)-?(V\d{2}(\.\w{1,3})?|\d{3}(\.\w{1,2})?|E\d{3}(\.\w{1,2})?)?')


问:
creating slideshow in java swing
I am trying to create a slideshow with Java Swing.
I began with implementing a class PicturePanel

```<code>public class PicturePanel extends JPanel {

private int counter = 0;
private ImageIcon[] images = new ImageIcon[10];
private JLabel label;

public PicturePanel()
{

for(int i = 0 ; i <images.length;i++)
{
images[counter] = new ImageIcon("check.png");
label = new JLabel();
add(label);
Timer timer = new Timer(100, new TimerListener());
}

}

private class TimerListener implements ActionListener {

    public TimerListener() {
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        counter++;
        //counter% =images.length;
        label.setIcon(images[counter]);

    }
}
}
</code>```

Then I am calling this class in my Jframe through this code :

```<code>panProfil= new PicturePanel();
</code>```

panProfil is a Jpanel in my form

When I run my project, I don't get any errors, but there is nothing in my form. Can someone point me in the right direction?

答:
```<code>public class Project2 {
    int c=0;
    public static void main(String arg[]) throws InterruptedException {
        JFrame login = new JFrame("Login");
        // creating a new frame
        login.setSize(700, 500);
        JPanel addPanel = new JPanel();
        JLabel pic = new JLabel();

        Project2 p2= new Project2();

        String[] list = {"C:\\Users\\divyatapadia\\Desktop\\pic1.jpg", "C:\\Users\\divyatapadia\\Desktop\\benefit.PNG" , "C:\\Users\\divyatapadia\\Desktop\\pic2.jpg"};
        pic.setBounds(40, 30, 500, 300);
        JButton log = new JButton("SHOW");ImageIcon[] img  = new ImageIcon[3];
        for(int time = 0;time<3;time++) {
            img[time]= new ImageIcon(list[time]);
            }
        addPanel.add(pic);
        addPanel.add(log);
        login.add(addPanel);
        login.setVisible(true);
        try {
            log.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                        Timer t  ;
                     t= new Timer(1000,new ActionListener() {

                            @Override
                            public void actionPerformed(ActionEvent e) {
                                if(p2.c<3) {

                                    pic.setIcon(img[p2.c]);
                                    p2.c++;
                                    }}

                            });
                     t.start();
                 }
}
);

}catch(Exception ex)
 {
            System.out.println(ex.toString());

}

    }
}
</code>```

Title: creating slideshow in java swing

Body:
I am trying to create a slideshow with Java Swing.
I began with implementing a class PicturePanel

public class PicturePanel extends JPanel {

private int counter = 0;
private ImageIcon[] images = new ImageIcon[10];
private JLabel label;

public PicturePanel()
{

for(int i = 0 ; i <images.length;i++)
{
images[counter] = new ImageIcon("check.png");
label = new JLabel();
add(label);
Timer timer = new Timer(100, new TimerListener());
}

}

private class TimerListener implements ActionListener {

    public TimerListener() {
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        counter++;
        //counter% =images.length;
        label.setIcon(images[counter]);

    }
}
}

Then I am calling this class in my Jframe through this code :

panProfil= new PicturePanel();

panProfil is a Jpanel in my form

When I run my project, I don't get any errors, but there is nothing in my form. Can someone point me in the right direction?


问:
I dont' know how to install libXtst.so.6 library required for my application deployed on heroku
I have made a spring-boot app printing some created files in Microsoft Word. Locally it works fine. However when i try to print them via an app deployed on heroku such a problem occurs:

There was an unexpected error (type=Internal Server Error,
  status=500). /app/.jdk/jre/lib/amd64/libawt_xawt.so: libXtst.so.6:
  cannot open shared object file: No such file or directory

From what i looked up in google i believe i should install somewhere libxrender1:i386 libxtst6:i386 libxi6:i386. I just don't know where to find it and where exactly should i put it. I would be really happy if someone could help me sort this out.

答:
From what i looked up in google i believe i should install somewhere libxrender1:i386 libxtst6:i386 libxi6:i386.

That is incorrect: the reference to the libXtst.so.6 comes from .../jre/lib/amd64/libawt_xawt.so, so you need a 64-bit version of libXtst.so.6, not a 32-bit one.

I just don't know where to find it and where exactly should i put it.

The answer is: use package manager that comes with your system (you didn't tell us what OS you are running).

This could be sudo apt install libxtst6 (Ubuntu / Debian), or sudo yum install libXtst (CentOS or RedHat or Fedora), or something else.


问:
lmer function in R-understading the formula structure in lmer4
I am a novice. I wonder, like the formula

```<code>lmer(extro~1+open+social, data)
</code>```

or

```<code>lmer(extro~open+social+(1+agree|school),data)
</code>```

or

```<code>glm(extro ~ open + agree + social + school*class - 1, data)
</code>```

what is the meaning of 1 playing as the predictor variable?

答:
1 indicates an intercept. By default, intercepts are always present, so 1 + doesn't actually add anything, but it can make it explicit that an intercept is being estimated, which can be useful for clarity. - 1 signals that an intercept should not be estimated. Another way to do this is 0 +.

In lmer(), when including random effects, including 1 is sometimes necessary but always useful. (1|school) means you want to estimate a random intercept that varies by school. (1 + open|school) means you want to estimate a random intercept and a random slope for open. Another way to write this is (open|school) because the intercept is implicit. This is bad practice because it's ambiguous whether a random intercept is being requested, whereas when including 1 + it is explicit. It's possible to estimate models with a fixed intercept but a random slope; to do this, you could include (open - 1|school).

Body:
I am a novice. I wonder, like the formula

lmer(extro~1+open+social, data)

or

lmer(extro~open+social+(1+agree|school),data)

or

glm(extro ~ open + agree + social + school*class - 1, data)

what is the meaning of 1 playing as the predictor variable?


问:
What is pipe() function in Angular
Pipes are filters for transforming data (formats) in the template.

I came across the pipe() function as below. What does this pipe() function exactly mean in this case?

```<code>return this.http.get<Hero>(url)
  .pipe(
    tap(_ => this.log(`fetched hero id=${id}`)),
    catchError(this.handleError<Hero>(`getHero id=${id}`))
);
</code>```

答:
Two very different types of Pipes Angular - Pipes and RxJS - Pipes

Angular-Pipe

A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-hero-birthday',
  template: `<p>The hero's birthday is {{ birthday | date }}</p>`
})
export class HeroBirthdayComponent {
  birthday = new Date(1988, 3, 15); // April 15, 1988
}
</code>```

RxJS - Pipe

Observable operators are composed using a pipe method known as Pipeable Operators. Here is an example.

```<code>import {Observable, range} from 'rxjs';
import {map, filter} from 'rxjs/operators';

const source$: Observable<number> = range(0, 10);

source$.pipe(
    map(x => x * 2),
    filter(x => x % 3 === 0)
).subscribe(x => console.log(x));
</code>```

The output for this in the console would be the following:

0

6

12

18

For any variable holding an observable, we can use the .pipe() method to pass in one or multiple operator functions that can work on and transform each item in the observable collection.

So this example takes each number in the range of 0 to 10, and multiplies it by 2. Then, the filter function to filter the result down to only the odd numbers.

Title: What is pipe() function in Angular

Body:
Pipes are filters for transforming data (formats) in the template.

I came across the pipe() function as below. What does this pipe() function exactly mean in this case?

return this.http.get<Hero>(url)
  .pipe(
    tap(_ => this.log(`fetched hero id=${id}`)),
    catchError(this.handleError<Hero>(`getHero id=${id}`))
);

Body:
Two very different types of Pipes Angular - Pipes and RxJS - Pipes

Angular-Pipe

A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.

import { Component } from '@angular/core';

@Component({
  selector: 'app-hero-birthday',
  template: `<p>The hero's birthday is {{ birthday | date }}</p>`
})
export class HeroBirthdayComponent {
  birthday = new Date(1988, 3, 15); // April 15, 1988
}

RxJS - Pipe

Observable operators are composed using a pipe method known as Pipeable Operators. Here is an example.

import {Observable, range} from 'rxjs';
import {map, filter} from 'rxjs/operators';

const source$: Observable<number> = range(0, 10);

source$.pipe(
    map(x => x * 2),
    filter(x => x % 3 === 0)
).subscribe(x => console.log(x));

The output for this in the console would be the following:

0

6

12

18

For any variable holding an observable, we can use the .pipe() method to pass in one or multiple operator functions that can work on and transform each item in the observable collection.

So this example takes each number in the range of 0 to 10, and multiplies it by 2. Then, the filter function to filter the result down to only the odd numbers.


问:
Define different value per profile for same Maven property
I'm facing a problem with maven property per profiles. I have two profiles, each one has the same property 'prop.key' with different values. When I call mvn clean package -PA -PB or mvn clean package -PB -PA both are using the same value 'B-1.0-SNAPSHOT'. I'm using maven 3.0.4.

Below my POM :

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.test.module</groupId>
    <artifactId>test-module</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <properties>
        <prop.key>UNKNOWN</prop.key>
    </properties>

    <profiles>
        <profile>
            <id>A</id>
            <properties>
                <prop.key>A-${project.version}</prop.key>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <version>1.2</version>
                        <executions>
                            <execution>
                                <id>A</id>
                                <phase>package</phase>
                                <configuration>
                                    <tasks name="a" description="a-desc">
                                        <echo message="RUN A = ${prop.key}" level="info"/>
                                    </tasks>
                                </configuration>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <profile>
            <id>B</id>
            <properties>
                <prop.key>B-${project.version}</prop.key>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <version>1.2</version>
                        <executions>
                            <execution>
                                <id>B</id>
                                <phase>package</phase>
                                <configuration>
                                    <tasks name="b" description="b-desc">
                                        <echo message="RUN B = ${prop.key}" level="info"/>
                                    </tasks>
                                </configuration>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>
</code>```

I have found 'similar topic' but with opposite result!
Is it a bug or a feature of maven?

答: When you run mvn package -PA,B, maven will read both profiles A and B, and the properties from later one in the pom.xml file will take precedence (B is defined below A in pom.xml), result in <prop.key>B-${project.version}</prop.key> will be used.

Body:
I'm facing a problem with maven property per profiles. I have two profiles, each one has the same property 'prop.key' with different values. When I call mvn clean package -PA -PB or mvn clean package -PB -PA both are using the same value 'B-1.0-SNAPSHOT'. I'm using maven 3.0.4.

Below my POM :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.test.module</groupId>
    <artifactId>test-module</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <properties>
        <prop.key>UNKNOWN</prop.key>
    </properties>

    <profiles>
        <profile>
            <id>A</id>
            <properties>
                <prop.key>A-${project.version}</prop.key>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <version>1.2</version>
                        <executions>
                            <execution>
                                <id>A</id>
                                <phase>package</phase>
                                <configuration>
                                    <tasks name="a" description="a-desc">
                                        <echo message="RUN A = ${prop.key}" level="info"/>
                                    </tasks>
                                </configuration>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <profile>
            <id>B</id>
            <properties>
                <prop.key>B-${project.version}</prop.key>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <version>1.2</version>
                        <executions>
                            <execution>
                                <id>B</id>
                                <phase>package</phase>
                                <configuration>
                                    <tasks name="b" description="b-desc">
                                        <echo message="RUN B = ${prop.key}" level="info"/>
                                    </tasks>
                                </configuration>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

I have found 'similar topic' but with opposite result!
Is it a bug or a feature of maven?


问:
How to split time into 10 min interval and make it as a separate column using Python
I am working on a data set that has epoch time. I want to create a new column which splits the time into 10 mins time interval.

Suppose
timestamp       timeblocks
5:00            1
5:02            1
5:11            2

How can i achieve this using python.
I tried resampling but i cannot able further process.

答:
I agree with the comments, you need to provide more.  After guessing what you're looking for, you may want histograms where intervals are known as bins.  You wrote "10 mins time interval" but your example doesn't show 10 mins.

Python's Numpy and matplotlib have histograms for epochs.

Here's an SO answer on histogram for epoch time.


问:
Get notified when a process quits
I have developed an OSX daemon application, written in Qt (C++) and Objective-C. I monitor when other applications and processes are launched, with the use of a kernel extension, but need to know when they are terminated.

Is there any way to receive a notification of the termination of other processes, without having to constantly poll the target process's pid or mach task?

答:
The following example takes a UNIX process ID as argument, and watches up to 20 seconds, and reports if the process terminates in that time

```<code>// cc test.c -framework CoreFoundation -O
#include <CoreFoundation/CoreFoundation.h>
#include <unistd.h>
#include <sys/event.h>
static void noteProcDeath(CFFileDescriptorRef fdref, CFOptionFlags callBackTypes, void *info) {
    struct kevent kev;
    int fd = CFFileDescriptorGetNativeDescriptor(fdref);
    kevent(fd, NULL, 0, &kev, 1, NULL);
    // take action on death of process here
    printf("process with pid '%u' died\n", (unsigned int)kev.ident);
    CFFileDescriptorInvalidate(fdref);
    CFRelease(fdref); // the CFFileDescriptorRef is no longer of any use in this example
}
// one argument, an integer pid to watch, required
int main(int argc, char *argv[]) {
    if (argc < 2) exit(1);
    int fd = kqueue();
    struct kevent kev;
    EV_SET(&kev, atoi(argv[1]), EVFILT_PROC, EV_ADD|EV_ENABLE, NOTE_EXIT, 0, NULL);
    kevent(fd, &kev, 1, NULL, 0, NULL);
    CFFileDescriptorRef fdref = CFFileDescriptorCreate(kCFAllocatorDefault, fd, true, noteProcDeath, NULL);
    CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack);
    CFRunLoopSourceRef source = CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, fdref, 0);
    CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopDefaultMode);
    CFRelease(source);
    // run the run loop for 20 seconds
    CFRunLoopRunInMode(kCFRunLoopDefaultMode, 20.0, false);
    return 0;
}
</code>```

For those who barely know C:

build: cc test.c -framework CoreFoundation -O

run: ./a.out 57168

57168 is the pid of the process being monitored. Kill it to test!

Surely you can increase the 20 seconds to make it last as long as you want.

Title: Get notified when a process quits

Body:
The following example takes a UNIX process ID as argument, and watches up to 20 seconds, and reports if the process terminates in that time

// cc test.c -framework CoreFoundation -O
#include <CoreFoundation/CoreFoundation.h>
#include <unistd.h>
#include <sys/event.h>
static void noteProcDeath(CFFileDescriptorRef fdref, CFOptionFlags callBackTypes, void *info) {
    struct kevent kev;
    int fd = CFFileDescriptorGetNativeDescriptor(fdref);
    kevent(fd, NULL, 0, &kev, 1, NULL);
    // take action on death of process here
    printf("process with pid '%u' died\n", (unsigned int)kev.ident);
    CFFileDescriptorInvalidate(fdref);
    CFRelease(fdref); // the CFFileDescriptorRef is no longer of any use in this example
}
// one argument, an integer pid to watch, required
int main(int argc, char *argv[]) {
    if (argc < 2) exit(1);
    int fd = kqueue();
    struct kevent kev;
    EV_SET(&kev, atoi(argv[1]), EVFILT_PROC, EV_ADD|EV_ENABLE, NOTE_EXIT, 0, NULL);
    kevent(fd, &kev, 1, NULL, 0, NULL);
    CFFileDescriptorRef fdref = CFFileDescriptorCreate(kCFAllocatorDefault, fd, true, noteProcDeath, NULL);
    CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack);
    CFRunLoopSourceRef source = CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, fdref, 0);
    CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopDefaultMode);
    CFRelease(source);
    // run the run loop for 20 seconds
    CFRunLoopRunInMode(kCFRunLoopDefaultMode, 20.0, false);
    return 0;
}

For those who barely know C:

build: cc test.c -framework CoreFoundation -O

run: ./a.out 57168

57168 is the pid of the process being monitored. Kill it to test!

Surely you can increase the 20 seconds to make it last as long as you want.


问:
spring boot 2.x console log does not print mapped controller info
I can access the controller in web browser, but I can't see its mapping message in the console log. Normally when spring boot app starts, the eclipse console should print out the mapped controller and the accessing url, why didn't I see it?

I have already added the logging.level.org.springframework.web=DEBUG to application.properties file, but it does not help.

Updated:
This is my pom.xml file:

```<code><modelVersion>4.0.0</modelVersion>

<groupId>com.yp</groupId>
<artifactId>BootTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>BootTest</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

The snippet of console log when app starts

Is there any way to show up mapped controller info when app starts?

答:
If only want to see controller mapping log. Try to set TRACE to RequestMappingHandlerMapping to prevent too much log.

```<code>logging.level.org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping=TRACE
</code>```

# spring boot 2.2.4

Body:
I can access the controller in web browser, but I can't see its mapping message in the console log. Normally when spring boot app starts, the eclipse console should print out the mapped controller and the accessing url, why didn't I see it?

I have already added the logging.level.org.springframework.web=DEBUG to application.properties file, but it does not help.

Updated:
This is my pom.xml file:

<modelVersion>4.0.0</modelVersion>

<groupId>com.yp</groupId>
<artifactId>BootTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>BootTest</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

The snippet of console log when app starts

Is there any way to show up mapped controller info when app starts?

Body:
If only want to see controller mapping log. Try to set TRACE to RequestMappingHandlerMapping to prevent too much log.

logging.level.org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping=TRACE

# spring boot 2.2.4


问:
Flutter : Boolean value in Checkbox doesn't change
I want to build a checkbox list which increase when i press a add button.
But checkbox isn't working, so i print boolean value of onChanged in checkbox and value of checkbox, i found both are same except first press(checkbox still not working). I changed value of checkbox to 'true', but result was same. Please help me to make a right code.I have copied all of my code please check addList function.</p>

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

void main() => runApp(FirstPage());

class FirstPage extends StatefulWidget {
  @override
  _FirstPageState createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {
  List<bool> listBool = [];
  List<Widget> listWidget = [];

  void addList(Text text) {
    int listLength = listWidget.length;
    listBool.add(false);

    listWidget.add(
      Row(
        children: <Widget>[
          Checkbox(
              value: listBool[listLength],
              onChanged: (bool newValue) {
                setState(() {
                  print(newValue);
                  print(listBool[listLength]);
                  listBool[listLength] = newValue;
                });
              }),
          text,
        ],
      ),
    );
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('toDoList'),
          backgroundColor: Colors.teal,
        ),
        body: SafeArea(
          child: Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Container(
                    height: 100,
                    width: 100,
                    color: Colors.red,
                  ),
                  Container(
                    width: 100,
                    height: 100,
                    color: Colors.blue,
                  ),
                ],
              ),
              Expanded(
                  child: ListView.builder(
                      itemCount: listWidget.length,
                      itemBuilder: (BuildContext ctxt, int index) {
                        return listWidget[index];
                      })),
              FloatingActionButton(
                child: Icon(Icons.add),
                onPressed: () => addList(Text('shopping')),
              )
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

答:
Please check below code and check output</p>

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

class FirstPage extends StatefulWidget {
  @override
  _FirstPageState createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {
  List<bool> listBool = [];
  List<Widget> listWidget = [];

  void addList() {
    setState(() {
      listBool.add(false);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('toDoList'),
          backgroundColor: Colors.teal,
        ),
        body: SafeArea(
          child: Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Container(
                    height: 100,
                    width: 100,
                    color: Colors.red,
                  ),
                  Container(
                    width: 100,
                    height: 100,
                    color: Colors.blue,
                  ),
                ],
              ),
              Expanded(
                  child: ListView.builder(
                      itemCount: listBool.length,
                      itemBuilder: (BuildContext ctxt, int index) {
                        return Row(
                          children: <Widget>[
                            Checkbox(
                                value: listBool[index],
                                onChanged: (bool newValue) {
                                  setState(() {
                                    print(newValue);
                                    print(listBool[index]);
                                    listBool[index] = newValue;
                                  });
                                }),
                            Text('shopping'),
                          ],
                        );
                      })),
              FloatingActionButton(
                child: Icon(Icons.add),
                onPressed: () => addList(),
              )
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

Body:
I want to build a checkbox list which increase when i press a add button.
But checkbox isn't working, so i print boolean value of onChanged in checkbox and value of checkbox, i found both are same except first press(checkbox still not working). I changed value of checkbox to 'true', but result was same. Please help me to make a right code.I have copied all of my code please check addList function.

import 'package:flutter/material.dart';

void main() => runApp(FirstPage());

class FirstPage extends StatefulWidget {
  @override
  _FirstPageState createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {
  List<bool> listBool = [];
  List<Widget> listWidget = [];

  void addList(Text text) {
    int listLength = listWidget.length;
    listBool.add(false);

    listWidget.add(
      Row(
        children: <Widget>[
          Checkbox(
              value: listBool[listLength],
              onChanged: (bool newValue) {
                setState(() {
                  print(newValue);
                  print(listBool[listLength]);
                  listBool[listLength] = newValue;
                });
              }),
          text,
        ],
      ),
    );
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('toDoList'),
          backgroundColor: Colors.teal,
        ),
        body: SafeArea(
          child: Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Container(
                    height: 100,
                    width: 100,
                    color: Colors.red,
                  ),
                  Container(
                    width: 100,
                    height: 100,
                    color: Colors.blue,
                  ),
                ],
              ),
              Expanded(
                  child: ListView.builder(
                      itemCount: listWidget.length,
                      itemBuilder: (BuildContext ctxt, int index) {
                        return listWidget[index];
                      })),
              FloatingActionButton(
                child: Icon(Icons.add),
                onPressed: () => addList(Text('shopping')),
              )
            ],
          ),
        ),
      ),
    );
  }
}

Body:
Please check below code and check output

import 'package:flutter/material.dart';

class FirstPage extends StatefulWidget {
  @override
  _FirstPageState createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {
  List<bool> listBool = [];
  List<Widget> listWidget = [];

  void addList() {
    setState(() {
      listBool.add(false);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('toDoList'),
          backgroundColor: Colors.teal,
        ),
        body: SafeArea(
          child: Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Container(
                    height: 100,
                    width: 100,
                    color: Colors.red,
                  ),
                  Container(
                    width: 100,
                    height: 100,
                    color: Colors.blue,
                  ),
                ],
              ),
              Expanded(
                  child: ListView.builder(
                      itemCount: listBool.length,
                      itemBuilder: (BuildContext ctxt, int index) {
                        return Row(
                          children: <Widget>[
                            Checkbox(
                                value: listBool[index],
                                onChanged: (bool newValue) {
                                  setState(() {
                                    print(newValue);
                                    print(listBool[index]);
                                    listBool[index] = newValue;
                                  });
                                }),
                            Text('shopping'),
                          ],
                        );
                      })),
              FloatingActionButton(
                child: Icon(Icons.add),
                onPressed: () => addList(),
              )
            ],
          ),
        ),
      ),
    );
  }
}


问:
Javascript object creation best practice
I have the following javascript :

```<code>            var MyObject = (function() {

                function Setup(args) {
                    this.prop1 = args.x;
                    this.prop2 = args.y
                    this.prop3 = this.prop1 + this.prop2;

                    this.Create = function() {
                        return 'a' + helperFunc();
                    }

                    function helperFunc() {
                        return this.prop3;
                    }
                }

                return {
                    init : function(args) {
                        var setup = new Setup(args);

                        setup.Create();
                    }
                }

            })();

            $(function() {

                MyObject.init(someArgs);

            });
</code>```

Is my approach to object construction a good practice?

I am getting undefined in the helperFunc when trying to access this.prop3.

I have also tried to assign this.prop1 + this.prop2 to a local variable and use a function to return this value like so:

```<code>        function Setup(args) {
                var total;

                this.prop1 = args.x;
                this.prop2 = args.y

                total = this.prop1 + this.prop2;
                this.getTotal = function() {
                        return total;
                };

                this.prop3 = this.prop1 + this.prop2;
                ...
</code>```

...and when calling this in the helperFunc like this:

```<code>                       return this.getTotal();
</code>```

.. i get this.getTotal is not a function

I have been reading around object creation and using closures to mimic private members and so on and since there is no one way to define objects I am getting confused.

TBH - I don't really understand the construct:

```<code>                       var myObject = (function() { ... } ();
</code>```

I've seen it used a lot in jQuery plugins but what does the first parenth followed by empty parenth at the end mean and do?

Any knowledge imparted would be much appreciated.

Also, I have on order the Douglas Crockford book on javascript and until it arrives I need to try to solve this problem

答:
If you have a function that uses this, you must make sure that the calling context is correct.  i.e. use this.helperFunc(), not just helperFunc() (but you'll also need to set things up so that this.helperFunc is defined).  The referent of this inside helperFunc in your example is not the same as it is in Create().

You can think of it as though functions are not defined as members of objects, but called as members of objects.

There are three things that this might resolve to, depending on context.

A newly created object, if the function call was preceded by the new keyword.

The Object to the left of the dot when the function was called.

The Global Object (window), if neither of the above are provided.

If a function is called without an object, as in the case of your call to helperFunc in this.Create, this will be bound to the global object (window, when used in a browser)

Given something like this:

```<code>var o = {someVal:"hello"};
o.doSomething = function (){alert(this.someVal)};
</code>```

Calling o.doSomething() will obviously alert "hello".

Given:

```<code>var o2  = {someVal:"world"};
o2.someFunc = o.doSomething;
</code>```

Calling o2.someFunc() will alert "world", not "hello", as you would expect if it were a pointer to the doSomething member of o.

And given:

```<code>var someFunc = o.doSomething
someVal = "sailor"
</code>```

Calling someFunc() will alert "sailor".

Another point of confusion is the use of this directly within Setup().  When you call a function using new, as you have done, this is not bound to the global object, but to a new instance of the Setup object.

For my example above, this means that calling new o.doSomething() will alert "undefined", as the new object that has been created for the call does not have a "someVal" member.

Body:
I have the following javascript :

            var MyObject = (function() {

                function Setup(args) {
                    this.prop1 = args.x;
                    this.prop2 = args.y
                    this.prop3 = this.prop1 + this.prop2;

                    this.Create = function() {
                        return 'a' + helperFunc();
                    }

                    function helperFunc() {
                        return this.prop3;
                    }
                }

                return {
                    init : function(args) {
                        var setup = new Setup(args);

                        setup.Create();
                    }
                }

            })();

            $(function() {

                MyObject.init(someArgs);

            });

Is my approach to object construction a good practice?

I am getting undefined in the helperFunc when trying to access this.prop3.

I have also tried to assign this.prop1 + this.prop2 to a local variable and use a function to return this value like so:

        function Setup(args) {
                var total;

                this.prop1 = args.x;
                this.prop2 = args.y

                total = this.prop1 + this.prop2;
                this.getTotal = function() {
                        return total;
                };

                this.prop3 = this.prop1 + this.prop2;
                ...

...and when calling this in the helperFunc like this:

                       return this.getTotal();

.. i get this.getTotal is not a function

I have been reading around object creation and using closures to mimic private members and so on and since there is no one way to define objects I am getting confused.

TBH - I don't really understand the construct:

                       var myObject = (function() { ... } ();

I've seen it used a lot in jQuery plugins but what does the first parenth followed by empty parenth at the end mean and do?

Any knowledge imparted would be much appreciated.

Also, I have on order the Douglas Crockford book on javascript and until it arrives I need to try to solve this problem

Body:
If you have a function that uses this, you must make sure that the calling context is correct.  i.e. use this.helperFunc(), not just helperFunc() (but you'll also need to set things up so that this.helperFunc is defined).  The referent of this inside helperFunc in your example is not the same as it is in Create().

You can think of it as though functions are not defined as members of objects, but called as members of objects.

There are three things that this might resolve to, depending on context.

A newly created object, if the function call was preceded by the new keyword.

The Object to the left of the dot when the function was called.

The Global Object (window), if neither of the above are provided.

If a function is called without an object, as in the case of your call to helperFunc in this.Create, this will be bound to the global object (window, when used in a browser)

Given something like this:

var o = {someVal:"hello"};
o.doSomething = function (){alert(this.someVal)};

Calling o.doSomething() will obviously alert "hello".

Given:

var o2  = {someVal:"world"};
o2.someFunc = o.doSomething;

Calling o2.someFunc() will alert "world", not "hello", as you would expect if it were a pointer to the doSomething member of o.

And given:

var someFunc = o.doSomething
someVal = "sailor"

Calling someFunc() will alert "sailor".

Another point of confusion is the use of this directly within Setup().  When you call a function using new, as you have done, this is not bound to the global object, but to a new instance of the Setup object.

For my example above, this means that calling new o.doSomething() will alert "undefined", as the new object that has been created for the call does not have a "someVal" member.


问:
jQuery not firing when clicking item in drop down menu
I'm updating the UI of my project that has two download buttons for PDF and CSV. I'm trying to put them now in a drop down menu to save some space and a cleaner UI. My problem now is, the jQuery are not working anymore after putting them in drop-down menu. Here's what I have:

```<code><div class="col-sm-8">
    <div class="btn-group float-right">
        <button type="button" class="btn btn-success" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-download"></i>Download
            <div class="dropdown-menu" role="menu" x-placement="top-start" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(-1px, -3px, 0px);">
                <a type="button" href="#" data-href="{{route('csv')}}"
                    class="dropdown-item download-csv">CSV</a>
                <div class="dropdown-divider"></div>
                <a type="button" href="#" data-href="{{ route('pdf') }}"
                    class="dropdown-item download-pdf">PDF</a>
            </div>
        </button>
    </div>
</div>
</code>```

js

```<code>$(document).on('click','.download-csv', function(){
    console.log('just here');
});
</code>```

BUTTON ONLY

```<code><div class="col-sm-4">
    <a type="button" href="#" data-href="{{route('csv')}}"
        class="btn btn-block btn-secondary btn-download custom-font-button download-csv"><i class="fa fa-download"></i>@lang('guest.csv')</a>
</div>
</code>```

It's as the same as before codes, but when I'm just using buttons, it's working well. What could be the possible cause for this one?

答:
First up type is not used like that on an a tag. If used it should provide info about the mime type. Just get rid of it.

Next, you can't have interactive content within a <button> element so you need to fix that.

Finally  has an inherent action, navigation, you need to stop that.

I'd go with something like:

$(document).on('click','.download-csv, .download-pdf', function(event){
    //Stop navigation
    event.preventDefault();
    //Get target location from href
    let location = this.href;
    console.log(`Do something with: ${location}"`);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-8">
    <div class="btn-group float-right">
        <button type="button" class="btn btn-success" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-download"></i>Download</button>
            <div class="dropdown-menu" role="menu" x-placement="top-start" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(-1px, -3px, 0px);">
                CSV
                <div class="dropdown-divider"></div>
                 href="{{ route('pdf') }}"
                    class="dropdown-item download-pdf">PDF
            </div>
    </div>
</div></code>```

Body:
I'm updating the UI of my project that has two download buttons for PDF and CSV. I'm trying to put them now in a drop down menu to save some space and a cleaner UI. My problem now is, the jQuery are not working anymore after putting them in drop-down menu. Here's what I have:

        <button type="button" class="btn btn-success" data-toggle="dropdown" aria-expanded="false">Download

                CSV

                PDF

        </button>

js

$(document).on('click','.download-csv', function(){
    console.log('just here');
});

BUTTON ONLY

    @lang('guest.csv')

It's as the same as before codes, but when I'm just using buttons, it's working well. What could be the possible cause for this one?

Body:
First up type is not used like that on an a tag. If used it should provide info about the mime type. Just get rid of it.

Next, you can't have interactive content within a <button> element so you need to fix that.

Finally <a href="#"> has an inherent action, navigation, you need to stop that.

I'd go with something like:

$(document).on('click','.download-csv, .download-pdf', function(event){
    //Stop navigation
    event.preventDefault();
    //Get target location from href
    let location = this.href;
    console.log(`Do something with: ${location}"`);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-8">
    <div class="btn-group float-right">
        <button type="button" class="btn btn-success" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-download"></i>Download</button>
            <div class="dropdown-menu" role="menu" x-placement="top-start" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(-1px, -3px, 0px);">
                <a href="{{route('csv')}}"
                    class="dropdown-item download-csv">CSV</a>
                <div class="dropdown-divider"></div>
                <a  href="{{ route('pdf') }}"
                    class="dropdown-item download-pdf">PDF</a>
            </div>
    </div>
</div>