问:
How to use Dispatch?
The compiler said,

Cannot pass function of type '() async -> Void' to parameter expecting
synchronous function type

This is the problem code：

```<code>DispatchQueue.global().async {
    await CreateFolder()

    do {
        let FilePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let FileName = UUID().uuidString
        try! Image.pngData()!.write(to: FilePath.appendingPathComponent("Images").appendingPathComponent("\(FileName).png"))
    } catch {
        Prompt(error.localizedDescription)
    }
}
</code>```

答:
Remove await from DispatchQueue closure.

Fixed：

```<code>    DispatchQueue.global().async {

    CreateFolder()

    do {
        let FilePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let FileName = UUID().uuidString
        try! Image.pngData()!.write(to: FilePath.appendingPathComponent("Images").appendingPathComponent("\(FileName).png"))
    } catch {
        Prompt(error.localizedDescription)
    }
    }
</code>```

Title: How to use Dispatch?

Body:
The compiler said,

Cannot pass function of type '() async -> Void' to parameter expecting
synchronous function type

This is the problem code：

DispatchQueue.global().async {
    await CreateFolder()

    do {
        let FilePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let FileName = UUID().uuidString
        try! Image.pngData()!.write(to: FilePath.appendingPathComponent("Images").appendingPathComponent("\(FileName).png"))
    } catch {
        Prompt(error.localizedDescription)
    }
}

Body:
Remove await from DispatchQueue closure.

Fixed：

    DispatchQueue.global().async {

    CreateFolder()

    do {
        let FilePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let FileName = UUID().uuidString
        try! Image.pngData()!.write(to: FilePath.appendingPathComponent("Images").appendingPathComponent("\(FileName).png"))
    } catch {
        Prompt(error.localizedDescription)
    }
    }


来源: stackexchange

问:
Swagger UI - " TypeError: Failed to fetch" on valid response
I've just pulled down the latest Swagger from the Git repo (3.0.19) using: https://github.com/swagger-api/swagger-ui.git and updated my API to use the new version.

Ran git describe --tags to confirm and my version is currently: v3.0.19-6-gaab1403

The problem I'm having is one described here, whereby my response is a 403 (I can see this in the inspector on the browser) and although I have a reponse for error 403, I still get the TypeError: Failed to fetch message.

Here's a snippet from my definition regarding the 403 response:

```<code>                    "403": {
                    "description": "Forbidden",
                    "headers": {
                        "Access-Control-Allow-Origin": {
                            "type": "string"
                        }
                    }
                },
</code>```

I've also noticed it reported here however, I know it's not a CORS issue as I have tested the endpoints and the OPTIONS are returning correct, as are the endpoints if called with valid information (I force this 403).

Could anyone point me in the right direction please?

Update: I have since tested on a 401 response, with the same response.

And that a 400 is working as expected:

答:
Below article might help.
I was facing same issue when from Swagger ui calling API Gateway which further calls Lambda function using proxy integration (which passes response headers from lambda). In my case I missed to set response headers Access-Control-Allow-Origin in Spring boot app lambda handler response-event object APIGatewayProxyResponseEvent. After setting this header in handler class, Swagger UI was able to call api gateway. See
https://fanchenbao.medium.com/thanks-for-the-article-it-is-a-great-way-to-get-started-with-deploying-swagger-ui-on-s3-7990c7b48851</p>

ContentLicense: CC BY-SA 3.0

Body:
I've just pulled down the latest Swagger from the Git repo (3.0.19) using: https://github.com/swagger-api/swagger-ui.git and updated my API to use the new version.

Ran git describe --tags to confirm and my version is currently: v3.0.19-6-gaab1403

The problem I'm having is one described here, whereby my response is a 403 (I can see this in the inspector on the browser) and although I have a reponse for error 403, I still get the TypeError: Failed to fetch message.

Here's a snippet from my definition regarding the 403 response:

                    "403": {
                    "description": "Forbidden",
                    "headers": {
                        "Access-Control-Allow-Origin": {
                            "type": "string"
                        }
                    }
                },

I've also noticed it reported here however, I know it's not a CORS issue as I have tested the endpoints and the OPTIONS are returning correct, as are the endpoints if called with valid information (I force this 403).

Could anyone point me in the right direction please?

Update: I have since tested on a 401 response, with the same response.

And that a 400 is working as expected:

ContentLicense: CC BY-SA 4.0


问:
How do I get the asdoc output table to show both the variable labels and value labels in Stata?
I'm trying to make a table using asdoc that will include both the value labels and the variable labels in the output. When I run the following line of code in Stata

```<code>asdoc list progname progtype progterm publicprivate cohortsize grereq, label
</code>```

I get this in the console (no variable labels):

But in the word doc, it comes out looking like this (has variable labels but no value labels in the table cells):

How do I get both the variable and value labels in the table?

答:
The last update of asdoc was on April 10, 2021. I announced the following in that update.

It is now almost three years that I have been developing asdoc and constantly adding features to it. With the addition of _docx and xl() classes to Stata, it is high time to add support for native docx and xlsx output to asdoc. Also, given that there exists a significant number of LaTeX users, asdoc should be able to create LaTeX documents.  It gives me immense pleasure to announce asdocx that is not only more flexible in making customized tables, but also creates documents in native docx, xlsx, html, and tex formats. If you have enjoyed and find asdoc useful, please consider buying a copy of asdocx to support its development. Details related to asdocx can be found on  this page.

I am still committed to fixing bugs / issues in asdoc. However, I think it makes more sense to me to add features to asdocx than asdoc, given that asdocx supports all latest developments in Word, Excel and LaTeX.

The requested feature is already available in asdocx. See the following example.

```<code>sysuse nlsw88
asdocx list industry age race married grade south in 1/20, replace label
</code>```

Body:
I'm trying to make a table using asdoc that will include both the value labels and the variable labels in the output. When I run the following line of code in Stata

asdoc list progname progtype progterm publicprivate cohortsize grereq, label

I get this in the console (no variable labels):

But in the word doc, it comes out looking like this (has variable labels but no value labels in the table cells):

How do I get both the variable and value labels in the table?

Body:
The last update of asdoc was on April 10, 2021. I announced the following in that update.

It is now almost three years that I have been developing asdoc and constantly adding features to it. With the addition of _docx and xl() classes to Stata, it is high time to add support for native docx and xlsx output to asdoc. Also, given that there exists a significant number of LaTeX users, asdoc should be able to create LaTeX documents.  It gives me immense pleasure to announce asdocx that is not only more flexible in making customized tables, but also creates documents in native docx, xlsx, html, and tex formats. If you have enjoyed and find asdoc useful, please consider buying a copy of asdocx to support its development. Details related to asdocx can be found on  this page.

I am still committed to fixing bugs / issues in asdoc. However, I think it makes more sense to me to add features to asdocx than asdoc, given that asdocx supports all latest developments in Word, Excel and LaTeX.

The requested feature is already available in asdocx. See the following example.

sysuse nlsw88
asdocx list industry age race married grade south in 1/20, replace label


问:
How to transform a process model into a code?
I need to tranform this scheme of the process flow into a code using only the functions in the table. I think, that there should be a loop after a decision if C1 or C2 is true, but I do not know how to exit the loop afterwards. Bold circle in the right is the final state.  enter image description here</p>

答:
The break statement can be used to jump out of a loop.

IF (C1 != TRUE AND C2 != TRUE)
BREAK;


问:
Vue Uncaught ReferenceError: process is not defined
I'm working on a Vue + typescript project. I want to use process.env.var_name to adjust the project is in development mode or production mode, just like

```<code>const isProduct = process.env.APP_ENV === "prod";
</code>```

; however I got an error below. I never meet this error before, so could any one give me a clue why this would happen so I can try to figure out what happend in the project and then fix it.

答:
I have a quasar project before and this one works for me.

I installed the dotenv library by running the yarn command

```<code>yarn add --dev dotenv
</code>```

Please let me know.

Body:
I'm working on a Vue + typescript project. I want to use process.env.var_name to adjust the project is in development mode or production mode, just like

const isProduct = process.env.APP_ENV === "prod";

; however I got an error below. I never meet this error before, so could any one give me a clue why this would happen so I can try to figure out what happend in the project and then fix it.

Body:
I have a quasar project before and this one works for me.

I installed the dotenv library by running the yarn command

yarn add --dev dotenv

Please let me know.


问:
How to change the textTheme in the ThemeData class?
I cannot change the color of the TextTheme property in the ThemeData class even though the code doesn't give any error.
Here is what I have done so far:

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

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

class BMICalculator extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        appBarTheme: AppBarTheme(
          backgroundColor: Color(0xff0a0e21),
        ),
        scaffoldBackgroundColor: Color(0xff0a0e21),
        textTheme: TextTheme(bodyText1: TextStyle(color: Colors.blue)),//the text remains white in the app.
      ),
      home: InputPage(),
    );
  }
}

class InputPage extends StatefulWidget {
  @override
  _InputPageState createState() => _InputPageState();
}

class _InputPageState extends State<InputPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BMI CALCULATOR'),
      ),
      body: Center(
        child: Text('Body Text'),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () => print('object'),
      ),
    );
  }
}
</code>```

What am I doing wrong?

答:
As much as I know there are a-lot of different properties in TextTheme class, such as bodytext1, bodytext2, headline1, headline2, caption etc etc...
And you can configure many of them to use them later, but there is no catalog or confirmation that which part of the app it will be applied to, i.e. Out of all the places that uses the text widget, to which bodytext1 will be applied to it is not known...but overtime you will get the feel for it.

But for now you have to call it manually where-ever you want to use that specific text configuration, such as in your code you have to do it like:

```<code>return Scaffold(
  appBar: AppBar(
    title: Text('BMI CALCULATOR'),
  ),
  body: Center(
    child: Text('Body Text', style: Theme.of(context).textTheme.bodyText1,),
  ),
  floatingActionButton: FloatingActionButton(
    child: Icon(Icons.add),
    onPressed: () => print('object'),
  ),
);
</code>```

The main point of adding theme is code-reusability and making it dynamic which is obviously achieved by this too.

Body:
I cannot change the color of the TextTheme property in the ThemeData class even though the code doesn't give any error.
Here is what I have done so far:

import 'package:flutter/material.dart';

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

class BMICalculator extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        appBarTheme: AppBarTheme(
          backgroundColor: Color(0xff0a0e21),
        ),
        scaffoldBackgroundColor: Color(0xff0a0e21),
        textTheme: TextTheme(bodyText1: TextStyle(color: Colors.blue)),//the text remains white in the app.
      ),
      home: InputPage(),
    );
  }
}

class InputPage extends StatefulWidget {
  @override
  _InputPageState createState() => _InputPageState();
}

class _InputPageState extends State<InputPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BMI CALCULATOR'),
      ),
      body: Center(
        child: Text('Body Text'),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () => print('object'),
      ),
    );
  }
}

What am I doing wrong?

Body:
As much as I know there are a-lot of different properties in TextTheme class, such as bodytext1, bodytext2, headline1, headline2, caption etc etc...
And you can configure many of them to use them later, but there is no catalog or confirmation that which part of the app it will be applied to, i.e. Out of all the places that uses the text widget, to which bodytext1 will be applied to it is not known...but overtime you will get the feel for it.

But for now you have to call it manually where-ever you want to use that specific text configuration, such as in your code you have to do it like:

return Scaffold(
  appBar: AppBar(
    title: Text('BMI CALCULATOR'),
  ),
  body: Center(
    child: Text('Body Text', style: Theme.of(context).textTheme.bodyText1,),
  ),
  floatingActionButton: FloatingActionButton(
    child: Icon(Icons.add),
    onPressed: () => print('object'),
  ),
);

The main point of adding theme is code-reusability and making it dynamic which is obviously achieved by this too.


问:
What is the correct way to prevent an error in React when an array of objects is still undefined?
It's common in React that an element is rendered before all its variables are defined, with final rendering being correct. To prevent fatal errors we usually use the ? operator as suggested in the response to Question by coding:

```<code>const property1 = object?.property1
</code>```

rather than:

const property1 = object.property1 or const { property1 } = object

This approach doesn't work when the object is an array of objects, for instance if I want to preempt a fatal error in react while my array is undefined, I can't use:

```<code>const property1 = array?[0]?.property1
</code>```

since it is syntactically incorrect (should it be?), so I am using:

```<code> `const property1 = array && array[0]?.property1`
</code>```

Is that the correct way?

Daniel Beck corrected an error in my original question, that is now fixed indicating that an alternative way to handle this situation would be:

```<code>const uid = array ? array[0].uid : undefined
</code>```

答:
You can use Array.isArray() method to determine whether the passed value is an Array or not.

Working Demo :

let obj = {
    property1: 'alpha'
};

const property1 = Array.isArray(obj) ? obj[0]?.property1 : obj.property1;

console.log(property1);```

