问:
Chakra UI: Responsive Toast Notifications
I'm using chakra UI for my application and this is the code block I'm calling to display the notification.

```<code>const successToast = useToast({
    title: 'Logged In',
    description: "Waiting for developers to build redirect pages",
    status: 'success',
    duration: 5000,
    isClosable: true,
    position: "bottom-right",
  })
</code>```

Chakra offers a way to handle responsive designs: https://chakra-ui.com/docs/features/responsive-styles. So I want the notification to be shown on top when using a mobile device. For which I tried doing:

```<code>position: {base: 'top-right', lg:'bottom-right'}
</code>```

But I get error saying:

```<code>(property) UseToastOptions.position?: ToastPositionWithLogical | undefined
The placement of the toast

@default

"bottom"
Type '{ base: string; lg: string; }' is not assignable to type 'ToastPositionWithLogical | undefined'.
  Type '{ base: string; lg: string; }' is not assignable to type '"bottom-right"'.
</code>```

Previously when I used this method to make other design elements it worked. How do I fix it or make it responsive for this.

Toast Notification Docs: https://chakra-ui.com/docs/feedback/toast

答:
You could use the useBreakpointValue hook.

const position = useBreakpointValue({ base: 'top-right', mlg: 'bottom-right' }) as any;

function displayToast(){
    const successToast = useToast({
    // [...]
    position: position,
  })
}
```

Edit: Added as any as position accepts only ToastPositionWithLogical

Body:
I'm using chakra UI for my application and this is the code block I'm calling to display the notification.

const successToast = useToast({
    title: 'Logged In',
    description: "Waiting for developers to build redirect pages",
    status: 'success',
    duration: 5000,
    isClosable: true,
    position: "bottom-right",
  })

Chakra offers a way to handle responsive designs: https://chakra-ui.com/docs/features/responsive-styles. So I want the notification to be shown on top when using a mobile device. For which I tried doing:

position: {base: 'top-right', lg:'bottom-right'}

But I get error saying:

(property) UseToastOptions.position?: ToastPositionWithLogical | undefined
The placement of the toast

@default

"bottom"
Type '{ base: string; lg: string; }' is not assignable to type 'ToastPositionWithLogical | undefined'.
  Type '{ base: string; lg: string; }' is not assignable to type '"bottom-right"'.

Previously when I used this method to make other design elements it worked. How do I fix it or make it responsive for this.

Toast Notification Docs: https://chakra-ui.com/docs/feedback/toast

Body:
You could use the useBreakpointValue hook.

const position = useBreakpointValue({ base: 'top-right', mlg: 'bottom-right' }) as any;

function displayToast(){
    const successToast = useToast({
    // [...]
    position: position,
  })
}

Edit: Added as any as position accepts only ToastPositionWithLogical


来源: stackexchange

问:
getting 'System.Text.Json.JsonElement' does not contain 'result' Parsing with JsonSerializer.DeserializeAsync
I have JSON in a response structured like this

```<code>{
   "statusCode": 200,
   "result": {
      "generalInfo": {
         "firstName": "",
         "lastName": ""
      },
      "isError": false
   },
   "sentDate": "2022-02-06T10:04:06.6853775Z",
}

var response = await _httpClient.PostAsJsonAsync(address, model);
Stream responseBody = await response.Content.ReadAsStreamAsync();

</code>```

The response from the endpoint is actually a bit more complex and I want to extract only specific fields so I used dynamic

```<code>dynamic data = await JsonSerializer.DeserializeAsync<dynamic>(responseBody)

var dataString = data.ToString();
</code>```

// dataString  is

```<code>{"result":{"generalInfo":{"firstName":"John","lastName":"Doe"},"isError":false}
</code>```

If I try to access dynamic properties like this

```<code>var firstName = data.result.generalInfo.firstName;
var lastName = data.result.generalInfo.lastName;
var isErr = data.IsError;
</code>```

I'm getting exception

'System.Text.Json.JsonElement' does not contain a definition for
'result'

答:
The problem is not DeserializeAsync, but that System.Text.Json uses JsonElements, so the dynamic value is actually a JsonElement. You'll need to parse the data from the JsonElement.

However, if you're using .Net 6 you can use JsonNode:

```<code>// deserialize into JsonNode
JsonNode data = await JsonSerializer.DeserializeAsync<JsonNode>(responseBody);
// OR parse the json string
JsonNode data = JsonNode.Parse(dataString);

int statusCode = (int)data["statusCode"];
var firstName = (string)data["result"]["generalInfo"]["firstName"];
var lastName = (string)data["result"]["generalInfo"]["lastName"];
var isErr = (bool)data["result"]["isError"];
</code>```

Demo in .Net6

Support for dynamic was added to .Net 6 preview v4-6 but was removed before final release in favour of the JsonNode approach above. See github What's new in .NET 6 Preview 7 for further details.

Otherwise, you could parse it manually:

```<code>bool isError = false;
string firstName = "";
string lastName = "";
if (data is JsonElement elt && elt.TryGetProperty("result", out elt))
{
    isError = elt.TryGetProperty("isError", out JsonElement boolElt) ? boolElt.GetBoolean() : false;
    if (elt.TryGetProperty("generalInfo", out var genInfo))
    {
        firstName = genInfo.TryGetProperty("firstName", out var firstElt) ? firstElt.GetString() : "";
        lastName = genInfo.TryGetProperty("lastName", out var lastElt) ? lastElt.GetString() : "";
    }
}
</code>```

However, my preferred approach is always to deserialize into defined classes if you can as it makes life much easier:

```<code>public class GeneralInfo
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}

public class Result
{
    public GeneralInfo generalInfo { get; set; }
    public bool isError { get; set; }
}

public class Root
{
    public Result result { get; set; }
}

var data = await JsonSerializer.DeserializeAsync<Root>(responseBody);
var firstName = data.result.generalInfo.firstName;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have JSON in a response structured like this

{
   "statusCode": 200,
   "result": {
      "generalInfo": {
         "firstName": "",
         "lastName": ""
      },
      "isError": false
   },
   "sentDate": "2022-02-06T10:04:06.6853775Z",
}

var response = await _httpClient.PostAsJsonAsync(address, model);
Stream responseBody = await response.Content.ReadAsStreamAsync();

The response from the endpoint is actually a bit more complex and I want to extract only specific fields so I used dynamic

dynamic data = await JsonSerializer.DeserializeAsync<dynamic>(responseBody)

var dataString = data.ToString();

// dataString  is

{"result":{"generalInfo":{"firstName":"John","lastName":"Doe"},"isError":false}

If I try to access dynamic properties like this

var firstName = data.result.generalInfo.firstName;
var lastName = data.result.generalInfo.lastName;
var isErr = data.IsError;

I'm getting exception

'System.Text.Json.JsonElement' does not contain a definition for
'result'

Body:
The problem is not DeserializeAsync, but that System.Text.Json uses JsonElements, so the dynamic value is actually a JsonElement. You'll need to parse the data from the JsonElement.

However, if you're using .Net 6 you can use JsonNode:

// deserialize into JsonNode
JsonNode data = await JsonSerializer.DeserializeAsync<JsonNode>(responseBody);
// OR parse the json string
JsonNode data = JsonNode.Parse(dataString);

int statusCode = (int)data["statusCode"];
var firstName = (string)data["result"]["generalInfo"]["firstName"];
var lastName = (string)data["result"]["generalInfo"]["lastName"];
var isErr = (bool)data["result"]["isError"];

Demo in .Net6

Support for dynamic was added to .Net 6 preview v4-6 but was removed before final release in favour of the JsonNode approach above. See github What's new in .NET 6 Preview 7 for further details.

Otherwise, you could parse it manually:

bool isError = false;
string firstName = "";
string lastName = "";
if (data is JsonElement elt && elt.TryGetProperty("result", out elt))
{
    isError = elt.TryGetProperty("isError", out JsonElement boolElt) ? boolElt.GetBoolean() : false;
    if (elt.TryGetProperty("generalInfo", out var genInfo))
    {
        firstName = genInfo.TryGetProperty("firstName", out var firstElt) ? firstElt.GetString() : "";
        lastName = genInfo.TryGetProperty("lastName", out var lastElt) ? lastElt.GetString() : "";
    }
}

However, my preferred approach is always to deserialize into defined classes if you can as it makes life much easier:

public class GeneralInfo
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}

public class Result
{
    public GeneralInfo generalInfo { get; set; }
    public bool isError { get; set; }
}

public class Root
{
    public Result result { get; set; }
}

var data = await JsonSerializer.DeserializeAsync<Root>(responseBody);
var firstName = data.result.generalInfo.firstName;


问:
HttpRequest.RouteValues property is not accessible from code but accessible from debugger
I am trying to create middleware which performs some checking for particular requests.

For example, I have such routes:

api/Test/{paramToCheck}/aaa

api/Test/bbb/ccc

and I have these requests:

http://some-host-and-port/api/Test/1234/aaa

http://some-host-and-port/api/Test/bbb/ccc

Now inside my middleware I want to check if request contains {paramToCheck} and get value of this parameter.

When I set breakpoint inside InvokeAsync I can see httpContext.Request.RouteValues property containing all needed data (Keys contains "paramToCheck" and Values contains its value).

But in code I can't access this property, I get error:

Error CS1061: 'HttpRequest' does not contain a definition for
  'RouteValues' and no accessible extension method 'RouteValues'
  accepting a first argument of type 'HttpRequest' could be found (are
  you missing a using directive or an assembly reference?)

var value = httpContext.Request.RouteValues["paramToCheck"];

How can I access this property or how can I perform needed check?

Code:

```<code>public class MyMiddleware
{
    private readonly RequestDelegate _next;

    public MyMiddleware
    (
        RequestDelegate next
    ) => this._next = next;

    public async Task InvokeAsync(HttpContext httpContext)
    {
        var value = httpContext.Request.RouteValues["paramToCheck"]; // error here

        //... some logis with value

        await this._next(httpContext);
    }
}
</code>```

EDIT

