问:
Adding a primary key with an "insert into" statement
I have the following query and need to add a Primary Key to the Column of Employeenumber:

```<code>SELECT [Exceptions].Employeenumber,[Exceptions].exceptiondate, [Exceptions].starttime, [exceptions].endtime, [Exceptions].code, datediff(minute, starttime, endtime)  as minutes INTO scratchpad3,
FROM Employees INNER JOIN Exceptions ON [Exceptions].EmployeeNumber = [Exceptions].Employeenumber
where [Exceptions].exceptiondate between '5/1/2011' and '5/8/2011'
GROUP BY [Exceptions].Employeenumber, [Exceptions].Exceptiondate, [Exceptions].starttime, [exceptions].endtime,
[Exceptions].code, [Exceptions].exceptiondate
</code>```

but don't know the proper syntax when you're doing a "create" this way. What's the propery syntax to add a primary key this way?

Thank you.

答:
You can't add a Primary Key to a SELECT statement. Primary Keys are identifying columns of tables. You'd need to ALTER TABLE and ADD PRIMARY KEY. The syntax is different, but it looks like you're using SQL Server. Statements can be found  Here.

If you're looking to just add a number for each record, try using ROW_NUMBER (might be different depending on the database you're using).

Hope that helps,
Jason

Body:
I have the following query and need to add a Primary Key to the Column of Employeenumber:

SELECT [Exceptions].Employeenumber,[Exceptions].exceptiondate, [Exceptions].starttime, [exceptions].endtime, [Exceptions].code, datediff(minute, starttime, endtime)  as minutes INTO scratchpad3,
FROM Employees INNER JOIN Exceptions ON [Exceptions].EmployeeNumber = [Exceptions].Employeenumber
where [Exceptions].exceptiondate between '5/1/2011' and '5/8/2011'
GROUP BY [Exceptions].Employeenumber, [Exceptions].Exceptiondate, [Exceptions].starttime, [exceptions].endtime,
[Exceptions].code, [Exceptions].exceptiondate

but don't know the proper syntax when you're doing a "create" this way. What's the propery syntax to add a primary key this way?

Thank you.


来源: stackexchange

问:
Xcode/iOS App freezing, how to track such errors
I have sometimes app freezing I do not know what is the source of problem.
It happens rarely but happens. I consider how to track such issue
I have crashlytics from firebase but there is no errors as freezing is I suppose something with threads maybe some deadlocks or infinite loops.

Is there way to track such things?
What maybe reasons of app freezing and being inactive (it is SwiftUI app) ?
Are there possibilities to track/profile apps installed on devices (not connected via Xcode) and send informations such that are available in Instrument to something like firebase console or other 3rd party tools.

Update

I think I do not indicated important fact.
It freezes UI definitely not for a few seconds but app need do be killed and restarted again.

答:
There might be some heavy process that locks your main thread, so it freezes your UI.

You track the problems, performance, leaks and more using Instruments.

There are sample topics:

Instruments Tutorial with Swift: Getting Started

How to find and fix slow code using Instruments

And WWDC videos like

Using Time Profiler in Instruments

Creating Custom Instruments

ContentLicense: CC BY-SA 4.0


问:
Reading all file contents in current directory to a vector
I want to read all the files in the current directory.

Here's my progress:

use std::fs;

fn main() {
    let files = fs::read_dir(".").unwrap();
    files
        .filter_map(Result::ok)
        .filter(|d| if let Some(e) = d.path().extension() { e == "txt" } else {false})
        .for_each(|f| println!("{:?}", f));
}
```

Here I got a little lost, how can I read all file contents? Should I add them to a growing Vec in the for_each block? if so then how?

答:
If you want a single vec with all files bytes in one you can use

```<code>let target_ext = OsString::from("txt");
let files = fs::read_dir(".").unwrap();
let file_bytes : Vec<u8> = files
    .filter_map(Result::ok)
    .map(|d| d.path())
    .filter(|path| path.extension() == Some(&target_ext))
    .flat_map(|path| fs::read(path).expect("Failed to read"))
    .collect();
</code>```

if you want a vec that contains each file's content separately, change flat_map to a map and it will return a Vec<Vec<u8>>

```<code>let file_bytes : Vec<Vec<u8>> = files
    .filter_map(Result::ok)
    .map(|d| d.path())
    .filter(|path| path.extension() == Some(&target_ext))
    .map(|path| fs::read(path).expect("Failed to read"))
    .collect();
</code>```

Body:
I want to read all the files in the current directory.

Here's my progress:

use std::fs;

fn main() {
    let files = fs::read_dir(".").unwrap();
    files
        .filter_map(Result::ok)
        .filter(|d| if let Some(e) = d.path().extension() { e == "txt" } else {false})
        .for_each(|f| println!("{:?}", f));
}

Here I got a little lost, how can I read all file contents? Should I add them to a growing Vec in the for_each block? if so then how?

Body:
If you want a single vec with all files bytes in one you can use

let target_ext = OsString::from("txt");
let files = fs::read_dir(".").unwrap();
let file_bytes : Vec<u8> = files
    .filter_map(Result::ok)
    .map(|d| d.path())
    .filter(|path| path.extension() == Some(&target_ext))
    .flat_map(|path| fs::read(path).expect("Failed to read"))
    .collect();

if you want a vec that contains each file's content separately, change flat_map to a map and it will return a Vec<Vec<u8>>

let file_bytes : Vec<Vec<u8>> = files
    .filter_map(Result::ok)
    .map(|d| d.path())
    .filter(|path| path.extension() == Some(&target_ext))
    .map(|path| fs::read(path).expect("Failed to read"))
    .collect();


问:
UIPickerView realtime update on TextField
As soon as I scroll the PickerView (or) UIDatePicker, I need the value to get displayed on a TextField :

While Scrolling. Even when the picker is moving the text field should update itself. Is it possible ?

On the event that the Picker stops moving and comes to rest. Is there an event for the PickerView to come to rest so that I could update the textField (as soon as the pickerView comes to rest).

```<code>  // I do not wish to use the TextFieldDidEndEditing
 // I want the textField to update itself when the picker view comes to rest.
</code>```

It would be helpful if anyone could solve 1) and 2)

答: For the first question, this isn't possible with the default control however there is nothing to stop you writing your own and simulate the effect using touchesMoved etc...

ContentLicense: CC BY-SA 3.0

Body:
As soon as I scroll the PickerView (or) UIDatePicker, I need the value to get displayed on a TextField :

While Scrolling. Even when the picker is moving the text field should update itself. Is it possible ?

On the event that the Picker stops moving and comes to rest. Is there an event for the PickerView to come to rest so that I could update the textField (as soon as the pickerView comes to rest).

  // I do not wish to use the TextFieldDidEndEditing
 // I want the textField to update itself when the picker view comes to rest.

It would be helpful if anyone could solve 1) and 2)


答:
```<code>self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3,
                      bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.Dropout(0.3),
            nn.Conv2d(64, 64, kernel_size=3, padding = 1
                      bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2, padding = 32),
        )
</code>```

Title: padding='same' conversion to PyTorch padding=#

Body:
I'm trying to convert the following Keras model code to pytorch, but am having problems dealing with padding='same'.

    model = Sequential()
    model.add(Conv2D(64, (3, 3), input_shape=img_size))
    model.add(BatchNormalization(axis=1))
    model.add(Activation('relu'))
    model.add(Dropout(0.3))
    model.add(Conv2D(64, (3, 3), padding='same'))
    model.add(BatchNormalization(axis=1))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))

Which produces the following summary:

Layer (type)                 Output Shape              Param #
=================================================================
conv2d_1 (Conv2D)            (None, 30, 30, 64)        1792
_________________________________________________________________
batch_normalization_1 (Batch (None, 30, 30, 64)        120
_________________________________________________________________
activation_1 (Activation)    (None, 30, 30, 64)        0
_________________________________________________________________
dropout_1 (Dropout)          (None, 30, 30, 64)        0
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 30, 30, 64)        36928
_________________________________________________________________
batch_normalization_2 (Batch (None, 30, 30, 64)        120
_________________________________________________________________
activation_2 (Activation)    (None, 30, 30, 64)        0
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 15, 15, 64)        0
=================================================================
Total params: 38,960
Trainable params: 38,840
Non-trainable params: 120

Right now, I would write:

self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3,
                      bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.Dropout(0.3),
            nn.Conv2d(64, 64, kernel_size=3, padding = ?
                      bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2, padding = ?),
        )

Where padding should have numerical value. I was wondering if there is an easier way to calculate this since we're using padding='same'.

Also, the next line of the Keras model looks like:

model.add(Conv2D(128, (3, 3), padding='same'))

So I really need to brush up on how to calculate padding, especially after stride too. From a rough eye only, is the padding 2?


问:
How to find who created a SQL Server in Azure Portal?
How to find who created a SQL Server in Azure Portal? I need to know the createdUserId of that particular SQL Server.</p>

答: You can get the information from the Activity Logs which has information about the created user and so on.</p>


问:
Which HTTP response code for "This email is already registered"?
I'm creating a RESTful API for creating users that enforces unique email addresses:

Successful POST /users: HTTP 201 Created

If I POST the same email address again, what should the response code be? Is 409 Conflict the appropriate response code?

答:
```<code>409 => Conflict
That mean.
</code>```

The request could not be completed due to a conflict.
For example,  POST ContentStore Folder API cannot complete if the given file or folder name already exists in the parent location.

Body:
409 => Conflict
That mean.

The request could not be completed due to a conflict.
For example,  POST ContentStore Folder API cannot complete if the given file or folder name already exists in the parent location.


问:
React Native build failed in android, @react-native-community/cli-platform-android /native_modules.gradle' line: 130
I've upgraded my ReactNative project from 0.59 to 0.61.2 iOS is building fine but in android i'm facing the issue in @react-native-community/cli-platform-android module.

My settings.gradle file

```<code>apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)

</code>```

My build.gradle file

```<code>apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
</code>```

I get the following error while building the app.

```<code>> Task :app:generatePackageList FAILED

FAILURE: Build failed with an exception.

* Where:
Script '/Users/yashwanth_c/Documents/projects/MobileApp/node_modules/@react-native-community/cli-platform-android
/native_modules.gradle' line: 130