Body:
It's common in React that an element is rendered before all its variables are defined, with final rendering being correct. To prevent fatal errors we usually use the ? operator as suggested in the response to Question by coding:

const property1 = object?.property1

rather than:

const property1 = object.property1 or const { property1 } = object

This approach doesn't work when the object is an array of objects, for instance if I want to preempt a fatal error in react while my array is undefined, I can't use:

const property1 = array?[0]?.property1

since it is syntactically incorrect (should it be?), so I am using:

 `const property1 = array && array[0]?.property1`

Is that the correct way?

Daniel Beck corrected an error in my original question, that is now fixed indicating that an alternative way to handle this situation would be:

const uid = array ? array[0].uid : undefined


问:
Are loop variables in Fortran SAVEd?
I have SAVE statement in subroutine or function. Also I haven't IMPLICIT NONE. In that case are loop variables in Fortran SAVEd? Example:

```<code>FUNCTION GLOB7S(P)
      REAL LONG
      LOGICAL mess
      COMMON/iounit/konsol,mess
      COMMON/LPOLY/PLG(9,4),CTLOC,STLOC,C2TLOC,S2TLOC,C3TLOC,S3TLOC,
     $ IYR,DAY,DF,DFA,APD,APDF,APT(4),LONG
      COMMON/CSW/SW(25),ISW,SWC(25)
      DIMENSION P(100),T(14)
      SAVE
      DATA DR/1.72142E-2/,DGTR/1.74533E-2/,PSET/2./
      DATA DAYL/-1./,P32,P18,P14,P39/4*-1000./
!$OMP THREADPRIVATE(/iounit/)
!$OMP THREADPRIVATE(/LPOLY/)
!$OMP THREADPRIVATE(/CSW/)

!$OMP THREADPRIVATE(T,DR,DGTR,PSET,DAYL,P32,P18,P14,P39)
!$OMP THREADPRIVATE(CD32,CD18,CD14,CD39)
!$OMP THREADPRIVATE(T71,T72,T81,T82,TT,GLOB7S)
C       CONFIRM PARAMETER SET
      IF(P(100).EQ.0) P(100)=PSET
      IF(P(100).NE.PSET) THEN
        if(mess) WRITE(konsol,900) PSET,P(100)
  900   FORMAT(1X,'WRONG PARAMETER SET FOR GLOB7S',3F10.1)
        STOP
      ENDIF
      DO 10 J=1,14
        T(J)=0.
   10 CONTINUE
      IF(DAY.NE.DAYL.OR.P32.NE.P(32)) CD32=COS(DR*(DAY-P(32)))
      IF(DAY.NE.DAYL.OR.P18.NE.P(18)) CD18=COS(2.*DR*(DAY-P(18)))
      IF(DAY.NE.DAYL.OR.P14.NE.P(14)) CD14=COS(DR*(DAY-P(14)))
      IF(DAY.NE.DAYL.OR.P39.NE.P(39)) CD39=COS(2.*DR*(DAY-P(39)))
      DAYL=DAY
      P32=P(32)
      P18=P(18)
      P14=P(14)
      P39=P(39)
...
</code>```

In this example is J SAVEd? I need to know this, because I'm trying to parallelize very old and very big Fortran code with OpenMP and I don't shure that I use THREADPRIVATE directive right.

答:
A DO construct of the form of the question is not a scoping unit. Further, a "loop variable" for such a construct is not a privileged entity: it's just a variable in the scope containing the loop which is used in a particular way.

j in this case is variable which exists before the DO construct, and it exists after the DO construct.

That j is of implicitly declared type is not relevant: a variable which is not a construct or statement entity with implicit type exists throughout the scoping unit (and possibly others) in which the reference appears (see later). That is, the implicitly typed j here exists throughout the function, not just from the point where it appears in the DO construct.

The SAVE statement applies to the whole (non-inclusive) scoping unit. If j is a local variable (in this case, not use- or host-associated) then the SAVE saves it.

As Steve Lionel points out in a comment, in general, things can be much more complicated. Although not relevant to this question there are exceptions to what may otherwise be seen as blanket statements above.

Consider the similar concepts (switching to free form code for clarity)

```<code>integer t(10)

data (t(j), integer :: j=1,10)/10*0/

t = [(0, integer :: j=1,10)]

forall (integer :: j=1:10) t(j) = 0

do concurrent (integer :: j=1:10)
  t(j) = 0
end do

end program
</code>```

In each of these cases j is of the scope of the statement or DO CONCURRENT construct. The SAVE statement will not apply to these variables, because they are not then local variables of the scoping unit.

Even without the explicit integer :: j, using implicit typing, these forms do not implicitly declare a variable outside the statement or construct.

In other constructs, such as an ASSOCIATE construct:

```<code>associate (a => 1+2)
end associate
</code>```

the entity has the scope of the construct, but in this case we should note that the type of any construct entity is not implicit: it is exactly that of the selector rather than being based on first letter of its name.

Finally, note that there is (currently) no such thing as

```<code>do integer :: j=1,10
end do
</code>```

which makes the normal DO construct pretty boring in this respect.

Title: Are loop variables in Fortran SAVEd?

Body:
I have SAVE statement in subroutine or function. Also I haven't IMPLICIT NONE. In that case are loop variables in Fortran SAVEd? Example:

FUNCTION GLOB7S(P)
      REAL LONG
      LOGICAL mess
      COMMON/iounit/konsol,mess
      COMMON/LPOLY/PLG(9,4),CTLOC,STLOC,C2TLOC,S2TLOC,C3TLOC,S3TLOC,
     $ IYR,DAY,DF,DFA,APD,APDF,APT(4),LONG
      COMMON/CSW/SW(25),ISW,SWC(25)
      DIMENSION P(100),T(14)
      SAVE
      DATA DR/1.72142E-2/,DGTR/1.74533E-2/,PSET/2./
      DATA DAYL/-1./,P32,P18,P14,P39/4*-1000./
!$OMP THREADPRIVATE(/iounit/)
!$OMP THREADPRIVATE(/LPOLY/)
!$OMP THREADPRIVATE(/CSW/)

!$OMP THREADPRIVATE(T,DR,DGTR,PSET,DAYL,P32,P18,P14,P39)
!$OMP THREADPRIVATE(CD32,CD18,CD14,CD39)
!$OMP THREADPRIVATE(T71,T72,T81,T82,TT,GLOB7S)
C       CONFIRM PARAMETER SET
      IF(P(100).EQ.0) P(100)=PSET
      IF(P(100).NE.PSET) THEN
        if(mess) WRITE(konsol,900) PSET,P(100)
  900   FORMAT(1X,'WRONG PARAMETER SET FOR GLOB7S',3F10.1)
        STOP
      ENDIF
      DO 10 J=1,14
        T(J)=0.
   10 CONTINUE
      IF(DAY.NE.DAYL.OR.P32.NE.P(32)) CD32=COS(DR*(DAY-P(32)))
      IF(DAY.NE.DAYL.OR.P18.NE.P(18)) CD18=COS(2.*DR*(DAY-P(18)))
      IF(DAY.NE.DAYL.OR.P14.NE.P(14)) CD14=COS(DR*(DAY-P(14)))
      IF(DAY.NE.DAYL.OR.P39.NE.P(39)) CD39=COS(2.*DR*(DAY-P(39)))
      DAYL=DAY
      P32=P(32)
      P18=P(18)
      P14=P(14)
      P39=P(39)
...

In this example is J SAVEd? I need to know this, because I'm trying to parallelize very old and very big Fortran code with OpenMP and I don't shure that I use THREADPRIVATE directive right.

Body:
A DO construct of the form of the question is not a scoping unit. Further, a "loop variable" for such a construct is not a privileged entity: it's just a variable in the scope containing the loop which is used in a particular way.

j in this case is variable which exists before the DO construct, and it exists after the DO construct.

That j is of implicitly declared type is not relevant: a variable which is not a construct or statement entity with implicit type exists throughout the scoping unit (and possibly others) in which the reference appears (see later). That is, the implicitly typed j here exists throughout the function, not just from the point where it appears in the DO construct.

The SAVE statement applies to the whole (non-inclusive) scoping unit. If j is a local variable (in this case, not use- or host-associated) then the SAVE saves it.

As Steve Lionel points out in a comment, in general, things can be much more complicated. Although not relevant to this question there are exceptions to what may otherwise be seen as blanket statements above.

Consider the similar concepts (switching to free form code for clarity)

integer t(10)

data (t(j), integer :: j=1,10)/10*0/

t = [(0, integer :: j=1,10)]

forall (integer :: j=1:10) t(j) = 0

do concurrent (integer :: j=1:10)
  t(j) = 0
end do

end program

In each of these cases j is of the scope of the statement or DO CONCURRENT construct. The SAVE statement will not apply to these variables, because they are not then local variables of the scoping unit.

Even without the explicit integer :: j, using implicit typing, these forms do not implicitly declare a variable outside the statement or construct.

In other constructs, such as an ASSOCIATE construct:

associate (a => 1+2)
end associate

the entity has the scope of the construct, but in this case we should note that the type of any construct entity is not implicit: it is exactly that of the selector rather than being based on first letter of its name.

Finally, note that there is (currently) no such thing as

do integer :: j=1,10
end do

which makes the normal DO construct pretty boring in this respect.


问:
Ajax request - get form data and loop through element_name[]
I am performing an AJAX-Reqest with form data and additional data as array (selected_members)

```<code>$.ajax({
    type: "POST",
    url: "inc/insert.inc.php",
    data: {
        frmData: $("#frmData").serialize(),
        selected_members: selected_members
    },
</code>```

How can I get these data in insert.inc.php as two arrays (form data and selected_members)?
The form contains also elements with name="element_name[]"

```<code>    var_dump($_POST);
        array(2) {
  ["frmData"]=>
  string(232) "datDate=2022-02-13&tmBeginn=17%3A00&tmEnde=17%3A00&cmb_Mittel%5B%5D=1&txt_Aufwandmenge%5B%5D=1&txt_mKh%5B%5D=1&cmb_Mittel%5B%5D=2&txt_Aufwandmenge%5B%5D=2&txt_mKh%5B%5D=3&cmbGeraet=1&cmbDuese=1&txtWasser=300&cmbGasse=2&cmbAnwender=1"
  ["selected_members"]=>
  array(2) {
    [0]=>
    string(1) "3"
    [1]=>
    string(1) "4"
  }
}
</code>```

How can I get the form data, and loop through each "row" of the three element_name[] inputs?