Middleware is inside netstandard2.1 class library and it cannot be moved to api project as it is common and should be used by several api projects.

UPDATE

Seems like currently it cannot be achieved as RouteValues propery was added in Microsoft.AspNetCore.Http.Abstractions 3.0.0 which is inside NetCoreApp 3 metapackage. And there is no possibility to install this package in netstandard 2.1 project because the latest version is 2.2.0.

答:
Alexander Ivanov's answer:

```<code>routeValues = ((dynamic)context.Request).RouteValues as IReadOnlyDictionary<string, object>;
</code>```

worked for me, thanks! It took me a little to get it working, however, as the following packages were required:

Microsoft.AspNetCore.Http.Abstractions

Microsoft.CSharp

Including this additional information in the hopes it saves someone some time.

Body:
I am trying to create middleware which performs some checking for particular requests.

For example, I have such routes:

api/Test/{paramToCheck}/aaa

api/Test/bbb/ccc

and I have these requests:

http://some-host-and-port/api/Test/1234/aaa

http://some-host-and-port/api/Test/bbb/ccc

Now inside my middleware I want to check if request contains {paramToCheck} and get value of this parameter.

When I set breakpoint inside InvokeAsync I can see httpContext.Request.RouteValues property containing all needed data (Keys contains "paramToCheck" and Values contains its value).

But in code I can't access this property, I get error:

Error CS1061: 'HttpRequest' does not contain a definition for
  'RouteValues' and no accessible extension method 'RouteValues'
  accepting a first argument of type 'HttpRequest' could be found (are
  you missing a using directive or an assembly reference?)

var value = httpContext.Request.RouteValues["paramToCheck"];

How can I access this property or how can I perform needed check?

Code:

public class MyMiddleware
{
    private readonly RequestDelegate _next;

    public MyMiddleware
    (
        RequestDelegate next
    ) => this._next = next;

    public async Task InvokeAsync(HttpContext httpContext)
    {
        var value = httpContext.Request.RouteValues["paramToCheck"]; // error here

        //... some logis with value

        await this._next(httpContext);
    }
}

EDIT

Middleware is inside netstandard2.1 class library and it cannot be moved to api project as it is common and should be used by several api projects.

UPDATE

Seems like currently it cannot be achieved as RouteValues propery was added in Microsoft.AspNetCore.Http.Abstractions 3.0.0 which is inside NetCoreApp 3 metapackage. And there is no possibility to install this package in netstandard 2.1 project because the latest version is 2.2.0.

Body:
Alexander Ivanov's answer:

routeValues = ((dynamic)context.Request).RouteValues as IReadOnlyDictionary<string, object>;

worked for me, thanks! It took me a little to get it working, however, as the following packages were required:

Microsoft.AspNetCore.Http.Abstractions

Microsoft.CSharp

Including this additional information in the hopes it saves someone some time.


问:
How to convert the apps script's onEdit function into a regular function?
I am using the following onEdit function to fetch color from cells and apply it to Main Sheet's column B values that match the content of the colored cell in another sheet (Settings). How can I convert this into a regular function? So, I can call it to go through all the rows/ cells of column B to apply the respective color at once.

Also, I want to specify the Main Sheet's column B start and end point (row) in the Settings Sheet's cell F1 and G1. For example: Apply colors to row 4 to 50 of the Main Sheet only and then terminate.

F
G

4
50

Please view the attached sheet for reference:
https://docs.google.com/spreadsheets/d/1UmHU76ZOoHhB-8HyHrY2ESZAjUpTq2FKkGFmGXNEQ2o/edit?usp=sharing

Code provided by @Tanaike

```<code>function onEdit(e){
if(e.source.getActiveSheet().getName() == "MAIN"){

  const {range, source, value} = e;
  const sheet = range.getSheet();
  if (sheet.getSheetName() != "MAIN" || range.columnStart != 2 || range.rowStart == 2) return;
  const settingSheet = source.getSheetByName("SETTINGS")
  const r = settingSheet.getRange("B5:C11" + settingSheet.getLastRow());
  const colors = r.getBackgrounds();
  const obj = r.getValues().reduce((o, [b], i) => (o[b] = colors[i][1], o), {});
  range.setBackground(obj[value] || null);
  }
}
</code>```

答:
I believe your goal is as follows.

You want to convert your script without using onEdit. And, you want to retrieve the values from "F1:G1" of "SETTINGS" sheet as the start and end rows of the column "B" of "MAIN" sheet.

In this case, how about the following modification?

Modified script:

function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const [main, settingSheet] = ["MAIN", "SETTINGS"].map(s => ss.getSheetByName(s));
  const [start, end] = settingSheet.getRange("F1:G1").getValues()[0];
  const range = main.getRange(`B${start}:B${end}`);
  const r = settingSheet.getRange("B5:C" + settingSheet.getLastRow());
  const colors = r.getBackgrounds();
  const obj = r.getValues().reduce((o, [b], i) => (o[b] = colors[i][1], o), {});
  const bk = range.getValues().map(([value]) => [obj[value] || null]);
  range.setBackgrounds(bk);
}
```

Body:
I am using the following onEdit function to fetch color from cells and apply it to Main Sheet's column B values that match the content of the colored cell in another sheet (Settings). How can I convert this into a regular function? So, I can call it to go through all the rows/ cells of column B to apply the respective color at once.

Also, I want to specify the Main Sheet's column B start and end point (row) in the Settings Sheet's cell F1 and G1. For example: Apply colors to row 4 to 50 of the Main Sheet only and then terminate.

F
G

4
50

Please view the attached sheet for reference:
https://docs.google.com/spreadsheets/d/1UmHU76ZOoHhB-8HyHrY2ESZAjUpTq2FKkGFmGXNEQ2o/edit?usp=sharing

Code provided by @Tanaike

function onEdit(e){
if(e.source.getActiveSheet().getName() == "MAIN"){

  const {range, source, value} = e;
  const sheet = range.getSheet();
  if (sheet.getSheetName() != "MAIN" || range.columnStart != 2 || range.rowStart == 2) return;
  const settingSheet = source.getSheetByName("SETTINGS")
  const r = settingSheet.getRange("B5:C11" + settingSheet.getLastRow());
  const colors = r.getBackgrounds();
  const obj = r.getValues().reduce((o, [b], i) => (o[b] = colors[i][1], o), {});
  range.setBackground(obj[value] || null);
  }
}


问:
StaggeredGridView is undefined
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; //import libray

flutter_staggered_grid_view: ^0.5.0 // package

```<code>    Flexible(
      child: Container(
        padding: EdgeInsets.only(top: 16.0, right: 16.0, left: 16.0),
        child: StaggeredGridView.countBuilder(
          physics: NeverScrollableScrollPhysics(),
          padding: EdgeInsets.zero,
          crossAxisCount: 4,
          itemCount: products.length,
          itemBuilder: (BuildContext context, int index) => new ClipRRect(
            borderRadius: BorderRadius.all(Radius.circular(5.0)),
            child: InkWell(
              onTap: () => Navigator.of(context).push(MaterialPageRoute(
                  builder: (_) => ProductPage(product: products[index]))),
              child: Container(
                  decoration: BoxDecoration(
                    gradient: RadialGradient(
                        colors: [
                          Colors.grey.withOpacity(0.3),
                          Colors.grey.withOpacity(0.7),
                        ],
                        center: Alignment(0, 0),
                        radius: 0.6,
                        focal: Alignment(0, 0),
                        focalRadius: 0.1),
                  ),
                  child: Hero(
                      tag: products[index].image,
                      child: Image.asset(products[index].image))),
            ),
          ),
          staggeredTileBuilder: (int index) =>
              StaggeredTile.count(2, index.isEven ? 3 : 2),
          mainAxisSpacing: 4.0,
          crossAxisSpacing: 4.0,
        ),
      ),
    ),
</code>```

Error:

lib/screens/main/components/recommended_list.dart:51:20: Error: The getter 'StaggeredGridView' isn't defined for the class 'RecommendedList'.

'RecommendedList' is from 'package:mobi_zilla/screens/main/components/recommended_list.dart' ('lib/screens/main/components/recommended_list.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'StaggeredGridView'.
child: StaggeredGridView.countBuilder(
^^^^^^^^^^^^^^^^^
lib/screens/main/components/recommended_list.dart:79:19: Error: The getter 'StaggeredTile' isn't defined for the class 'RecommendedList'.

'RecommendedList' is from 'package:mobi_zilla/screens/main/components/recommended_list.dart' ('lib/screens/main/components/recommended_list.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'StaggeredTile'.
StaggeredTile.count(2, index.isEven ? 3 : 2),
^^^^^^^^^^^^^

答: The pub.dev documentation for the plugin doesn't suggest anything about the method being deprecated or scrapped in the latest version i.e flutter_staggered_grid_view 0.6.1. I tried using flutter_staggered_grid_view: ^0.4.0 but that didn't work either. The workaround seems to be to use version 0.3.1 which then recognized the StaggeredGridView method.

Title: StaggeredGridView is undefined

Body:
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; //import libray

flutter_staggered_grid_view: ^0.5.0 // package

    Flexible(
      child: Container(
        padding: EdgeInsets.only(top: 16.0, right: 16.0, left: 16.0),
        child: StaggeredGridView.countBuilder(
          physics: NeverScrollableScrollPhysics(),
          padding: EdgeInsets.zero,
          crossAxisCount: 4,
          itemCount: products.length,
          itemBuilder: (BuildContext context, int index) => new ClipRRect(
            borderRadius: BorderRadius.all(Radius.circular(5.0)),
            child: InkWell(
              onTap: () => Navigator.of(context).push(MaterialPageRoute(
                  builder: (_) => ProductPage(product: products[index]))),
              child: Container(
                  decoration: BoxDecoration(
                    gradient: RadialGradient(
                        colors: [
                          Colors.grey.withOpacity(0.3),
                          Colors.grey.withOpacity(0.7),
                        ],
                        center: Alignment(0, 0),
                        radius: 0.6,
                        focal: Alignment(0, 0),
                        focalRadius: 0.1),
                  ),
                  child: Hero(
                      tag: products[index].image,
                      child: Image.asset(products[index].image))),
            ),
          ),
          staggeredTileBuilder: (int index) =>
              StaggeredTile.count(2, index.isEven ? 3 : 2),
          mainAxisSpacing: 4.0,
          crossAxisSpacing: 4.0,
        ),
      ),
    ),

Error:

lib/screens/main/components/recommended_list.dart:51:20: Error: The getter 'StaggeredGridView' isn't defined for the class 'RecommendedList'.

'RecommendedList' is from 'package:mobi_zilla/screens/main/components/recommended_list.dart' ('lib/screens/main/components/recommended_list.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'StaggeredGridView'.
child: StaggeredGridView.countBuilder(
^^^^^^^^^^^^^^^^^
lib/screens/main/components/recommended_list.dart:79:19: Error: The getter 'StaggeredTile' isn't defined for the class 'RecommendedList'.

'RecommendedList' is from 'package:mobi_zilla/screens/main/components/recommended_list.dart' ('lib/screens/main/components/recommended_list.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'StaggeredTile'.
StaggeredTile.count(2, index.isEven ? 3 : 2),
^^^^^^^^^^^^^


问:
The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined
I'm trying to upload a file (pdf/jpg) using a Lambda function written in NodeJS by triggering the request from Postman but I'm getting the following error:-

```<code>2022-02-02T15:09:51.135Z    743939db-7511-4003-8e49-40c95ada47b4    ERROR   Invoke Error
{
    "errorType": "TypeError",
    "errorMessage": "The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined",
    "code": "ERR_INVALID_ARG_TYPE",
    "stack": [
        "TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined",
        "    at new NodeError (internal/errors.js:322:7)",
        "    at Function.from (buffer.js:334:9)",
        "    at Runtime.exports.lambdaHandler [as handler] (/var/task/app.js:68:23)"
    ]
}
</code>```

The following is a chunk of event object getting logged on the CloudWatch:-

```<code>2022-02-02T20:39:52.136+05:30