* What went wrong:
Execution failed for task ':app:generatePackageList'.
> ReactNativeModules$_generatePackagesFile_closure3

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.5/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 5m 21s
4 actionable tasks: 4 executed
</code>```

As always i've cleaned the cache and deleted the node_module folder, tried many times but no luck. Also googled for more than a week but still not able to find a fix, any advice is appreciated.

答:
If your react-native app fails to install on android emulator,

try going to

```<code>gradle-wrapper.propeties
</code>```

and update

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip
</code>```

Make sure that gradle is updated to the stable and lastest version according to what it suits

Body:
I've upgraded my ReactNative project from 0.59 to 0.61.2 iOS is building fine but in android i'm facing the issue in @react-native-community/cli-platform-android module.

My settings.gradle file

apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)

My build.gradle file

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

I get the following error while building the app.

> Task :app:generatePackageList FAILED

FAILURE: Build failed with an exception.

* Where:
Script '/Users/yashwanth_c/Documents/projects/MobileApp/node_modules/@react-native-community/cli-platform-android
/native_modules.gradle' line: 130

* What went wrong:
Execution failed for task ':app:generatePackageList'.
> ReactNativeModules$_generatePackagesFile_closure3

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.5/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 5m 21s
4 actionable tasks: 4 executed

As always i've cleaned the cache and deleted the node_module folder, tried many times but no luck. Also googled for more than a week but still not able to find a fix, any advice is appreciated.

Body:
If your react-native app fails to install on android emulator,

try going to

gradle-wrapper.propeties

and update

distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip

Make sure that gradle is updated to the stable and lastest version according to what it suits


问:
Using CASE statements as a precursor for COUNT function in single (large) SQL query, syntax
I'm having trouble incorporating a bit of logic into a large SQL query. I'm using SQL Server Reporting Services 2005 with the Report Designer, and it only gives you one area to define a single SQL query to populate the report with. Hopefully someone can tell me what's wrong with my syntax so I can get it running.