答:
As we can see, cmb_item and txt_amount are existing values in $yourarray and they are arrays of items. They do not need to be associative arrays, because they share the same name and differ in value only. In order to refer to them, you can simply do $yourarray['cmb_item'] and $yourarray['txt_amount'], respectively.

EDIT

Example:

```<code><?php

$foo = 'datDate=2022-02-13&tmStart=15%3A00&tmEnd=15%3A00&cmb_item%5B%5D=1&txt_amount%5B%5D=30&cmb_item%5B%5D=2&txt_amount%5B%5D=50&&cmbDevice=1';

parse_str($foo, $bar);

echo var_dump($bar['cmb_item']);
</code>```

The result is

```<code>array(2) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
}
</code>```

Body:
I am performing an AJAX-Reqest with form data and additional data as array (selected_members)

$.ajax({
    type: "POST",
    url: "inc/insert.inc.php",
    data: {
        frmData: $("#frmData").serialize(),
        selected_members: selected_members
    },

How can I get these data in insert.inc.php as two arrays (form data and selected_members)?
The form contains also elements with name="element_name[]"

    var_dump($_POST);
        array(2) {
  ["frmData"]=>
  string(232) "datDate=2022-02-13&tmBeginn=17%3A00&tmEnde=17%3A00&cmb_Mittel%5B%5D=1&txt_Aufwandmenge%5B%5D=1&txt_mKh%5B%5D=1&cmb_Mittel%5B%5D=2&txt_Aufwandmenge%5B%5D=2&txt_mKh%5B%5D=3&cmbGeraet=1&cmbDuese=1&txtWasser=300&cmbGasse=2&cmbAnwender=1"
  ["selected_members"]=>
  array(2) {
    [0]=>
    string(1) "3"
    [1]=>
    string(1) "4"
  }
}

How can I get the form data, and loop through each "row" of the three element_name[] inputs?

Body:
As we can see, cmb_item and txt_amount are existing values in $yourarray and they are arrays of items. They do not need to be associative arrays, because they share the same name and differ in value only. In order to refer to them, you can simply do $yourarray['cmb_item'] and $yourarray['txt_amount'], respectively.

EDIT

Example:

<?php

$foo = 'datDate=2022-02-13&tmStart=15%3A00&tmEnd=15%3A00&cmb_item%5B%5D=1&txt_amount%5B%5D=30&cmb_item%5B%5D=2&txt_amount%5B%5D=50&&cmbDevice=1';

parse_str($foo, $bar);

echo var_dump($bar['cmb_item']);

The result is

array(2) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
}


问:
Laravel Sum with where and alias with Eloquent
I have this query for an old Codeigniter project:

```<code>$this->db->select("SUM(source = 'FBS) AS facebook");
$this->db->select("SUM(source = 'FBS' AND promotion = 0) AS facebook_promotion");
$this->db->select("SUM(source = 'IG') AS instagram");
$this->db->select("SUM(source = 'LP') AS landing_page");
</code>```

I'd like to have same result using Laravel, if is possible with Eloquent instead of Query Builder or Raw Query.

答:
Solved in this way using DB::raw;</p>
```<code>$data = CONTACT::select(
    DB::raw('DATE_FORMAT(created_at, "%m-%d-%Y")),
    DB::raw('SUM(source = "IG") as instagram'),
    DB::raw('SUM(source = "FBS") as facebook')
)
->orderBy('data', 'DESC')
->groupBy(DB::raw("DATE_FORMAT(created_at, '%d-%m-%Y')"))
->get();
return response()->json(['success' => $data], 200);
</code>```

Body:
I have this query for an old Codeigniter project:

$this->db->select("SUM(source = 'FBS) AS facebook");
$this->db->select("SUM(source = 'FBS' AND promotion = 0) AS facebook_promotion");
$this->db->select("SUM(source = 'IG') AS instagram");
$this->db->select("SUM(source = 'LP') AS landing_page");

I'd like to have same result using Laravel, if is possible with Eloquent instead of Query Builder or Raw Query.

Body:
Solved in this way using DB::raw;

$data = CONTACT::select(
    DB::raw('DATE_FORMAT(created_at, "%m-%d-%Y")),
    DB::raw('SUM(source = "IG") as instagram'),
    DB::raw('SUM(source = "FBS") as facebook')
)
->orderBy('data', 'DESC')
->groupBy(DB::raw("DATE_FORMAT(created_at, '%d-%m-%Y')"))
->get();
return response()->json(['success' => $data], 200);


问:
How do you do a 3-way merge in FileMerge?
I see the option for specifying three files (left, right, and ancestor), but it doesn't seem to be possible to actually display the ancestor.

The bottom pane shows the result of the merge. I'd rather see what the original content was, so I could understand the context for the left and right sides of the conflict. Is this possible? FileMerge has awful help documentation.

答:
Looks like in version 2.5 they have finally added this feature. "Ancestor" now actually means "Ancestor" and there is a separate "merge" option

From the command line you can do something like this:

```<code>$ opendiff mine theirs --ancestor base
</code>```

Where "mine" is my version of the file, "theirs" is the version I'm trying to merge with, and "base" is the common ancestor of "mine" and "theirs.

This command will open File Merge and show the ancestor at the bottom (where the merge is in my example from 2010).

Unfortunately, it's not possible to use the --merge option along with the --ancestor option. So you can't view a three-way merge AND use File Merge to resolve the conflicts at the same time.

I am starting to use File Merge for viewing and understanding the conflict, then editing the conflict markers in a text editor as usual. (sigh...)

Body:
Looks like in version 2.5 they have finally added this feature. "Ancestor" now actually means "Ancestor" and there is a separate "merge" option

From the command line you can do something like this:

$ opendiff mine theirs --ancestor base

Where "mine" is my version of the file, "theirs" is the version I'm trying to merge with, and "base" is the common ancestor of "mine" and "theirs.

This command will open File Merge and show the ancestor at the bottom (where the merge is in my example from 2010).

Unfortunately, it's not possible to use the --merge option along with the --ancestor option. So you can't view a three-way merge AND use File Merge to resolve the conflicts at the same time.

I am starting to use File Merge for viewing and understanding the conflict, then editing the conflict markers in a text editor as usual. (sigh...)


问:
Docker container to container DNS with containerised DNS server
I'm having difficulty figuring out how to get the DNS working for container to container communication. I have dnsmasq and Traefik as well as a bunch of other services. The below docker-compose.yml is a trimmed down version to illustrate my setup.

Essentially I think I want to direct containers and external traffic looking for *.domain.test to the Traefik container. I've gone round in circles looking for an elegant way to do this. Any help is much appreciated.

After bringing the stack up I run:

```<code>docker run --rm --network=traefik praqma/network-multitool dig domain.test
</code>```

and get:

```<code>; <<>> DiG 9.14.8 <<>> domain.test
;; global options: +cmd
:: connection timed out; no servers could be reached
</code>```

docker-compose.yml

```<code>version: "3.7"

networks:
  dns: {}
  traefik:
    name: traefik

volumes:
  heimdall-data:

services:
  dnsmasq:
    cap_add:
    - NET_ADMIN
    command:
    - --cache-size=1000
    - --local-ttl=10
    - --address=/.domain.test/192.168.1.10
    - --address=/#/0.0.0.0
    container_name: dnsmasq
    image: andyshinn/dnsmasq:2.78
    labels:
      traefik.enable: "False"
    networks:
      dns: null
    ports:
    - "53:53/tcp"
    - "53:53/udp"
    restart: unless-stopped

  traefik:
    command:
    - --api.insecure=true
    - --providers.docker=true
    - --providers.docker.exposedbydefault=true
    - --entrypoints.web.address=:80
    - --log.level=ERROR
    container_name: traefik
    image: traefik:2.1
    labels:
      traefik.enable: "true"
      traefik.http.routers.api.entrypoints: web
      traefik.http.routers.api.rule: Host(`traefik.domain.test`)
      traefik.http.routers.api.service: api@internal
    networks:
      traefik: null
    ports:
    - 80:80
    - 443:443
    restart: unless-stopped
    volumes:
    - /var/run/docker.sock:/var/run/docker.sock:ro

  heimdall:
    container_name: heimdall
    image: linuxserver/heimdall:2.2.2-ls66
    labels:
      traefik.docker.network: traefik
      traefik.http.routers.heimdall.entrypoints: web
      traefik.http.routers.heimdall.rule: Host(`www.domain.test`, `domain.test`)
    networks:
      traefik: null
    restart: unless-stopped
    volumes:
    - heimdall-data:/config:rw

</code>```

答:
when you run your container with --net or --network docker will use a self DNS server to discover services that run with it. and all DNS queries sent to the docker engine.

in normal time (when using default network) you can use the --dns option on your run command
but when you run your images with a self-defined network you must add your customize resolv. conf file to the container.
you make an on your system and name it custom-resolv.conf.

at this file, you can add your custom dns address and add it to your container.

```<code>nameserver 1.0.0.1
nameserver 4.2.2.4
</code>```

then you must add this small part to your run command:

```<code>-v /path/to/file/custom-resolv.conf:/etc/resolv.conf:ro
</code>```
```<code>docker run --rm --network=traefik -v /path/to/file/custom-resolv.conf:/etc/resolv.conf:ro praqma/network-multitool dig domain.test
</code>```

use ro for read-only volume mapping.
ven your container started you can exec to your container and check /etc/resolv.conf file
that must be the same as custom-resolv.conf

now all your DNS requests are sent to your DNS server

Body:
I'm having difficulty figuring out how to get the DNS working for container to container communication. I have dnsmasq and Traefik as well as a bunch of other services. The below docker-compose.yml is a trimmed down version to illustrate my setup.

Essentially I think I want to direct containers and external traffic looking for *.domain.test to the Traefik container. I've gone round in circles looking for an elegant way to do this. Any help is much appreciated.

After bringing the stack up I run:

docker run --rm --network=traefik praqma/network-multitool dig domain.test

and get:

; <<>> DiG 9.14.8 <<>> domain.test
;; global options: +cmd
:: connection timed out; no servers could be reached

docker-compose.yml

version: "3.7"

networks:
  dns: {}
  traefik:
    name: traefik

volumes:
  heimdall-data:

services:
  dnsmasq:
    cap_add:
    - NET_ADMIN
    command:
    - --cache-size=1000
    - --local-ttl=10
    - --address=/.domain.test/192.168.1.10
    - --address=/#/0.0.0.0
    container_name: dnsmasq
    image: andyshinn/dnsmasq:2.78
    labels:
      traefik.enable: "False"
    networks:
      dns: null
    ports:
    - "53:53/tcp"
    - "53:53/udp"
    restart: unless-stopped

  traefik:
    command:
    - --api.insecure=true
    - --providers.docker=true
    - --providers.docker.exposedbydefault=true
    - --entrypoints.web.address=:80
    - --log.level=ERROR
    container_name: traefik
    image: traefik:2.1
    labels:
      traefik.enable: "true"
      traefik.http.routers.api.entrypoints: web
      traefik.http.routers.api.rule: Host(`traefik.domain.test`)
      traefik.http.routers.api.service: api@internal
    networks:
      traefik: null
    ports:
    - 80:80
    - 443:443
    restart: unless-stopped
    volumes:
    - /var/run/docker.sock:/var/run/docker.sock:ro

  heimdall:
    container_name: heimdall
    image: linuxserver/heimdall:2.2.2-ls66
    labels:
      traefik.docker.network: traefik
      traefik.http.routers.heimdall.entrypoints: web
      traefik.http.routers.heimdall.rule: Host(`www.domain.test`, `domain.test`)
    networks:
      traefik: null
    restart: unless-stopped
    volumes:
    - heimdall-data:/config:rw

Body:
when you run your container with --net or --network docker will use a self DNS server to discover services that run with it. and all DNS queries sent to the docker engine.

in normal time (when using default network) you can use the --dns option on your run command
but when you run your images with a self-defined network you must add your customize resolv. conf file to the container.
you make an on your system and name it custom-resolv.conf.

at this file, you can add your custom dns address and add it to your container.

nameserver 1.0.0.1
nameserver 4.2.2.4

then you must add this small part to your run command:

-v /path/to/file/custom-resolv.conf:/etc/resolv.conf:ro

docker run --rm --network=traefik -v /path/to/file/custom-resolv.conf:/etc/resolv.conf:ro praqma/network-multitool dig domain.test

use ro for read-only volume mapping.
ven your container started you can exec to your container and check /etc/resolv.conf file
that must be the same as custom-resolv.conf

now all your DNS requests are sent to your DNS server


问:
Failed to connect to mysql at 127.0.0.1:3306 with user root access denied for user 'root'@'localhost'(using password:YES)
I've been trying to create a new database connection on workbench. However, every time I test a connection there is an error message that says

Failed to connect to mysql at 127.0.0.1:3306 with user root access denied for user 'root'@'localhost'(using password:YES)

I don't know what's the cause of this error. I have tried uninstalling and re-installing my workbench 6.1 and mysql server 5.6 but the error is still unsolved.

答:
https://i.stack.imgur.com/AHYaI.png - click on "ADD"

https://i.stack.imgur.com/pzSOD.png - select a server from the given list

next ->  next ->  add a password and click "finish"..

check the connection using the workbench


问:
Error: cannot find symbol import com.google.android.gms.ads.InterstitialAd
I had added google AdMob to the project and found this error :
error: cannot find symbol
import com.google.android.gms.ads.InterstitialAd;
^
symbol:   class InterstitialAd
location: package com.google.android.gms.ads</p>

答:
If you get this error after updating your com.google.android.gms:play-services-ads dependency to a more recent version, know that importing com.google.android.gms.ads.InterstitialAd has been deprecated since version 19.7.0 and has since been totally removed.

The new import should be:

import com.google.android.gms.ads.interstitial.InterstitialAd;
```

Either revert com.google.android.gms:play-services-ads to a version pre-19.7.0 or update your code by following the documentation here: https://developers.google.com/admob/android/interstitial.

Body:
If you get this error after updating your com.google.android.gms:play-services-ads dependency to a more recent version, know that importing com.google.android.gms.ads.InterstitialAd has been deprecated since version 19.7.0 and has since been totally removed.

The new import should be:

import com.google.android.gms.ads.interstitial.InterstitialAd;

Either revert com.google.android.gms:play-services-ads to a version pre-19.7.0 or update your code by following the documentation here: https://developers.google.com/admob/android/interstitial.


问:
Agents not leaving the queue before a transporter is free
in my model I have a queue were multiple agents from different sources come together to seize an transporter ( see picture). But now they leave immediately after they enter the queue to the seize transporter block. But I want to keep them in to queue until a transporter is free and then the first one in the queue should seize a transporter and so should move to the seize transporter block. How should I fix this?

答:
seizeTransporter has its own embedded queue. You can access that value with seizeTransporter4.size(). If you insist on having them separately, instead of queue, use delay block, with stopDelay option. Whenever the seizeTransporter4.size() drops below number of available transporters, run the stop delay function. Like

```<code>if (seizeTransporter4.size()<=3){
myDelay.stopDelay(myDelay.get(0));
}

</code>```

Body:
seizeTransporter has its own embedded queue. You can access that value with seizeTransporter4.size(). If you insist on having them separately, instead of queue, use delay block, with stopDelay option. Whenever the seizeTransporter4.size() drops below number of available transporters, run the stop delay function. Like

if (seizeTransporter4.size()<=3){
myDelay.stopDelay(myDelay.get(0));
}


问:
Transport error with Egit
I have set up a gitstack repo on a local server, I have also signed up for a free github account just to see what its like.

But when I try to clone a repository from either my local repository or git hub repository I get this error:

```<code>Transport Error
Cannot List the available branches
Reason:
Exception caught during execution of ls-remote command
</code>```

What does this mean and how do i go about solving this problem?

答:
There is another transport-related possible error when cloning a remote repository.

Cloning from a repository that does not yet have any branches or tags but has other refs resulted in a "remote transport reported error", which has been corrected with Git 2.36 (Q2 2022).

See commit dccea60 (24 Jan 2022) by Jonathan Tan (jhowtan).

(Merged by Junio C Hamano -- gitster -- in commit d991df4, 09 Feb 2022)

clone: support unusual remote ref configurations

Signed-off-by: Jonathan Tan

When cloning a branchless and tagless but not refless remote using protocol v0 or v1, Git calls transport_fetch_refs() with an empty ref list.

This makes the clone fail with the message "remote transport reported error".

Git should have refrained from calling transport_fetch_refs(), just like it does in the case that the remote is refless.

Therefore, teach Git to do this.

In protocol v2, this does not happen because the client passes ref-prefix arguments that filter out non-branches and non-tags in the ref advertisement, making the remote appear empty.

Note that this bug concerns logic in builtin/clone.c and only affects cloning, not fetching.

Title: Transport error with Egit

Body:
I have set up a gitstack repo on a local server, I have also signed up for a free github account just to see what its like.

But when I try to clone a repository from either my local repository or git hub repository I get this error:

Transport Error
Cannot List the available branches
Reason:
Exception caught during execution of ls-remote command

What does this mean and how do i go about solving this problem?


问:
In Rails 3.x, how to design a view for a nested resource that refers to the parent resource?
Let's say I have a nested resource like in the Rails guide example:
http://guides.rubyonrails.org/routing.html#nested-resources

```<code>resources :magazines do
  resources :ads
end
</code>```

This routes a call to /magazines/newsweek/ads to the AdsController#index. It requires a magazine_id in the URL...how should I go about creating a view that is based off of a template used for Ads#index yet also includes the context of the parent resource?

For example, all parent resources that have Ads will have a table list of those ads. But I'd like the top of the view to include boilerplate information for each Magazine. If /magazines/newsweek/ads goes directly to the generic AdsController#index, how do I make that #index view aware of the need to include boilerplate generated from the Magazine model?

And if other models have relationships to ads (TelevisionShow has_many :ads), I'd like AdsController#index to react differently to those as well.

EDIT:

This is how I've done such things in the past, going through MagazinesController. Let's say I want a separate Magazine#show action...the routes would be:

```<code>resources :magazines
resources :ads
get "magazines/:id/ads", :controller=>"companies", :action=>"ads"
</code>```

And the controller would be:

```<code>class MagazinesController < ApplicationController
  def show
    ...
  end

  def ads
    ...
  end

end
</code>```

And then Magazine#ads would have a partial for ads listings that would be shared across all other types of resources.

Makes sense to me, but that route seems like it could somehow be DRYer?

答:
It sounds like you should be working in the magazine controller.

```<code>#Magazine_controller
def show
  @magazine = Magazine.find(params[:id])
  @ads = @magazine.ads
end
</code>```

Then in your view just render a partial for your collection of ads. Your ads partial will be saved in the ads area.  So in your veiw:

```<code><%= render :partial => "ads/ad", :collection => @ads %>
</code>```

http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials

Body:
Let's say I have a nested resource like in the Rails guide example:
http://guides.rubyonrails.org/routing.html#nested-resources

resources :magazines do
  resources :ads
end

This routes a call to /magazines/newsweek/ads to the AdsController#index. It requires a magazine_id in the URL...how should I go about creating a view that is based off of a template used for Ads#index yet also includes the context of the parent resource?

For example, all parent resources that have Ads will have a table list of those ads. But I'd like the top of the view to include boilerplate information for each Magazine. If /magazines/newsweek/ads goes directly to the generic AdsController#index, how do I make that #index view aware of the need to include boilerplate generated from the Magazine model?

And if other models have relationships to ads (TelevisionShow has_many :ads), I'd like AdsController#index to react differently to those as well.

EDIT:

This is how I've done such things in the past, going through MagazinesController. Let's say I want a separate Magazine#show action...the routes would be:

resources :magazines
resources :ads
get "magazines/:id/ads", :controller=>"companies", :action=>"ads"

And the controller would be:

class MagazinesController < ApplicationController
  def show
    ...
  end

  def ads
    ...
  end

end

And then Magazine#ads would have a partial for ads listings that would be shared across all other types of resources.

Makes sense to me, but that route seems like it could somehow be DRYer?

Body:
It sounds like you should be working in the magazine controller.

#Magazine_controller
def show
  @magazine = Magazine.find(params[:id])
  @ads = @magazine.ads
end

Then in your view just render a partial for your collection of ads. Your ads partial will be saved in the ads area.  So in your veiw:

<%= render :partial => "ads/ad", :collection => @ads %>

http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials


问:
Stripe Webhooks StripeSignatureVerificationError
I'm currently testing the Stripe Webhook Endpoints for the Checkout Process.

I'm confused because Stripe shows two different snippets how to set up the Webhook endpoint in their docs.

In the Checkout Doc they show this code snippet:

```<code>const stripe = require('stripe')('sk_test_...');

// Find your endpoint's secret in your Dashboard's webhook settings
const endpointSecret = 'whsec_...';

// Using Express
const app = require('express')();

// Use body-parser to retrieve the raw body as a buffer
const bodyParser = require('body-parser');

// Match the raw body to content type application/json
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
  const sig = request.headers['stripe-signature'];

  let event;

  try {
    event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
  } catch (err) {
    return response.status(400).send(`Webhook Error: ${err.message}`);
  }

  // Handle the checkout.session.completed event
  if (event.type === 'checkout.session.completed') {
    const session = event.data.object;

    // Fulfill the purchase...
    handleCheckoutSession(session);
  }

  // Return a response to acknowledge receipt of the event
  response.json({received: true});
});