Copy
info: Event:: {"body":"{\n    \"base64String\": \"/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAcHBwcIBwgJCQgMDAsMDBEQDg4QERoSFBIUEhonGB0YGB0YJyMqIiAiKiM+MSsrMT5IPDk8SFdOTldtaG2Pj8ABBwcHBwgHCAkJCAwMCwwMERAODhARGhIUEhQSGicYHRgYHRgnIyoiICIqIz4xKysxPkg8OTxIV05OV21obY+PwP/CABEICHAPAAMBIgACEQEDEQH/xAAcAAEAAgMBAQEAAAAAAAAAAAAABwgBBQYEAwL/2gAIAQEAAAAAsiAA
</code>```

Lambda (NodeJS code):-

```<code>'use-strict'

const AWS = require("aws-sdk");

const logger = require('./logger').logger;

const moment = require('moment');

const fileType = ('file-type');

const { Buffer } = require('buffer');

//const { fileTypeFromFile } = 'file-type';

const ddbTable = process.env.RUNTIME_DDB_TABLE_FREE_USER_DOCUMENT;

const s3TempBucket = process.env.RUNTIME_S3_TEMP_BUCKET;

const s3 = new AWS.S3();

const getFile = (fileMime, buffer, userId) => {
  let fileExt = fileMime.ext;
  let hash = sha1(new Buffer(new Date().toString()));
  let now = moment().format('YYYY-MM-DD HH:mm:ss');

  let filePath = hash + '/';
  let fileName = unixTime(now) + '.' + fileExt;
  let fileFullName = filePath + fileName;
  let fileFullPath = s3TempBucket + userId + fileFullName;

  const params = {
    Body: buffer,
    Bucket: s3TempBucket,
    Key: fileName
  };

  let uploadFile = {
    size: buffer.toString('ascii').length,
    type: fileMime.mime,
    name: fileName,
    fullPath: fileFullPath
  }

  return {
    'params': params,
    'uploadFile': uploadFile
  }
}

exports.lambdaHandler = async (event, context) => {
  logger.info("Event::", event);
  logger.info('Uploading file to bucket::', s3TempBucket);

  let body, data;
  let statusCode = 200;
  const headers = {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': '*'
  };

  let request = JSON.parse(event.body);
  let base64String = await request.base64String;
  logger.info("base64String::", base64String);

  let buffer = Buffer.from(base64String, 'base64');

  //let buffer = new Buffer(base64String, 'base64');
  let fileMime = fileType(buffer);
  logger.info(fileMime);

  if (fileMime === null) {
    return context.fail('String supplied is not file type');
  }

  //let file = getFile(fileMime, buffer, user.id);
  let file = getFile(fileMime, buffer, 'b06eb6f4-0ff0-5cb5-a41c-e000af66c8e9');
  let params = file.params;

  try {
    //await new Promise((resolve, reject) => {
      s3.putObject(params, (err, results) => {
        if (err) reject(err);
        else {
          console.log(results);
          body = results;
          resolve(results)
        }
      });
   // });

  } catch (err) {
    logger.info(err);
    statusCode = 400;
    body = err.message;
    return err;
  } finally {
    body = JSON.stringify(data);
  }

  return {
    statusCode,
    body,
    headers
  };

}
</code>```

The base64String is coming as undefined not sure why as I can see clearly in the event object?:-

```<code>let buffer = Buffer.from(base64String, 'base64');
</code>```

Please assist, thanks

Postman request:-

答:
If you use API Gateway, you don't need base64 encode because API Gateway does automatically.

A sample is provided in AWS.

Select Create function

Select Browse serverless app repository

Find "uploader: Serverless web application for uploading files to
S3"

Deploy

uploader's github

This creates API gateway and NodeJS Lambda. (You need to provide S3 bucket.)

The instruction says that to upload a file, open InvokeURL in browser and drag drop a file. You can do this with Postman too as follows.

Input POST InvokeURL/api/file/text.pdf.

Set body KEY to File and input text.pdf. Select the pdf file as VALUE.

Send

You can find the code in index.js and extract what you need.

Body:
I'm trying to upload a file (pdf/jpg) using a Lambda function written in NodeJS by triggering the request from Postman but I'm getting the following error:-

2022-02-02T15:09:51.135Z    743939db-7511-4003-8e49-40c95ada47b4    ERROR   Invoke Error
{
    "errorType": "TypeError",
    "errorMessage": "The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined",
    "code": "ERR_INVALID_ARG_TYPE",
    "stack": [
        "TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined",
        "    at new NodeError (internal/errors.js:322:7)",
        "    at Function.from (buffer.js:334:9)",
        "    at Runtime.exports.lambdaHandler [as handler] (/var/task/app.js:68:23)"
    ]
}

The following is a chunk of event object getting logged on the CloudWatch:-

2022-02-02T20:39:52.136+05:30

Copy
info: Event:: {"body":"{\n    \"base64String\": \"/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAcHBwcIBwgJCQgMDAsMDBEQDg4QERoSFBIUEhonGB0YGB0YJyMqIiAiKiM+MSsrMT5IPDk8SFdOTldtaG2Pj8ABBwcHBwgHCAkJCAwMCwwMERAODhARGhIUEhQSGicYHRgYHRgnIyoiICIqIz4xKysxPkg8OTxIV05OV21obY+PwP/CABEICHAPAAMBIgACEQEDEQH/xAAcAAEAAgMBAQEAAAAAAAAAAAAABwgBBQYEAwL/2gAIAQEAAAAAsiAA

Lambda (NodeJS code):-

'use-strict'

const AWS = require("aws-sdk");

const logger = require('./logger').logger;

const moment = require('moment');

const fileType = ('file-type');

const { Buffer } = require('buffer');

//const { fileTypeFromFile } = 'file-type';

const ddbTable = process.env.RUNTIME_DDB_TABLE_FREE_USER_DOCUMENT;

const s3TempBucket = process.env.RUNTIME_S3_TEMP_BUCKET;

const s3 = new AWS.S3();

const getFile = (fileMime, buffer, userId) => {
  let fileExt = fileMime.ext;
  let hash = sha1(new Buffer(new Date().toString()));
  let now = moment().format('YYYY-MM-DD HH:mm:ss');

  let filePath = hash + '/';
  let fileName = unixTime(now) + '.' + fileExt;
  let fileFullName = filePath + fileName;
  let fileFullPath = s3TempBucket + userId + fileFullName;

  const params = {
    Body: buffer,
    Bucket: s3TempBucket,
    Key: fileName
  };

  let uploadFile = {
    size: buffer.toString('ascii').length,
    type: fileMime.mime,
    name: fileName,
    fullPath: fileFullPath
  }

  return {
    'params': params,
    'uploadFile': uploadFile
  }
}

exports.lambdaHandler = async (event, context) => {
  logger.info("Event::", event);
  logger.info('Uploading file to bucket::', s3TempBucket);

  let body, data;
  let statusCode = 200;
  const headers = {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': '*'
  };

  let request = JSON.parse(event.body);
  let base64String = await request.base64String;
  logger.info("base64String::", base64String);

  let buffer = Buffer.from(base64String, 'base64');

  //let buffer = new Buffer(base64String, 'base64');
  let fileMime = fileType(buffer);
  logger.info(fileMime);

  if (fileMime === null) {
    return context.fail('String supplied is not file type');
  }

  //let file = getFile(fileMime, buffer, user.id);
  let file = getFile(fileMime, buffer, 'b06eb6f4-0ff0-5cb5-a41c-e000af66c8e9');
  let params = file.params;

  try {
    //await new Promise((resolve, reject) => {
      s3.putObject(params, (err, results) => {
        if (err) reject(err);
        else {
          console.log(results);
          body = results;
          resolve(results)
        }
      });
   // });

  } catch (err) {
    logger.info(err);
    statusCode = 400;
    body = err.message;
    return err;
  } finally {
    body = JSON.stringify(data);
  }

  return {
    statusCode,
    body,
    headers
  };

}

The base64String is coming as undefined not sure why as I can see clearly in the event object?:-

let buffer = Buffer.from(base64String, 'base64');

Please assist, thanks

Postman request:-


问:
Observe runs multiple times on button click for the second time
I have this code in an activity SignInActivity:

```<code>signInButton.setOnClickListener{
            val query: HashMap<String, String> = HashMap()
            query["email"] = signInEmail.text.toString()
            query["password"] = signInPassword.text.toString()
            signInViewModel.getAuthToken(query)
            signInViewModel.signInResponse.observe(this, {
                response->  when(response){
                is NetworkResult.Success ->{
                    response.data?.let { Toast.makeText(this, it.access, Toast.LENGTH_SHORT).show()}
                }

                is NetworkResult.Error ->{
                    Toast.makeText(this, response.message.toString(), Toast.LENGTH_SHORT).show()
                }

                is NetworkResult.Loading -> {

                }
                }
            })

        }
</code>```

Let's suppose in the first try I wrote my password wrong and it only runs once, but then after that if I click it again it runs multiple time by creating multiple toasts in this example.

答:
Like @gpunto says, you're adding a new Observer every click, so they're stacking up and each one fires when the LiveData updates.

But really, the observer doesn't have anything to do with the actual click anyway, it just receives updates to signInResponse and displays a thing. The click just calls getAuthToken with the current query. If doing that happens to cause a signInResponse update, then you have everything wired up to react to that event. But the Activity doesn't need to know how all that stuff works, or be written so one thing follows another.

That's a reactive pattern, where your UI is really just sending events (like getAuthToken when there's a click) and then reacting to other events so it can display them. By separating these things, you get a simple system that Just Works, and can react to updates no matter what caused them (e.g. a click, or restoring state) without having to write code to handle each case.

That said, this is a slightly tricky case because you have an event you want to consume. If you just set up that observer on signInResponse, it will fire every time you get a value for that LiveData. And that includes when the Activity is recreated (e.g. on rotation), observes the LiveData, and gets the current (last-set) value. Basically, if you show a Toast, the same Toast will appear every time the Activity is recreated. That would be fine for setting the current value on a TextView, but it's bad for a popup that should only appear once.

This is the current official recommendation for handling this situation. They're creating a UI state, which basically holds everything that needs to be displayed, including any popup messages (which acts like a queue, which is useful!). When the UI displays a message, it basically tells the ViewModel it's done so, and that handles removing the message from the state.

You could just implement this your own way, even if it's something simple like a clearResponse() function in your VM that clears the current value when you've seen it. It really depends on your app and what state you need to maintain. Here's some other examples from the Android devs - but like it says at the top, this advice is deprecated following the recommendations I linked earlier

Body:
I have this code in an activity SignInActivity:

signInButton.setOnClickListener{
            val query: HashMap<String, String> = HashMap()
            query["email"] = signInEmail.text.toString()
            query["password"] = signInPassword.text.toString()
            signInViewModel.getAuthToken(query)
            signInViewModel.signInResponse.observe(this, {
                response->  when(response){
                is NetworkResult.Success ->{
                    response.data?.let { Toast.makeText(this, it.access, Toast.LENGTH_SHORT).show()}
                }

                is NetworkResult.Error ->{
                    Toast.makeText(this, response.message.toString(), Toast.LENGTH_SHORT).show()
                }

                is NetworkResult.Loading -> {

                }
                }
            })

        }

Let's suppose in the first try I wrote my password wrong and it only runs once, but then after that if I click it again it runs multiple time by creating multiple toasts in this example.


问:
native-image says "unknown type name 'uint8_t'" during compilation
I'm getting this error:

```<code>$ native-image -jar foo.jar bin/java-Objects.bin
...
[bin/java-Objects.bin:24855]    classlist:   1,143.29 ms,  0.96 GB
[bin/java-Objects.bin:24855]        (cap):   1,803.60 ms,  0.96 GB
[bin/java-Objects.bin:24855]        setup:   2,304.75 ms,  0.96 GB
Error: Error compiling query code (in /var/folders/vl/633jwjvn2jvbj9zfg1sgglhw0000gp/T/SVM-3396448792019069231/PosixDirectives.c). Compiler command '/usr/bin/cc -Wall -Werror -ObjC -o /var/folders/vl/633jwjvn2jvbj9zfg1sgglhw0000gp/T/SVM-3396448792019069231/PosixDirectives /var/folders/vl/633jwjvn2jvbj9zfg1sgglhw0000gp/T/SVM-3396448792019069231/PosixDirectives.c' output included error: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.1.sdk/usr/include/sys/resource.h:202:2:
error: unknown type name 'uint8_t'
</code>```

I'm with Clang:

```<code>$ clang --version
Homebrew clang version 13.0.0
Target: x86_64-apple-darwin20.6.0
Thread model: posix
InstalledDir: /usr/local/opt/llvm/bin
</code>```

It seems that the problem is with this code in sys/resource.h:

```<code>#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL
#include <stdint.h>
#endif /* __DARWIN_C_LEVEL >= __DARWIN_C_FULL */
</code>```

This line with stdint.h doesn't get included and that's why uint8_t doesn't get defined.

答:
Possible solution

Please, consider trying to follow the instruction from quarkus/faq.adoc at main · quarkusio/quarkus:

1. Native compilation

Native executable fails on macOS with error: unknown type name 'uint8_t'

Your macOS has the wrong *.h files compared to the OS and no gcc compilation will work. This can happen when you migrate from versions of the OS. See Cannot compile any C++ programs; error: unknown type name 'uint8_t'

The solution is to

sudo mv /usr/local/include /usr/local/include.old

Reinstall XCode for good measure

(optional?) brew install llvm

generally reinstall your brew dependencies with native compilation

The executable should work now.

The purpose of (the idea behind) renaming the include directory (from include to include.old) seems to be explained in the answer.

Additional references

Related question. May contain some possible solutions. Broken c++ std libraries on macOS High Sierra 10.13 - Stack Overflow.

Body:
I'm getting this error:

$ native-image -jar foo.jar bin/java-Objects.bin
...
[bin/java-Objects.bin:24855]    classlist:   1,143.29 ms,  0.96 GB
[bin/java-Objects.bin:24855]        (cap):   1,803.60 ms,  0.96 GB
[bin/java-Objects.bin:24855]        setup:   2,304.75 ms,  0.96 GB
Error: Error compiling query code (in /var/folders/vl/633jwjvn2jvbj9zfg1sgglhw0000gp/T/SVM-3396448792019069231/PosixDirectives.c). Compiler command '/usr/bin/cc -Wall -Werror -ObjC -o /var/folders/vl/633jwjvn2jvbj9zfg1sgglhw0000gp/T/SVM-3396448792019069231/PosixDirectives /var/folders/vl/633jwjvn2jvbj9zfg1sgglhw0000gp/T/SVM-3396448792019069231/PosixDirectives.c' output included error: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.1.sdk/usr/include/sys/resource.h:202:2:
error: unknown type name 'uint8_t'

I'm with Clang:

$ clang --version
Homebrew clang version 13.0.0
Target: x86_64-apple-darwin20.6.0
Thread model: posix
InstalledDir: /usr/local/opt/llvm/bin

It seems that the problem is with this code in sys/resource.h:

#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL
#include <stdint.h>
#endif /* __DARWIN_C_LEVEL >= __DARWIN_C_FULL */

This line with stdint.h doesn't get included and that's why uint8_t doesn't get defined.


问:
How can I read numeric strings in Excel cells as string (not numbers)?

I have excel file with such contents:

A1: SomeString

A2: 2

All fields are set to String format.

When I read the file in java using POI, it tells that A2 is in numeric cell format.

The problem is that the value in A2 can be 2 or 2.0 (and I want to be able to distinguish them) so I can't just use .toString().

What can I do to read the value as string?

答:
I don't think we had this class back when you asked the question, but today there is an easy answer.

What you want to do is use the DataFormatter class. You pass this a cell, and it does its best to return you a string containing what Excel would show you for that cell. If you pass it a string cell, you'll get the string back. If you pass it a numeric cell with formatting rules applied, it will format the number based on them and give you the string back.

For your case, I'd assume that the numeric cells have an integer formatting rule applied to them. If you ask DataFormatter to format those cells, it'll give you back a string with the integer string in it.

Also, note that lots of people suggest doing cell.setCellType(Cell.CELL_TYPE_STRING), but the Apache POI JavaDocs quite clearly state that you shouldn't do this! Doing the setCellType call will loose formatting, as the javadocs explain the only way to convert to a String with formatting remaining is to use the DataFormatter class.

A simple example of using this class:

DataFormatter dataFormatter = new DataFormatter();
String formattedCellStr = dataFormatter.formatCellValue(cell);
```

ContentLicense: CC BY-SA 3.0


问:
Are we allowed to use conditional expression inside the let-in expression in Haskell?
```<code>kinerja :: Int -> Int -> Int -> (Int, Int, Int, Int)
kinerja j m d =
    let seconds = j*3600 + m*60 + d
    in
        let
            durasi x = abs (seconds - 17*3600 + m*30)
        in
            let js = durasi `div` 3600
                ms = (durasi `div` 60) `mod` 60
                ds = durasi `mod` 60
            in
                if j <= 17 && m < 30 then (js,ms,ds,1)
                else if j == 17 && m == 30 then (js,ms,ds,0)
                else (js,ms,ds,(-1))
</code>```

I'm getting error with these code. I'm trying to have tuple output. The element js, ms, and ds are the gap between the clock input and 17.30. The problem is on the element js, ms, and ds. Is there any advice on how to fix it?

答:
Personally, i always define Functions explicitly and i dont trust the implicit ones. Doing that and removing the "x" from durasi, which didnt make any sense to me, it works now:

kinerja :: Int -> Int -> Int -> (Int, Int, Int, Int)
kinerja j m d =
    let seconds :: Int
        seconds = j*3600 + m*60 + d
    in
        let durasi :: Int
            durasi = abs (seconds - 17*3600 + m*30)
        in
            let js :: Int
                js = durasi `div` 3600
                ms :: Int
                ms = (durasi `div` 60) `mod` 60
                ds :: Int
                ds = durasi `mod` 60
            in
                if j <= 17 && m < 30 then (durasi `div` 3600 ,ms,ds,1)
                else if j == 17 && m == 30 then (js,ms,ds,0)
                else (js,ms,ds,-1)

kinerja2 :: Int -> Int -> Int -> (Int, Int, Int, Int)
kinerja2 j m d
    | j <= 17 && m < 30 = (durasi `div` 3600 ,ms,ds,1)
    | j == 17 && m == 30 = (js,ms,ds,0)
    | otherwise =  (js,ms,ds, -1)
    where
        seconds :: Int
        seconds = j*3600 + m*60 + d
        durasi :: Int
        durasi = abs (seconds - 17*3600 + m*30)
        js :: Int
        js = durasi `div` 3600
        ms :: Int
        ms = (durasi `div` 60) `mod` 60
        ds :: Int
        ds = durasi `mod` 60
```

Body:
kinerja :: Int -> Int -> Int -> (Int, Int, Int, Int)
kinerja j m d =
    let seconds = j*3600 + m*60 + d
    in
        let
            durasi x = abs (seconds - 17*3600 + m*30)
        in
            let js = durasi `div` 3600
                ms = (durasi `div` 60) `mod` 60
                ds = durasi `mod` 60
            in
                if j <= 17 && m < 30 then (js,ms,ds,1)
                else if j == 17 && m == 30 then (js,ms,ds,0)
                else (js,ms,ds,(-1))

I'm getting error with these code. I'm trying to have tuple output. The element js, ms, and ds are the gap between the clock input and 17.30. The problem is on the element js, ms, and ds. Is there any advice on how to fix it?


问:
Java Synchronized on the same file, but not different
I have this static class:

```<code>public class FileManager{
    ....
    public static void writeOnFile(String something, String filepath){
        File f= new File(filepath);

        // Append
        PrintWriter writer = new PrintWriter(new FileWriter(f, true));
        writer.append(something);
    }
    ...
}
</code>```

that have lots of methods and this one above is one of these.

what I would like to do is that if two callers write to the same file, the writing should be done in mutual exclusion. But when callers write to different files, this doesn't happen (they don't write in mutual exclusion).

This versione below:

```<code>public class FileManager{
    ....
    public synchronized static void writeOnFile(String something, String filepath){
        File f= new File(filepath);

        // Append
        PrintWriter writer = new PrintWriter(new FileWriter(f, true));
        writer.append(something);
    }
    ...
}
</code>```

I don't think that's what I want to accomplish. In this case the callers will write in mutual exclusion even if the files they write to are different.

I wanted to ask: this second version:

```<code>public class FileManager{
    ....
    public static void writeOnFile(String something, String filepath){
        File f= new File(filepath);

        // Append
        synchronized(f){
            PrintWriter writer = new PrintWriter(new FileWriter(f, true));
            writer.append(something);
        }
    }
    ...
}
</code>```

would work?. if not, would I have to create an object that contains the filepath of each file in order to use the locks as I would like?

答:
Synchronization will only work if done on the same actual object. Your second version will not work because it creates a new object, and therefore a new lock. What you would need is a registry of locks. A small example, using not synchronized but ReentrantLock:

```<code>private static final Map<String, Lock> LOCKS = new ConcurrentHashMap<>();

...

Lock lock = LOCKS.computeIfAbsent(filepath, p -> new ReentrantLock());
lock.lock();
try {
    ....
} finally {
    lock.unlock();
}
</code>```

The combination of a ConcurrentHashMap and computeIfAbsent should result in the same Lock object each time the method is called with the same filepath value.

An alternative is perhaps to use FileLock. That uses the native locking mechanism (if it actually exists), and is based on actual files, not Java objects.

Body:
I have this static class:

public class FileManager{
    ....
    public static void writeOnFile(String something, String filepath){
        File f= new File(filepath);

        // Append
        PrintWriter writer = new PrintWriter(new FileWriter(f, true));
        writer.append(something);
    }
    ...
}

that have lots of methods and this one above is one of these.

what I would like to do is that if two callers write to the same file, the writing should be done in mutual exclusion. But when callers write to different files, this doesn't happen (they don't write in mutual exclusion).

This versione below:

public class FileManager{
    ....
    public synchronized static void writeOnFile(String something, String filepath){
        File f= new File(filepath);

        // Append
        PrintWriter writer = new PrintWriter(new FileWriter(f, true));
        writer.append(something);
    }
    ...
}

I don't think that's what I want to accomplish. In this case the callers will write in mutual exclusion even if the files they write to are different.

I wanted to ask: this second version:

public class FileManager{
    ....
    public static void writeOnFile(String something, String filepath){
        File f= new File(filepath);

        // Append
        synchronized(f){
            PrintWriter writer = new PrintWriter(new FileWriter(f, true));
            writer.append(something);
        }
    }
    ...
}

would work?. if not, would I have to create an object that contains the filepath of each file in order to use the locks as I would like?

Body:
Synchronization will only work if done on the same actual object. Your second version will not work because it creates a new object, and therefore a new lock. What you would need is a registry of locks. A small example, using not synchronized but ReentrantLock:

private static final Map<String, Lock> LOCKS = new ConcurrentHashMap<>();

...

Lock lock = LOCKS.computeIfAbsent(filepath, p -> new ReentrantLock());
lock.lock();
try {
    ....
} finally {
    lock.unlock();
}

The combination of a ConcurrentHashMap and computeIfAbsent should result in the same Lock object each time the method is called with the same filepath value.

An alternative is perhaps to use FileLock. That uses the native locking mechanism (if it actually exists), and is based on actual files, not Java objects.


问:
Bootstrap vertically push to the bottom
html

```<code><div class="container">
  <div id="movies" class="well">
    <div class="col-md-3">
      <div class="well text-center">
        <img src="#">
        <h5>title</h5>
        <a class="btn btn-primary" href="#">Detail</a>
      </div>
    </div>
    <div class="col-md-3">
      <div class="well text-center">
        <img src="#">
        <h5>title</h5>
        <a class="btn btn-primary" href="#">Detail</a>
      </div>
    </div>
  </div>
</div>
</code>```

css

```<code>#movies img, #movie img{
  width: 100%;
}
@media(min-width:960px){
  #movies .col-md-3 .well{
    height: 390px;
  }
  #movies .col-md-3 img{
    height: 240px;
  }
}
</code>```

img As you can see in the image, the Detail buttons are not in the same horizontal line. I would like to push the first one down.

答:
You can use flexbox to achieve this. Try this (View it in "full page" mode).

#movies img, #movie img {
  width: 100%;
}

@media(min-width:960px) {
  #movies .col-md-3 .well {
    height: 350px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  #movies .col-md-3 img {
    height: 240px;
  }
  #movies .btn {
    margin-top: auto;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<div class="container">
  <div id="movies" class="row well">
    <div class="col-md-3">
      <div class="well text-center">
        <img src="https://via.placeholder.com/260">
        <h5>Qui minim nulla veniam.</h5>
        Detail
      </div>
    </div>
    <div class="col-md-3">
      <div class="well text-center">
        <img src="https://via.placeholder.com/260">
        <h5>Ut reprehenderit cillum occaecat sint voluptate</h5>
        Detail
      </div>
    </div>
  </div>
</div></code>```