I need to not only select a bunch of attributes filtering by (QuoteOrderStatus != 'Closed'), but also to only count the quotes with (ItemStatus != 'inactive') in a COUNT(DISTINCT ItemID's) statement (an aggregate function). I don't want to simply filter out the quotes with inactive items, because I still want to display the quotes with zero items. I only want to not include them in the total itemCount.

I did research and it seems the way to accomplish this type of logic is using CASE statements, but I'm having trouble incorporating them into this one obfuscated query. Report Designer simply tells me it's wrong and rearranges it to a way that I want even less. Can anyone help me with fixing this statement so it would be accepted as a valid query?

I've researched this for hours now without finding a good resource for this specific kind of problem. Sorry if the code is unclear, I tried to explain this as well as I can. Please ask questions if you want me to clarify in some way, and I appreciate any help anyone can offer.

```<code>SELECT DISTINCT
    BIAdmin.Quote.QuoteOrderSalesOffice, BIAdmin.Quote.ManufacturerQuoteNumber,
    BIAdmin.Quote.CustomerName, BIAdmin.Quote.Project_JobTitle,
    BIAdmin.Quote.EndUserName, BIAdmin.Quote.QuoteOrderStatus,
    SUM(BIAdmin.Item.TotalPriceOfItemNumber) AS totalValue, BIAdmin.Item.ItemStatus
FROM BIAdmin.Quote LEFT OUTER JOIN BIAdmin.Item ON BIAdmin.Quote.ID = BIAdmin.Item.QuoteID
WHERE   BIAdmin.Item.ItemStatus LIKE
    CASE WHEN NOT (BIAdmin.Item.ItemStatus = 'inactive') THEN
    SELECT DISTINCT COUNT(BIAdmin.Item.ID) AS itemCount
GROUP BY BIAdmin.Quote.QuoteOrderSalesOffice, BIAdmin.Quote.ManufacturerQuoteNumber,
    BIAdmin.Quote.CustomerName, BIAdmin.Quote.Project_JobTitle,
    BIAdmin.Quote.EndUserName, BIAdmin.Quote.QuoteOrderStatus, BIAdmin.Item.ItemStatus
HAVING (NOT (BIAdmin.Quote.QuoteOrderStatus = N'[Closed]'))
</code>```

答:
There is no END for your CASE statement, and your last SELECT is not valid in that context. Try something like this:</p>

```<code>SELECT BIAdmin.Quote.QuoteOrderSalesOffice, BIAdmin.Quote.ManufacturerQuoteNumber,
    BIAdmin.Quote.CustomerName, BIAdmin.Quote.Project_JobTitle,
    BIAdmin.Quote.EndUserName, BIAdmin.Quote.QuoteOrderStatus,
    SUM(BIAdmin.Item.TotalPriceOfItemNumber) AS totalValue, BIAdmin.Item.ItemStatus,
    sum(case when BIAdmin.Item.ItemStatus != 'inactive' then 1 end) as NotInactiveCount,
    count(*) as TotalCount
FROM BIAdmin.Quote
LEFT OUTER JOIN BIAdmin.Item ON BIAdmin.Quote.ID = BIAdmin.Item.QuoteID
GROUP BY BIAdmin.Quote.QuoteOrderSalesOffice, BIAdmin.Quote.ManufacturerQuoteNumber,
    BIAdmin.Quote.CustomerName, BIAdmin.Quote.Project_JobTitle,
    BIAdmin.Quote.EndUserName, BIAdmin.Quote.QuoteOrderStatus, BIAdmin.Item.ItemStatus
HAVING (NOT (BIAdmin.Quote.QuoteOrderStatus = N'[Closed]'))
</code>```

Body:
I'm having trouble incorporating a bit of logic into a large SQL query. I'm using SQL Server Reporting Services 2005 with the Report Designer, and it only gives you one area to define a single SQL query to populate the report with. Hopefully someone can tell me what's wrong with my syntax so I can get it running.

I need to not only select a bunch of attributes filtering by (QuoteOrderStatus != 'Closed'), but also to only count the quotes with (ItemStatus != 'inactive') in a COUNT(DISTINCT ItemID's) statement (an aggregate function). I don't want to simply filter out the quotes with inactive items, because I still want to display the quotes with zero items. I only want to not include them in the total itemCount.

I did research and it seems the way to accomplish this type of logic is using CASE statements, but I'm having trouble incorporating them into this one obfuscated query. Report Designer simply tells me it's wrong and rearranges it to a way that I want even less. Can anyone help me with fixing this statement so it would be accepted as a valid query?

I've researched this for hours now without finding a good resource for this specific kind of problem. Sorry if the code is unclear, I tried to explain this as well as I can. Please ask questions if you want me to clarify in some way, and I appreciate any help anyone can offer.

SELECT DISTINCT
    BIAdmin.Quote.QuoteOrderSalesOffice, BIAdmin.Quote.ManufacturerQuoteNumber,
    BIAdmin.Quote.CustomerName, BIAdmin.Quote.Project_JobTitle,
    BIAdmin.Quote.EndUserName, BIAdmin.Quote.QuoteOrderStatus,
    SUM(BIAdmin.Item.TotalPriceOfItemNumber) AS totalValue, BIAdmin.Item.ItemStatus
FROM BIAdmin.Quote LEFT OUTER JOIN BIAdmin.Item ON BIAdmin.Quote.ID = BIAdmin.Item.QuoteID
WHERE   BIAdmin.Item.ItemStatus LIKE
    CASE WHEN NOT (BIAdmin.Item.ItemStatus = 'inactive') THEN
    SELECT DISTINCT COUNT(BIAdmin.Item.ID) AS itemCount
GROUP BY BIAdmin.Quote.QuoteOrderSalesOffice, BIAdmin.Quote.ManufacturerQuoteNumber,
    BIAdmin.Quote.CustomerName, BIAdmin.Quote.Project_JobTitle,
    BIAdmin.Quote.EndUserName, BIAdmin.Quote.QuoteOrderStatus, BIAdmin.Item.ItemStatus
HAVING (NOT (BIAdmin.Quote.QuoteOrderStatus = N'[Closed]'))

Body:
There is no END for your CASE statement, and your last SELECT is not valid in that context. Try something like this:

SELECT BIAdmin.Quote.QuoteOrderSalesOffice, BIAdmin.Quote.ManufacturerQuoteNumber,
    BIAdmin.Quote.CustomerName, BIAdmin.Quote.Project_JobTitle,
    BIAdmin.Quote.EndUserName, BIAdmin.Quote.QuoteOrderStatus,
    SUM(BIAdmin.Item.TotalPriceOfItemNumber) AS totalValue, BIAdmin.Item.ItemStatus,
    sum(case when BIAdmin.Item.ItemStatus != 'inactive' then 1 end) as NotInactiveCount,
    count(*) as TotalCount
FROM BIAdmin.Quote
LEFT OUTER JOIN BIAdmin.Item ON BIAdmin.Quote.ID = BIAdmin.Item.QuoteID
GROUP BY BIAdmin.Quote.QuoteOrderSalesOffice, BIAdmin.Quote.ManufacturerQuoteNumber,
    BIAdmin.Quote.CustomerName, BIAdmin.Quote.Project_JobTitle,
    BIAdmin.Quote.EndUserName, BIAdmin.Quote.QuoteOrderStatus, BIAdmin.Item.ItemStatus
HAVING (NOT (BIAdmin.Quote.QuoteOrderStatus = N'[Closed]'))


问:
Why translations.js does not contain any string from .pot file during nggettext_compile?
```<code>grunt.loadNpmTasks('grunt-angular-gettext');
grunt.initConfig({
nggettext_extract:{
  pot:{
    files:{
      'po/template.pot':['**/*.html']
    }
  }
},
nggettext_compile: {
  all:{
    files:{
      'translations.js':['po/*.po']
    }
  }
}
});
</code>```

controller

```<code>app.run(['gettextCatalog',function(gettextCatalog){
  gettextCatalog.currentLanguage='de';
  gettextCatalog.debug='true';
}])
</code>```

html

```<code><div class="row margin-bottom">
    <div ng-controller="DefCtrl">
      <p translate> Welcome!!!!</p>
      <p translate> Testing globalization and localization</p>
    </div>
  </div>
</code>```

I am running these commands:

```<code>grunt nggettext_extract
grunt nggettext_compile
</code>```

Both run successfully but translations.js does not contain any string from .pot file

答: In case anyone is still looking for the documentation you have to use waybackwhen. https://web.archive.org/ and then paste the link.</p>

Body:
grunt.loadNpmTasks('grunt-angular-gettext');
grunt.initConfig({
nggettext_extract:{
  pot:{
    files:{
      'po/template.pot':['**/*.html']
    }
  }
},
nggettext_compile: {
  all:{
    files:{
      'translations.js':['po/*.po']
    }
  }
}
});

controller

app.run(['gettextCatalog',function(gettextCatalog){
  gettextCatalog.currentLanguage='de';
  gettextCatalog.debug='true';
}])

html

 Welcome!!!!

 Testing globalization and localization

I am running these commands:

grunt nggettext_extract
grunt nggettext_compile

Both run successfully but translations.js does not contain any string from .pot file


问:
How to run PySpark on AWS EMR with AWS Lambda
How may I make my PySpark code to run with AWS EMR from AWS Lambda? Do I have to use AWS Lambda to create an auto-terminating EMR cluster to run my S3-stored code once?</p>

答:
What are the processes available to create a EMR cluster:

Using  boto3
  /  AWS
  CLI
  / Java
  SDK

Using cloudformation

Using Data Pipeline

Do I have to use AWS Lambda to create an auto-terminating EMR cluster to run my S3-stored code once?

No. It isn’t mandatory to use lambda to create an auto-terminating cluster.

You just need to specify a flag --auto-terminate while creating a cluster using boto3 / CLi / Java-SDK. But this case you need to submit the job along with cluster config. Ref

Note:

Its not possible to create an auto-terminating cluster using cloudformation. By design, CloudFormation assumes that the
  resources that are being created will be permanent to some extent.

If you REALLY had to do it this way, you could make an AWS api call to
  delete the CF stack upon finishing your EMR tasks.

How may I make my PySpark code to run with AWS EMR from AWS Lambda?

You can design your lambda to submit spark
  job.
  You can find an example
  here

In my use case I have one parameterised lambda which invoke CF to create cluster, submit job and terminate cluster.


问:
How to fetch json data in flutter
This is my json array.I want to get the data from gallery data in flutter

```<code>  {
        "status": true,
        "message": "Data Gallery",
        "data": {
            "gallery": [
                {
                    "gal_id": "21103",
                    "shop_id": "49",
                    "img": "1589530294IMG_8982.PNG",
                    "place": "6091",
                    "status": "New",
                    "title": "1",
                    "description": ""
                },
                {
                    "gal_id": "21102",
                    "shop_id": "49",
                    "img": "1589530294IMG_8981.PNG",
                    "place": "6091",
                    "status": "New",
                    "title": "1",
                    "description": ""
                }

            ]
        },
        "total": 2
    }
</code>```

This function is use to call the http request

```<code>  List<Gallery> list;

  Future<List<Gallery>> getData() async {

    String link =Constant.base_url+"manage/api/gallery/all/?X-Api-Key="+Constant.API_KEY+"&start=0&limit=10&field=shop_id&ield=shop_id&filter="+Constant.Shop_id+"&parent=0&loc_id= ";

    final response = await http.get(link);
//    print(response.body);
    if (response.statusCode == 200) {
      var cat = categoryFromMap(response.body.toString());

    return list;
  };
</code>```

How to access the gallery data?

My model class is

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

Category categoryFromMap(String str) => Category.fromMap(json.decode(str));

String categoryToMap(Category data) => json.encode(data.toMap());

class Category {
  Category({
    this.status,
    this.message,
    this.data,
    this.total,
  });

  bool status;
  String message;
  Data data;
  int total;

  factory Category.fromMap(Map<String, dynamic> json) => Category(
    status: json["status"],
    message: json["message"],
    data: Data.fromMap(json["data"]),
    total: json["total"],
  );

  Map<String, dynamic> toMap() => {
    "status": status,
    "message": message,
    "data": data.toMap(),
    "total": total,
  };
}

class Data {
  Data({
    this.gallery,
  });

  List<Gallery> gallery;

  factory Data.fromMap(Map<String, dynamic> json) => Data(
    gallery: List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
  );

  Map<String, dynamic> toMap() => {
    "gallery": List<dynamic>.from(gallery.map((x) => x.toMap())),
  };
}

class Gallery {
      Gallery({
        this.galId,
        this.shopId,
        this.img,
        this.place,
        this.status,
        this.title,
        this.description,
      });

      String galId;
      String shopId;
      String img;
      String place;
      String status;
      String title;
      String description;

      factory Gallery.fromJson(Map<String, dynamic> json) => Gallery(
        galId: json["gal_id"],
        shopId: json["shop_id"],
        img: json["img"],
        place: json["place"],
        status: json["status"],
        title: json["title"],
        description: json["description"],
      );

  Map<String, dynamic> toMap() => {
    "gal_id": galId,
    "shop_id": shopId,
    "img": img,
    "place": place,
    "status": status,
    "title": title,
    "description": description,
  };
}
</code>```

Please help me to retrieve the data.

答:
You can copy paste run full code below

You can use FutureBuilder and check connectionState then display with   Text(snapshot.data.data.gallery[index].img,)

code snippet

```<code> @override
  void initState() {
    _future = getData();
    ...

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<Category> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.data.gallery.length,
                        itemBuilder: (context, index) {
</code>```

working demo

full code

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

Category categoryFromMap(String str) => Category.fromMap(json.decode(str));

String categoryToMap(Category data) => json.encode(data.toMap());

class Category {
  Category({
    this.status,
    this.message,
    this.data,
    this.total,
  });

  bool status;
  String message;
  Data data;
  int total;

  factory Category.fromMap(Map<String, dynamic> json) => Category(
        status: json["status"],
        message: json["message"],
        data: Data.fromMap(json["data"]),
        total: json["total"],
      );

  Map<String, dynamic> toMap() => {
        "status": status,
        "message": message,
        "data": data.toMap(),
        "total": total,
      };
}

class Data {
  Data({
    this.gallery,
  });

  List<Gallery> gallery;

  factory Data.fromMap(Map<String, dynamic> json) => Data(
        gallery:
            List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
      );

  Map<String, dynamic> toMap() => {
        "gallery": List<dynamic>.from(gallery.map((x) => x.toMap())),
      };
}

class Gallery {
  Gallery({
    this.galId,
    this.shopId,
    this.img,
    this.place,
    this.status,
    this.title,
    this.description,
  });

  String galId;
  String shopId;
  String img;
  String place;
  String status;
  String title;
  String description;

  factory Gallery.fromJson(Map<String, dynamic> json) => Gallery(
        galId: json["gal_id"],
        shopId: json["shop_id"],
        img: json["img"],
        place: json["place"],
        status: json["status"],
        title: json["title"],
        description: json["description"],
      );

  Map<String, dynamic> toMap() => {
        "gal_id": galId,
        "shop_id": shopId,
        "img": img,
        "place": place,
        "status": status,
        "title": title,
        "description": description,
      };
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Future<Category> _future;

  Future<Category> getData() async {
    String jsonString = '''
   {
        "status": true,
        "message": "Data Gallery",
        "data": {
            "gallery": [
                {
                    "gal_id": "21103",
                    "shop_id": "49",
                    "img": "1589530294IMG_8982.PNG",
                    "place": "6091",
                    "status": "New",
                    "title": "1",
                    "description": ""
                },
                {
                    "gal_id": "21102",
                    "shop_id": "49",
                    "img": "1589530294IMG_8981.PNG",
                    "place": "6091",
                    "status": "New",
                    "title": "1",
                    "description": ""
                }

            ]
        },
        "total": 2
    }
    ''';

    var response = http.Response(jsonString, 200);

    if (response.statusCode == 200) {
      return categoryFromMap(response.body);
    } else {
      print(response.statusCode);
    }
  }

  @override
  void initState() {
    _future = getData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<Category> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.data.gallery.length,
                        itemBuilder: (context, index) {
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot
                                        .data.data.gallery[index].galId),
                                    Spacer(),
                                    Text(
                                      snapshot.data.data.gallery[index].img,
                                    ),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}
</code>```

Title: How to fetch json data in flutter

Body:
This is my json array.I want to get the data from gallery data in flutter

  {
        "status": true,
        "message": "Data Gallery",
        "data": {
            "gallery": [
                {
                    "gal_id": "21103",
                    "shop_id": "49",
                    "img": "1589530294IMG_8982.PNG",
                    "place": "6091",
                    "status": "New",
                    "title": "1",
                    "description": ""
                },
                {
                    "gal_id": "21102",
                    "shop_id": "49",
                    "img": "1589530294IMG_8981.PNG",
                    "place": "6091",
                    "status": "New",
                    "title": "1",
                    "description": ""
                }

            ]
        },
        "total": 2
    }

This function is use to call the http request

  List<Gallery> list;

  Future<List<Gallery>> getData() async {

    String link =Constant.base_url+"manage/api/gallery/all/?X-Api-Key="+Constant.API_KEY+"&start=0&limit=10&field=shop_id&ield=shop_id&filter="+Constant.Shop_id+"&parent=0&loc_id= ";

    final response = await http.get(link);
//    print(response.body);
    if (response.statusCode == 200) {
      var cat = categoryFromMap(response.body.toString());

    return list;
  };

How to access the gallery data?

My model class is

import 'dart:convert';

Category categoryFromMap(String str) => Category.fromMap(json.decode(str));

String categoryToMap(Category data) => json.encode(data.toMap());

class Category {
  Category({
    this.status,
    this.message,
    this.data,
    this.total,
  });

  bool status;
  String message;
  Data data;
  int total;

  factory Category.fromMap(Map<String, dynamic> json) => Category(
    status: json["status"],
    message: json["message"],
    data: Data.fromMap(json["data"]),
    total: json["total"],
  );

  Map<String, dynamic> toMap() => {
    "status": status,
    "message": message,
    "data": data.toMap(),
    "total": total,
  };
}

class Data {
  Data({
    this.gallery,
  });

  List<Gallery> gallery;

  factory Data.fromMap(Map<String, dynamic> json) => Data(
    gallery: List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
  );

  Map<String, dynamic> toMap() => {
    "gallery": List<dynamic>.from(gallery.map((x) => x.toMap())),
  };
}

class Gallery {
      Gallery({
        this.galId,
        this.shopId,
        this.img,
        this.place,
        this.status,
        this.title,
        this.description,
      });

      String galId;
      String shopId;
      String img;
      String place;
      String status;
      String title;
      String description;

      factory Gallery.fromJson(Map<String, dynamic> json) => Gallery(
        galId: json["gal_id"],
        shopId: json["shop_id"],
        img: json["img"],
        place: json["place"],
        status: json["status"],
        title: json["title"],
        description: json["description"],
      );

  Map<String, dynamic> toMap() => {
    "gal_id": galId,
    "shop_id": shopId,
    "img": img,
    "place": place,
    "status": status,
    "title": title,
    "description": description,
  };
}

Please help me to retrieve the data.

Body:
You can copy paste run full code below

You can use FutureBuilder and check connectionState then display with   Text(snapshot.data.data.gallery[index].img,)

code snippet

 @override
  void initState() {
    _future = getData();
    ...

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<Category> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.data.gallery.length,
                        itemBuilder: (context, index) {

working demo

full code

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

Category categoryFromMap(String str) => Category.fromMap(json.decode(str));

String categoryToMap(Category data) => json.encode(data.toMap());

class Category {
  Category({
    this.status,
    this.message,
    this.data,
    this.total,
  });

  bool status;
  String message;
  Data data;
  int total;

  factory Category.fromMap(Map<String, dynamic> json) => Category(
        status: json["status"],
        message: json["message"],
        data: Data.fromMap(json["data"]),
        total: json["total"],
      );

  Map<String, dynamic> toMap() => {
        "status": status,
        "message": message,
        "data": data.toMap(),
        "total": total,
      };
}

class Data {
  Data({
    this.gallery,
  });

  List<Gallery> gallery;

  factory Data.fromMap(Map<String, dynamic> json) => Data(
        gallery:
            List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
      );

  Map<String, dynamic> toMap() => {
        "gallery": List<dynamic>.from(gallery.map((x) => x.toMap())),
      };
}

class Gallery {
  Gallery({
    this.galId,
    this.shopId,
    this.img,
    this.place,
    this.status,
    this.title,
    this.description,
  });

  String galId;
  String shopId;
  String img;
  String place;
  String status;
  String title;
  String description;

  factory Gallery.fromJson(Map<String, dynamic> json) => Gallery(
        galId: json["gal_id"],
        shopId: json["shop_id"],
        img: json["img"],
        place: json["place"],
        status: json["status"],
        title: json["title"],
        description: json["description"],
      );

  Map<String, dynamic> toMap() => {
        "gal_id": galId,
        "shop_id": shopId,
        "img": img,
        "place": place,
        "status": status,
        "title": title,
        "description": description,
      };
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Future<Category> _future;

  Future<Category> getData() async {
    String jsonString = '''
   {
        "status": true,
        "message": "Data Gallery",
        "data": {
            "gallery": [
                {
                    "gal_id": "21103",
                    "shop_id": "49",
                    "img": "1589530294IMG_8982.PNG",
                    "place": "6091",
                    "status": "New",
                    "title": "1",
                    "description": ""
                },
                {
                    "gal_id": "21102",
                    "shop_id": "49",
                    "img": "1589530294IMG_8981.PNG",
                    "place": "6091",
                    "status": "New",
                    "title": "1",
                    "description": ""
                }

            ]
        },
        "total": 2
    }
    ''';

    var response = http.Response(jsonString, 200);

    if (response.statusCode == 200) {
      return categoryFromMap(response.body);
    } else {
      print(response.statusCode);
    }
  }

  @override
  void initState() {
    _future = getData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<Category> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.data.gallery.length,
                        itemBuilder: (context, index) {
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot
                                        .data.data.gallery[index].galId),
                                    Spacer(),
                                    Text(
                                      snapshot.data.data.gallery[index].img,
                                    ),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}


问:
javascript draw image into html from buffer (nodejs/socket.io)
(sorry for my english)
Hi, i have an appplication created with nodejs to push image data into a webpage.

the data from nodejs server is pushed into webpage using socket.io

This data is the complete image, i try to write to disc to see the image and is good.
The data is put into a buffer to encode in base64 then send to the webpage and i try to show using
'data:image/png;base64,'+data
but nothing happend... The data seems to be "complete" including the headers of the PNG image.

The server use thrift to communicate with another client (this in C++), this client create the images and send to the nodejs-thrift server, when a image is receive, the nodejs-socket.io server push into webpage.

some code:
serverside

```<code>var http = require('http'),
url = require('url'),
fs  = require('fs'),
sys = require('sys');
var hserver = http.createServer(function(request,response){
var path = url.parse(request.url).pathname;
switch(path){
   case '/':

        fs.readFile(__dirname + '/index.html',function(err,data){
           if(err) return send404(res);
           response.writeHead(200,{'Content-Type':'text/html'});
           response.write(data,'utf8');
           response.end();
        });
    break;
    default: send404(response);
}
   }),
send404 = function(res){
 res.writeHead(404);
 res.write('404');
 res.end();
};

hserver.listen(8080);
var io = require('socket.io');
var socket = io.listen(hserver);
//this is the function in the Thrift part to send the image data to webpage using socket.io
var receiveImage = function(image,success){
buff= new Buffer(image.data.toString('base64'),'base64');
socket.broadcast({
    data: buff.toString('base64'),
    width: image.width,
    height: image.height
});
success(true);
}
</code>```

In the webpage i try to load the image using the on.message callback of socket.io

```<code><script>
var socket = new io.Socket(null,{port:8080});
socket.connect();
socket.on('message',function(obj){
        document.getElementById('imagenes').src='data:image/png;base64,'+obj.data.toString();
});
socket.on('connect',function(){
    document.getElementById('stream').innerHTML = "Conectado!"
});
</script>
</code>```

But i can't see the image..
The obj.data.toString('base64') create a string like this:

```<code> PNGIHDRKIDATxYw5L1LlFMM/migzWUadOadLUd+43PIfPU9VU5AJAg3dIWUmHAMajS8GUuq ............
 .............
 /NIlWDHUDmIPdHIEND
</code>```

is the all data of the image..

how can i show the image?? (maybe using img tag or into canvas)

Thanks in advance.

EDIT: Some changes to code, but nothing change.. my guess.. the image don't show because the data (PNGIHDRKIDATxYw......PdHIENDB) isn't the correct data.. i search about this and the png data used to show images inline is diferent (without the header PNGIHDRKIDAT and the tail ENDB), i remove the header and tail and don't show .. maybe the data i receive isn't correct, but if i try to write to filesystem in the server side using nodejs (fs) i get the correct images (with fs.writeFileSync("imagen.png",image.data.toString('binary'),'binary') ) using binary encode, but with base64 encode theres no image.

答: In the C++ side (where i create the images and send them to the nodejs server). I need to encode the data in base64. Then in node i get this data put into a buffer with base64 encoding and send it to the webpage.</p>

Body:
(sorry for my english)
Hi, i have an appplication created with nodejs to push image data into a webpage.

the data from nodejs server is pushed into webpage using socket.io

This data is the complete image, i try to write to disc to see the image and is good.
The data is put into a buffer to encode in base64 then send to the webpage and i try to show using
'data:image/png;base64,'+data
but nothing happend... The data seems to be "complete" including the headers of the PNG image.

The server use thrift to communicate with another client (this in C++), this client create the images and send to the nodejs-thrift server, when a image is receive, the nodejs-socket.io server push into webpage.

some code:
serverside

var http = require('http'),
url = require('url'),
fs  = require('fs'),
sys = require('sys');
var hserver = http.createServer(function(request,response){
var path = url.parse(request.url).pathname;
switch(path){
   case '/':

        fs.readFile(__dirname + '/index.html',function(err,data){
           if(err) return send404(res);
           response.writeHead(200,{'Content-Type':'text/html'});
           response.write(data,'utf8');
           response.end();
        });
    break;
    default: send404(response);
}
   }),
send404 = function(res){
 res.writeHead(404);
 res.write('404');
 res.end();
};

hserver.listen(8080);
var io = require('socket.io');
var socket = io.listen(hserver);
//this is the function in the Thrift part to send the image data to webpage using socket.io
var receiveImage = function(image,success){
buff= new Buffer(image.data.toString('base64'),'base64');
socket.broadcast({
    data: buff.toString('base64'),
    width: image.width,
    height: image.height
});
success(true);
}

In the webpage i try to load the image using the on.message callback of socket.io

But i can't see the image..
The obj.data.toString('base64') create a string like this:

 PNGIHDRKIDATxYw5L1LlFMM/migzWUadOadLUd+43PIfPU9VU5AJAg3dIWUmHAMajS8GUuq ............
 .............
 /NIlWDHUDmIPdHIEND

is the all data of the image..

how can i show the image?? (maybe using img tag or into canvas)

Thanks in advance.

EDIT: Some changes to code, but nothing change.. my guess.. the image don't show because the data (PNGIHDRKIDATxYw......PdHIENDB) isn't the correct data.. i search about this and the png data used to show images inline is diferent (without the header PNGIHDRKIDAT and the tail ENDB), i remove the header and tail and don't show .. maybe the data i receive isn't correct, but if i try to write to filesystem in the server side using nodejs (fs) i get the correct images (with fs.writeFileSync("imagen.png",image.data.toString('binary'),'binary') ) using binary encode, but with base64 encode theres no image.


问:
Ansible yaml brake long link like string with variable interpolation to multiple line
```<code>- hosts: localhost
  vars:
  composer_version: 0.0.7
  composer_download_url: https://search.maven.org/remotecontent?filepath=org/sonatype/nexus/plugins/nexus-repository-composer/{ composer_version }}/nexus-repository-composer-{{ composer_version  }}-bundle.kar
</code>```

How to break this composer_download_url value string to multiple lines,
to improve readability.

Looking something like this:

```<code>composer_download_url:
  "https://search.maven.org/remotecontent?filepath=org/sonatype/nexus/plugins/nexus-repository-composer/
  {{ composer_version }}/nexus-repository-composer-{{ composer_version }}-bundle.kar"
</code>```

Tried with indicators
composer_download_url: |
composer_download_url: |-
composer_download_url: |-2
but no luck

答:
You escape the newline:

composer_download_url:
  "https://search.maven.org/remotecontent?filepath=org/sonatype/nexus/plugins/nexus-repository-composer/\
  {{ composer_version }}/nexus-repository-composer-{{ composer_version }}-bundle.kar"
```

Body:
- hosts: localhost
  vars:
  composer_version: 0.0.7
  composer_download_url: https://search.maven.org/remotecontent?filepath=org/sonatype/nexus/plugins/nexus-repository-composer/{ composer_version }}/nexus-repository-composer-{{ composer_version  }}-bundle.kar

How to break this composer_download_url value string to multiple lines,
to improve readability.

Looking something like this:

composer_download_url:
  "https://search.maven.org/remotecontent?filepath=org/sonatype/nexus/plugins/nexus-repository-composer/
  {{ composer_version }}/nexus-repository-composer-{{ composer_version }}-bundle.kar"

Tried with indicators
composer_download_url: |
composer_download_url: |-
composer_download_url: |-2
but no luck


问:
display a table showing model instances as rows and let users select instances (rows) to delete
In my app, users can upload files. These files are represented by a model with attributes for associated meta-data (upload time, file name, user created note, max value, etc).

A user will upload several files and I want to show them a table of their uploaded files with a checkbox next to each row that can be used to delete selected files and associated model instances.

I'm not sure what the right approach is, I've looked at the following options but there doesn't seem to be an obvious solution:

model forms, using CheckboxSelectMultiple

django_tables2 - seems to be an established 3rd party app

reuse the django admin code (form and view).

The default django admin app behavior is perfect for my use case, but I'm not sure what the best way is to reproduce it?

app/models.py

import uuid

from django.contrib.auth import get_user_model
from django.db import models

User = get_user_model()

class Document(models.Model):
    def rename_file(self, filename):
        ext = filename.split('.')[-1]
        new_name = uuid.uuid4().hex

        return f'documents/{new_name}.{ext}'

    owner = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        editable=True,
    )
    document = models.FileField(upload_to=rename_file)
    notes = models.CharField(max_length=258, blank=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)
    nice_name = models.CharField(max_length=128, null=True, blank=False)
    start_date = models.DateField(null=True, blank=False)
    end_date = models.DateField(null=True, blank=False)

    def __str__(self):
        return str(self.document)
```

<p><em>app/admin.py</em></p>

<pre class="lang-py prettyprint-override"><code>from django.contrib import admin

from .models import Document

def uuid(obj):
    return obj.owner.uuid

uuid.short_description = 'user id'

@admin.register(Document)
class DocumentAdmin(admin.ModelAdmin):
    fields = ('document', 'notes')
    list_display = (
        'owner',
        uuid,
        'document',
        'nice_name',
        'notes',
        'uploaded_at',
        'start_date',
        'end_date'
    )
</code>```

app/forms.py

from django import forms
from django.forms.widgets import CheckboxSelectMultiple

from .models import Document

class DeleteDocumentsForm(forms.ModelForm):

    document = forms.ModelMultipleChoiceField(queryset=None, widget=forms.CheckboxSelectMultiple)
    nice_name = forms.ModelMultipleChoiceField(queryset=None, widget=forms.CheckboxSelectMultiple)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        qs = Document.objects.filter(owner_id=user)
        #  super(DeleteDocumentsForm, self).__init__(*args, **kwargs)
        super().__init__(*args, **kwargs)
        self.fields['document'].queryset = qs
        self.fields['nice_name'].queryset = qs.values('nice_name')

    #  document.fields['nice_name'].widget.attrs['readonly'] = True

    class Meta:
        model = Document
        fields = ('document', 'nice_name')
        widgets = {
            'document': CheckboxSelectMultiple,
            'nice_name': CheckboxSelectMultiple,
        }
```

答:
To achieve what you want to do, you need to create a form that encapsulates a table. When the for loop iterates over each item from your database, provide a checkbox which value would be the unique ID of the uploaded file. By submitting the form, you would also then be submitting these IDs.

So this would be your view:

```<code><form action="." method="post">
   {% csrf_token %}
   <table>
      {% for upload in uploads %}
         <tr>
            <td><input type="checkbox" name="selected" value="{{ upload.id }}"></td>
            <td><img src="{{ upload.url }}" alt="image"></td>
            <td>{{ upload.name }}</td>
          </tr>
       {% endfor %}
   </table>
   <button type="submit">Delete</button>
</form>
</code>```

Once the user has selected one or multiple checkboxes, and after pressing on delete, you will receive a query dict with the IDs of the selected items that you'll be able to process as you want in your view:

```<code><QueryDict: {'csrfmiddlewaretoken': [''], 'selected': ['2', '3']}>
</code>```

As for the form, I don't really see any use of it IMO.

Body:
In my app, users can upload files. These files are represented by a model with attributes for associated meta-data (upload time, file name, user created note, max value, etc).

A user will upload several files and I want to show them a table of their uploaded files with a checkbox next to each row that can be used to delete selected files and associated model instances.

I'm not sure what the right approach is, I've looked at the following options but there doesn't seem to be an obvious solution:

model forms, using CheckboxSelectMultiple

django_tables2 - seems to be an established 3rd party app

reuse the django admin code (form and view).

The default django admin app behavior is perfect for my use case, but I'm not sure what the best way is to reproduce it?

app/models.py

import uuid

from django.contrib.auth import get_user_model
from django.db import models

User = get_user_model()

class Document(models.Model):
    def rename_file(self, filename):
        ext = filename.split('.')[-1]
        new_name = uuid.uuid4().hex

        return f'documents/{new_name}.{ext}'

    owner = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        editable=True,
    )
    document = models.FileField(upload_to=rename_file)
    notes = models.CharField(max_length=258, blank=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)
    nice_name = models.CharField(max_length=128, null=True, blank=False)
    start_date = models.DateField(null=True, blank=False)
    end_date = models.DateField(null=True, blank=False)

    def __str__(self):
        return str(self.document)

app/admin.py

from django.contrib import admin

from .models import Document

def uuid(obj):
    return obj.owner.uuid

uuid.short_description = 'user id'

@admin.register(Document)
class DocumentAdmin(admin.ModelAdmin):
    fields = ('document', 'notes')
    list_display = (
        'owner',
        uuid,
        'document',
        'nice_name',
        'notes',
        'uploaded_at',
        'start_date',
        'end_date'
    )

app/forms.py

from django import forms
from django.forms.widgets import CheckboxSelectMultiple

from .models import Document

class DeleteDocumentsForm(forms.ModelForm):

    document = forms.ModelMultipleChoiceField(queryset=None, widget=forms.CheckboxSelectMultiple)
    nice_name = forms.ModelMultipleChoiceField(queryset=None, widget=forms.CheckboxSelectMultiple)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        qs = Document.objects.filter(owner_id=user)
        #  super(DeleteDocumentsForm, self).__init__(*args, **kwargs)
        super().__init__(*args, **kwargs)
        self.fields['document'].queryset = qs
        self.fields['nice_name'].queryset = qs.values('nice_name')

    #  document.fields['nice_name'].widget.attrs['readonly'] = True

    class Meta:
        model = Document
        fields = ('document', 'nice_name')
        widgets = {
            'document': CheckboxSelectMultiple,
            'nice_name': CheckboxSelectMultiple,
        }

Body:
To achieve what you want to do, you need to create a form that encapsulates a table. When the for loop iterates over each item from your database, provide a checkbox which value would be the unique ID of the uploaded file. By submitting the form, you would also then be submitting these IDs.

So this would be your view:

<form action="." method="post">
   {% csrf_token %}
   <table>
      {% for upload in uploads %}
         <tr>
            <td><input type="checkbox" name="selected" value="{{ upload.id }}"></td>
            <td><img src="{{ upload.url }}" alt="image"></td>
            <td>{{ upload.name }}</td>
          </tr>
       {% endfor %}
   </table>
   <button type="submit">Delete</button>
</form>

Once the user has selected one or multiple checkboxes, and after pressing on delete, you will receive a query dict with the IDs of the selected items that you'll be able to process as you want in your view:

<QueryDict: {'csrfmiddlewaretoken': [''], 'selected': ['2', '3']}>

As for the form, I don't really see any use of it IMO.


问:
How can I detect that all page components were loaded in Oro application?
I have a task to get some data from API asynchronously - page loads, components initialize and fill data object with mediator, and after all components were initialized - send request, get it and do some other logic. So, the question is, how can I detect that all page components have been initialized?</p>

答:
Mediator triggers page:afterChange event once all standard components are initialized and ready to use. So you can listen to that event.

https://doc.oroinc.com/frontend/javascript/#page-controller


问:
Flow: How to filter for a type from a set of union types
I am tring to filter for a specific type of object from a list of union types. Here is my attempt so far.

```<code>/* @flow */

type Human = {|
  name: string
|};

type Droid = {|
  model: string
|};

type LivingThings = {
   things: [Human | Droid]
}

const getHumans = (livingThings: LivingThings): Human[] => {
    return livingThings.things.filter((thing) => {
       return 'name' in thing;
    })
}
</code>```

However this complains of an error as per this link: Link

return livingThings.things.filter((thing) => {
                 ^ Cannot return livingThings.things.filter(...) because property model is missing in Human 1 but exists in Droid [2] in arr

答:
Unfortunately, Flow does not refine types with filter. The linked issue is quite old and it has been on the roadmap for quite some time. As suggested above you can cast to any or use $ExpectError to create a locally unsafe function. Alternatively, you can use an imperative loop approach:

const res: Human[] = [];
for (thing of livingThings.things) {
  if (typeof thing.name === 'string') {
    res.push(thing)
  }
}
return res;
```

<p>Or create a useful helper function <code>mapMaybe</code> that you can reuse in many other cases:</p>

<pre class="lang-js prettyprint-override"><code>function mapMaybe<A, B>(f: A => ?B, xs: A[]): B[] {
  // $ExpectError or alternatively write loop here
  return xs.map(f).filter(notUndefinedOrNull);
}

mapMaybe(thing => {
  if (typeof thing.name === 'string') {
    return thing;
  }
  return null;
}, livingThings.things);
</code>```

Body:
I am tring to filter for a specific type of object from a list of union types. Here is my attempt so far.

/* @flow */

type Human = {|
  name: string
|};

type Droid = {|
  model: string
|};

type LivingThings = {
   things: [Human | Droid]
}

const getHumans = (livingThings: LivingThings): Human[] => {
    return livingThings.things.filter((thing) => {
       return 'name' in thing;
    })
}

However this complains of an error as per this link: Link

return livingThings.things.filter((thing) => {
                 ^ Cannot return livingThings.things.filter(...) because property model is missing in Human 1 but exists in Droid [2] in arr

Body:
Unfortunately, Flow does not refine types with filter. The linked issue is quite old and it has been on the roadmap for quite some time. As suggested above you can cast to any or use $ExpectError to create a locally unsafe function. Alternatively, you can use an imperative loop approach:

const res: Human[] = [];
for (thing of livingThings.things) {
  if (typeof thing.name === 'string') {
    res.push(thing)
  }
}
return res;

Or create a useful helper function mapMaybe that you can reuse in many other cases:

function mapMaybe<A, B>(f: A => ?B, xs: A[]): B[] {
  // $ExpectError or alternatively write loop here
  return xs.map(f).filter(notUndefinedOrNull);
}

mapMaybe(thing => {
  if (typeof thing.name === 'string') {
    return thing;
  }
  return null;
}, livingThings.things);


问:
Qt mouse cursor transparency
I would like to change the stock cursor with a translucent one, a simple filled circle, of various sizes, depending on the level of zoom in the underlying widget (say, RGBA = 200, 200, 200, 128).

Is this at all possible with Qt? If not, is it a limitation in Qt or the underlying libs? Do you have suggestions as to how this could be accomplished by other means, e.g., hiding the cursor and overlaying a transparent pixmap at the cursor position (albeit slower)? TIA

答: QCursor can take a QPixmap which does support alpha channel. So I don't see why it can't be done.</p>

Title: Qt mouse cursor transparency


问:
React Redux - Waiting for async api call to finish before next action is dispatched
I am working on a web app that uses React + Redux, with a backend using Django (DRF). I am using axios to send in my API request, which is asynchronous. The issue I am facing right now is that the actions dispatched do not wait for the API call to finish before the next action is dispatched. Below is my code

```<code>const mapDispatchToProps = dispatch => ({
    success: id => {
        dispatch(fetchSalesProject(id));
        dispatch(createMessage('Requirement successfully updated!'))
    }
})
</code>```

fetchSalesProject action (axiosInstance is just a custom modification of axios call, the functionality is the same)

```<code>export const fetchSalesProject = (id) => (dispatch) => {
    console.log('enter sales project action')
    axiosInstance
        .get(`/sales-project/detail/${id}/`)
        .then((res) => {
            console.log('fetched data')
            dispatch({
                type: FETCH_SALES_PROJECT,
                payload: res.data,
            });
        })
        .catch((err) => dispatch(returnErrors(err.response.data, err.response.status)));
};
</code>```

createMessage action

```<code>export const createMessage = (message) => {
  console.log('message')
  return {
    type: CREATE_MESSAGE,
    message: message,
  };
};
</code>```

When calling this.props.success (refer to mapDispatchToProps), the message is displayed before the api call response data is received (evident by the fact that console.log('message') runs before console.log('fetched data'))

I would want the data to be fetched from the api call before i run the createMessage action, is there any advise on how to accomplish that? I am new to React and especially Redux, so hope that you guys can point me in the right direction on how to accomplish that.

Also, can I check whether it is wrong to have a dispatch in the mapDispatchToProps, and also a dispatch within the action (refer to fetchSalesProject action). Would it cause any issues with performance or is it frowned upon to do so? Please advise me as I am quite confused with Redux.

Thanks all for reading through, all help is appreciated :-)

答:
while you are dispatching from UI, you just sending an object towards reducer which in his turn will modify the state at the store and in the end of the process will re-render components that refer to props that changed. At the moment you are dispatching the first action, there is nothing that tells the component that it should wait before sending the next object to the reducer

So you have 2 options,

the first is at UI itself use componentDidUpdate or useEffect for run the second action after the first action reduced

```<code> componentDidUpdate(prevProps) {
       if (prevProps.salesProject != this.props.salesProject)
         dispatch(createMessage('Requirement successfully updated!'))
      }
</code>```

while I assume that dispatch(fetchSalesProject(id)); modify salesProject prop

Another way to do that, and in case you actually fine with that message and salesProject will gonna get together to the reducer, is to dispatch them in one action

```<code> export const fetchSalesProjectAndMessage = (id, message) => (dispatch) => {
  console.log('enter sales project action')
  axiosInstance
    .get(`/sales-project/detail/${id}/`)
    .then((res) => {
        console.log('fetched data')
        dispatch({
            type: FETCH_SALES_PROJECT_AND_MESSAGE,
            payload: { data: res.data, message }
        });
    })
    .catch((err) => dispatch(returnErrors(err.response.data, err.response.status)));
 };
</code>```

and at reducer payload.data either payload.message will refer to desired info

Body:
I am working on a web app that uses React + Redux, with a backend using Django (DRF). I am using axios to send in my API request, which is asynchronous. The issue I am facing right now is that the actions dispatched do not wait for the API call to finish before the next action is dispatched. Below is my code

const mapDispatchToProps = dispatch => ({
    success: id => {
        dispatch(fetchSalesProject(id));
        dispatch(createMessage('Requirement successfully updated!'))
    }
})

fetchSalesProject action (axiosInstance is just a custom modification of axios call, the functionality is the same)

export const fetchSalesProject = (id) => (dispatch) => {
    console.log('enter sales project action')
    axiosInstance
        .get(`/sales-project/detail/${id}/`)
        .then((res) => {
            console.log('fetched data')
            dispatch({
                type: FETCH_SALES_PROJECT,
                payload: res.data,
            });
        })
        .catch((err) => dispatch(returnErrors(err.response.data, err.response.status)));
};

createMessage action

export const createMessage = (message) => {
  console.log('message')
  return {
    type: CREATE_MESSAGE,
    message: message,
  };
};

When calling this.props.success (refer to mapDispatchToProps), the message is displayed before the api call response data is received (evident by the fact that console.log('message') runs before console.log('fetched data'))

I would want the data to be fetched from the api call before i run the createMessage action, is there any advise on how to accomplish that? I am new to React and especially Redux, so hope that you guys can point me in the right direction on how to accomplish that.

Also, can I check whether it is wrong to have a dispatch in the mapDispatchToProps, and also a dispatch within the action (refer to fetchSalesProject action). Would it cause any issues with performance or is it frowned upon to do so? Please advise me as I am quite confused with Redux.

Thanks all for reading through, all help is appreciated :-)

Body:
while you are dispatching from UI, you just sending an object towards reducer which in his turn will modify the state at the store and in the end of the process will re-render components that refer to props that changed. At the moment you are dispatching the first action, there is nothing that tells the component that it should wait before sending the next object to the reducer

So you have 2 options,

the first is at UI itself use componentDidUpdate or useEffect for run the second action after the first action reduced

 componentDidUpdate(prevProps) {
       if (prevProps.salesProject != this.props.salesProject)
         dispatch(createMessage('Requirement successfully updated!'))
      }

while I assume that dispatch(fetchSalesProject(id)); modify salesProject prop

Another way to do that, and in case you actually fine with that message and salesProject will gonna get together to the reducer, is to dispatch them in one action

 export const fetchSalesProjectAndMessage = (id, message) => (dispatch) => {
  console.log('enter sales project action')
  axiosInstance
    .get(`/sales-project/detail/${id}/`)
    .then((res) => {
        console.log('fetched data')
        dispatch({
            type: FETCH_SALES_PROJECT_AND_MESSAGE,
            payload: { data: res.data, message }
        });
    })
    .catch((err) => dispatch(returnErrors(err.response.data, err.response.status)));
 };

and at reducer payload.data either payload.message will refer to desired info


问:
Generating Positive Kinetic Energy (PKE) from car velocity
I have a data frame with 3 columns, Time (each second), Dpeed(KM/H) in each second, from this data frame I want to calculate positive kinetic energy.
This formula i found in this research :

https://www.researchgate.net/publication/235721432_Quality_assurance_of_exhaust_emissions_test_data

PKE = pow(Vf,2) - pow(Vi,2) / distance
I'm new to python and I'm wondering how to implement it.
any help will be appreciated .
what i have tried :

this to calculate the time in hour

```<code>start=df['Time'].iloc[0]

end=df['Time'].iloc[df.shape[0]-1]
diff = end - start
hr = diff.seconds/3600 #to hr
hr
</code>```

and this to calculate distance

```<code>avgspeed = df['Vehicle Speed Sensor [km/h]'].mean()
dis = avgspeed * hr
dis
</code>```

and this to calculate pke :

```<code>z = 0
df['pke'] = 0
for i in range(1,len(df)):
    z = pow(df['Vehicle Speed Sensor [km/h]'].loc[i],2) - pow(df['Vehicle Speed Sensor [km/h]'].loc[i-1],2)
    pke = z / dis
    df['pke'].loc[i] = pke
</code>```

this is the data how its presented
enter image description here

答: I recommend to do calculations over Excel then compare code output to Excel output to assure your results.</p>

Body:
I have a data frame with 3 columns, Time (each second), Dpeed(KM/H) in each second, from this data frame I want to calculate positive kinetic energy.
This formula i found in this research :

https://www.researchgate.net/publication/235721432_Quality_assurance_of_exhaust_emissions_test_data

PKE = pow(Vf,2) - pow(Vi,2) / distance
I'm new to python and I'm wondering how to implement it.
any help will be appreciated .
what i have tried :

this to calculate the time in hour

start=df['Time'].iloc[0]

end=df['Time'].iloc[df.shape[0]-1]
diff = end - start
hr = diff.seconds/3600 #to hr
hr

and this to calculate distance

avgspeed = df['Vehicle Speed Sensor [km/h]'].mean()
dis = avgspeed * hr
dis

and this to calculate pke :

z = 0
df['pke'] = 0
for i in range(1,len(df)):
    z = pow(df['Vehicle Speed Sensor [km/h]'].loc[i],2) - pow(df['Vehicle Speed Sensor [km/h]'].loc[i-1],2)
    pke = z / dis
    df['pke'].loc[i] = pke

this is the data how its presented
enter image description here


问:
Troubleshooting a deploy to heroku - RuntimeError: The reset parameter is False but there is no n_features_in_ attribute. Is this estimator fitted?
Hi Stackeoverflow Community. I working on a simple project for a class involving hosting a flask app that allows users to input values and get a prediction of who is going to win. Well, in runs OK on our local machines using python flask, but is presenting challenges on heroku. Stumped!

The code is not lengthy or complicated. Also know that we have some opps as well.

our App.py file looks like:

```<code>import flask
import tensorflow
import sklearn
import pandas as pd
import numpy as np
from tensorflow import keras
from pickle import load
from load import *

model = init()

scaler = load(open('model/scaler.pkl', 'rb'))
print("Awesome, your scaler has been loaded from disk! Cool beans!")

app = flask.Flask(__name__, template_folder='templates')

@app.route('/', methods=['GET', 'POST'])
def main():
    global model
    if flask.request.method == 'GET':
        return(flask.render_template('main.html'))
    if flask.request.method == 'POST':
        R_Weight = flask.request.form['R_Weight']
        R_Height = flask.request.form['R_Height']
        R_Age = flask.request.form['R_Age']
        B_Weight = flask.request.form['B_Weight']
        B_Height = flask.request.form['B_Height']
        B_Age = flask.request.form['B_Age']
        RPrev = 2.130049
        BPrev = 1.756650
        BStreak = 0.643350
        RStreak = 0.748768
        input_variables = pd.DataFrame([[BPrev, BStreak, B_Age,B_Height,B_Weight,RPrev, RStreak, R_Age,R_Height,R_Weight]],
                                    columns=['BPrev','BStreak','B_Age','B_Height','B_Weight','RPrev','RStreak','R_Age','R_Height','R_Weight'],
                                    dtype=float)
        input_scaled = scaler.transform(input_variables)
        prediction = model.predict(input_scaled)[0][0]
        if np.round(prediction) == 0:
            prediction = "Blue"
        else:
            prediction = "Red"

        if int(R_Weight) < 20:
            prediction = "Invalid Weight"
        elif int(B_Weight) < 20:
            prediction = "Invalid Weight"
        elif int(R_Height) < 20:
            prediction = "Invalid Height"
        elif int(B_Height) < 20:
            prediction = "Invalid Height"
        elif int(R_Age) < 18:
            prediction = "Invalid Age"
        elif int(B_Age) < 18:
            prediction = "Invalid Age"

        return flask.render_template('main.html',
                                      original_input={'R_Weight' :R_Weight,
                                                    'R_Height' :R_Height,
                                                    'R_Age' :R_Age,
                                                    'B_Weight' :B_Weight,
                                                    'B_Height' :B_Height,
                                                    'B_Age' :B_Age
                                                     },
                                     result=prediction
                                     )

@app.route('/logisticregression')
def logreg():
    return(flask.render_template('00_model_logisticsregression.html'))

@app.route('/gridsearch')
def grisea():
    return(flask.render_template('00_model_gridsearch.html'))

@app.route('/deeplearning')
def deelea():
    return(flask.render_template('01_training_model.html'))

@app.route('/viz1')
def viz1():
    return(flask.render_template('00_data_visualization_a.html'))

@app.route('/viz2')
def viz2():
    return(flask.render_template('00_data_visualization_b.html'))

@app.route('/viz3')
def viz3():
    return(flask.render_template('00_data_visualization_c.html'))

@app.route('/trained')
def traine():
    return(flask.render_template('02_notraining_model.html'))

@app.route('/debugging')
def debugg():
    return(flask.render_template('03_debugger.html'))

if __name__ == '__main__':
    app.run(debug=True)
</code>```

The error I see in heroku is:

```<code>2020-05-31T19:43:05.000000+00:00 app[api]: Build succeeded
2020-05-31T19:48:29.426002+00:00 app[web.1]: 10.81.161.51 - - [31/May/2020:19:48:29 +0000] "GET / HTTP/1.1" 200 4710 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
2020-05-31T19:48:29.432446+00:00 heroku[router]: at=info method=GET path="/" host=bcs-final.herokuapp.com request_id=1df55828-886a-45d1-9605-aafd3414f9e3 fwd="71.143.151.112" dyno=web.1 connect=1ms service=56ms status=200 bytes=4872 protocol=https
2020-05-31T19:48:29.623294+00:00 app[web.1]: 10.81.161.51 - - [31/May/2020:19:48:29 +0000] "GET /reset.css HTTP/1.1" 404 232 "https://bcs-final.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
2020-05-31T19:48:29.623792+00:00 heroku[router]: at=info method=GET path="/reset.css" host=bcs-final.herokuapp.com request_id=40816718-e41b-44e9-a3d5-da5ff2030adb fwd="71.143.151.112" dyno=web.1 connect=1ms service=7ms status=404 bytes=400 protocol=https
2020-05-31T19:48:29.625560+00:00 app[web.1]: 10.7.244.15 - - [31/May/2020:19:48:29 +0000] "GET /style.css HTTP/1.1" 404 232 "https://bcs-final.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
2020-05-31T19:48:29.627392+00:00 heroku[router]: at=info method=GET path="/style.css" host=bcs-final.herokuapp.com request_id=bd01a28c-7d1e-4dc6-9a85-405b1bdbb8ea fwd="71.143.151.112" dyno=web.1 connect=1ms service=8ms status=404 bytes=400 protocol=https
2020-05-31T19:48:37.727173+00:00 app[web.1]: [2020-05-31 19:48:37,723] ERROR in app: Exception on / [POST]
2020-05-31T19:48:37.727185+00:00 app[web.1]: Traceback (most recent call last):
2020-05-31T19:48:37.727186+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 2447, in wsgi_app
2020-05-31T19:48:37.727186+00:00 app[web.1]: response = self.full_dispatch_request()
2020-05-31T19:48:37.727187+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1952, in full_dispatch_request
2020-05-31T19:48:37.727215+00:00 app[web.1]: rv = self.handle_user_exception(e)
2020-05-31T19:48:37.727216+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1821, in handle_user_exception
2020-05-31T19:48:37.727217+00:00 app[web.1]: reraise(exc_type, exc_value, tb)
2020-05-31T19:48:37.727218+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
2020-05-31T19:48:37.727218+00:00 app[web.1]: raise value
2020-05-31T19:48:37.727219+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1950, in full_dispatch_request
2020-05-31T19:48:37.727219+00:00 app[web.1]: rv = self.dispatch_request()
2020-05-31T19:48:37.727220+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1936, in dispatch_request
2020-05-31T19:48:37.727220+00:00 app[web.1]: return self.view_functions[rule.endpoint](**req.view_args)
2020-05-31T19:48:37.727221+00:00 app[web.1]: File "/app/app.py", line 36, in main
2020-05-31T19:48:37.727221+00:00 app[web.1]: input_scaled = scaler.transform(input_variables)
2020-05-31T19:48:37.727222+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/sklearn/preprocessing/_data.py", line 794, in transform
2020-05-31T19:48:37.727222+00:00 app[web.1]: force_all_finite='allow-nan')
2020-05-31T19:48:37.727222+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/sklearn/base.py", line 436, in _validate_data
2020-05-31T19:48:37.727223+00:00 app[web.1]: self._check_n_features(X, reset=reset)
2020-05-31T19:48:37.727223+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/sklearn/base.py", line 373, in _check_n_features
2020-05-31T19:48:37.727223+00:00 app[web.1]: "The reset parameter is False but there is no "
2020-05-31T19:48:37.727314+00:00 app[web.1]: RuntimeError: The reset parameter is False but there is no n_features_in_ attribute. Is this estimator fitted?
2020-05-31T19:48:37.728944+00:00 app[web.1]: 10.7.244.15 - - [31/May/2020:19:48:37 +0000] "POST / HTTP/1.1" 500 290 "https://bcs-final.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
2020-05-31T19:48:37.730539+00:00 heroku[router]: at=info method=POST path="/" host=bcs-final.herokuapp.com request_id=2ba8ae51-f913-48d0-9b45-78aef407c15e fwd="71.143.151.112" dyno=web.1 connect=1ms service=27ms status=500 bytes=470 protocol=https
</code>```

答:
Looking at the code I can not say for sure what is the difference between running your app locally vs on heroku. The only sane guess would be that your local env has different version of the lib than the one that is run on heroku.

Anyhow, if we focus on what heroku's version is telling us, your error is coming from this line:

```<code># ...
input_scaled = scaler.transform(input_variables) # <--- here
# ...
</code>```

The error basically says: the estimator - which is actually your scaler (see the source code here) - is not fitted.

The message itself is printed out here and the part saying "n_features_in_ attribute missing" essentially means that your input_variables sparse matrix (in scikit-learn source code referred as X) is missing the attribute n_features_in_. That attribute is set  as part of the fitting process.

Bottom line, invoke fit before transform and that might help. So something like:

```<code>input_scaled = scaler.fit(input_variables).transform(input_variables)
</code>```

Body:
Hi Stackeoverflow Community. I working on a simple project for a class involving hosting a flask app that allows users to input values and get a prediction of who is going to win. Well, in runs OK on our local machines using python flask, but is presenting challenges on heroku. Stumped!

The code is not lengthy or complicated. Also know that we have some opps as well.

our App.py file looks like:

import flask
import tensorflow
import sklearn
import pandas as pd
import numpy as np
from tensorflow import keras
from pickle import load
from load import *

model = init()

scaler = load(open('model/scaler.pkl', 'rb'))
print("Awesome, your scaler has been loaded from disk! Cool beans!")

app = flask.Flask(__name__, template_folder='templates')

@app.route('/', methods=['GET', 'POST'])
def main():
    global model
    if flask.request.method == 'GET':
        return(flask.render_template('main.html'))
    if flask.request.method == 'POST':
        R_Weight = flask.request.form['R_Weight']
        R_Height = flask.request.form['R_Height']
        R_Age = flask.request.form['R_Age']
        B_Weight = flask.request.form['B_Weight']
        B_Height = flask.request.form['B_Height']
        B_Age = flask.request.form['B_Age']
        RPrev = 2.130049
        BPrev = 1.756650
        BStreak = 0.643350
        RStreak = 0.748768
        input_variables = pd.DataFrame([[BPrev, BStreak, B_Age,B_Height,B_Weight,RPrev, RStreak, R_Age,R_Height,R_Weight]],
                                    columns=['BPrev','BStreak','B_Age','B_Height','B_Weight','RPrev','RStreak','R_Age','R_Height','R_Weight'],
                                    dtype=float)
        input_scaled = scaler.transform(input_variables)
        prediction = model.predict(input_scaled)[0][0]
        if np.round(prediction) == 0:
            prediction = "Blue"
        else:
            prediction = "Red"

        if int(R_Weight) < 20:
            prediction = "Invalid Weight"
        elif int(B_Weight) < 20:
            prediction = "Invalid Weight"
        elif int(R_Height) < 20:
            prediction = "Invalid Height"
        elif int(B_Height) < 20:
            prediction = "Invalid Height"
        elif int(R_Age) < 18:
            prediction = "Invalid Age"
        elif int(B_Age) < 18:
            prediction = "Invalid Age"

        return flask.render_template('main.html',
                                      original_input={'R_Weight' :R_Weight,
                                                    'R_Height' :R_Height,
                                                    'R_Age' :R_Age,
                                                    'B_Weight' :B_Weight,
                                                    'B_Height' :B_Height,
                                                    'B_Age' :B_Age
                                                     },
                                     result=prediction
                                     )

@app.route('/logisticregression')
def logreg():
    return(flask.render_template('00_model_logisticsregression.html'))

@app.route('/gridsearch')
def grisea():
    return(flask.render_template('00_model_gridsearch.html'))

@app.route('/deeplearning')
def deelea():
    return(flask.render_template('01_training_model.html'))

@app.route('/viz1')
def viz1():
    return(flask.render_template('00_data_visualization_a.html'))

@app.route('/viz2')
def viz2():
    return(flask.render_template('00_data_visualization_b.html'))

@app.route('/viz3')
def viz3():
    return(flask.render_template('00_data_visualization_c.html'))

@app.route('/trained')
def traine():
    return(flask.render_template('02_notraining_model.html'))

@app.route('/debugging')
def debugg():
    return(flask.render_template('03_debugger.html'))

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

The error I see in heroku is:

2020-05-31T19:43:05.000000+00:00 app[api]: Build succeeded
2020-05-31T19:48:29.426002+00:00 app[web.1]: 10.81.161.51 - - [31/May/2020:19:48:29 +0000] "GET / HTTP/1.1" 200 4710 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
2020-05-31T19:48:29.432446+00:00 heroku[router]: at=info method=GET path="/" host=bcs-final.herokuapp.com request_id=1df55828-886a-45d1-9605-aafd3414f9e3 fwd="71.143.151.112" dyno=web.1 connect=1ms service=56ms status=200 bytes=4872 protocol=https
2020-05-31T19:48:29.623294+00:00 app[web.1]: 10.81.161.51 - - [31/May/2020:19:48:29 +0000] "GET /reset.css HTTP/1.1" 404 232 "https://bcs-final.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
2020-05-31T19:48:29.623792+00:00 heroku[router]: at=info method=GET path="/reset.css" host=bcs-final.herokuapp.com request_id=40816718-e41b-44e9-a3d5-da5ff2030adb fwd="71.143.151.112" dyno=web.1 connect=1ms service=7ms status=404 bytes=400 protocol=https
2020-05-31T19:48:29.625560+00:00 app[web.1]: 10.7.244.15 - - [31/May/2020:19:48:29 +0000] "GET /style.css HTTP/1.1" 404 232 "https://bcs-final.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
2020-05-31T19:48:29.627392+00:00 heroku[router]: at=info method=GET path="/style.css" host=bcs-final.herokuapp.com request_id=bd01a28c-7d1e-4dc6-9a85-405b1bdbb8ea fwd="71.143.151.112" dyno=web.1 connect=1ms service=8ms status=404 bytes=400 protocol=https
2020-05-31T19:48:37.727173+00:00 app[web.1]: [2020-05-31 19:48:37,723] ERROR in app: Exception on / [POST]
2020-05-31T19:48:37.727185+00:00 app[web.1]: Traceback (most recent call last):
2020-05-31T19:48:37.727186+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 2447, in wsgi_app
2020-05-31T19:48:37.727186+00:00 app[web.1]: response = self.full_dispatch_request()
2020-05-31T19:48:37.727187+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1952, in full_dispatch_request
2020-05-31T19:48:37.727215+00:00 app[web.1]: rv = self.handle_user_exception(e)
2020-05-31T19:48:37.727216+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1821, in handle_user_exception
2020-05-31T19:48:37.727217+00:00 app[web.1]: reraise(exc_type, exc_value, tb)
2020-05-31T19:48:37.727218+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
2020-05-31T19:48:37.727218+00:00 app[web.1]: raise value
2020-05-31T19:48:37.727219+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1950, in full_dispatch_request
2020-05-31T19:48:37.727219+00:00 app[web.1]: rv = self.dispatch_request()
2020-05-31T19:48:37.727220+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1936, in dispatch_request
2020-05-31T19:48:37.727220+00:00 app[web.1]: return self.view_functions[rule.endpoint](**req.view_args)
2020-05-31T19:48:37.727221+00:00 app[web.1]: File "/app/app.py", line 36, in main
2020-05-31T19:48:37.727221+00:00 app[web.1]: input_scaled = scaler.transform(input_variables)
2020-05-31T19:48:37.727222+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/sklearn/preprocessing/_data.py", line 794, in transform
2020-05-31T19:48:37.727222+00:00 app[web.1]: force_all_finite='allow-nan')
2020-05-31T19:48:37.727222+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/sklearn/base.py", line 436, in _validate_data
2020-05-31T19:48:37.727223+00:00 app[web.1]: self._check_n_features(X, reset=reset)
2020-05-31T19:48:37.727223+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/sklearn/base.py", line 373, in _check_n_features
2020-05-31T19:48:37.727223+00:00 app[web.1]: "The reset parameter is False but there is no "
2020-05-31T19:48:37.727314+00:00 app[web.1]: RuntimeError: The reset parameter is False but there is no n_features_in_ attribute. Is this estimator fitted?
2020-05-31T19:48:37.728944+00:00 app[web.1]: 10.7.244.15 - - [31/May/2020:19:48:37 +0000] "POST / HTTP/1.1" 500 290 "https://bcs-final.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
2020-05-31T19:48:37.730539+00:00 heroku[router]: at=info method=POST path="/" host=bcs-final.herokuapp.com request_id=2ba8ae51-f913-48d0-9b45-78aef407c15e fwd="71.143.151.112" dyno=web.1 connect=1ms service=27ms status=500 bytes=470 protocol=https

Body:
Looking at the code I can not say for sure what is the difference between running your app locally vs on heroku. The only sane guess would be that your local env has different version of the lib than the one that is run on heroku.

Anyhow, if we focus on what heroku's version is telling us, your error is coming from this line:

# ...
input_scaled = scaler.transform(input_variables) # <--- here
# ...

The error basically says: the estimator - which is actually your scaler (see the source code here) - is not fitted.

The message itself is printed out here and the part saying "n_features_in_ attribute missing" essentially means that your input_variables sparse matrix (in scikit-learn source code referred as X) is missing the attribute n_features_in_. That attribute is set  as part of the fitting process.

Bottom line, invoke fit before transform and that might help. So something like:

input_scaled = scaler.fit(input_variables).transform(input_variables)


问:
Is "types" the equivalent of "main" for TypeScript projects?
From the module resolution docs:

Similarly, a non-relative import will follow the Node.js resolution
  logic, first looking up a file, then looking up an applicable folder.
  So import { b } from "moduleB" in source file /root/src/moduleA.ts
  would result in the following lookups:

/root/src/node_modules/moduleB.ts

/root/src/node_modules/moduleB.tsx

/root/src/node_modules/moduleB.d.ts

/root/src/node_modules/moduleB/package.json (if it specifies a "types" property)

/root/src/node_modules/@types/moduleB.d.ts

/root/src/node_modules/moduleB/index.ts

/root/src/node_modules/moduleB/index.tsx

/root/src/node_modules/moduleB/index.d.ts

So TypeScript doesn't seem to take the "main" property into account  (as Node.js does), but it does look for "types". Are they equivalent, or does the latter only import *.d.ts files?

答: I think you are talking about properties of a package.json file. If this is the case, as you guessed, types is an entry used by TypeScript to load the typing (and only the typing) of the module. The main entry is still required to load the JavaScript side of the module.


问:
Which Result Content types are valid for discovery and which are valid for non-discovery retrieves?
The oneM2M specs (various versions) seem to be very unclear about what should be returned for various combinations of rcn & fu flags.

can some please clarify? possibly with pointers to spec sections?

for example:

In TS-0001 v2.27, section 8.1.2, the only 'Result Content' type description that mentions discovery is child-resource-references which says "This option can be used within the context of resource discovery mechanisms". Does this imply that none of the other Result Content types can be used within the context of resource discovery mechanisms, since their descriptions do not explicitly allow this?

If that is the case, then why does TS-0004, section (7.2.1.2) talk about both URIList and resourceRefList in Discovery responses? These two things seem to be in conflict.

答:
You may have a look at TS-0001 v4.4.0 table 8.1.2-1 "Summary of Result Content Values". This table, and the text above it, gives an overview about which result content types are allowed for which request type.

Some of the RCN types return just references (or attributes + references). In this case some resource attributes as well as a list of URI's (resource ID's) is returned.