app.listen(8000, () => console.log('Running on port 8000'));
</code>```

And in their Webhook Docs they are showing this snippet:

```<code>const app = require('express')();
// Use body-parser to retrieve the raw body as a buffer
const bodyParser = require('body-parser');

// Match the raw body to content type application/json
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
  let event;

  try {
    event = JSON.parse(request.body);
  } catch (err) {
    response.status(400).send(`Webhook Error: ${err.message}`);
  }

  // Handle the event
  switch (event.type) {
    case 'payment_intent.succeeded':
      const paymentIntent = event.data.object;
      // Then define and call a method to handle the successful payment intent.
      // handlePaymentIntentSucceeded(paymentIntent);
      break;
    case 'payment_method.attached':
      const paymentMethod = event.data.object;
      // Then define and call a method to handle the successful attachment of a PaymentMethod.
      // handlePaymentMethodAttached(paymentMethod);
      break;
    // ... handle other event types
    default:
      // Unexpected event type
      return response.status(400).end();
  }
  // Return a response to acknowledge receipt of the event
  response.json({received: true});
});

app.listen(8000, () => console.log('Running on port 8000'));
</code>```

I tried both snippets but nothing seems to work for me.

The first one gives me the StripeSignatureVerificationError when I try to constructEvent(...)

and the second one is telling me that the Object event  is undefined.

Does someone know why both of these endpoints are not working for me ?

答:
Before using JSON Body parser configure to receive RAW body

```<code>app.use(bodyParser.raw({type: "*/*"}))  <-- This line need to be added
app.use(bodyParser.json())
</code>```

More discussion https://github.com/stripe/stripe-node/issues/331

Body:
I'm currently testing the Stripe Webhook Endpoints for the Checkout Process.

I'm confused because Stripe shows two different snippets how to set up the Webhook endpoint in their docs.

In the Checkout Doc they show this code snippet:

const stripe = require('stripe')('sk_test_...');

// Find your endpoint's secret in your Dashboard's webhook settings
const endpointSecret = 'whsec_...';

// Using Express
const app = require('express')();

// Use body-parser to retrieve the raw body as a buffer
const bodyParser = require('body-parser');

// Match the raw body to content type application/json
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
  const sig = request.headers['stripe-signature'];

  let event;

  try {
    event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
  } catch (err) {
    return response.status(400).send(`Webhook Error: ${err.message}`);
  }

  // Handle the checkout.session.completed event
  if (event.type === 'checkout.session.completed') {
    const session = event.data.object;

    // Fulfill the purchase...
    handleCheckoutSession(session);
  }

  // Return a response to acknowledge receipt of the event
  response.json({received: true});
});

app.listen(8000, () => console.log('Running on port 8000'));

And in their Webhook Docs they are showing this snippet:

const app = require('express')();
// Use body-parser to retrieve the raw body as a buffer
const bodyParser = require('body-parser');

// Match the raw body to content type application/json
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
  let event;

  try {
    event = JSON.parse(request.body);
  } catch (err) {
    response.status(400).send(`Webhook Error: ${err.message}`);
  }

  // Handle the event
  switch (event.type) {
    case 'payment_intent.succeeded':
      const paymentIntent = event.data.object;
      // Then define and call a method to handle the successful payment intent.
      // handlePaymentIntentSucceeded(paymentIntent);
      break;
    case 'payment_method.attached':
      const paymentMethod = event.data.object;
      // Then define and call a method to handle the successful attachment of a PaymentMethod.
      // handlePaymentMethodAttached(paymentMethod);
      break;
    // ... handle other event types
    default:
      // Unexpected event type
      return response.status(400).end();
  }
  // Return a response to acknowledge receipt of the event
  response.json({received: true});
});

app.listen(8000, () => console.log('Running on port 8000'));

I tried both snippets but nothing seems to work for me.

The first one gives me the StripeSignatureVerificationError when I try to constructEvent(...)

and the second one is telling me that the Object event  is undefined.

Does someone know why both of these endpoints are not working for me ?

Body:
Before using JSON Body parser configure to receive RAW body

app.use(bodyParser.raw({type: "*/*"}))  <-- This line need to be added
app.use(bodyParser.json())

More discussion https://github.com/stripe/stripe-node/issues/331


问:
ASP.NET Core routes GET call to DELETE method
I have an ASP.NET Core web API controller with (among others) two methods that have the same signature.

Shortened down, this looks as follows:

[Route("my/route")]
public class MyApiController : ApiController
{
    [HttpGet("{*id}", Order = 2)]
    [Route("{*id}", Order = 2)]
    public MyObject Load([FromUri] String id) => new MyObject();

    [HttpDelete("{*id}", Order = 1)]
    [Route("{*id}", Order = 1)]
    public void Delete([FromUri] String id)
    {
    }
}
```