Title: Bootstrap vertically push to the bottom

Body:
html

title

        Detail

title

        Detail

css

#movies img, #movie img{
  width: 100%;
}
@media(min-width:960px){
  #movies .col-md-3 .well{
    height: 390px;
  }
  #movies .col-md-3 img{
    height: 240px;
  }
}

img As you can see in the image, the Detail buttons are not in the same horizontal line. I would like to push the first one down.

Body:
You can use flexbox to achieve this. Try this (View it in "full page" mode).

#movies img, #movie img {
  width: 100%;
}

@media(min-width:960px) {
  #movies .col-md-3 .well {
    height: 350px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  #movies .col-md-3 img {
    height: 240px;
  }
  #movies .btn {
    margin-top: auto;
  }
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<div class="container">
  <div id="movies" class="row well">
    <div class="col-md-3">
      <div class="well text-center">
        <img src="https://via.placeholder.com/260">
        <h5>Qui minim nulla veniam.</h5>
        <a class="btn btn-primary" href="#">Detail</a>
      </div>
    </div>
    <div class="col-md-3">
      <div class="well text-center">
        <img src="https://via.placeholder.com/260">
        <h5>Ut reprehenderit cillum occaecat sint voluptate</h5>
        <a class="btn btn-primary" href="#">Detail</a>
      </div>
    </div>
  </div>
</div>


问:
Dump facility in C++ like var_dump() in PHP?
When I was in college i did some C/C++, but in near future i was working in PHP, and now I wish to put more time in learning C/C++.

In PHP i was using print_r() or var_dump() in order to display datas from structures or arrays. Do I have such a default functionality in C, in order to see what do i have in a struct or array?

答:
I usually use GDB printing.

for example this code:

```<code>#include <string.h>
struct _example_ {
    int a;
    int b;
    char c[20];
};

int main(){
    struct _example_ example;
    example.a = 1;
    example.b = 2;
    strcpy(example.c,"example_c");
}
</code>```

compile with gcc main.c -o executable -g

if you want to know the values for the struct example, you should execute the program with GDB, put a break on the line that you want and then print the variable, like below.

```<code>Breakpoint 1, main () at main.c:12
12      strcpy(example.c,"example_c");
(gdb) n
13  }
(gdb) print example
$1 = {a = 1, b = 2, c = "example_c\000\000\000\000\000\000\000`PUU"}
(gdb)
</code>```

In this case i put breakpoint on line 12, and print the variable example, then i got all the variables and values on the struct example

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: anon

Body:
I usually use GDB printing.

for example this code:

#include <string.h>
struct _example_ {
    int a;
    int b;
    char c[20];
};

int main(){
    struct _example_ example;
    example.a = 1;
    example.b = 2;
    strcpy(example.c,"example_c");
}

compile with gcc main.c -o executable -g

if you want to know the values for the struct example, you should execute the program with GDB, put a break on the line that you want and then print the variable, like below.

Breakpoint 1, main () at main.c:12
12      strcpy(example.c,"example_c");
(gdb) n
13  }
(gdb) print example
$1 = {a = 1, b = 2, c = "example_c\000\000\000\000\000\000\000`PUU"}
(gdb)