Now, I am issuing a call:

GET my/route/123/456

Shockingly, this call ends up in the Delete method. I literally have a breapoint in the first line of my (in real life, non-empty) Delete method, and the Immediate window in VS tells me HttpContext.Request.Method is "GET", yet I end up in the method explicitly marked as HttpDelete.

What is going on here? Luckily, my call happened from within an automated test to test the web API, but if someone had issued that call to retrieve actual data from the DB, they would have ended up deleting that data instead. Is there any misunderstanding on my side with respect to the [HttpDelete] attribute?

答:
If you have an [ApiController] attribute, you have to remove it since you will need full explicit route attribute. Or  it is much better to use explicit routes</p>
```<code>[Route("my/[action]")]
public class MyApiController : ApiController
{
    [HttpGet("my/load/{id}")]
    public MyObject Load(string id) => new MyObject();

     [HttpDelete("my/delete/{id}")]
     [HttpGet("my/delete/{id}")]
    public void Delete(string id)
    {
    }
}
</code>```

Body:
I have an ASP.NET Core web API controller with (among others) two methods that have the same signature.

Shortened down, this looks as follows:

[Route("my/route")]
public class MyApiController : ApiController
{
    [HttpGet("{*id}", Order = 2)]
    [Route("{*id}", Order = 2)]
    public MyObject Load([FromUri] String id) => new MyObject();

    [HttpDelete("{*id}", Order = 1)]
    [Route("{*id}", Order = 1)]
    public void Delete([FromUri] String id)
    {
    }
}

Now, I am issuing a call:

GET my/route/123/456

Shockingly, this call ends up in the Delete method. I literally have a breapoint in the first line of my (in real life, non-empty) Delete method, and the Immediate window in VS tells me HttpContext.Request.Method is "GET", yet I end up in the method explicitly marked as HttpDelete.

What is going on here? Luckily, my call happened from within an automated test to test the web API, but if someone had issued that call to retrieve actual data from the DB, they would have ended up deleting that data instead. Is there any misunderstanding on my side with respect to the [HttpDelete] attribute?

Body:
If you have an [ApiController] attribute, you have to remove it since you will need full explicit route attribute. Or  it is much better to use explicit routes

[Route("my/[action]")]
public class MyApiController : ApiController
{
    [HttpGet("my/load/{id}")]
    public MyObject Load(string id) => new MyObject();

     [HttpDelete("my/delete/{id}")]
     [HttpGet("my/delete/{id}")]
    public void Delete(string id)
    {
    }
}


问:
Expose endpoint with native query without creating entity
I want to run some native queries and expose the results through endpoints, but I want to do this without having to create all the entities. I just want the data obtained from the database to be exposed as it comes.

I found some suggestions at: Create spring repository without entity

However, I was not able to make them work. I'm very new to Spring.

I tried Maciej Kowalski's solution like this:

Interface:

```<code>public interface CustomNativeRepository {
    Object runNativeQuery();
}
</code>```

Implementation:

```<code>@Repository
public class CustomNativeRepositoryImpl implements CustomNativeRepository {

    @Autowired
    private EntityManager entityManager;

    @Override
    public Object runNativeQuery() {
        return entityManager.createNativeQuery(
                """
                SELECT 1 as col1, 2 as col2, 3 as col3
                UNION ALL SELECT 4, 5, 6
                UNION ALL SELECT 7, 8, 9
                """
                )
        .getResultList();
    }
}
</code>```

However, no endpoints were exposed, as happens when you extend CrudRepository. Should I have done something else with CustomNativeRepositoryImpl? I don't know how to proceed.

I also tried Gagarwa's solution:

RootEntity:

```<code>@Entity
public class RootEntity {
    @Id
    private Integer id;
}
</code>```

RootEntityRepository:

```<code>@Repository
public interface RootEntityRepository extends JpaRepository<RootEntity, Integer> {

    @Query(value = """
            SELECT 1 as col1, 2 as col2, 3 as col3
            UNION ALL SELECT 4, 5, 6
            UNION ALL SELECT 7, 8, 9""",
            nativeQuery = true)
    public Collection<Object> findFromCustomQuery();

}
</code>```

The endpoint http://localhost:8080/rootEntities was exposed, but when I accessed it, I got the exception: "Relation root_entity does not exist". So, I created the table in the database:

```<code>create table root_entity(
    id SERIAL PRIMARY KEY
)
</code>```

After that, the endpoint worked, and returned an empty array (the table root_entity is empty in the database).

I tried to access the endpoint: http://localhost:8080/rootEntities/search/findFromCustomQuery, but I got an exception (Couldn't find PersistentEntity for type class).

Again, I was not able to make it work.

After trying a lot, I made some progress doing the following:

```<code>@RestController
public class CustomQueryController {

    @Autowired
    private EntityManager entityManager;

    @GetMapping("/myEndpoint")
    @ResponseBody
    public Object runNativeQuery() {

        return ResponseEntity
                .ok()
                .body(
                    entityManager.createNativeQuery(
                        """
                        SELECT 1 as col1, 2 as col2, 3 as col3
                        UNION ALL SELECT 4, 5, 6
                        UNION ALL SELECT 7, 8, 9
                        """
                    ).getResultList()
                );
    }
}
</code>```

With the code above, I can access http://localhost:8080/myEndpoint and see the result of the query.

However, the endpoint didn't appear in the endpoints listing that is showed in http://localhost:8080/. I had to type it manually in the browser. I would like the endpoint to be exposed in order to see it in Swagger.

Also, I have a feeling that there must be a better way to do this. And I want to learn.

I would like help to:

Get a solution that works and exposes the endpoint.

Understand what I did wrong and how to implement Kowalski's and Gagarwa's solutions.

Being able to expose the endpoint for the last solution (CustomQueryController).

Thanks in advance!

答:
try changing your CustomQueryController to implement RepresentationModelProcessor

```<code>public class CustomQueryController implements RepresentationModelProcessor<RepresentationModel<RepositoryLinksResource>> {
</code>```

and implementing the process method with:

```<code>@Override
public RepresentationModel<RepositoryLinksResource> process(RepresentationModel<RepositoryLinksResource> model) {
    if (model instanceof RepositoryLinksResource) {
        model.add(Link.of( "http://localhost:8080" + "/myEndpoint", "myEndpoint"));
    }
    return model;
}
</code>```

https://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.customizing-json-output.representation-model-processor

Body:
I want to run some native queries and expose the results through endpoints, but I want to do this without having to create all the entities. I just want the data obtained from the database to be exposed as it comes.

I found some suggestions at: Create spring repository without entity

However, I was not able to make them work. I'm very new to Spring.

I tried Maciej Kowalski's solution like this:

Interface:

public interface CustomNativeRepository {
    Object runNativeQuery();
}

Implementation:

@Repository
public class CustomNativeRepositoryImpl implements CustomNativeRepository {

    @Autowired
    private EntityManager entityManager;

    @Override
    public Object runNativeQuery() {
        return entityManager.createNativeQuery(
                """
                SELECT 1 as col1, 2 as col2, 3 as col3
                UNION ALL SELECT 4, 5, 6
                UNION ALL SELECT 7, 8, 9
                """
                )
        .getResultList();
    }
}

However, no endpoints were exposed, as happens when you extend CrudRepository. Should I have done something else with CustomNativeRepositoryImpl? I don't know how to proceed.

I also tried Gagarwa's solution:

RootEntity:

@Entity
public class RootEntity {
    @Id
    private Integer id;
}

RootEntityRepository:

@Repository
public interface RootEntityRepository extends JpaRepository<RootEntity, Integer> {

    @Query(value = """
            SELECT 1 as col1, 2 as col2, 3 as col3
            UNION ALL SELECT 4, 5, 6
            UNION ALL SELECT 7, 8, 9""",
            nativeQuery = true)
    public Collection<Object> findFromCustomQuery();

}

The endpoint http://localhost:8080/rootEntities was exposed, but when I accessed it, I got the exception: "Relation root_entity does not exist". So, I created the table in the database:

create table root_entity(
    id SERIAL PRIMARY KEY
)

After that, the endpoint worked, and returned an empty array (the table root_entity is empty in the database).

I tried to access the endpoint: http://localhost:8080/rootEntities/search/findFromCustomQuery, but I got an exception (Couldn't find PersistentEntity for type class).

Again, I was not able to make it work.

After trying a lot, I made some progress doing the following:

@RestController
public class CustomQueryController {

    @Autowired
    private EntityManager entityManager;

    @GetMapping("/myEndpoint")
    @ResponseBody
    public Object runNativeQuery() {

        return ResponseEntity
                .ok()
                .body(
                    entityManager.createNativeQuery(
                        """
                        SELECT 1 as col1, 2 as col2, 3 as col3
                        UNION ALL SELECT 4, 5, 6
                        UNION ALL SELECT 7, 8, 9
                        """
                    ).getResultList()
                );
    }
}

With the code above, I can access http://localhost:8080/myEndpoint and see the result of the query.

However, the endpoint didn't appear in the endpoints listing that is showed in http://localhost:8080/. I had to type it manually in the browser. I would like the endpoint to be exposed in order to see it in Swagger.

Also, I have a feeling that there must be a better way to do this. And I want to learn.

I would like help to:

Get a solution that works and exposes the endpoint.

Understand what I did wrong and how to implement Kowalski's and Gagarwa's solutions.

Being able to expose the endpoint for the last solution (CustomQueryController).

Thanks in advance!

Body:
try changing your CustomQueryController to implement RepresentationModelProcessor

public class CustomQueryController implements RepresentationModelProcessor<RepresentationModel<RepositoryLinksResource>> {

and implementing the process method with:

@Override
public RepresentationModel<RepositoryLinksResource> process(RepresentationModel<RepositoryLinksResource> model) {
    if (model instanceof RepositoryLinksResource) {
        model.add(Link.of( "http://localhost:8080" + "/myEndpoint", "myEndpoint"));
    }
    return model;
}

https://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.customizing-json-output.representation-model-processor


问:
Basic practice for throwing exception/error from function
For example I have script like this

```<code>def form_valid:
    temp = form.save(commit=False)
    try:
       temp.contents = makecontents()
    except:
        messages.error(self.request, error)
        return self.render_to_response(self.get_context_data(form=form))
    messages.success(self.request, self.success_message)
    return super().form_valid(form)

def makecontents():
    if (if works well):
       return "this is my contents"
    else:
       return "this is error!!"
</code>```

So, my basic idea is when makecontents() success it returns the string s and set this as member of model instance.

However makecontents() failed , I want to return the error to form_valid.

So, maybe ,, I should change return "this is error!!" somehow..

Is it possible? , or my idea is wrong??

答:
you could use anraise '<an Exception Type>("error message")' to raise an Error, and then except Exception as e: to get the exception message:

```<code>def makecontents(works_well):
    try:
        if (works_well):
            return "this is my contents"
        else:
            raise SyntaxError("this is an error")
    except Exception as e:
        return str(e)
print(makecontents(works_well=False).__repr__())
</code>```

output:

```<code>"this is an error"
</code>```

Body:
For example I have script like this

def form_valid:
    temp = form.save(commit=False)
    try:
       temp.contents = makecontents()
    except:
        messages.error(self.request, error)
        return self.render_to_response(self.get_context_data(form=form))
    messages.success(self.request, self.success_message)
    return super().form_valid(form)

def makecontents():
    if (if works well):
       return "this is my contents"
    else:
       return "this is error!!"

So, my basic idea is when makecontents() success it returns the string s and set this as member of model instance.

However makecontents() failed , I want to return the error to form_valid.

So, maybe ,, I should change return "this is error!!" somehow..

Is it possible? , or my idea is wrong??

Body:
you could use anraise '<an Exception Type>("error message")' to raise an Error, and then except Exception as e: to get the exception message:

def makecontents(works_well):
    try:
        if (works_well):
            return "this is my contents"
        else:
            raise SyntaxError("this is an error")
    except Exception as e:
        return str(e)
print(makecontents(works_well=False).__repr__())

output:

"this is an error"


问:
How do I fetch a value from a var file using Jinja2 into an JSON file in Ansible
I would like to fetch/replace a value in the input YAML — abc.yml — from a var file — var.yml — based on the matching id value (here id value is 123) between input file and var file using Jinja2 and create a JSON as expected result.

Jinja2 code:

```<code>[
    {% for list in abc['fwrules'] %}
        {
            {% for item in abc['details'] %}
            "country": "{{item.Country}}",
            "destCidr": "{{list.destCidr}}"
            {% endfor %}
        }{% if not loop.last %},
        {% endif %}
    {% endfor %}
]
</code>```

Input yml — abc.yml:

---
details:
         -   Country: "abc"
             id: 123
fwrules:
         -   destCidr: "{{ DNS }}, 10.20.20.20/24"
             srcCidr: "10.30.20.20/24"

         -   destCidr: "10.30.30.30/24"
             srcCidr: "{{ NTP }}, 10.40.20.20/24"
```
<p>Var file — <em>var.yml</em>:</p>
<pre class="lang-yaml prettyprint-override"><code>---
names:
    -   id: "123"
        DNS: "10.10.10.10"
        NTP: "10.100.100.100"

    -   id: "456"
        DNS: "20.20.20.20"
        NTP: "10.200.200.200"
</code>```

Expected JSON result:

[
    {
        "country": "abc",
        "destCidr": "10.10.10.10, 10.20.20.20/24",
        "srcCidr": "10.30.20.20/24"
    },
    {
        "country": "abc",
        "destCidr": "10.30.30.30/24"
        "srcCidr": "10.100.100.100, 10.40.20.20/24"
    }
]
```

答:
You can achieve this with the usage of filters only.

Given the two yaml — abc.yml and var.yml — you provided, using this two tasks:

- include_vars:
    file: "{{ item }}.yml"
  loop:
    - var
    - abc

- set_fact:
    output: >-
      {{
        output | default([])
          + [{
            'country': details.0.Country,
            'destCidr': item.destCidr,
            'srcCidr': item.srcCidr
          }]
      }}
  loop: "{{ fwrules }}"
  vars:
    _matched_id: >-
      {{
        names
        | selectattr('id', 'eq', details.0.id | string)
        | first
      }}
    DNS: "{{ _matched_id.DNS }}"
    NTP: "{{ _matched_id.NTP }}"
```
<p>Would create a variable <code>output</code> having your desired output.</p>
<pre class="lang-none prettyprint-override"><code>TASK [debug] ********************************************************************
ok: [localhost] => {
    "output": [
        {
            "country": "abc",
            "destCidr": "10.10.10.10, 10.20.20.20/24",
            "srcCidr": "10.30.20.20/24"
        },
        {
            "country": "abc",
            "destCidr": "10.30.30.30/24",
            "srcCidr": "10.100.100.100, 10.40.20.20/24"
        }
    ]
}
</code>```

You can, then, dump that output in a JSON file if that's what you need:

- copy:
    content: "{{ output | to_nice_json }}"
    dest: output.json
```

Body:
I would like to fetch/replace a value in the input YAML — abc.yml — from a var file — var.yml — based on the matching id value (here id value is 123) between input file and var file using Jinja2 and create a JSON as expected result.

Jinja2 code:

[
    {% for list in abc['fwrules'] %}
        {
            {% for item in abc['details'] %}
            "country": "{{item.Country}}",
            "destCidr": "{{list.destCidr}}"
            {% endfor %}
        }{% if not loop.last %},
        {% endif %}
    {% endfor %}
]

Input yml — abc.yml:

---
details:
         -   Country: "abc"
             id: 123
fwrules:
         -   destCidr: "{{ DNS }}, 10.20.20.20/24"
             srcCidr: "10.30.20.20/24"

         -   destCidr: "10.30.30.30/24"
             srcCidr: "{{ NTP }}, 10.40.20.20/24"

Var file — var.yml:

---
names:
    -   id: "123"
        DNS: "10.10.10.10"
        NTP: "10.100.100.100"

    -   id: "456"
        DNS: "20.20.20.20"
        NTP: "10.200.200.200"

Expected JSON result:

[
    {
        "country": "abc",
        "destCidr": "10.10.10.10, 10.20.20.20/24",
        "srcCidr": "10.30.20.20/24"
    },
    {
        "country": "abc",
        "destCidr": "10.30.30.30/24"
        "srcCidr": "10.100.100.100, 10.40.20.20/24"
    }
]

Body:
You can achieve this with the usage of filters only.

Given the two yaml — abc.yml and var.yml — you provided, using this two tasks:

- include_vars:
    file: "{{ item }}.yml"
  loop:
    - var
    - abc

- set_fact:
    output: >-
      {{
        output | default([])
          + [{
            'country': details.0.Country,
            'destCidr': item.destCidr,
            'srcCidr': item.srcCidr
          }]
      }}
  loop: "{{ fwrules }}"
  vars:
    _matched_id: >-
      {{
        names
        | selectattr('id', 'eq', details.0.id | string)
        | first
      }}
    DNS: "{{ _matched_id.DNS }}"
    NTP: "{{ _matched_id.NTP }}"

Would create a variable output having your desired output.

TASK [debug] ********************************************************************
ok: [localhost] => {
    "output": [
        {
            "country": "abc",
            "destCidr": "10.10.10.10, 10.20.20.20/24",
            "srcCidr": "10.30.20.20/24"
        },
        {
            "country": "abc",
            "destCidr": "10.30.30.30/24",
            "srcCidr": "10.100.100.100, 10.40.20.20/24"
        }
    ]
}

You can, then, dump that output in a JSON file if that's what you need:

- copy:
    content: "{{ output | to_nice_json }}"
    dest: output.json


问:
What the heck is this: background-image: url("/images/sprites.png?v=3");

Possible Duplicate:

  What's a queryString doing in this stylesheet's href?

Can someone explain the significance and function of the 1) query string and 2) specific name/value pair (e.g. ?v=3) in the css snippet please?

```<code>/*Here is the snippet:*/
    .css-class {
       background-image: url("/images/sprites.png?v=3");
    }
</code>```

I've seen this used on link tags also on http://html5boilerplate.com/:

```<code>   <link rel="stylesheet" href="css/style.css?v=2">
</code>```

答: It's like version. WHen there is a new version, owners want you to use new updated one, not one from cache, so ?v is changed and CSS is redownloaded

Body:
Possible Duplicate:

  What's a queryString doing in this stylesheet's href?

Can someone explain the significance and function of the 1) query string and 2) specific name/value pair (e.g. ?v=3) in the css snippet please?

/*Here is the snippet:*/
    .css-class {
       background-image: url("/images/sprites.png?v=3");
    }

I've seen this used on link tags also on http://html5boilerplate.com/:

   <link rel="stylesheet" href="css/style.css?v=2">


问:
Can I supply image icons in Java in a higher resolution to avoid blurred icons after scaling?
I am designing a GUI with Java Swing and AWT (Java 8) and am struggling with the icons I use.

I load a large PNG image and scale it to 18x18px and then use it in a button or label. It works well in all resolutions when the operating system does not zoom in.

However, with the advent of large screen resolutions (hidpi), it is common practice to use operating system settings to zoom in on user interface controls, including buttons and such things in Java applications. For example, on Windows I use a 150% or 200% scaling of user elements with my 4K resolution to ensure the user interface is still usable. I imagine many users will do so as well.

When that is the case, however, the icons are merely increased in size after already scaling them down to 18x18px. That is, I first scale them down and then the operating system tries to scale them up again with the little information that is still left in the image.

Is there any way to design image icons in Java that are based on a higher resolution when the zooming/scaling capabilities of the operating system are used in order to avoid them appearing blurred?

Here is a working example:

import java.awt.Container;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
class Example extends JFrame {

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