In this case i put breakpoint on line 12, and print the variable example, then i got all the variables and values on the struct example


问:
TypeError("can't convert expression to float")
The code which I wrote might look foolish, because it is integration of a derivative function. since it is the basic foundation to the other code which I'm writing on acoustical analysis. this analysis contains integration of different derivative functions which are in multiplication. for this purpose I'm using SciPy for integration and sympy for differentiation. but it is giving an error showing TypeError("can't convert expression to float"). below is the code which I wrote. hoping a solution for this.</p>
```<code>import sympy
from sympy import *
from scipy.integrate import quad
var('r')
def diff(r):
    r=symbols('x')
    Z = 64.25 * r ** 5 - 175.71 *r ** 4 + 170.6 *r ** 3 - 71.103 *r ** 2 + 3 * r
    E=sympy.diff(Z,r)
    print(E)
    return E
R=quad(diff,0,1)[0]
print(R)
</code>```

答:
I have to say that I'm a bit confused by your statement "integration of a derivative function" since the fundamental theorem of calculus would suggest that this is just a waste of CPU cycles. I'll presume that you know what you're doing though and that you just want to be able to compute some definite integrals numerically...

The SymPy expression that you want to integrate is this:

```<code>In [33]: from sympy import *

In [34]: r = symbols("x")  # Why are you calling this x?

In [35]: Z = 64.25 * r ** 5 - 175.71 * r ** 4 + 170.6 * r ** 3 - 71.103 * r ** 2 +
    ...: 3 * r

In [36]: E = diff(Z, r)

In [37]: E
Out[37]:
        4           3          2
321.25⋅x  - 702.84⋅x  + 511.8⋅x  - 142.206⋅x + 3
</code>```

There are a two basic ways to do this with SymPy:

```<code>In [38]: integrate(E, (r, 0, 1))  # symbolic integration
Out[38]: -8.96299999999999

In [39]: Integral(E, (r, 0, 1)).evalf()  # numeric integration
Out[39]: -8.96300000000002
</code>```

Note that had you used exact rational numbers you would see a more accurate result in either case:

```<code>In [40]: nsimplify(E)
Out[40]:
      4          3         2
1285⋅x    17571⋅x    2559⋅x    71103⋅x
─────── - ──────── + ─────── - ─────── + 3
   4         25         5        500

In [41]: integrate(nsimplify(E), (r, 0, 1))
Out[41]:
-8963
──────
 1000

In [42]: Integral(nsimplify(E), (r, 0, 1)).evalf()
Out[42]: -8.96300000000000
</code>```

While the approaches above are very accurate and work nicely for this particular integral which is easy to compute both symbolically and numerically they are both slower than using something like scipy's quad function which works with machine precision floating point and efficient numpy arrays for the calculation. To use scipy's quad function you need to lambdify your expression into an ordinary Python function:

```<code>In [44]: from scipy.integrate import quad

In [45]: f = lambdify(r, E, "numpy")

In [46]: f(0)
Out[46]: 3.0

In [47]: f(1)
Out[47]: -8.99600000000001

In [48]: quad(f, 0, 1)[0]
Out[48]: -8.963000000000001
</code>```

What lambdify does is just to generate an efficient Python function for you. You can see the code that it uses like this:

```<code>In [51]: import inspect

In [52]: print(inspect.getsource(f))
def _lambdifygenerated(x):
    return 321.25*x**4 - 702.84*x**3 + 511.8*x**2 - 142.206*x + 3
</code>```

The quad routine will pass in numpy arrays for x and so this can be very efficient. If you have high-order polynomials then sympy's horner function can be used to optimise the expression:

```<code>In [53]: horner(E)
Out[53]: x⋅(x⋅(x⋅(321.25⋅x - 702.84) + 511.8) - 142.206) + 3.0

In [54]: f2 = lambdify(r, horner(E), "numpy")

In [56]: print(inspect.getsource(f2))
def _lambdifygenerated(x):
    return x*(x*(x*(321.25*x - 702.84) + 511.8) - 142.206) + 3.0
</code>```

https://docs.sympy.org/latest/tutorial/calculus.html#integrals
https://docs.sympy.org/latest/modules/utilities/lambdify.html#sympy.utilities.lambdify.lambdify
https://docs.sympy.org/latest/modules/polys/reference.html#sympy.polys.polyfuncs.horner

Body:
The code which I wrote might look foolish, because it is integration of a derivative function. since it is the basic foundation to the other code which I'm writing on acoustical analysis. this analysis contains integration of different derivative functions which are in multiplication. for this purpose I'm using SciPy for integration and sympy for differentiation. but it is giving an error showing TypeError("can't convert expression to float"). below is the code which I wrote. hoping a solution for this.

import sympy
from sympy import *
from scipy.integrate import quad
var('r')
def diff(r):
    r=symbols('x')
    Z = 64.25 * r ** 5 - 175.71 *r ** 4 + 170.6 *r ** 3 - 71.103 *r ** 2 + 3 * r
    E=sympy.diff(Z,r)
    print(E)
    return E
R=quad(diff,0,1)[0]
print(R)

Body:
I have to say that I'm a bit confused by your statement "integration of a derivative function" since the fundamental theorem of calculus would suggest that this is just a waste of CPU cycles. I'll presume that you know what you're doing though and that you just want to be able to compute some definite integrals numerically...

The SymPy expression that you want to integrate is this:

In [33]: from sympy import *

In [34]: r = symbols("x")  # Why are you calling this x?

In [35]: Z = 64.25 * r ** 5 - 175.71 * r ** 4 + 170.6 * r ** 3 - 71.103 * r ** 2 +
    ...: 3 * r

In [36]: E = diff(Z, r)

In [37]: E
Out[37]:
        4           3          2
321.25⋅x  - 702.84⋅x  + 511.8⋅x  - 142.206⋅x + 3

There are a two basic ways to do this with SymPy:

In [38]: integrate(E, (r, 0, 1))  # symbolic integration
Out[38]: -8.96299999999999

In [39]: Integral(E, (r, 0, 1)).evalf()  # numeric integration
Out[39]: -8.96300000000002

Note that had you used exact rational numbers you would see a more accurate result in either case:

In [40]: nsimplify(E)
Out[40]:
      4          3         2
1285⋅x    17571⋅x    2559⋅x    71103⋅x
─────── - ──────── + ─────── - ─────── + 3
   4         25         5        500

In [41]: integrate(nsimplify(E), (r, 0, 1))
Out[41]:
-8963
──────
 1000

In [42]: Integral(nsimplify(E), (r, 0, 1)).evalf()
Out[42]: -8.96300000000000

While the approaches above are very accurate and work nicely for this particular integral which is easy to compute both symbolically and numerically they are both slower than using something like scipy's quad function which works with machine precision floating point and efficient numpy arrays for the calculation. To use scipy's quad function you need to lambdify your expression into an ordinary Python function:

In [44]: from scipy.integrate import quad

In [45]: f = lambdify(r, E, "numpy")

In [46]: f(0)
Out[46]: 3.0

In [47]: f(1)
Out[47]: -8.99600000000001

In [48]: quad(f, 0, 1)[0]
Out[48]: -8.963000000000001

What lambdify does is just to generate an efficient Python function for you. You can see the code that it uses like this:

In [51]: import inspect

In [52]: print(inspect.getsource(f))
def _lambdifygenerated(x):
    return 321.25*x**4 - 702.84*x**3 + 511.8*x**2 - 142.206*x + 3

The quad routine will pass in numpy arrays for x and so this can be very efficient. If you have high-order polynomials then sympy's horner function can be used to optimise the expression:

In [53]: horner(E)
Out[53]: x⋅(x⋅(x⋅(321.25⋅x - 702.84) + 511.8) - 142.206) + 3.0

In [54]: f2 = lambdify(r, horner(E), "numpy")

In [56]: print(inspect.getsource(f2))
def _lambdifygenerated(x):
    return x*(x*(x*(321.25*x - 702.84) + 511.8) - 142.206) + 3.0

https://docs.sympy.org/latest/tutorial/calculus.html#integrals
https://docs.sympy.org/latest/modules/utilities/lambdify.html#sympy.utilities.lambdify.lambdify
https://docs.sympy.org/latest/modules/polys/reference.html#sympy.polys.polyfuncs.horner


问:
Index signature for type 'string' is missing
I am trying to type my data in Firebase Cloud Functions using Typescript:

```<code>type SpotPriceByDay = {
  NOK_per_kWh: number;
  valid_from: string;
  valid_to: string;
}
type SpotPrices = {
  [date: string]: SpotPriceByDay
}
</code>```

My Typescript compiler gives me an error when trying to use this

```<code>let data: SpotPrices = response.data;
data = Object.keys(data).map((key) => {
  const newKey = new Date(key).toISOString();
  return {[newKey]: data[key]};
});
</code>```
```<code>error TS2322: Type '{ [x: string]: SpotPriceByDay; }[]' is not assignable to type 'SpotPrices'.
Index signature for type 'string' is missing in type '{ [x: string]: SpotPriceByDay; }[]'.
</code>```

I have tried to understand how I can fix this error, but I have no clue. Any help would be appreciated!

答:
data is a map of type SpotPrices but the map function here returns an array of SpotPrices objects. Assigning the result of the map should be a way to resolve this:

```<code>const data: SpotPrices = response.data;

const parsedData = Object.keys(data).map((key) => {
  const newKey = new Date(key).toISOString();
  return { [newKey]: data[key] };
});
</code>```

Another way would be changing type of data to either SpotPrices or SpotPrices[]:

```<code>let data: SpotPrices | SpotPrices[] = response.data;

data = Object.keys(data).map((key) => {
  const newKey = new Date(key).toISOString();
  return { [newKey]: (data as SpotPrices)[key] };
});
</code>```

Body:
I am trying to type my data in Firebase Cloud Functions using Typescript:

type SpotPriceByDay = {
  NOK_per_kWh: number;
  valid_from: string;
  valid_to: string;
}
type SpotPrices = {
  [date: string]: SpotPriceByDay
}

My Typescript compiler gives me an error when trying to use this

let data: SpotPrices = response.data;
data = Object.keys(data).map((key) => {
  const newKey = new Date(key).toISOString();
  return {[newKey]: data[key]};
});

error TS2322: Type '{ [x: string]: SpotPriceByDay; }[]' is not assignable to type 'SpotPrices'.
Index signature for type 'string' is missing in type '{ [x: string]: SpotPriceByDay; }[]'.

I have tried to understand how I can fix this error, but I have no clue. Any help would be appreciated!

Body:
data is a map of type SpotPrices but the map function here returns an array of SpotPrices objects. Assigning the result of the map should be a way to resolve this:

const data: SpotPrices = response.data;

const parsedData = Object.keys(data).map((key) => {
  const newKey = new Date(key).toISOString();
  return { [newKey]: data[key] };
});

Another way would be changing type of data to either SpotPrices or SpotPrices[]:

let data: SpotPrices | SpotPrices[] = response.data;

data = Object.keys(data).map((key) => {
  const newKey = new Date(key).toISOString();
  return { [newKey]: (data as SpotPrices)[key] };
});


问:
How do I get values out of a flutter List<class>?
I am trying to make an app using GetX in Flutter.
However, after sorting the values using the where operator in a List that has a structure of Class, I try to save it as a List and use it.

In my current code, the String displayed in the Text widget is "Instance of 'Product'".
I hope you guys can tell me how to retrieve the stored value in a simple way without running a for loop.

Model and List Data are as follows.

```<code>class Product {
  final String id;
  final String title;
  final String description;
  final double price;
  final String imageUrl;
  bool isFavorite;

  Product({
    required this.id,
    required this.title,
    required this.description,
    required this.price,
    required this.imageUrl,
    this.isFavorite = false,
  });
}

List<Product> lodedProduct = [
  Product(
    id: 'p1',
    title: 'Red Shirt',
    description: 'A red shirt - it is pretty red!',
    price: 29.99,
    imageUrl:
        'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-t-shirt-1710578_1280.jpg',
  ),
  Product(
    id: 'p2',
    title: 'Trousers',
    description: 'A nice pair of trousers.',
    price: 59.99,
    imageUrl:
        'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Trousers%2C_dress_%28AM_1960.022-8%29.jpg/512px-Trousers%2C_dress_%28AM_1960.022-8%29.jpg',
  ),
  Product(
    id: 'p3',
    title: 'Yellow Scarf',
    description: 'Warm and cozy - exactly what you need for the winter.',
    price: 19.99,
    imageUrl: 'https://live.staticflickr.com/4043/4438260868_cc79b3369d_z.jpg',
  ),
  Product(
    id: 'p4',
    title: 'A Pan',
    description: 'Prepare any meal you want.',
    price: 49.99,
    imageUrl:
        'https://upload.wikimedia.org/wikipedia/commons/thumb/1/14/Cast-Iron-Pan.jpg/1024px-Cast-Iron-Pan.jpg',
  ),
];
</code>```

The part to be displayed is as follows.

```<code>import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:myshop/data/product_data.dart';

import '../models/product.dart';

class ProductDetailScreen extends StatelessWidget {
  ProductDetailScreen({Key? key}) : super(key: key);

  var filteredList = lodedProduct
      .where((element) => element.id.contains(Get.arguments))
      .map((e) => e)
      .toList();
//Here, get the id from the previous page with Get.arguments. id is the 0th id in the List.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).primaryColor,
        centerTitle: true,
        title: Text(Get.arguments),
      ),
      body: Center(
        child: Container(
          child: Text(filteredList.toString()),
//Here, I want to get the value of filteredList as a string.
        ),
      ),
    );
  }
}
</code>```

答:
Finally I found the answer.
The correct answer was to use firstWhere, not where.</p>
```<code> @override
  Widget build(BuildContext context) {

    final productId =
        controller.items.firstWhere((element) => element.id == Get.arguments);

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).primaryColor,
        centerTitle: true,
        title: Text(productId.title),
      ),
      body: Center(
        child: Column(
          children: [
            Container(
              width: double.maxFinite,
              height: 250,
              alignment: Alignment.bottomCenter,
              decoration: BoxDecoration(
                image: DecorationImage(
                  fit: BoxFit.cover,
                  image: NetworkImage(productId.imageUrl),
                ),
              ),
              child: Container(
                height: 50,
                width: double.maxFinite,
                alignment: Alignment.center,
                color: Colors.black.withOpacity(0.3),
                child: Text(
                  productId.title,
                  style: const TextStyle(
                    fontSize: 30,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
            const SizedBox(height: 20),
            Text(productId.description),
            const SizedBox(height: 20),
            Text('\$ ' + productId.price.toString()),
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
I am trying to make an app using GetX in Flutter.
However, after sorting the values using the where operator in a List that has a structure of Class, I try to save it as a List and use it.

In my current code, the String displayed in the Text widget is "Instance of 'Product'".
I hope you guys can tell me how to retrieve the stored value in a simple way without running a for loop.

Model and List Data are as follows.

class Product {
  final String id;
  final String title;
  final String description;
  final double price;
  final String imageUrl;
  bool isFavorite;

  Product({
    required this.id,
    required this.title,
    required this.description,
    required this.price,
    required this.imageUrl,
    this.isFavorite = false,
  });
}

List<Product> lodedProduct = [
  Product(
    id: 'p1',
    title: 'Red Shirt',
    description: 'A red shirt - it is pretty red!',
    price: 29.99,
    imageUrl:
        'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-t-shirt-1710578_1280.jpg',
  ),
  Product(
    id: 'p2',
    title: 'Trousers',
    description: 'A nice pair of trousers.',
    price: 59.99,
    imageUrl:
        'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Trousers%2C_dress_%28AM_1960.022-8%29.jpg/512px-Trousers%2C_dress_%28AM_1960.022-8%29.jpg',
  ),
  Product(
    id: 'p3',
    title: 'Yellow Scarf',
    description: 'Warm and cozy - exactly what you need for the winter.',
    price: 19.99,
    imageUrl: 'https://live.staticflickr.com/4043/4438260868_cc79b3369d_z.jpg',
  ),
  Product(
    id: 'p4',
    title: 'A Pan',
    description: 'Prepare any meal you want.',
    price: 49.99,
    imageUrl:
        'https://upload.wikimedia.org/wikipedia/commons/thumb/1/14/Cast-Iron-Pan.jpg/1024px-Cast-Iron-Pan.jpg',
  ),
];

The part to be displayed is as follows.

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:myshop/data/product_data.dart';

import '../models/product.dart';

class ProductDetailScreen extends StatelessWidget {
  ProductDetailScreen({Key? key}) : super(key: key);

  var filteredList = lodedProduct
      .where((element) => element.id.contains(Get.arguments))
      .map((e) => e)
      .toList();
//Here, get the id from the previous page with Get.arguments. id is the 0th id in the List.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).primaryColor,
        centerTitle: true,
        title: Text(Get.arguments),
      ),
      body: Center(
        child: Container(
          child: Text(filteredList.toString()),
//Here, I want to get the value of filteredList as a string.
        ),
      ),
    );
  }
}

Body:
Finally I found the answer.
The correct answer was to use firstWhere, not where.

 @override
  Widget build(BuildContext context) {

    final productId =
        controller.items.firstWhere((element) => element.id == Get.arguments);

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).primaryColor,
        centerTitle: true,
        title: Text(productId.title),
      ),
      body: Center(
        child: Column(
          children: [
            Container(
              width: double.maxFinite,
              height: 250,
              alignment: Alignment.bottomCenter,
              decoration: BoxDecoration(
                image: DecorationImage(
                  fit: BoxFit.cover,
                  image: NetworkImage(productId.imageUrl),
                ),
              ),
              child: Container(
                height: 50,
                width: double.maxFinite,
                alignment: Alignment.center,
                color: Colors.black.withOpacity(0.3),
                child: Text(
                  productId.title,
                  style: const TextStyle(
                    fontSize: 30,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
            const SizedBox(height: 20),
            Text(productId.description),
            const SizedBox(height: 20),
            Text('\$ ' + productId.price.toString()),
          ],
        ),
      ),
    );
  }
}


问:
How to set token expiration time when using django-rest-authtoken?
I'm using the django-rest-authtoken library (https://github.com/wichmannpas/django-rest-authtoken) to manage my API users.
The biggest inconvenience is that the user authentication tokens expire in 24 hours, effectively requiring to perform login every day.
Unfortunately I couldn't find a way to change the token expiration time.
Any help appreciated.</p>

答:
Looks like 1 day is default value in settings:

https://github.com/wichmannpas/django-rest-authtoken/blob/master/rest_authtoken/settings.py#L10

so setting AUTH_TOKEN_VALIDITY in your project should do the job.


问:
AJAX & Disabled JavaScript. Do you worry?
I'm new to PHP, AJAX, and databases.

But I want to know what experiences programmers think and do.

When using AJAX, do you worry about users who have JavaScript disabled?

Do you have a backup solution? Or is the number of those who have JavaScript disabled so small that it isn't a concern?

Wow I got a lot of opinions, which is good, but I think it's important for me to clarify a bit.

I'm asking specifically in terms of AJAX in websites.

When it comes to JavaScript in my websites, I work with the goal of using it to ENHANCE the experience of the user, but ensure that the core of the site will still function for users with JavaScript disabled.
But from my understanding of AJAX, it IS the core functionality is it not? It communicates with the server or database the way PHP does. So how do you make a fallback for that? Or do you?

Again, if I'm mistaken about the role of AJAX, please forgive and enlighten me.

答: When creating a website, the key is to create a site that works regardless of the user's settings. Your site's design and functionality should not be dependent on the user having Javascript enabled.</p>


问:
Why would you declare an Interface and then instantiate an object with it in Java?
A friend and I are studying Java. We were looking at interfaces today and we got into a bit of an discussion about how interfaces are used.

The example code my friend showed me contained this:

```<code>IVehicle modeOfTransport1 = new Car();
IVehicle modeOfTransport2 = new Bike();
</code>```

Where IVehicle is an interface that's implemented in both the car and bike classes.
When defining a method that accepts IVehicle as a parameter you can use the interface methods, and when you run the code the above objects work as normal. However, this works perfectly fine when declaring the car and bike as you normally would like this:

```<code>Car modeOfTransport1 = new Car();
Bike modeOfTransport2 = new Bike();
</code>```

So, my question is - why would you use the former method over the latter when declaring and instantiating the modeOfTransport objects? Does it matter?

答:
Even in 2022, it's confusing to understand the true purpose of an interface even to a trained eye who didn't start his/her career in java.

After reading a lot of answers in various online posts, I think that an interface is just a way to not care about the implementation details of a certain activity which is being passed down to a common goal (a certain method). To make it easy, a method doesn't really care how you implement your operations but only cares about what you pass down to it.

The OP is correct in a way to ask why we couldn't just reference to the type of the concrete class than to use an interface. But, we cannot think or understand the use case of an interface in a isolated pov.
Most explanation won't justify it's use unless you look at how classes like ArrayList and LinkedList are derived. Here is my simple explanation.

```<code>Class CustomerDelivery {

line 2 -> public void deliverMeMyIphone( DeliveryRoutes x //I don't care how you deliver it){
         //Just deliver to my home address.
    }
line 3 -> DeliveryRoutes a = new AmazonDelivery();
               DeliveryRoutes b = new EbayDelivery();

//sending IPhone using Amazon Delivery. Final act.
deliverMeMyIphone(a.route());

//sending IPhone using eBay Delivery. Final act
deliverMeMyIphone(b.route());
}

Interface DeliveryRoutes {

    void route(); // I dont care what route you take, and also the method which takes me as an argument won't care and that's the contract.

}
Class AmazonDelivery implements DeliveryRoutes {
   @overide route() {
           // Amazon guy takes a different route
     }
}

Class EbayDelivery implements DeliveryRoutes {
   @overide route() {
           // ebay guy takes a different route
     }
}
</code>```

From the above example In line 2, just imagine to yourself what would happen if you cast the type of value x to a concrete class like AmazonDelivery and not the interface DeliveryRoutes type? or what would happen in line 3 if you change the type from the interface to AmazonDelivery type? It would be a mess. Why? because the method deliverMeMyIphone will be forced to work with only one type of delivery i.e AmazonDelivery and won't accept anything else.

Most answers confuse us with by saying Interfaces helps in multiple inheritance which is true, don't get me wrong, but it's not the only story.

Body:
A friend and I are studying Java. We were looking at interfaces today and we got into a bit of an discussion about how interfaces are used.

The example code my friend showed me contained this:

IVehicle modeOfTransport1 = new Car();
IVehicle modeOfTransport2 = new Bike();

Where IVehicle is an interface that's implemented in both the car and bike classes.
When defining a method that accepts IVehicle as a parameter you can use the interface methods, and when you run the code the above objects work as normal. However, this works perfectly fine when declaring the car and bike as you normally would like this:

Car modeOfTransport1 = new Car();
Bike modeOfTransport2 = new Bike();

So, my question is - why would you use the former method over the latter when declaring and instantiating the modeOfTransport objects? Does it matter?

Body:
Even in 2022, it's confusing to understand the true purpose of an interface even to a trained eye who didn't start his/her career in java.

After reading a lot of answers in various online posts, I think that an interface is just a way to not care about the implementation details of a certain activity which is being passed down to a common goal (a certain method). To make it easy, a method doesn't really care how you implement your operations but only cares about what you pass down to it.

The OP is correct in a way to ask why we couldn't just reference to the type of the concrete class than to use an interface. But, we cannot think or understand the use case of an interface in a isolated pov.
Most explanation won't justify it's use unless you look at how classes like ArrayList and LinkedList are derived. Here is my simple explanation.

Class CustomerDelivery {

line 2 -> public void deliverMeMyIphone( DeliveryRoutes x //I don't care how you deliver it){
         //Just deliver to my home address.
    }
line 3 -> DeliveryRoutes a = new AmazonDelivery();
               DeliveryRoutes b = new EbayDelivery();

//sending IPhone using Amazon Delivery. Final act.
deliverMeMyIphone(a.route());

//sending IPhone using eBay Delivery. Final act
deliverMeMyIphone(b.route());
}

Interface DeliveryRoutes {

    void route(); // I dont care what route you take, and also the method which takes me as an argument won't care and that's the contract.

}
Class AmazonDelivery implements DeliveryRoutes {
   @overide route() {
           // Amazon guy takes a different route
     }
}

Class EbayDelivery implements DeliveryRoutes {
   @overide route() {
           // ebay guy takes a different route
     }
}

From the above example In line 2, just imagine to yourself what would happen if you cast the type of value x to a concrete class like AmazonDelivery and not the interface DeliveryRoutes type? or what would happen in line 3 if you change the type from the interface to AmazonDelivery type? It would be a mess. Why? because the method deliverMeMyIphone will be forced to work with only one type of delivery i.e AmazonDelivery and won't accept anything else.

Most answers confuse us with by saying Interfaces helps in multiple inheritance which is true, don't get me wrong, but it's not the only story.


问:
What is the definite way to debug backend and frontend at the same time in vscode?
It seems there are 1 million launch configurations out there, and the more you try the more confused you get.

As of 2/6/22 what is the way to launch debugger so it will work for both Nodejs (npm start debug = nodemon --inspect index.js) AND also work for bundled + sourcemap + minified JS on frontend

答:
It depends on your project, however you do not really much custom configurations with VS Code since mostly is done automatically, the least way of debugging your nodejs project, is by simply attaching your debugger to nodejs running process, here is an example of one of my launch.json configurations:

```<code>
    {
      "type": "node",
      "request": "attach",
      "name": "Attach to process",
      "sourceMaps": true,
      "processId": "${command:PickProcess}",
      "restart": true,
      "protocol": "inspector"
    },
</code>```

If you want to debug nodejs from it's starting point since attaching happens after it already started (this is if you are using nodemon - nodemon is a tool we use to monitor the code changes and rebuild-rerun for us everytime we make a change):

```<code>
    {
      "type": "node",
      "request": "launch",
      "name": "Debug watch api",
      "outFiles": [
        "${workspaceFolder}/dist/..." // in my case, i have typescript and my nodejs build goes into that folder
      ],
      "runtimeArgs": ["${workspaceFolder}/node_modules/nodemon/bin/nodemon"],
      "cwd": "${workspaceFolder}",
      "args": ["--config", "nodemon-debug.json"],
      "sourceMaps": true,
      "autoAttachChildProcesses": true,
      "protocol": "inspector",
      "serverReadyAction": {
        "action": "openExternally",
        "uriFormat": "http://localhost:3000",
        "pattern": "<what-string-do-you-want-vscode-to-see-to-open-a-browser-for-you-automatically>"
      },
      "env": {
        "TS_NODE_PROJECT": "tsconfig.build.json",
      }
    },
</code>```

example nodemon-debug.json:

```<code>{
  "$schema": "http://json.schemastore.org/nodemon",
  "watch": ["src"],
  "ext": "ts",
  "ignore": ["src/**/*.spec.js"], // what files to ignore from watching
  "exec": "node --trace-uncaught --nolazy {{pwd}}/src/main.js"
}
</code>```

Generally, all you need is to configure .vscode/launch.json file, vscode automatically debugs for you. See https://code.visualstudio.com/docs/editor/debugging for more details.

You can debug as many processes as you want at the same time via Start additional session (if your api and ui are on 2 different processes).

Body:
It depends on your project, however you do not really much custom configurations with VS Code since mostly is done automatically, the least way of debugging your nodejs project, is by simply attaching your debugger to nodejs running process, here is an example of one of my launch.json configurations:

    {
      "type": "node",
      "request": "attach",
      "name": "Attach to process",
      "sourceMaps": true,
      "processId": "${command:PickProcess}",
      "restart": true,
      "protocol": "inspector"
    },

If you want to debug nodejs from it's starting point since attaching happens after it already started (this is if you are using nodemon - nodemon is a tool we use to monitor the code changes and rebuild-rerun for us everytime we make a change):

    {
      "type": "node",
      "request": "launch",
      "name": "Debug watch api",
      "outFiles": [
        "${workspaceFolder}/dist/..." // in my case, i have typescript and my nodejs build goes into that folder
      ],
      "runtimeArgs": ["${workspaceFolder}/node_modules/nodemon/bin/nodemon"],
      "cwd": "${workspaceFolder}",
      "args": ["--config", "nodemon-debug.json"],
      "sourceMaps": true,
      "autoAttachChildProcesses": true,
      "protocol": "inspector",
      "serverReadyAction": {
        "action": "openExternally",
        "uriFormat": "http://localhost:3000",
        "pattern": "<what-string-do-you-want-vscode-to-see-to-open-a-browser-for-you-automatically>"
      },
      "env": {
        "TS_NODE_PROJECT": "tsconfig.build.json",
      }
    },

example nodemon-debug.json:

{
  "$schema": "http://json.schemastore.org/nodemon",
  "watch": ["src"],
  "ext": "ts",
  "ignore": ["src/**/*.spec.js"], // what files to ignore from watching
  "exec": "node --trace-uncaught --nolazy {{pwd}}/src/main.js"
}

Generally, all you need is to configure .vscode/launch.json file, vscode automatically debugs for you. See https://code.visualstudio.com/docs/editor/debugging for more details.

You can debug as many processes as you want at the same time via Start additional session (if your api and ui are on 2 different processes).