    public Example() {
        Container c = getContentPane();
        JPanel panel = new JPanel();
        ImageIcon icon = new ImageIcon(new ImageIcon(getClass().getResource("tabler-icon-beach.png")).getImage().getScaledInstance(18, 18, Image.SCALE_SMOOTH));
        JButton button = new JButton("Test button", icon);
        panel.add(button);
        c.add(panel);
        this.pack();
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
}
```

You can find the icon here. All icons are available as PNG or SVG files.

To illustrate the problem, let me first show you two screenshots in the normal 100% screen resolution:

On Linux with 100% zoom:

On Windows with 100% zoom:

And now when I set Windows 7 to have a 200% magnification of layout elements, it's obviously just the 18x18px version stretched out, which becomes blurred:

Is there any way to provide a higher-resolution image icon that is used when the operating system uses a scaling that is larger than 100%? Moreover, you can see that even at 100% the image quality is not perfect; is there any way to improve that as well?

答:
Java 8 does not support High DPI, the UI gets scaled up by Windows. You should use Java 11 or a later version which support per-monitor High DPI settings.

If your goal is to make the icons look crisp, prepare a set of icons for different resolutions using BaseMultiResolutionImage (the basic implementation of MultiResolutionImage) to provide higher resolution alternatives. (These are not available in Java 8.)

You say that you scaled down the original image (240×240) to 18×18px. If the UI needs a higher resolution according to the system setting, all it has now is your small icon (18×18) which will be scaled up, which results in poor quality. You should use a MultiResolutionImage or paint the original image into the required size, letting Graphics to scale it down for you.

No Down-Scale

This is the simplest way I came up with to make the icon 18×18 without downscaling the original image:

```<code>private static final String IMAGE_URL =
        "https://tabler-icons.io/static/tabler-icons/icons-png/beach.png";

private static ImageIcon getIcon() {
    return new ImageIcon(Toolkit.getDefaultToolkit()
                                .getImage(new URL(IMAGE_URL))) {
        @Override
        public int getIconWidth() {
            return 18;
        }
        @Override
        public int getIconHeight() {
            return 18;
        }

        @Override
        public synchronized void paintIcon(Component c, Graphics g,
                                           int x, int y) {
            g.drawImage(getImage(), x, y, 18, 18, null);
        }
    };
}
</code>```

I left out the exception handling code for MalformedURLException which can be thrown from the URL constructor.

In this case, the painted image gets down-scaled each time it's painted, which is ineffective. Yet the quality is better. Well, for the standard resolution screen, it's nearly the same as if you down-scaled the image when loading. But in High DPI case, it looks better. It's because for 200% UI Scale, the image will be rendered to 36×36 pixels and these pixels will be created from the source of 240×240 rather than up-scaling the down-scaled version which lost its quality.

To get even better results, I recommend using MultiResolutionImage.

MultiResolutionImage

The app below loads the images from base64-encoded strings (for simplicity so that there are no external dependencies). There are three variants provided: 24×24 (100%, 96dpi), 36×36 (150%, 144dpi), 48×48 (200%, 192dpi).

If the current scale factor is set to any of the provided resolutions, the image will be rendered as is. If 125% or 175% are used, the larger image will be scaled down; if the scale is greater than 200%, then the image for 200% will be scaled up. You can add more resolutions if needed.

The app doesn't compile in Java 8 because MultiResolutionImage is not available there. To compile it with JDK 11, you have to replace text blocks with regular String concatenation.

import java.awt.Image;
import java.awt.image.BaseMultiResolutionImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Base64;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class BeachIconButton {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(BeachIconButton::new);
    }

    private BeachIconButton() {
        JPanel panel = new JPanel();
        ImageIcon icon = getIcon();
        JButton button = new JButton("Test button", icon);
        panel.add(button);

        JFrame frame = new JFrame("Beach Icon Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static ImageIcon getIcon() {
        return new ImageIcon(
               new BaseMultiResolutionImage(
               Arrays.stream(new String[] { BEACH_100, BEACH_150, BEACH_200})
                     .map(BeachIconButton::loadImage)
                     .toArray(Image[]::new)));
    }

    private static Image loadImage(String base64) {
        try {
            return ImageIO.read(new ByteArrayInputStream(
                                Base64.getMimeDecoder().decode(base64)));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static final String BEACH_100 = """
            iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAA7DAAAO
            wwHHb6hkAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAXxJ
            REFUSInl1E9LVVEUBfAfVJBIIoWGIDiRGtagN7Yg+gTZXPwICU4FyUGDahBRCTrK
            qUVNIxrkJHjWJMKZikIjSyHoYd0GZ186vOef7n2zWnB4e591WXudt/c5/G8Ywiw+
            4gd28QGLuNCt+C18RXHI+onJuuLjIVBgGWOYyPb2syI3q4qfzZw/ir1raMXeNBay
            k+zgfNUC25nTBWxGPhfffI78XfzOVD1FP+5lrgusoweXIv+C6xE3qxYocRFrWZHv
            eBPxA5yJeK9ugRJPdU7QGPoi3+1GfFBqZIFn+BVxC88jft9NgdL9q8gH8MSfUa3V
            5BKXQ6gl9aOdey1N2GBV4VO4ik/h8CWG67rMcQ53Hf5ErOBGXfEGtjKxVSxhHi/w
            LeMe4mQV8ROZ67fSZWrHadyW7kKBqaonuC89Bcc5uyKNZ+M4wTvS9d/AY/RmXK80
            iht/wa+HVgfKB61cTYzGaups8FH89kEFhjBSUzDnR0LrSFT5Sw7i/yH8BmQ0mnmX
            f2wqAAAAAElFTkSuQmCC""";

    private static final String BEACH_150 = """
            iVBORw0KGgoAAAANSUhEUgAAACQAAAAkCAYAAADhAJiYAAAACXBIWXMAABYlAAAW
            JQFJUiTwAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAoVJ
            REFUWIXt1kuoTVEYB/DfdZWiq7gykZBHHokyw0QGREpKLgMDGSojQ6+JARFi4JFn
            ySPyyoCJR8zcIUVJiPLopiMhLoO1d3ftc+7Z95xrnYHyr1V7feu/1/ff3/etby/+
            4x9DW8K9ZmE9FmTP7fiBp3iE03iS0F9dTMQN/G5gvMLMVopZhi8NisnHD6xohZiV
            2ea5o584h+WYgAclor5jaUoxE9ATOXiOednaUMUU9mKPkK5YVCXbJwkuKkZmYbS2
            t8rxpsz+QW2krqYSdF5tCnZjCX5F9h0Zf25k66nizEghaBSOV22cRyt/vhnxd0b2
            E7gQzXelEJRjnv6L96dQ9IR+9CxaWymcsnx+L6UgQnPtUizyfDwRaiiff8JwjIts
            71MLytGBy0I9xaLitG7LuCMi2+d4kyEJBVWwWkhPfz568UaI6Mho/XtCDTXYqO/L
            v+GF2jQ+wNZofrdVYjrwNnK0XYjOYSEt9bp20lMWY0/k5LVQJzlGCn2qur56Mb0V
            YiYLKcodddXhTcX1iJesU1cj/nc9NPA9axE2Cw02GUYITe6UYgoOCv+29pTOyjAH
            VxRT1N/4iP0Y2yohHTij9v810Khgiwavy43eqSfhGmZHtt/oxm2h4fUI0Zim75IW
            4wI24GuDPutiCF4q1sklAx/XJXisGK2zfysGhum7N3/F2ibebce+SNCdFIJgMQ4J
            F63BYBUOYEqzL87HLaEeKrivPCLrMk5lEPyezNf8MkHv9H9STioegDbF/vM3/Hdl
            grpLnBxFJ8bgWAmvWX53maBOId/jMRpHGnB8JOM2yx+f+eosE1SNNiH89TY/oTY1
            zfAHjS7hMv45G3exJiH/P/5d/AHE21JDZYKOHAAAAABJRU5ErkJggg==""";

    private static final String BEACH_200 = """
            iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAB2HAAAd
            hwGP5fFlAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAA5FJ
            REFUaIHt2ctrXFUcB/BPYoWGVGOwBZtYQQoqhUp9IFEoulC04spGExQEpYoiVBBc
            qVAVwYX/gEWqooKboItqN4oV0frWPgR3XRSl9mHT2GjaJh0X5w6ZOXPuzO08roL5
            wlnM+T3O93cev3vOb1jCEv7f6CtpnBswjg1Yh2HM4wx+wh58jC9K4lMIfXgIB1Ap
            2H7FC7jwX+Bbh2uwW3HiqUDWlE26io040YJgkXYKd5TM3Z34K0HmNKYwgavxgLD/
            WwUxi1vKIr8GfyRIfIAravTuxtmE3g+Jvkrm86pek+/XuOfP4elIbz1mIr15bBUm
            IG8lPtHjjLkpMeg+jNboDOKXSOcsJjP5bU0CqODBsgOoHsRnsRyvJ+RP1vh4PpId
            in7v7WUA/diRE0QFhxN92yMfeyL5MxoP+nW9DAJuxY85QdS2AxiosVsrnJmqfAGX
            4/3I7uVeBwAX4DEcaRLAFFbV2LwSyXdn/ZNR/86es6/BCmyTTpnVWX4Tl2pMv49k
            PtZF/QfLIl+L9fhN/mrEK3XE4vYajGQzZRKPcTuOyw+k2rbV2FwSyY7GTvt7yTjC
            UQwV0FspEKf+nMBcVxmdJz7VeEVYkF6F43gKD0f9H5bOOsN9Gkluws04lpBV21z0
            +7myiRO+wgcjInE6HE/opNpYOZTrEV8RzghX6hjLhWvHKWny35RBNsZogtCrLWxG
            8JrG8zHRO5r5eCci8bvFDNMKY/hMeNRsF77wpWJM/f2mgke7PciyLvtbKby4NuJe
            9Y+QGdyEv7FLSJX/CfThfqGmM691Jqlkep8L6bWs2lQSd+F7xUjnte+EYkCpGMQb
            HRKP247M73mhneVbhY9wY0J2TpjRnUKV4bBQIxrGalyPe4RSY+oe9q1who61wasQ
            +vC1xtlbwFu4sqCftXhb+i70lR6ei+HEgPtxbZv+NuDnhM/hjpnmoE+YoepAu7Sx
            byOsELZkWyvQzlINCTWaGbwnpMROsUx4/16Md3GyE2cDQqXsS0wLRPfhJfWFqjyM
            Zrr78WcX7KczLlvVVzJyMSU/1U1brKSlMJnp9Mp+qkgAs00cVL+imxN244p9iTux
            ny0SQLMVqLY5PCHs2SGhRHi6gF2n9oVWYABbhOLUZbgoGyx+3rUi+Hhm26n96ozL
            FgXPQB4262yLdGrfFUxo/vfRCc1fTp3adwUjeFEod5/M2l7h38WREuyXsIQl1OAf
            9zFZ1uiy3BkAAAAASUVORK5CYII=""";
}
```

Body:
I am designing a GUI with Java Swing and AWT (Java 8) and am struggling with the icons I use.

I load a large PNG image and scale it to 18x18px and then use it in a button or label. It works well in all resolutions when the operating system does not zoom in.

However, with the advent of large screen resolutions (hidpi), it is common practice to use operating system settings to zoom in on user interface controls, including buttons and such things in Java applications. For example, on Windows I use a 150% or 200% scaling of user elements with my 4K resolution to ensure the user interface is still usable. I imagine many users will do so as well.

When that is the case, however, the icons are merely increased in size after already scaling them down to 18x18px. That is, I first scale them down and then the operating system tries to scale them up again with the little information that is still left in the image.

Is there any way to design image icons in Java that are based on a higher resolution when the zooming/scaling capabilities of the operating system are used in order to avoid them appearing blurred?

Here is a working example:

import java.awt.Container;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
class Example extends JFrame {

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

    public Example() {
        Container c = getContentPane();
        JPanel panel = new JPanel();
        ImageIcon icon = new ImageIcon(new ImageIcon(getClass().getResource("tabler-icon-beach.png")).getImage().getScaledInstance(18, 18, Image.SCALE_SMOOTH));
        JButton button = new JButton("Test button", icon);
        panel.add(button);
        c.add(panel);
        this.pack();
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
}

You can find the icon here. All icons are available as PNG or SVG files.

To illustrate the problem, let me first show you two screenshots in the normal 100% screen resolution:

On Linux with 100% zoom:

On Windows with 100% zoom:

And now when I set Windows 7 to have a 200% magnification of layout elements, it's obviously just the 18x18px version stretched out, which becomes blurred:

Is there any way to provide a higher-resolution image icon that is used when the operating system uses a scaling that is larger than 100%? Moreover, you can see that even at 100% the image quality is not perfect; is there any way to improve that as well?

Body:
Java 8 does not support High DPI, the UI gets scaled up by Windows. You should use Java 11 or a later version which support per-monitor High DPI settings.

If your goal is to make the icons look crisp, prepare a set of icons for different resolutions using BaseMultiResolutionImage (the basic implementation of MultiResolutionImage) to provide higher resolution alternatives. (These are not available in Java 8.)

You say that you scaled down the original image (240×240) to 18×18px. If the UI needs a higher resolution according to the system setting, all it has now is your small icon (18×18) which will be scaled up, which results in poor quality. You should use a MultiResolutionImage or paint the original image into the required size, letting Graphics to scale it down for you.

No Down-Scale

This is the simplest way I came up with to make the icon 18×18 without downscaling the original image:

private static final String IMAGE_URL =
        "https://tabler-icons.io/static/tabler-icons/icons-png/beach.png";

private static ImageIcon getIcon() {
    return new ImageIcon(Toolkit.getDefaultToolkit()
                                .getImage(new URL(IMAGE_URL))) {
        @Override
        public int getIconWidth() {
            return 18;
        }
        @Override
        public int getIconHeight() {
            return 18;
        }

        @Override
        public synchronized void paintIcon(Component c, Graphics g,
                                           int x, int y) {
            g.drawImage(getImage(), x, y, 18, 18, null);
        }
    };
}

I left out the exception handling code for MalformedURLException which can be thrown from the URL constructor.

In this case, the painted image gets down-scaled each time it's painted, which is ineffective. Yet the quality is better. Well, for the standard resolution screen, it's nearly the same as if you down-scaled the image when loading. But in High DPI case, it looks better. It's because for 200% UI Scale, the image will be rendered to 36×36 pixels and these pixels will be created from the source of 240×240 rather than up-scaling the down-scaled version which lost its quality.

To get even better results, I recommend using MultiResolutionImage.

MultiResolutionImage

The app below loads the images from base64-encoded strings (for simplicity so that there are no external dependencies). There are three variants provided: 24×24 (100%, 96dpi), 36×36 (150%, 144dpi), 48×48 (200%, 192dpi).

If the current scale factor is set to any of the provided resolutions, the image will be rendered as is. If 125% or 175% are used, the larger image will be scaled down; if the scale is greater than 200%, then the image for 200% will be scaled up. You can add more resolutions if needed.

The app doesn't compile in Java 8 because MultiResolutionImage is not available there. To compile it with JDK 11, you have to replace text blocks with regular String concatenation.

import java.awt.Image;
import java.awt.image.BaseMultiResolutionImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Base64;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class BeachIconButton {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(BeachIconButton::new);
    }

    private BeachIconButton() {
        JPanel panel = new JPanel();
        ImageIcon icon = getIcon();
        JButton button = new JButton("Test button", icon);
        panel.add(button);

        JFrame frame = new JFrame("Beach Icon Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static ImageIcon getIcon() {
        return new ImageIcon(
               new BaseMultiResolutionImage(
               Arrays.stream(new String[] { BEACH_100, BEACH_150, BEACH_200})
                     .map(BeachIconButton::loadImage)
                     .toArray(Image[]::new)));
    }

    private static Image loadImage(String base64) {
        try {
            return ImageIO.read(new ByteArrayInputStream(
                                Base64.getMimeDecoder().decode(base64)));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static final String BEACH_100 = """
            iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAA7DAAAO
            wwHHb6hkAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAXxJ
            REFUSInl1E9LVVEUBfAfVJBIIoWGIDiRGtagN7Yg+gTZXPwICU4FyUGDahBRCTrK
            qUVNIxrkJHjWJMKZikIjSyHoYd0GZ186vOef7n2zWnB4e591WXudt/c5/G8Ywiw+
            4gd28QGLuNCt+C18RXHI+onJuuLjIVBgGWOYyPb2syI3q4qfzZw/ir1raMXeNBay
            k+zgfNUC25nTBWxGPhfffI78XfzOVD1FP+5lrgusoweXIv+C6xE3qxYocRFrWZHv
            eBPxA5yJeK9ugRJPdU7QGPoi3+1GfFBqZIFn+BVxC88jft9NgdL9q8gH8MSfUa3V
            5BKXQ6gl9aOdey1N2GBV4VO4ik/h8CWG67rMcQ53Hf5ErOBGXfEGtjKxVSxhHi/w
            LeMe4mQV8ROZ67fSZWrHadyW7kKBqaonuC89Bcc5uyKNZ+M4wTvS9d/AY/RmXK80
            iht/wa+HVgfKB61cTYzGaups8FH89kEFhjBSUzDnR0LrSFT5Sw7i/yH8BmQ0mnmX
            f2wqAAAAAElFTkSuQmCC""";

    private static final String BEACH_150 = """
            iVBORw0KGgoAAAANSUhEUgAAACQAAAAkCAYAAADhAJiYAAAACXBIWXMAABYlAAAW
            JQFJUiTwAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAoVJ
            REFUWIXt1kuoTVEYB/DfdZWiq7gykZBHHokyw0QGREpKLgMDGSojQ6+JARFi4JFn
            ySPyyoCJR8zcIUVJiPLopiMhLoO1d3ftc+7Z95xrnYHyr1V7feu/1/ff3/etby/+
            4x9DW8K9ZmE9FmTP7fiBp3iE03iS0F9dTMQN/G5gvMLMVopZhi8NisnHD6xohZiV
            2ea5o584h+WYgAclor5jaUoxE9ATOXiOednaUMUU9mKPkK5YVCXbJwkuKkZmYbS2
            t8rxpsz+QW2krqYSdF5tCnZjCX5F9h0Zf25k66nizEghaBSOV22cRyt/vhnxd0b2
            E7gQzXelEJRjnv6L96dQ9IR+9CxaWymcsnx+L6UgQnPtUizyfDwRaiiff8JwjIts
            71MLytGBy0I9xaLitG7LuCMi2+d4kyEJBVWwWkhPfz568UaI6Mho/XtCDTXYqO/L
            v+GF2jQ+wNZofrdVYjrwNnK0XYjOYSEt9bp20lMWY0/k5LVQJzlGCn2qur56Mb0V
            YiYLKcodddXhTcX1iJesU1cj/nc9NPA9axE2Cw02GUYITe6UYgoOCv+29pTOyjAH
            VxRT1N/4iP0Y2yohHTij9v810Khgiwavy43eqSfhGmZHtt/oxm2h4fUI0Zim75IW
            4wI24GuDPutiCF4q1sklAx/XJXisGK2zfysGhum7N3/F2ibebce+SNCdFIJgMQ4J
            F63BYBUOYEqzL87HLaEeKrivPCLrMk5lEPyezNf8MkHv9H9STioegDbF/vM3/Hdl
            grpLnBxFJ8bgWAmvWX53maBOId/jMRpHGnB8JOM2yx+f+eosE1SNNiH89TY/oTY1
            zfAHjS7hMv45G3exJiH/P/5d/AHE21JDZYKOHAAAAABJRU5ErkJggg==""";

    private static final String BEACH_200 = """
            iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAB2HAAAd
            hwGP5fFlAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAA5FJ
            REFUaIHt2ctrXFUcB/BPYoWGVGOwBZtYQQoqhUp9IFEoulC04spGExQEpYoiVBBc
            qVAVwYX/gEWqooKboItqN4oV0frWPgR3XRSl9mHT2GjaJh0X5w6ZOXPuzO08roL5
            wlnM+T3O93cev3vOb1jCEv7f6CtpnBswjg1Yh2HM4wx+wh58jC9K4lMIfXgIB1Ap
            2H7FC7jwX+Bbh2uwW3HiqUDWlE26io040YJgkXYKd5TM3Z34K0HmNKYwgavxgLD/
            WwUxi1vKIr8GfyRIfIAravTuxtmE3g+Jvkrm86pek+/XuOfP4elIbz1mIr15bBUm
            IG8lPtHjjLkpMeg+jNboDOKXSOcsJjP5bU0CqODBsgOoHsRnsRyvJ+RP1vh4PpId
            in7v7WUA/diRE0QFhxN92yMfeyL5MxoP+nW9DAJuxY85QdS2AxiosVsrnJmqfAGX
            4/3I7uVeBwAX4DEcaRLAFFbV2LwSyXdn/ZNR/86es6/BCmyTTpnVWX4Tl2pMv49k
            PtZF/QfLIl+L9fhN/mrEK3XE4vYajGQzZRKPcTuOyw+k2rbV2FwSyY7GTvt7yTjC
            UQwV0FspEKf+nMBcVxmdJz7VeEVYkF6F43gKD0f9H5bOOsN9Gkluws04lpBV21z0
            +7myiRO+wgcjInE6HE/opNpYOZTrEV8RzghX6hjLhWvHKWny35RBNsZogtCrLWxG
            8JrG8zHRO5r5eCci8bvFDNMKY/hMeNRsF77wpWJM/f2mgke7PciyLvtbKby4NuJe
            9Y+QGdyEv7FLSJX/CfThfqGmM691Jqlkep8L6bWs2lQSd+F7xUjnte+EYkCpGMQb
            HRKP247M73mhneVbhY9wY0J2TpjRnUKV4bBQIxrGalyPe4RSY+oe9q1who61wasQ
            +vC1xtlbwFu4sqCftXhb+i70lR6ei+HEgPtxbZv+NuDnhM/hjpnmoE+YoepAu7Sx
            byOsELZkWyvQzlINCTWaGbwnpMROsUx4/16Md3GyE2cDQqXsS0wLRPfhJfWFqjyM
            Zrr78WcX7KczLlvVVzJyMSU/1U1brKSlMJnp9Mp+qkgAs00cVL+imxN244p9iTux
            ny0SQLMVqLY5PCHs2SGhRHi6gF2n9oVWYABbhOLUZbgoGyx+3rUi+Hhm26n96ozL
            FgXPQB4262yLdGrfFUxo/vfRCc1fTp3adwUjeFEod5/M2l7h38WREuyXsIQl1OAf
            9zFZ1uiy3BkAAAAASUVORK5CYII=""";
}


问:
How do I get the user IP address from the incoming request in loopback 4?
Am new to loopback 4, I want to get the user IP address, their domain details, user agent and the url they are trying to access so on so i wrote a sequence, i have accessed the request context but couldn't get the exact key to find out the details am looking for</p>
```<code>export class MySequence extends MiddlewareSequence {
  async handle(context: RequestContext): Promise<void> {
    const {request, response} = context;

    console.log('Isnide', {request});
    const data = await super.handle(context);
  }
}
</code>```

答:
Have a look at the context documentation and the properties:

https://loopback.io/doc/en/lb4/apidocs.rest.requestcontext.html

context.requestedBaseUrl and context.basePath are probably useful to you.

If you want specific HTTP headers, see here:

https://developer.mozilla.org/en-US/docs/Glossary/Request_header

Host and Referer are probably interesting for you too.

Body:
Am new to loopback 4, I want to get the user IP address, their domain details, user agent and the url they are trying to access so on so i wrote a sequence, i have accessed the request context but couldn't get the exact key to find out the details am looking for

export class MySequence extends MiddlewareSequence {
  async handle(context: RequestContext): Promise<void> {
    const {request, response} = context;

    console.log('Isnide', {request});
    const data = await super.handle(context);
  }
}