问:
Google Maps Directions API blank response
I'm trying to get directions using the Google Maps Directions API.

It's pretty much what Google's own documentation shows to do https://developers.google.com/maps/documentation/directions/get-directions#maps_http_directions_toronto_montreal-java

The requested URL works when pasted into a browser, so that's correct.

And I can see an additional Directions API request after running this.

The response has no JSON directions in it.

What am I doing wrong?

```<code>private class getDirections extends AsyncTask<LatLng, Void, String> {
        @Override
        protected String doInBackground(LatLng... point) {
            try {
                OkHttpClient client = new OkHttpClient().newBuilder()
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .build();
                Request request = new Request.Builder()
                        .url("https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key="+MAPS_API_KEY)
                        .method("GET", null)
                        .build();
                    Response response = client.newCall(request).execute();
                    Log.d("response1", response.message());
                    if (response.message() == "") {
                        return "error";
                    }
                    return response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
        }

    }
</code>```

Image of 'response' in the debugger

答:
response.message() is not the body, it's just the string after the 200.

HTTP/1.1 200

check the response numerically or via if (!response.isSuccessful) {

This query is working for me.

```<code>{
  "geocoded_waypoints": [
    {
      "geocoder_status": "OK",
      "place_id": "ChIJpTvG15DL1IkRd8S0KlBVNTI",
      "types": [
        "locality",
        "political"
      ]
    },
    {
      "geocoder_status": "OK",
      "place_id": "ChIJDbdkHFQayUwR7-8fITgxTmU",
      "types": [
        "locality",
        "political"
      ]
    }
  ],
  "routes": [
    {
      "bounds": {
        "northeast": {
          "lat": 45.5017123,
          "lng": -73.5672184
        },
        "southwest": {
          "lat": 43.6533961,
          "lng": -79.3834913
        }
      },
</code>```

Body:
I'm trying to get directions using the Google Maps Directions API.

It's pretty much what Google's own documentation shows to do https://developers.google.com/maps/documentation/directions/get-directions#maps_http_directions_toronto_montreal-java

The requested URL works when pasted into a browser, so that's correct.

And I can see an additional Directions API request after running this.

The response has no JSON directions in it.

What am I doing wrong?

private class getDirections extends AsyncTask<LatLng, Void, String> {
        @Override
        protected String doInBackground(LatLng... point) {
            try {
                OkHttpClient client = new OkHttpClient().newBuilder()
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .build();
                Request request = new Request.Builder()
                        .url("https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key="+MAPS_API_KEY)
                        .method("GET", null)
                        .build();
                    Response response = client.newCall(request).execute();
                    Log.d("response1", response.message());
                    if (response.message() == "") {
                        return "error";
                    }
                    return response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
        }

    }

Image of 'response' in the debugger

Body:
response.message() is not the body, it's just the string after the 200.

HTTP/1.1 200

check the response numerically or via if (!response.isSuccessful) {

This query is working for me.

{
  "geocoded_waypoints": [
    {
      "geocoder_status": "OK",
      "place_id": "ChIJpTvG15DL1IkRd8S0KlBVNTI",
      "types": [
        "locality",
        "political"
      ]
    },
    {
      "geocoder_status": "OK",
      "place_id": "ChIJDbdkHFQayUwR7-8fITgxTmU",
      "types": [
        "locality",
        "political"
      ]
    }
  ],
  "routes": [
    {
      "bounds": {
        "northeast": {
          "lat": 45.5017123,
          "lng": -73.5672184
        },
        "southwest": {
          "lat": 43.6533961,
          "lng": -79.3834913
        }
      },


来源: stackexchange

问:
Cloudformation fails with 'failed validation constraint for keyword [pattern]'
I am trying to create a Workflow object using AWS CloudFormation. This workflow will be used with AWS File Transfer Family so that files get copied to S3 upon uploading.

```<code>AWSTemplateFormatVersion: "2010-09-09"

Resources:
  SftpToS3Workflow:
    Type: AWS::Transfer::Workflow
    Properties:
      Description: 'Workflow used by AWS File Transfer Family. Copies the files to S3'
      Steps:
        - Type: COPY
          CopyStepDetails:
            Name: copt-to-s3-wf-step
            DestinationFileLocation:
              S3FileLocation:
                Bucket: !ImportValue GenesysS3BucketName
                Key: "genesys/"
            OverwriteExisting: 'TRUE'

Outputs:
    SftpToS3WorkflowId:
      Description: 'Id of the Workflow'
      Value: !GetAtt SftpToS3Workflow.WorkflowId
      Export:
        Name: SftpToS3WorkflowId
</code>```

Unfortunately, this script fails with the below error. The error does not say what property is failing validation. Can someone help, please? I could not find even one single example on GitHub.

Properties validation failed for resource SftpToS3Workflow with message: #/Description: failed validation constraint for keyword [pattern]

I have used this CloudFormation schema to write the code:

https://github.com/APIs-guru/openapi-directory/blob/0380216a44c364b4517b31a93295089a6f4f23b9/APIs/amazonaws.com/transfer/2018-11-05/openapi.yaml

答:
The Description can only be

```<code>^[\w- ]*$
</code>```

So it should be:

```<code>Description: 'Workflow used by AWS File Transfer Family - Copies the files to S3'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a Workflow object using AWS CloudFormation. This workflow will be used with AWS File Transfer Family so that files get copied to S3 upon uploading.

AWSTemplateFormatVersion: "2010-09-09"

Resources:
  SftpToS3Workflow:
    Type: AWS::Transfer::Workflow
    Properties:
      Description: 'Workflow used by AWS File Transfer Family. Copies the files to S3'
      Steps:
        - Type: COPY
          CopyStepDetails:
            Name: copt-to-s3-wf-step
            DestinationFileLocation:
              S3FileLocation:
                Bucket: !ImportValue GenesysS3BucketName
                Key: "genesys/"
            OverwriteExisting: 'TRUE'

Outputs:
    SftpToS3WorkflowId:
      Description: 'Id of the Workflow'
      Value: !GetAtt SftpToS3Workflow.WorkflowId
      Export:
        Name: SftpToS3WorkflowId

Unfortunately, this script fails with the below error. The error does not say what property is failing validation. Can someone help, please? I could not find even one single example on GitHub.

Properties validation failed for resource SftpToS3Workflow with message: #/Description: failed validation constraint for keyword [pattern]

I have used this CloudFormation schema to write the code:

https://github.com/APIs-guru/openapi-directory/blob/0380216a44c364b4517b31a93295089a6f4f23b9/APIs/amazonaws.com/transfer/2018-11-05/openapi.yaml

Body:
The Description can only be

^[\w- ]*$

So it should be:

Description: 'Workflow used by AWS File Transfer Family - Copies the files to S3'


问:
Spring - display PDF-file in browser instead of downloading
i am trying to display a pdf in my browser with spring.
my problem is that the browser downloads the file instead of displaying it.
this is my code:

```<code>@RequestMapping(value="/getpdf1", method=RequestMethod.GET)
public ResponseEntity<byte[]> getPDF1() {

    HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    String filename = "pdf1.pdf";

    headers.add("content-disposition", "inline;filename=" + filename);

    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(pdf1Bytes, headers, HttpStatus.OK);
    return response;
}
</code>```

i am looking forward to your answers!
thanks

答:
View in browser (use inline) :

```<code>header.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + pdfFile.getName());
</code>```

For Download (use attachment) :

```<code>header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + pdfFile.getName());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i am trying to display a pdf in my browser with spring.
my problem is that the browser downloads the file instead of displaying it.
this is my code:

@RequestMapping(value="/getpdf1", method=RequestMethod.GET)
public ResponseEntity<byte[]> getPDF1() {

    HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    String filename = "pdf1.pdf";

    headers.add("content-disposition", "inline;filename=" + filename);

    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(pdf1Bytes, headers, HttpStatus.OK);
    return response;
}

i am looking forward to your answers!
thanks

Body:
View in browser (use inline) :

header.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + pdfFile.getName());

For Download (use attachment) :

header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + pdfFile.getName());


问:
Incompatible types: 'string' and 'Double'
I would like to use a Label or a Memo to view information:

```<code>function GetCPUSpeed: Double;
const
  DelayTime = 500;
var
  TimerHi, TimerLo: DWORD;
  PriorityClass, Priority: Integer;
begin
  PriorityClass := GetPriorityClass(GetCurrentProcess);
  Priority      := GetThreadPriority(GetCurrentThread);
  SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
  SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL);
  Sleep(10);
  asm
    dw 310Fh
    mov TimerLo, eax
    mov TimerHi, edx
  end;
  Sleep(DelayTime);
  asm
    dw 310Fh
    sub eax, TimerLo
    sbb edx, TimerHi
    mov TimerLo, eax
    mov TimerHi, edx
  end;
  SetThreadPriority(GetCurrentThread, Priority);
  SetPriorityClass(GetCurrentProcess, PriorityClass);
  Result := TimerLo / (1000 * DelayTime);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(Format('Your CPU speed: %f MHz', [GetCPUSpeed]));
  Label1.caption := GetCPUSpeed;
  Memo1.Lines := GetCPUSpeed;
end;
</code>```

To use the Label or a Memo, I have to convert data into a string. How can I do that?

[DCC Error] speed_cpu.pas(62): E2010 Incompatible types: 'string' and 'Double'

答:
Thank you problem solved.</p>
```<code>    function Tipo_cpu: string;
        var
          aVendor: array[0..2] of DWord;
          iI, iJ : Integer;
        begin
          asm
            push ebx
            xor   eax, eax
            dw    $A20F // CPUID instruction
            mov   DWord ptr aVendor, ebx
            mov   DWord ptr aVendor[+4], edx
            mov   DWord ptr aVendor[+8], ecx
            pop   ebx
          end;
          for iI := 0 to 2 do
            for iJ := 0 to 3 do
            Result := Result + Chr((aVendor[iI] and ($000000FF shl (iJ * 8))) shr (iJ * 8));
        end;

    function GetCPUSpeed: Double;
    const
      DelayTime = 500;
    var
      TimerHi, TimerLo: DWORD;
      PriorityClass, Priority: Integer;
    begin
      PriorityClass := GetPriorityClass(GetCurrentProcess);
      Priority      := GetThreadPriority(GetCurrentThread);
      SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
      SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL);
      Sleep(10);
      asm
        dw 310Fh
        mov TimerLo, eax
        mov TimerHi, edx
      end;
      Sleep(DelayTime);
      asm
        dw 310Fh
        sub eax, TimerLo
        sbb edx, TimerHi
        mov TimerLo, eax
        mov TimerHi, edx
      end;
      SetThreadPriority(GetCurrentThread, Priority);
      SetPriorityClass(GetCurrentProcess, PriorityClass);
      Result := TimerLo / (1000 * DelayTime);
    end;

procedure TForm1.FormCreate(Sender: TObject);
var
  ids: TidIpWatch;
  Speed: Double;
begin
 ids := TidIpWatch.Create;
 Speed := GetCPUSpeed;
 Memo1.Text := 'IP:' + (ids.LocalIP);
 Memo1.Text := (Tipo_cpu);
 Memo1.Text := Format('%f', [Speed]);
 ids.Free;
 end;
</code>```

Body:
I would like to use a Label or a Memo to view information:

function GetCPUSpeed: Double;
const
  DelayTime = 500;
var
  TimerHi, TimerLo: DWORD;
  PriorityClass, Priority: Integer;
begin
  PriorityClass := GetPriorityClass(GetCurrentProcess);
  Priority      := GetThreadPriority(GetCurrentThread);
  SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
  SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL);
  Sleep(10);
  asm
    dw 310Fh
    mov TimerLo, eax
    mov TimerHi, edx
  end;
  Sleep(DelayTime);
  asm
    dw 310Fh
    sub eax, TimerLo
    sbb edx, TimerHi
    mov TimerLo, eax
    mov TimerHi, edx
  end;
  SetThreadPriority(GetCurrentThread, Priority);
  SetPriorityClass(GetCurrentProcess, PriorityClass);
  Result := TimerLo / (1000 * DelayTime);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(Format('Your CPU speed: %f MHz', [GetCPUSpeed]));
  Label1.caption := GetCPUSpeed;
  Memo1.Lines := GetCPUSpeed;
end;

To use the Label or a Memo, I have to convert data into a string. How can I do that?

[DCC Error] speed_cpu.pas(62): E2010 Incompatible types: 'string' and 'Double'

Body:
Thank you problem solved.

    function Tipo_cpu: string;
        var
          aVendor: array[0..2] of DWord;
          iI, iJ : Integer;
        begin
          asm
            push ebx
            xor   eax, eax
            dw    $A20F // CPUID instruction
            mov   DWord ptr aVendor, ebx
            mov   DWord ptr aVendor[+4], edx
            mov   DWord ptr aVendor[+8], ecx
            pop   ebx
          end;
          for iI := 0 to 2 do
            for iJ := 0 to 3 do
            Result := Result + Chr((aVendor[iI] and ($000000FF shl (iJ * 8))) shr (iJ * 8));
        end;

    function GetCPUSpeed: Double;
    const
      DelayTime = 500;
    var
      TimerHi, TimerLo: DWORD;
      PriorityClass, Priority: Integer;
    begin
      PriorityClass := GetPriorityClass(GetCurrentProcess);
      Priority      := GetThreadPriority(GetCurrentThread);
      SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
      SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL);
      Sleep(10);
      asm
        dw 310Fh
        mov TimerLo, eax
        mov TimerHi, edx
      end;
      Sleep(DelayTime);
      asm
        dw 310Fh
        sub eax, TimerLo
        sbb edx, TimerHi
        mov TimerLo, eax
        mov TimerHi, edx
      end;
      SetThreadPriority(GetCurrentThread, Priority);
      SetPriorityClass(GetCurrentProcess, PriorityClass);
      Result := TimerLo / (1000 * DelayTime);
    end;

procedure TForm1.FormCreate(Sender: TObject);
var
  ids: TidIpWatch;
  Speed: Double;
begin
 ids := TidIpWatch.Create;
 Speed := GetCPUSpeed;
 Memo1.Text := 'IP:' + (ids.LocalIP);
 Memo1.Text := (Tipo_cpu);
 Memo1.Text := Format('%f', [Speed]);
 ids.Free;
 end;


问:
Pass a selected row details on Datagrid row select
Am unable to get selected row details, instead i am getting all values.</p>
```<code>   <DataGrid
        justifyContent="end"
        rows={rows}
        columns={columns}
        pageSize={pageSize}
        onPageSizeChange={(newPageSize) => setPageSize(newPageSize)}
        rowsPerPageOptions={[10, 20]}
        disableSelectionOnClick={true}
        onRowClick={onRowSelect(rows)}
      />

const onRowSelect = (event) => {
  console.log("on row click", event);
};
</code>```

答:
You need to pass a function to onRowClick, instead you are invoking it with all values.

```<code>onRowClick={onRowSelect}
</code>```

Read more about row data in Mui Docs

Body:
Am unable to get selected row details, instead i am getting all values.

   <DataGrid
        justifyContent="end"
        rows={rows}
        columns={columns}
        pageSize={pageSize}
        onPageSizeChange={(newPageSize) => setPageSize(newPageSize)}
        rowsPerPageOptions={[10, 20]}
        disableSelectionOnClick={true}
        onRowClick={onRowSelect(rows)}
      />

const onRowSelect = (event) => {
  console.log("on row click", event);
};

Body:
You need to pass a function to onRowClick, instead you are invoking it with all values.

onRowClick={onRowSelect}

Read more about row data in Mui Docs


问:
SAS: How to replace delimit and split column to multiple rows?
I have just started to learn SAS programming and I'm trying to experiment with replacing a phrase "@@@@" with "|" before splitting the cell into multiple rows in SAS Studio.

I have created an example below for this experiment. It was reference from How to split a column into multiple rows in SAS but I couldn't get it to work. The SYSTEM_ID column is printing well but the ITEM_LIST is not splitting.

My current output is as follows:

Here's my current code. Please help.

```<code>data example1;
    input SYSTEM_ID $ ITEM_LIST $ 5-50 ;
    datalines;
    ID_1 Apple Juice @@@@ Orange @@@@ Banana Milk
    ;
run;

data example2 (keep=SYSTEM_ID ITEM_LIST_SUB rename=(ITEM_LIST_SUB=ITEM_LIST));
    set example1;

    ITEM_LIST_TRANS = tranwrd(ITEM_LIST,"@@@@","|");
    do i = 1 to countw(ITEM_LIST_TRANS,"|");
       ITEM_LIST_SUB = scan(ITEM_LIST,i,"|");
       output;
    end;
run;

proc print data = example2;run;
</code>```

答:
There are two small problems to your otherwise fine solution :-)

You reference ITEM_LIST in the Scan Function instead of ITEM_LIST_TRANS

In your example data, your data is indented, so ID_1 becomes part of ITEM_LIST.

See if this works for you

```<code>data example1;
input SYSTEM_ID $ ITEM_LIST $ 5-50 ;
datalines;
ID_1 Apple Juice @@@@ Orange @@@@ Banana Milk
;
run;

data example2 (keep=SYSTEM_ID ITEM_LIST_SUB rename=(ITEM_LIST_SUB=ITEM_LIST));
    set example1;

    ITEM_LIST_TRANS = tranwrd(ITEM_LIST,"@@@@","|");
    do i = 1 to countw(ITEM_LIST_TRANS,"|");
       ITEM_LIST_SUB = scan(ITEM_LIST_TRANS,i,"|");
       output;
    end;
run;

proc print data = example2;run;
</code>```

Result:

```<code>Obs SYSTEM_ID ITEM_LIST
1   ID_1      Apple Juice
2   ID_1      Orange
3   ID_1      Banana Milk
</code>```

Body:
I have just started to learn SAS programming and I'm trying to experiment with replacing a phrase "@@@@" with "|" before splitting the cell into multiple rows in SAS Studio.

I have created an example below for this experiment. It was reference from How to split a column into multiple rows in SAS but I couldn't get it to work. The SYSTEM_ID column is printing well but the ITEM_LIST is not splitting.

My current output is as follows:

Here's my current code. Please help.

data example1;
    input SYSTEM_ID $ ITEM_LIST $ 5-50 ;
    datalines;
    ID_1 Apple Juice @@@@ Orange @@@@ Banana Milk
    ;
run;

data example2 (keep=SYSTEM_ID ITEM_LIST_SUB rename=(ITEM_LIST_SUB=ITEM_LIST));
    set example1;

    ITEM_LIST_TRANS = tranwrd(ITEM_LIST,"@@@@","|");
    do i = 1 to countw(ITEM_LIST_TRANS,"|");
       ITEM_LIST_SUB = scan(ITEM_LIST,i,"|");
       output;
    end;
run;

proc print data = example2;run;

Body:
There are two small problems to your otherwise fine solution :-)

You reference ITEM_LIST in the Scan Function instead of ITEM_LIST_TRANS

In your example data, your data is indented, so ID_1 becomes part of ITEM_LIST.

See if this works for you

data example1;
input SYSTEM_ID $ ITEM_LIST $ 5-50 ;
datalines;
ID_1 Apple Juice @@@@ Orange @@@@ Banana Milk
;
run;

data example2 (keep=SYSTEM_ID ITEM_LIST_SUB rename=(ITEM_LIST_SUB=ITEM_LIST));
    set example1;

    ITEM_LIST_TRANS = tranwrd(ITEM_LIST,"@@@@","|");
    do i = 1 to countw(ITEM_LIST_TRANS,"|");
       ITEM_LIST_SUB = scan(ITEM_LIST_TRANS,i,"|");
       output;
    end;
run;

proc print data = example2;run;

Result:

Obs SYSTEM_ID ITEM_LIST
1   ID_1      Apple Juice
2   ID_1      Orange
3   ID_1      Banana Milk


问:
How to make a fill parent+wrap_content (in that order) Android
I'll try to simplify the problem for avoiding long code pieces: I want to do something like that in my layout

The structure should be easy with something like:

```<code> LinearLayoutA (vertical)
      LinearLayoutB (vertical)
           LinearLayoutC    (horizontal)
           LinearLayoutC'   (horizontal)
      LinearLayoutB' (vertical)
           LinearLayoutC''  (horizontal)
           LinearLayoutC''' (horizontal)
  All with weight=1
</code>```

the problem for me is define what to put within the LinearLayoutC. So focusing now the elements inside LinearLayoutC:

My first option was another LinearLayout (vertical) the problem is that if the image is taller than the LinearLayoutC the TextView is not visible.

So I used that RelativeLayout:

```<code><RelativeLayout
    android:id="@+id/RelativeLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Eiffel"
        android:textSize="45sp"
        android:id="@+id/text"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
    ></TextView>
    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/eiffel2"
        android:id="@+id/image"
        android:layout_above="@id/text"
    android:layout_centerHorizontal="true"></ImageView>

</RelativeLayout>
</code>```

Nice it works! But not for long =(. (We will call it from now RelativeLayout1) When the screen is smaller than the views the layout seems perfect but when going into a larger screen the block is aligned to the bottom of the parent and I'd like it to be centered in the screen (or the sublayout). Like shows that screen:

That is because of the android:layout_alignParentBottom="true" at the TextView.

Trying to solve that I used a RelativeLayout2 for wrap the RelativeLayout1 with a code like:

```<code><RelativeLayout2
android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>

     <RelativeLayout1
      android:layout_centerInParent="true"
      .....
     ></RelativeLayout1>

 </RelativeLayout2>
</code>```

But even with that the layout RelativeLayout1 still aligned to the bottom of the image (and filling all the screen vertically as it had a height= fill_parent and I don't understand why is that happening and how can I solve it. Please can you help me? I've tried for hours. Thanks in advance

答:
Add
 android:adjustViewBounds="true" in your ImageView

Body:
I'll try to simplify the problem for avoiding long code pieces: I want to do something like that in my layout

The structure should be easy with something like:

 LinearLayoutA (vertical)
      LinearLayoutB (vertical)
           LinearLayoutC    (horizontal)
           LinearLayoutC'   (horizontal)
      LinearLayoutB' (vertical)
           LinearLayoutC''  (horizontal)
           LinearLayoutC''' (horizontal)
  All with weight=1

the problem for me is define what to put within the LinearLayoutC. So focusing now the elements inside LinearLayoutC:

My first option was another LinearLayout (vertical) the problem is that if the image is taller than the LinearLayoutC the TextView is not visible.

So I used that RelativeLayout:

<RelativeLayout
    android:id="@+id/RelativeLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Eiffel"
        android:textSize="45sp"
        android:id="@+id/text"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
    ></TextView>
    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/eiffel2"
        android:id="@+id/image"
        android:layout_above="@id/text"
    android:layout_centerHorizontal="true"></ImageView>

</RelativeLayout>

Nice it works! But not for long =(. (We will call it from now RelativeLayout1) When the screen is smaller than the views the layout seems perfect but when going into a larger screen the block is aligned to the bottom of the parent and I'd like it to be centered in the screen (or the sublayout). Like shows that screen:

That is because of the android:layout_alignParentBottom="true" at the TextView.

Trying to solve that I used a RelativeLayout2 for wrap the RelativeLayout1 with a code like:

<RelativeLayout2
android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>

     <RelativeLayout1
      android:layout_centerInParent="true"
      .....
     ></RelativeLayout1>

 </RelativeLayout2>

But even with that the layout RelativeLayout1 still aligned to the bottom of the image (and filling all the screen vertically as it had a height= fill_parent and I don't understand why is that happening and how can I solve it. Please can you help me? I've tried for hours. Thanks in advance


问:
How to get the return value in asm?
I want to extract the return value that type is org.apache.commons.dbcp.BasicDataSource How can I achieve this in asm?

I have to get the instance of the class, org.apache.commons.dbcp.BasicDataSource right after it is created in createDataSource(). So I will visit this method and put some bytecode for getting the return value.

答:
the original code is:

```<code>public String getParameter(String name) {
    if (!this.parametersParsed) {
        this.parseParameters();
    }
    return this.coyoteRequest.getParameters().getParameter(name);
}
</code>```

after modification:

```<code>public String getParameter(String name) {
    if (!this.parametersParsed) {
        this.parseParameters();
    }
    String var10000 = this.coyoteRequest.getParameters().getParameter(name);
    System.out.print("cf: @" + var10000);
    return var10000;
}
</code>```

This is my first time to answer a question. Here is my solution.

```<code>@Override
public void visitInsn(int opcode) {
    if ((opcode >= IRETURN && opcode <= RETURN) || opcode == ATHROW) {

        mv.visitInsn(DUP); //clone "getParameter" function returned value at top of stack

    mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); //push System.out in stack
//swap System.out and returned value, make returned value as the top of stack again
    mv.visitInsn(SWAP);
    mv.visitTypeInsn(NEW, "java/lang/StringBuilder");
    mv.visitInsn(DUP);
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false);
        mv.visitLdcInsn("cf: @");
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);
        mv.visitInsn(SWAP); //swap StringBuilder().append("cf: @") and returned value, make returned value as the top of stack again

        //////////////////print value at top of stack for dbg purpose ///////////////////////////////////
        ///////user can use this segment of code to check current top stack value to determine next action
        //mv.visitInsn(DUP);
        //mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
        //mv.visitInsn(SWAP);
        //mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "print", "(Ljava/lang/String;)V", false);
        /////////////////////////////////////////////////////

        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);

        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);

        mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "print", "(Ljava/lang/String;)V", false);
    }
    mv.visitInsn(opcode);
}
</code>```

Title: How to get the return value in asm?

Body:
the original code is:

public String getParameter(String name) {
    if (!this.parametersParsed) {
        this.parseParameters();
    }
    return this.coyoteRequest.getParameters().getParameter(name);
}

after modification:

public String getParameter(String name) {
    if (!this.parametersParsed) {
        this.parseParameters();
    }
    String var10000 = this.coyoteRequest.getParameters().getParameter(name);
    System.out.print("cf: @" + var10000);
    return var10000;
}

This is my first time to answer a question. Here is my solution.

@Override
public void visitInsn(int opcode) {
    if ((opcode >= IRETURN && opcode <= RETURN) || opcode == ATHROW) {

        mv.visitInsn(DUP); //clone "getParameter" function returned value at top of stack

    mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); //push System.out in stack
//swap System.out and returned value, make returned value as the top of stack again
    mv.visitInsn(SWAP);
    mv.visitTypeInsn(NEW, "java/lang/StringBuilder");
    mv.visitInsn(DUP);
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false);
        mv.visitLdcInsn("cf: @");
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);
        mv.visitInsn(SWAP); //swap StringBuilder().append("cf: @") and returned value, make returned value as the top of stack again

        //////////////////print value at top of stack for dbg purpose ///////////////////////////////////
        ///////user can use this segment of code to check current top stack value to determine next action
        //mv.visitInsn(DUP);
        //mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
        //mv.visitInsn(SWAP);
        //mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "print", "(Ljava/lang/String;)V", false);
        /////////////////////////////////////////////////////

        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);

        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);

        mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "print", "(Ljava/lang/String;)V", false);
    }
    mv.visitInsn(opcode);
}


问:
Loop through each div of containers and compare the height on the base of index number
I am trying to loop through 2 main divs and their child divs too. Here is the code sample:

```<code><div class="containers">
    <div class="columns">Content 1</div>
    <div class="columns">Content 2</div>
    <div class="columns">Content 3</div>
</div>
<div class="containers">
    <div class="columns">Content 1</div>
    <div class="columns">Content 2</div>
    <div class="columns">Content 3</div>
</div>
</code>```

Applied the following jQuery code:

```<code>jQuery(".containers").each(function() {
    jQuery(this).find(".columns").each(function(index) {
       var colHeight = jQuery(this).outerHeight();
       console.log("Current index is " + index);
    });
});
</code>```

I'm getting index as per required: 0 1 2 0 1 2. How can I compare now the height of columns which are on index 0 and apply max height to both after compare? and same with next index 1, 2 and so on.

答:
you can stored the value of max height in an array an alwas redefine height of all columns matching the current index after comparing with new size

var maxHeightArray = [];

jQuery(".containers").each(function() {
    jQuery(this).find(".columns").each(function(index) {
       if (!maxHeightArray[index]) {
        maxHeightArray[index] = {
          height:0,
          columns:[]
        };
       }

       var currentColHeight = jQuery(this).outerHeight();
       if (!maxHeightArray[index].height || currentColHeight > maxHeightArray[index].height) {
          maxHeightArray[index].height = currentColHeight;
       }

       maxHeightArray[index].columns.push(jQuery(this));

       jQuery.each(maxHeightArray[index].columns,function() {
        jQuery(this).height(maxHeightArray[index].height);
       });
    });
});

console.log(maxHeightArray);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="containers">
    <div class="columns">Content 1</div>
    <div class="columns">Content 2</div>
    <div class="columns">Content 3</div>
</div>
<div class="containers">
    <div class="columns">Content 1</div>
    <div class="columns">Content 2</div>
    <div class="columns">Content 3</div>
</div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script></code>```

Body:
I am trying to loop through 2 main divs and their child divs too. Here is the code sample:

Content 1

Content 2

Content 3

Content 1

Content 2

Content 3

Applied the following jQuery code:

jQuery(".containers").each(function() {
    jQuery(this).find(".columns").each(function(index) {
       var colHeight = jQuery(this).outerHeight();
       console.log("Current index is " + index);
    });
});

I'm getting index as per required: 0 1 2 0 1 2. How can I compare now the height of columns which are on index 0 and apply max height to both after compare? and same with next index 1, 2 and so on.

Body:
you can stored the value of max height in an array an alwas redefine height of all columns matching the current index after comparing with new size

var maxHeightArray = [];

jQuery(".containers").each(function() {
    jQuery(this).find(".columns").each(function(index) {
       if (!maxHeightArray[index]) {
        maxHeightArray[index] = {
          height:0,
          columns:[]
        };
       }

       var currentColHeight = jQuery(this).outerHeight();
       if (!maxHeightArray[index].height || currentColHeight > maxHeightArray[index].height) {
          maxHeightArray[index].height = currentColHeight;
       }

       maxHeightArray[index].columns.push(jQuery(this));

       jQuery.each(maxHeightArray[index].columns,function() {
        jQuery(this).height(maxHeightArray[index].height);
       });
    });
});

console.log(maxHeightArray);

<div class="containers">
    <div class="columns">Content 1</div>
    <div class="columns">Content 2</div>
    <div class="columns">Content 3</div>
</div>
<div class="containers">
    <div class="columns">Content 1</div>
    <div class="columns">Content 2</div>
    <div class="columns">Content 3</div>
</div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


问:
EF Core 3.1 using Authentication=Active Directory Integrated
[Update 1]

I could make it work using the following connection string

```<code>Server=tcp:mydatabaseserver.database.windows.net,1433;Initial Catalog=mydbname
</code>```

and implementing an interceptor as mentioned in this article.

This proves that Azure is correctly configured, and the problem is somewhere in the application (maybe a missing package?).

Anyway, I would still like to be able to change the connection string and switch between AAD authentication and sql authentication, without additional logic in the application.

[/Update 1]

I'm using EF Core 3.1.4 on an Azure WebApp, and I would like to use the Azure AD identity assigned to the application for authentication, but I run into the following exception:

```<code>ArgumentException: Invalid value for key 'authentication'.
Microsoft.Data.Common.DbConnectionStringBuilderUtil.ConvertToAuthenticationType(string keyword, object value)
</code>```

This is the connection string:

```<code>{
    "ConnectionStrings": {
        "Admin": "Server=tcp:mydatabaseserver.database.windows.net,1433;Initial Catalog=mydbname;Authentication=Active Directory Integrated"
    }
}
</code>```

I initialize the context using the following code:

var connectionString = this.Configuration.GetConnectionString("Admin");
services.AddDbContext<NetCoreDataContext>(builder => builder.UseSqlServer(connectionString));
```

The Microsoft.Azure.Services.AppAuthentication package is also imported (version 1.5.0)

答:
Upgrading the Nuget packages:
Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer to 6.0.1 and using Authentication=Active Directory Managed Identity in the connection string helped me resolve the issue.

Body:
[Update 1]

I could make it work using the following connection string

Server=tcp:mydatabaseserver.database.windows.net,1433;Initial Catalog=mydbname

and implementing an interceptor as mentioned in this article.

This proves that Azure is correctly configured, and the problem is somewhere in the application (maybe a missing package?).

Anyway, I would still like to be able to change the connection string and switch between AAD authentication and sql authentication, without additional logic in the application.

[/Update 1]

I'm using EF Core 3.1.4 on an Azure WebApp, and I would like to use the Azure AD identity assigned to the application for authentication, but I run into the following exception:

ArgumentException: Invalid value for key 'authentication'.
Microsoft.Data.Common.DbConnectionStringBuilderUtil.ConvertToAuthenticationType(string keyword, object value)

This is the connection string:

{
    "ConnectionStrings": {
        "Admin": "Server=tcp:mydatabaseserver.database.windows.net,1433;Initial Catalog=mydbname;Authentication=Active Directory Integrated"
    }
}

I initialize the context using the following code:

var connectionString = this.Configuration.GetConnectionString("Admin");
services.AddDbContext<NetCoreDataContext>(builder => builder.UseSqlServer(connectionString));

The Microsoft.Azure.Services.AppAuthentication package is also imported (version 1.5.0)


问:
WebDriver explicit wait in Scala
How would the Java explicit wait example here be written in Scala: </p>

```<code>WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
  .until(new ExpectedCondition<WebElement>(){
    @Override
    public WebElement apply(WebDriver d) {
      return d.findElement(By.id("myDynamicElement"));
    }});
</code>```

答:
It would look very similar. Some types and parenthesis could be omitted. But as long there is no special Scala API that uses some of the Scala features, it would look something like this (maybe more dots could be comitted, too):</p>

```<code>val driver: WebDriver = new FireFoxDriver
driver.get("http://somedomain/url_that_delays_loading")
val myDynamicElement = new WebdriverWait(driver, 10).until(
  new ExpectedCondition[WebElement] {
    override def apply(d: WebDriver) = d.findElement(By.id("myDynamicElement"))
  })
</code>```

Title: WebDriver explicit wait in Scala

Body:
How would the Java explicit wait example here be written in Scala:

WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
  .until(new ExpectedCondition<WebElement>(){
    @Override
    public WebElement apply(WebDriver d) {
      return d.findElement(By.id("myDynamicElement"));
    }});

Body:
It would look very similar. Some types and parenthesis could be omitted. But as long there is no special Scala API that uses some of the Scala features, it would look something like this (maybe more dots could be comitted, too):

val driver: WebDriver = new FireFoxDriver
driver.get("http://somedomain/url_that_delays_loading")
val myDynamicElement = new WebdriverWait(driver, 10).until(
  new ExpectedCondition[WebElement] {
    override def apply(d: WebDriver) = d.findElement(By.id("myDynamicElement"))
  })


问:
Search data in C# from Database SQL Server
I want to ask you regarding for the searching in C# and why there is a Not Found statement if already found the answer or the data itself.

Here is the code:

```<code>                    Console.WriteLine("Enter Plate Number: ");
                    string plateNumber1 = Console.ReadLine();
                    var searchPlateNumberDAL = new ParkingSystemDAL(_iconfiguration);
                    var listSlotParking = searchPlateNumberDAL.GetList();
                    listSlotParking.ForEach(item =>
                    {
                        bool searchItem = item.plateNumber == plateNumber1;
                        if (searchItem == true)
                        {
                            Console.WriteLine(item.parkingId);
                        }
                        else
                        {
                            Console.WriteLine("Not Found");
                        }
                    });
</code>```

output

答:
I think there some garbage value is present.

So, code will be

```<code>if(item.plateNumber.ToString().Trim().ToUpper() == plateNumber1.ToString().Trim().ToUpper())
{
  Console.WriteLine(item.parkingId);
}
</code>```

you can also use Linq Where  expression instead of ForEach

```<code>if( listSlotParking.Where(x =>x.planteNumberplateNumber.ToString().Trim().ToUpper() == plateNumber1.ToString().Trim().ToUpper()).ToList().Count()>0)
{
 Console.WriteLine(item.parkingId);
}
</code>```

Body:
I want to ask you regarding for the searching in C# and why there is a Not Found statement if already found the answer or the data itself.

Here is the code:

                    Console.WriteLine("Enter Plate Number: ");
                    string plateNumber1 = Console.ReadLine();
                    var searchPlateNumberDAL = new ParkingSystemDAL(_iconfiguration);
                    var listSlotParking = searchPlateNumberDAL.GetList();
                    listSlotParking.ForEach(item =>
                    {
                        bool searchItem = item.plateNumber == plateNumber1;
                        if (searchItem == true)
                        {
                            Console.WriteLine(item.parkingId);
                        }
                        else
                        {
                            Console.WriteLine("Not Found");
                        }
                    });

output

Body:
I think there some garbage value is present.

So, code will be

if(item.plateNumber.ToString().Trim().ToUpper() == plateNumber1.ToString().Trim().ToUpper())
{
  Console.WriteLine(item.parkingId);
}

you can also use Linq Where  expression instead of ForEach

if( listSlotParking.Where(x =>x.planteNumberplateNumber.ToString().Trim().ToUpper() == plateNumber1.ToString().Trim().ToUpper()).ToList().Count()>0)
{
 Console.WriteLine(item.parkingId);
}


问:
 tag doesn't work anymore in VSCode with JDK 17
Up until recently, I always used the ```</code> tag in javadoc to format code and it always worked, but since I switched to JDK 17 a few days ago, anything inside <code>``` tags seems to be ignored by VSCode.
For example:

/**
 * The following code should be formatted correctly:
 * ```
 * Code
 * ```
 */
public class Test {
...
```

renders as

How can I make it so it shows up properly again?

答: I have tried, and it's a little difference between java17 and java14. Different CSS styles caused it. You can take F12 to check the HTML sources.</p>

Title: <pre> tag doesn't work anymore in VSCode with JDK 17

Body:
Up until recently, I always used the
 tag in javadoc to format code and it always worked, but since I switched to JDK 17 a few days ago, anything inside
 tags seems to be ignored by VSCode.
For example:

/**
 * The following code should be formatted correctly:
 *

 * Code
 *

 */
public class Test {
...

renders as

How can I make it so it shows up properly again?


问:
Using Amadeus flight search API, how does my users search for flight when they don't have location code
I am using amadeus flight search API, built the endpoint with PHP and tested on postman, working perfectly now i am worried about how my users will use the frontend to search for flight, do they have to know the city codes to be able to search for flights? I want a situation whereby they just entered the names of the cities in the form from my frontend and they get to search for flights not entering city codes</p>

答:
All the airport and city codes are based on IATA standard.
Amadeus provides also another API to get this information : Airport and city search API. you can integrate this so that your user can type a keyword for your application to get the corresponding codes.</p>


问:
computing multiple covariance matrices
I have a matrix X of size (1875, 77). For each column, I want to compute the covariance matrix, i.e., x_1 @ x_1.T where x_1 has a shape (1875, 1). Ideally, I want to do this in one-go without a for loop. Is there an easy way to do this?

I was thinking about padding with zeros for each column up and down based on the column index(so x_1 will have 76 zeros columns, x_2 will have one (77, 1) zero column pad on top and 75 zero column pads), but this seems to complicate things more.

答:
You probably want this:

```<code>import numpy as np
r, c = 1875, 77
X = np.random.rand(r, c)
covs = X.T[..., None] @ X.T[:, None, :]
covs.shape
# (77, 1875, 1875)
</code>```

This simply performs c number of matrix multiplications, 1 for each column of X. Here X.T[..., None] is of shape (c, r, 1) and X.T[:, None, :] is of shape (c, 1, r) and this makes the matrix multiple between them compatible.

Title: computing multiple covariance matrices

Body:
You probably want this:

import numpy as np
r, c = 1875, 77
X = np.random.rand(r, c)
covs = X.T[..., None] @ X.T[:, None, :]
covs.shape
# (77, 1875, 1875)

This simply performs c number of matrix multiplications, 1 for each column of X. Here X.T[..., None] is of shape (c, r, 1) and X.T[:, None, :] is of shape (c, 1, r) and this makes the matrix multiple between them compatible.


问:
Interpretation SSIM skimage.metrics.structural_similarity()
I am working with medical images in python. I generate a binary threshold of this image (ImageA, 0, 1 encoded). From this image, I run a detection algorithm that generates another image B (also binary 0,1 encoded) and aims to detect the structures in image A so I can count them.

To better understand what I mean I made a sketch as follows:

As you can see, image B failed to recapitulate the structure in the upper right corner. Somehow, I want to test for this. I want to know, how well the algorithm performed that created image B, which aims at contouring the structures it detects in image A.

Is the SSIM algorithm that tests for structural similarity useful for this? Does it take into account to compare the location of structures in the image?

I am working with the structural_similarity() function of skimage.metrics.

答:
SSIM algorithm will indeed give you what you need : a good score when img B resembles img A.

However, it is more common to use metrics such as Intersection over Union (see Intersection-over-union between two detections) to measure the performance of an object detection algorithm.
Intersection over Union is much more intuitive for binary images than the SSIM that is made to account for local features and textures.


问:
Disable redirects in OkHttp3 for ONE request only
I have a singleton (object in Kotlin) that holds an instance of OkHttpClient which as per the search on stack is the way to go.

Now I come to the scenario where for just ONE request in my app I need to skip the redirect to get the Location header.

It seems that the way to do it is via

```<code>val client = OkHttpClient.Builder()
            .followRedirects(false)
            .followSslRedirects(false)
            .build()
</code>```

This is fine and dandy, but now I need to store two instances of OkHttpClient and the non-redirecting one is not even to be always used coz it pertains to a login flow for my app only.

Is it possible (e.g. via writing a network interceptor maybe?) to disable redirect for just ONE request?

答:
You can definitely do this in a network interceptor.  Arguably @samthecodingman solution is cleaner, and it definitely works for "one" request.

But if you implement it as an interceptor then you don't need the client code to be aware.

See discussion here

https://github.com/square/okhttp/issues/6871

Something like

```<code>      client = OkHttpClient.Builder()
        .addNetworkInterceptor {
          it.proceed(it.request()).let { response ->
            if (request.url.encodedPath == "foo") {
              response.newBuilder()
                .removeHeader("Location")
                .build()
            } else {
              response
            }
          }
        }
</code>```

Body:
I have a singleton (object in Kotlin) that holds an instance of OkHttpClient which as per the search on stack is the way to go.

Now I come to the scenario where for just ONE request in my app I need to skip the redirect to get the Location header.

It seems that the way to do it is via

val client = OkHttpClient.Builder()
            .followRedirects(false)
            .followSslRedirects(false)
            .build()

This is fine and dandy, but now I need to store two instances of OkHttpClient and the non-redirecting one is not even to be always used coz it pertains to a login flow for my app only.

Is it possible (e.g. via writing a network interceptor maybe?) to disable redirect for just ONE request?

Body:
You can definitely do this in a network interceptor.  Arguably @samthecodingman solution is cleaner, and it definitely works for "one" request.

But if you implement it as an interceptor then you don't need the client code to be aware.

See discussion here

https://github.com/square/okhttp/issues/6871

Something like

      client = OkHttpClient.Builder()
        .addNetworkInterceptor {
          it.proceed(it.request()).let { response ->
            if (request.url.encodedPath == "foo") {
              response.newBuilder()
                .removeHeader("Location")
                .build()
            } else {
              response
            }
          }
        }


问:
Azure: I don't have permissions, but I am Owner
I've been added to a RG as owner in a subscription outside på company. Navigating to the Access contol (IAM) of the RG and clicking "View my access". clearly says "Grants full access to manage all resources, including the ability to assign roles in Azure RBAC.":

But I can not create any resources w/o getting:

```<code>The client 'mikael.hakansson@xxx.com' with object id 'xxx' does not have authorization to perform action 'Microsoft.Storage/register/action' over scope '/subscriptions/xxx' or the scope is invalid. If access was recently granted, please refresh your credentials. (Code: AuthorizationFailed) (Code: AuthorizationFailed)
</code>```

Neither can I view Role assignments: "You do not have permissions to read this directory. Contact a Global Administrator and have them assign you the Directory Readers role in Azure Active Directory."

Thank you for any input

答:
As I have mentioned in comments , The Owner Role that you have assigned to is in  for the resource Group as its showing This Resource. If it was assigned to Subscription then it would have been seen as Subscription(Inherited) in the resource group level.

Example:

The client 'mikael.hakansson@xxx.com' with object id 'xxx' does not
have authorization to perform action
'Microsoft.Storage/register/action' over scope '/subscriptions/xxx' or
the scope is invalid. If access was recently granted, please refresh
your credentials. (Code: AuthorizationFailed) (Code:
AuthorizationFailed)

Coming to the above error , its because you have permission on only resource group level. You need to have access on Subscription level which may be Owner/Contributor  to create resources. As When you are creating resources Azure API registers that resource provider on subscription and gets a token on your user to create a resource for that resource provider in any resource group on the subscription , if you don't have proper permissions on subscription then it fails to register the resource provider and get the token on your name and returns an error.

Body:
I've been added to a RG as owner in a subscription outside på company. Navigating to the Access contol (IAM) of the RG and clicking "View my access". clearly says "Grants full access to manage all resources, including the ability to assign roles in Azure RBAC.":

But I can not create any resources w/o getting:

The client 'mikael.hakansson@xxx.com' with object id 'xxx' does not have authorization to perform action 'Microsoft.Storage/register/action' over scope '/subscriptions/xxx' or the scope is invalid. If access was recently granted, please refresh your credentials. (Code: AuthorizationFailed) (Code: AuthorizationFailed)

Neither can I view Role assignments: "You do not have permissions to read this directory. Contact a Global Administrator and have them assign you the Directory Readers role in Azure Active Directory."

Thank you for any input


问:
3D modelling for Virtual Tour type web application
When I was developing for realtors, we referred to a service that would photograph the inside of a listed property, run overlapping images through their process, and produce a '3d tour' of the property, where Joe public viewing the listing could experience the images as if they were inside the property, using their mouse to rotate their viewpoint fully 360 degrees in two planes. Here is an example of such a Virtual Tour service.

I would like to develop a similar application, but less detailed, and using less real imagery in favour of textures and artificial, injected imagery, to allow the placement of posters, menus etc. inside the model of the venue, on walls etc.  I suspect using a 3D gaming engine here would give me more control of the content than the total virtual tour type setup, but I need to be able to fairly easily create a large surface texture, such as a wall, from a photo of that wall.

Where do I start if I want to enable my web portal to offer such modelling for my clients, in my ASP.NET MVC3 application?  I know I'll be making extensive use here of third party libraries, but I would prefer recommendations on those that don't offer a total solution, just the tools to for me to assemble a total solution.

答:
Unity3d (unity3d.com) is an affordable but powerful game engine that might be a good fit for you for these reasons:

It offers a web plugin so you could host it via your mvc project and inject data into it from your mvc controllers when pages are requested.

Its native language is C#, so the virtual tour/game engine parts of your project will be in the same language as the mvc backend (and presumably other parts of your ecosystem).

It is capable of stunning visual quality with features such as its "Beast" light mapping engine. Rendering virtual venues should be a home run.

You can use your photos as textures easily.

They have a free trial and an active community at forum.unity3d.com, so give it a look.


问:
Error: The non-abstract class 'InternalSelectableMathState'
I just updated flutter version from 2.5.3 to 2.8. I have the following error that i dont know how resolve it. There is no error on any plugin installed, It seems that the error comes from the inner classes themselves and I don't know in which part of my application the error is throwed:

```<code>../../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/flutter_math_fork-0.3.3+1/lib/src/widgets/selectable.dart:407:7: Error: The non-abstract class 'InternalSelectableMathState' is missing implementations for these members:
 - TextSelectionDelegate.copySelection
 - TextSelectionDelegate.cutSelection
 - TextSelectionDelegate.pasteText
 - TextSelectionDelegate.selectAll
Try to either
 - provide an implementation,
 - inherit an implementation from a superclass or mixin,
 - mark the class as abstract, or
 - provide a 'noSuchMethod' implementation.

class InternalSelectableMathState extends State<InternalSelectableMath>
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:985:8: Context: 'TextSelectionDelegate.copySelection' is defined here.
  void copySelection(SelectionChangedCause cause);
       ^^^^^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:965:8: Context: 'TextSelectionDelegate.cutSelection' is defined here.
  void cutSelection(SelectionChangedCause cause);
       ^^^^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:973:16: Context: 'TextSelectionDelegate.pasteText' is defined here.
  Future<void> pasteText(SelectionChangedCause cause);
               ^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:979:8: Context: 'TextSelectionDelegate.selectAll' is defined here.
  void selectAll(SelectionChangedCause cause);
       ^^^^^^^^^

FAILURE: Build failed with an exception.

* Where:
Script 'C:\desarrollo\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1070

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\desarrollo\flutter\bin\flutter.bat'' finished with non-zero exit value 1

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

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

BUILD FAILED in 8m 5s
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

I dont have declared flutter_math_fork on my pubspec.

My flutter doctor output:

```<code>Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.8.0, on Microsoft Windows [VersiÃ³n 10.0.19041.1348], locale es-ES)
[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[√] Chrome - develop for the web
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.62.3)
[√] Connected device (3 available)

• No issues found!
</code>```

I have tried: flutter clean, flutter upgrade and invalidate cache / restart.

Any suggestion is appreciated.

答:
I faced the same error, i add following codes to pubscpec.yaml, it's working now.
If it doesn't work you can follow the above methods</p>
```<code>dependency_overrides:
provider: 6.0.0
</code>```

Body:
I just updated flutter version from 2.5.3 to 2.8. I have the following error that i dont know how resolve it. There is no error on any plugin installed, It seems that the error comes from the inner classes themselves and I don't know in which part of my application the error is throwed:

../../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/flutter_math_fork-0.3.3+1/lib/src/widgets/selectable.dart:407:7: Error: The non-abstract class 'InternalSelectableMathState' is missing implementations for these members:
 - TextSelectionDelegate.copySelection
 - TextSelectionDelegate.cutSelection
 - TextSelectionDelegate.pasteText
 - TextSelectionDelegate.selectAll
Try to either
 - provide an implementation,
 - inherit an implementation from a superclass or mixin,
 - mark the class as abstract, or
 - provide a 'noSuchMethod' implementation.

class InternalSelectableMathState extends State<InternalSelectableMath>
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:985:8: Context: 'TextSelectionDelegate.copySelection' is defined here.
  void copySelection(SelectionChangedCause cause);
       ^^^^^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:965:8: Context: 'TextSelectionDelegate.cutSelection' is defined here.
  void cutSelection(SelectionChangedCause cause);
       ^^^^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:973:16: Context: 'TextSelectionDelegate.pasteText' is defined here.
  Future<void> pasteText(SelectionChangedCause cause);
               ^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:979:8: Context: 'TextSelectionDelegate.selectAll' is defined here.
  void selectAll(SelectionChangedCause cause);
       ^^^^^^^^^

FAILURE: Build failed with an exception.

* Where:
Script 'C:\desarrollo\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1070

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\desarrollo\flutter\bin\flutter.bat'' finished with non-zero exit value 1

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

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

BUILD FAILED in 8m 5s
Exception: Gradle task assembleDebug failed with exit code 1

I dont have declared flutter_math_fork on my pubspec.

My flutter doctor output:

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.8.0, on Microsoft Windows [VersiÃ³n 10.0.19041.1348], locale es-ES)
[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[√] Chrome - develop for the web
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.62.3)
[√] Connected device (3 available)

• No issues found!

I have tried: flutter clean, flutter upgrade and invalidate cache / restart.

Any suggestion is appreciated.

Body:
I faced the same error, i add following codes to pubscpec.yaml, it's working now.
If it doesn't work you can follow the above methods

dependency_overrides:
provider: 6.0.0


问:
Model Building Issues in Microsoft.ML
I'm learning the Microsoft.ml framework, I tried to implement a simple model, but it produces very strange numbers. Tell me what I'm doing wrong:

```<code>    MLContext mlContext = new MLContext();

    IDataView trainingData = mlContext.Data.LoadFromEnumerable(data);

    var pipeline = mlContext.Transforms.Concatenate("Features", new[] {"R"})//, "R"
        .Append(mlContext.Regression.Trainers.Sdca(labelColumnName: "P",  maximumNumberOfIterations: 1000));

    var model = pipeline.Fit(trainingData);

    var result = mlContext.Model.CreatePredictionEngine<EnterData, Prediction>(model).Predict(seachValue);

    return result;
</code>```

The model is tuned for regression analysis of experimental data. I'm going to implement several network nodes, but for now I'm testing on a simple linear regression. In fact, the method should process the incoming data, train the model on it, make a prediction and return the answer to the test number.

The class wrapper is rolled out above. The problem is not in the message further down the code. There:

```<code>MessageBox.Show(result.P.ToString());
</code>```

答:
Buddy, Your question is not clear. What is your model type ? Sentiment Analysis, Facial Recognition or Cost Prediction??
Whatever,  I think that the problem is issued in the last line of your code.

for example = return result.prediction();

Title: Model Building Issues in Microsoft.ML

Body:
I'm learning the Microsoft.ml framework, I tried to implement a simple model, but it produces very strange numbers. Tell me what I'm doing wrong:

    MLContext mlContext = new MLContext();

    IDataView trainingData = mlContext.Data.LoadFromEnumerable(data);

    var pipeline = mlContext.Transforms.Concatenate("Features", new[] {"R"})//, "R"
        .Append(mlContext.Regression.Trainers.Sdca(labelColumnName: "P",  maximumNumberOfIterations: 1000));

    var model = pipeline.Fit(trainingData);

    var result = mlContext.Model.CreatePredictionEngine<EnterData, Prediction>(model).Predict(seachValue);

    return result;

The model is tuned for regression analysis of experimental data. I'm going to implement several network nodes, but for now I'm testing on a simple linear regression. In fact, the method should process the incoming data, train the model on it, make a prediction and return the answer to the test number.

The class wrapper is rolled out above. The problem is not in the message further down the code. There:

MessageBox.Show(result.P.ToString());


问:
JSX props should not use functions react/jsx-no-bind
i am forking a app. but in gives me this errors. instead or arrow function what should i use or should i download any dependencies?

here is the code

```<code>    const modalBottom = () => {
    return (
      <ConfirmAddModalBottom
        price={price}
        currencies={currencies}
        parsedAmounts={parsedAmounts}
        noLiquidity={noLiquidity}
        onAdd={onAdd}
        poolTokenPercentage={poolTokenPercentage}
      />
    )
  }
</code>```

error: 8:  JSX props should not use functions  react/jsx-no-bind

答:
I found that the problem was solved by following the eslint documentation to this section.

Essentially, move any of your functions into a useCallback hook and that should stop the error.

Body:
i am forking a app. but in gives me this errors. instead or arrow function what should i use or should i download any dependencies?

here is the code

    const modalBottom = () => {
    return (
      <ConfirmAddModalBottom
        price={price}
        currencies={currencies}
        parsedAmounts={parsedAmounts}
        noLiquidity={noLiquidity}
        onAdd={onAdd}
        poolTokenPercentage={poolTokenPercentage}
      />
    )
  }

error: 8:  JSX props should not use functions  react/jsx-no-bind


问:
Websocket won't reconnect unless I close the browser tab and restart it
I have a webserver with websockets set up on an ESP8266.  The application runs fine on both client and server sides, sending and receiving data.  However, if the server side disconnects (power cycle or upload new code), the client (Chrome) won't reconnect to the websocket.  I can reload/refresh the web page, and it claims (according to the console log) to be connecting to the websocket, but it does not.  The only solution I have found that works is to close the tab, and then restart a new session.

My code is heavily based on this tutorial from Random Nerd Tutorials

```<code>var gateway = `ws://${window.location.hostname}/ws`;
var websocket;

function initWebSocket() {
  console.log('Trying to open a WebSocket connection...');
  websocket = new WebSocket(gateway);
  websocket.onopen    = onOpen;
  websocket.onclose   = onClose;
  websocket.onmessage = onMessage; // <-- add this line
}

function onOpen(event) {
  console.log('Connection opened');
}

function onClose(event) {
  console.log('Connection closed');
  setTimeout(initWebSocket, 2000);
}
</code>```

Is there something that is missing from the code above to make it more reliable?

答:
You probably need to use setInterval. Try this, you may have to tweek it a bit.

```<code>var gateway = `ws://${window.location.hostname}/ws`;
var websocket, sockTimer=null;

function initWebSocket() {
  console.log('Trying to open a WebSocket connection...');
  websocket = new WebSocket(gateway);
  websocket.onopen    = onOpen;
  websocket.onerror    = onError;    //  new
  websocket.onclose   = onClose;
  websocket.onmessage = onMessage; // <-- add this line
}

function onOpen(event) {
  clearInterval(sockTimer) // <= better
  console.log('Connection opened');

}
function onError() {   // <= New
       sockTimer = setInterval(init, 1000 * 60);

};
function onClose(event) {
  console.log('Connection closed');
  //setTimeout(initWebSocket, 2000);
sockTimer = setInterval(initWebSocket, 1000 * 60); // <=new
}
</code>```

Body:
I have a webserver with websockets set up on an ESP8266.  The application runs fine on both client and server sides, sending and receiving data.  However, if the server side disconnects (power cycle or upload new code), the client (Chrome) won't reconnect to the websocket.  I can reload/refresh the web page, and it claims (according to the console log) to be connecting to the websocket, but it does not.  The only solution I have found that works is to close the tab, and then restart a new session.

My code is heavily based on this tutorial from Random Nerd Tutorials

var gateway = `ws://${window.location.hostname}/ws`;
var websocket;

function initWebSocket() {
  console.log('Trying to open a WebSocket connection...');
  websocket = new WebSocket(gateway);
  websocket.onopen    = onOpen;
  websocket.onclose   = onClose;
  websocket.onmessage = onMessage; // <-- add this line
}

function onOpen(event) {
  console.log('Connection opened');
}

function onClose(event) {
  console.log('Connection closed');
  setTimeout(initWebSocket, 2000);
}

Is there something that is missing from the code above to make it more reliable?

Body:
You probably need to use setInterval. Try this, you may have to tweek it a bit.

var gateway = `ws://${window.location.hostname}/ws`;
var websocket, sockTimer=null;

function initWebSocket() {
  console.log('Trying to open a WebSocket connection...');
  websocket = new WebSocket(gateway);
  websocket.onopen    = onOpen;
  websocket.onerror    = onError;    //  new
  websocket.onclose   = onClose;
  websocket.onmessage = onMessage; // <-- add this line
}

function onOpen(event) {
  clearInterval(sockTimer) // <= better
  console.log('Connection opened');

}
function onError() {   // <= New
       sockTimer = setInterval(init, 1000 * 60);

};
function onClose(event) {
  console.log('Connection closed');
  //setTimeout(initWebSocket, 2000);
sockTimer = setInterval(initWebSocket, 1000 * 60); // <=new
}


问:
WP7 Panorama items binding and adding other custom panorama items c#
I am running into an issue where i am using a panorama control and binding it to a datasource. But i still do want other custom items on another panorama items where i need a textblock, a grid and so on. So if i am adding it in the backend it doesnt show up those panorama items. It just shows the datasource binded items. Why is that so? Both of them should work out.

Can anybody help me with a solution for this.

Thank You.

答:
Since you're wanting to manually add PanoramaItems, I can think of two approaches:

Make sure your Panorama.ItemsSource is set to an ObservableCollection that is accessible in the code behind or viewmodel, and then add your new items to that ObservableCollection which should update the Panorama.

Don't databind the Panorama control's Items - just add items manually when you want them.

Either way, the Panorama's ItemTemplate gets evaluated when the items are added to the underlying collection, so using a DataTemplateSelector will allow your code to determine which DataTemplate to apply when the new item is added without affecting the templates for previous items.

/chris


问:
how can I filter an array of objects based on a specific property and return only one property when I insert the parameter into the function?
I can't do this thing. I would like the parameter inserted in the function to return that specific value of the object to me.

If I insert "over" I would like an array with the names whose age is over 50, while on the contrary if I insert under, it doesn't work!

const person = [
  { name: 'Jessica', age: 25 },
  { name: 'Ilary', age: 27 },
  { name: 'Frank', age: 70 },
  { name: 'Dan', age: 65 },
  { name: 'Pop', age: 22 },
  { name: 'Maur', age: 68 },
];

let nameOver50 = [];
let nameUnder50 = [];

function check(enter) {
  person.filter(({ name, age }) => {
    if (age > 50 && enter === 'over') {
      nameOver50.push({ name });
    } else if (age < 50 && enter === 'under') {
      nameUnder50.push(name);
    }
  });
  console.log(nameUnder50);
}

check('over');```

thank you in advance!

答:
From what I understand, if you want it to return as an array of names, then you should return the name only, which is as a string, instead of returning the name object.

const person = [
  { name: 'Jessica', age: 25 },
  { name: 'Ilary', age: 27 },
  { name: 'Frank', age: 70 },
  { name: 'Dan', age: 65 },
  { name: 'Pop', age: 22 },
  { name: 'Maur', age: 68 },
];

let nameOver50 = [];
let nameUnder50 = [];

function check(enter) {
  enter === 'over'
    ? (nameOver50 = person
        .filter(({ name, age }) => age > 50)
        .map(({ name }) => name))
    : (nameUnder50 = person
        .filter(({ name, age }) => age < 50)
        .map(({ name }) => name));
}

check('over');
check('under');

console.log(nameOver50);
console.log(nameUnder50);```

Body:
I can't do this thing. I would like the parameter inserted in the function to return that specific value of the object to me.

If I insert "over" I would like an array with the names whose age is over 50, while on the contrary if I insert under, it doesn't work!

const person = [
  { name: 'Jessica', age: 25 },
  { name: 'Ilary', age: 27 },
  { name: 'Frank', age: 70 },
  { name: 'Dan', age: 65 },
  { name: 'Pop', age: 22 },
  { name: 'Maur', age: 68 },
];

let nameOver50 = [];
let nameUnder50 = [];

function check(enter) {
  person.filter(({ name, age }) => {
    if (age > 50 && enter === 'over') {
      nameOver50.push({ name });
    } else if (age < 50 && enter === 'under') {
      nameUnder50.push(name);
    }
  });
  console.log(nameUnder50);
}

check('over');

thank you in advance!


问:
NetworkingDriverKit - How can I access packet data?
I've been creating a virtual ethernet interface. I've opened asynchronous communication with a controlling application and every time there are new packets, the controlling app is notified and then asks for the packet data. The packet data is stored in a simple struct, with uint8_t[1600] for the bytes, and uint32_t for the length. The dext is able to populate this struct with dummy data every time a packet is available, with the dummy data visible on the controlling application. However, I'm struggling to fill it with the real packet data.

The IOUserNetworkPacket provides metadata about a packet. It contains a packets timestamp, size, etc, but it doesn't seem to contain the packet's data. There are the GetDataOffset() and GetMemorySegmentOffset() methods which seem to return byte offsets for where the packet data is located in their memory buffer. My instinct tells me to add this offset to the pointer of wherever the packet data is stored. The problem is I have no idea where the packets are actually stored.

I know they are managed by the IOUserNetworkPacketBufferPool, but I don't think that's where their memory is. There is the CopyMemoryDescriptor() method which gives an IOMemoryDescriptor of its contents. I tried using the descriptor to create an IOMemoryMap, using it to call GetAddress(). The pointers to all the mentioned objects lead to junk data.

I must be approaching this entirely wrong. If anyone knows how to access the packet data, or has any ideas, I would appreciate any help. Thanks.

Code snippet within IOUserClient::ExternalMethod:

```<code>case GetPacket:
{
    IOUserNetworkPacket *packet =
            ivars->m_provider->getPacket();

    GetPacket_Output output;
    output.packet_size = packet->getDataLength();

    IOUserNetworkPacketBufferPool *pool;
    packet->GetPacketBufferPool(&pool);

    IOMemoryDescriptor *memory = nullptr;
    pool->CopyMemoryDescriptor(&memory);

    IOMemoryMap *map = nullptr;
    memory->CreateMapping(0, 0, 0, 0, 0, &map);

    uint64_t address = map->GetAddress()
            + packet->getMemorySegmentOffset();
    memcpy(output.packet_data,
            (void*)address, packet->getDataLength());

    in_arguments->structureOutput = OSData::withBytes(
            &output, sizeof(GetPacket_Output));

    // free stuff

} break;
</code>```

答:
The problem was caused by an IOUserNetworkPacketBufferPool bug. My bufferSize was set to 1600 except this value was ignored and replaced with 2048. The IOUserNetworkPackets acted as though the bufferSize was 1600 and so they gave an invalid offset.

Creating the buffer pool and mapping it:

```<code>kern_return_t
IMPL(FooDriver, Start)
{
    // ...
    IOUserNetworkPacketBufferPool::Create(this, "FooBuffer",
        32, 32, 2048, &ivars->packet_buffer));

    packet_buffer->CopyMemoryDescriptor(ivars->packet_buffer_md);

    ivars->packet_md->Map(0, 0, 0, IOVMPageSize,
        &ivars->packet_buffer_addr, &ivars->packet_buffer_length));
   // ...
}
</code>```

Getting the packet data:

```<code>void FooDriver::getPacketData(
        IOUserNetworkPacket  *packet,
        uint8_t              *packet_data,
        uint32_t             *packet_size
) {
    uint8_t  packet_head;
    uint64_t packet_offset;

    packet->GetHeadroom(&packet_head);
    packet->GetMemorySegmentOffset(&packet_offset);

    uint8_t *buffer = (uint8_t*)(ivars->packet_buffer_addr
        + packet_offset + packet_head);
    *packet_size = packet->getDataLength();

    memcpy(packet_data, buffer, *packet_size);
}
</code>```

Body:
I've been creating a virtual ethernet interface. I've opened asynchronous communication with a controlling application and every time there are new packets, the controlling app is notified and then asks for the packet data. The packet data is stored in a simple struct, with uint8_t[1600] for the bytes, and uint32_t for the length. The dext is able to populate this struct with dummy data every time a packet is available, with the dummy data visible on the controlling application. However, I'm struggling to fill it with the real packet data.

The IOUserNetworkPacket provides metadata about a packet. It contains a packets timestamp, size, etc, but it doesn't seem to contain the packet's data. There are the GetDataOffset() and GetMemorySegmentOffset() methods which seem to return byte offsets for where the packet data is located in their memory buffer. My instinct tells me to add this offset to the pointer of wherever the packet data is stored. The problem is I have no idea where the packets are actually stored.

I know they are managed by the IOUserNetworkPacketBufferPool, but I don't think that's where their memory is. There is the CopyMemoryDescriptor() method which gives an IOMemoryDescriptor of its contents. I tried using the descriptor to create an IOMemoryMap, using it to call GetAddress(). The pointers to all the mentioned objects lead to junk data.

I must be approaching this entirely wrong. If anyone knows how to access the packet data, or has any ideas, I would appreciate any help. Thanks.

Code snippet within IOUserClient::ExternalMethod:

case GetPacket:
{
    IOUserNetworkPacket *packet =
            ivars->m_provider->getPacket();

    GetPacket_Output output;
    output.packet_size = packet->getDataLength();

    IOUserNetworkPacketBufferPool *pool;
    packet->GetPacketBufferPool(&pool);

    IOMemoryDescriptor *memory = nullptr;
    pool->CopyMemoryDescriptor(&memory);

    IOMemoryMap *map = nullptr;
    memory->CreateMapping(0, 0, 0, 0, 0, &map);

    uint64_t address = map->GetAddress()
            + packet->getMemorySegmentOffset();
    memcpy(output.packet_data,
            (void*)address, packet->getDataLength());

    in_arguments->structureOutput = OSData::withBytes(
            &output, sizeof(GetPacket_Output));

    // free stuff

} break;

Body:
The problem was caused by an IOUserNetworkPacketBufferPool bug. My bufferSize was set to 1600 except this value was ignored and replaced with 2048. The IOUserNetworkPackets acted as though the bufferSize was 1600 and so they gave an invalid offset.

Creating the buffer pool and mapping it:

kern_return_t
IMPL(FooDriver, Start)
{
    // ...
    IOUserNetworkPacketBufferPool::Create(this, "FooBuffer",
        32, 32, 2048, &ivars->packet_buffer));

    packet_buffer->CopyMemoryDescriptor(ivars->packet_buffer_md);

    ivars->packet_md->Map(0, 0, 0, IOVMPageSize,
        &ivars->packet_buffer_addr, &ivars->packet_buffer_length));
   // ...
}

Getting the packet data:

void FooDriver::getPacketData(
        IOUserNetworkPacket  *packet,
        uint8_t              *packet_data,
        uint32_t             *packet_size
) {
    uint8_t  packet_head;
    uint64_t packet_offset;

    packet->GetHeadroom(&packet_head);
    packet->GetMemorySegmentOffset(&packet_offset);

    uint8_t *buffer = (uint8_t*)(ivars->packet_buffer_addr
        + packet_offset + packet_head);
    *packet_size = packet->getDataLength();

    memcpy(packet_data, buffer, *packet_size);
}


问:
How to allow push queries to be streamed continuously/ for more than ten minutes at a time?
I am working on a java consumer for ksqlDB, that uses PULL and PUSH queries.

Currently, a single push query may be streamed for a maximum of ten minutes at a time, after which the server closes the connection if consumer is idle. Even if there is a change in the streams or tables, we cannot receive these changes because of connection timeout.
Is there any way to keep this connection alive continuously?

答:
One workaround is to ping ksqlDB server every few minutes.
but it will obviously hold server's resources unnecessarily.
https://github.com/confluentinc/ksql/issues/6970

or else one can write simple onError method using Reactive Streams Subscriber (for more details refer to, https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-clients/java-client/), in which the re-subscription logic can be written.
So that if next change in the ksqlDB server occurs even after few hours, timeout exception will be caught by onError method and then we can re-subscribe to the push queries.

```<code>@Override
    public synchronized void onError(Throwable t) {
        logger.error("Received an error in onError method : " + t);
        getPushQueryResult();
    }

public void getPushQueryResult() {
        try {
            client.streamQuery("query").thenAccept(streamedQueryResult -> {
                logger.info("Query has started. Query ID: " + streamedQueryResult.queryID());
                RowSubscriber subscriber = new RowSubscriber();
                streamedQueryResult.subscribe(subscriber);
            }).exceptionally(e -> {
                logger.error("Request failed : " + e);
                return null;
            });
        } catch (Exception e) {
            logger.error("Exception in getPushQueryResult method : " + e);
        }

    }
</code>```

Body:
One workaround is to ping ksqlDB server every few minutes.
but it will obviously hold server's resources unnecessarily.
https://github.com/confluentinc/ksql/issues/6970

or else one can write simple onError method using Reactive Streams Subscriber (for more details refer to, https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-clients/java-client/), in which the re-subscription logic can be written.
So that if next change in the ksqlDB server occurs even after few hours, timeout exception will be caught by onError method and then we can re-subscribe to the push queries.

@Override
    public synchronized void onError(Throwable t) {
        logger.error("Received an error in onError method : " + t);
        getPushQueryResult();
    }

public void getPushQueryResult() {
        try {
            client.streamQuery("query").thenAccept(streamedQueryResult -> {
                logger.info("Query has started. Query ID: " + streamedQueryResult.queryID());
                RowSubscriber subscriber = new RowSubscriber();
                streamedQueryResult.subscribe(subscriber);
            }).exceptionally(e -> {
                logger.error("Request failed : " + e);
                return null;
            });
        } catch (Exception e) {
            logger.error("Exception in getPushQueryResult method : " + e);
        }

    }


答:
It looks like you're only logging nameUnder50 yet you are passing 'over' to the function

nameOver50 is the array you should be logging or both:

const person = [
    { name: 'Jessica', age: 25 },
    { name: 'Ilary', age: 27 },
    { name: 'Frank', age: 70 },
    { name: 'Dan', age: 65 },
    { name: 'Pop', age: 22 },
    { name: 'Maur', age: 68 },
  ];

  let nameOver50 = [];
  let nameUnder50 = [];

  function check(enter) {
    person.filter(({ name, age }) => {
      if (age > 50 && enter === 'over') {
        nameOver50.push( name );
        // nameOver50.push({ name });
        // You could alternatively just push the name, if you want an array of the names only
      } else if (age < 50 && enter === 'under') {
        nameUnder50.push(name);
      }
    });
    console.log(nameUnder50);
    console.log(nameOver50);
  }

  check('over');
  check('under');```

Title: how can I filter an array of objects based on a specific property and return only one property when I insert the parameter into the function?


问:
Django - Cannot create migrations for ImageField with dynamic upload_to value
I just upgraded my app to 1.7 (actually still trying).

This is what i had in models.py:

```<code>def path_and_rename(path):
    def wrapper(instance, filename):
        ext = filename.split('.')[-1]
        # set filename as random string
        filename = '{}.{}'.format(uuid4().hex, ext)
        # return the whole path to the file
        return os.path.join(path, filename)
    return wrapper

class UserProfile(AbstractUser):
    #...
    avatar = models.ImageField(upload_to=path_and_rename("avatars/"),
                               null=True, blank=True,
                               default="avatars/none/default.png",
                               height_field="image_height",
                               width_field="image_width")
</code>```

When i try to makemigrations, it throws:

```<code>ValueError: Could not find function wrapper in webapp.models.
Please note that due to Python 2 limitations, you cannot serialize unbound method functions (e.g. a method declared
and used in the same class body). Please move the function into the main module body to use migrations.
</code>```

答:
```<code>field=models.ImageField(blank=True, upload_to="/smth", *(), **{'thumbnail': True})),
</code>```

instead of

```<code>field=models.ImageField(blank=True, upload_to=functools.partial(news.models.upload_image_location, *(), **{'thumbnail': True}))
</code>```

Body:
I just upgraded my app to 1.7 (actually still trying).

This is what i had in models.py:

def path_and_rename(path):
    def wrapper(instance, filename):
        ext = filename.split('.')[-1]
        # set filename as random string
        filename = '{}.{}'.format(uuid4().hex, ext)
        # return the whole path to the file
        return os.path.join(path, filename)
    return wrapper

class UserProfile(AbstractUser):
    #...
    avatar = models.ImageField(upload_to=path_and_rename("avatars/"),
                               null=True, blank=True,
                               default="avatars/none/default.png",
                               height_field="image_height",
                               width_field="image_width")

When i try to makemigrations, it throws:

ValueError: Could not find function wrapper in webapp.models.
Please note that due to Python 2 limitations, you cannot serialize unbound method functions (e.g. a method declared
and used in the same class body). Please move the function into the main module body to use migrations.

Body:
field=models.ImageField(blank=True, upload_to="/smth", *(), **{'thumbnail': True})),

instead of

field=models.ImageField(blank=True, upload_to=functools.partial(news.models.upload_image_location, *(), **{'thumbnail': True}))


问:
How to configure Azure APIM policy to send emails in case 401 errors
I have a requirement to send alerts via emails in case if an API fails with 401 (Unauthorized access) errors. These apis use api-key for authentication.
I tried to trigger a logic app from the on-error section of the Azure APIM policy but that didn't work. Is there a way to trigger an email (via logic app or any other means) in case of a 401 error?

Please note: I have already configured Azure Monitor alerts for 401 errors which notify us when the number of 401 errors exceed a threshold value. However, for some of our critical APIs we want to get alerted as soon as there is an unauthorised access error.

答:
No need to make things complicated with logic apps or azure functions.

Simply use Azure Alerts and create a query for your API logs that checks for status code 401

If you then see 401 the alert can send emails, send push messages, do many things out of the box it can also be setup to send messages to slack channels or teams, it is very powerful.


问:
What does 0x80020101 represent?
A simple question that I can't find an answer for in Microsoft's error lookup or easily using google: what does the HRESULT 0x80020101 represent?</p>

答:
http://support.microsoft.com/kb/247784

The HRESULT 0x80020101 translates to SCRIPT_E_REPORTED. This error can be observed when a scripting component fails under MTS.

Title: What does 0x80020101 represent?


问:
Scala - what is this map + case syntax?
I can't seem to find further information on this language feature where you can put a case inside a map like this:

```<code>   val sVersion = CrossVersion.partialVersion(scalaVersion)
      .map { case (major:Long, minor: Long) => s"_$major.$minor" } getOrElse ""
</code>```

I've been starting to use this syntax, but what is it called and where can I find more information on it?

答:
I've been starting to use this syntax, but what is it called […]

It is officially called a Pattern Matching Anonymous Function. The Scala community also sometimes refers to it as a Partial Function Literal.

[…] and where can I find more information on it?

The ultimate source of truth for everything in the Scala Programming Language is the Scala Language Specification (aka SLS). You will note that I have linked to version 2.13 of the spec – unfortunately, a single consolidated spec for Scala 3 has not been published yet.

See Scala Language Specification 8.5 Pattern Matching Anonymous Functions for all the gory details. Simply put, the expression

{
  case p1 => e1
  case p2 => e2
  // …
  case pn => en
}
```
<p>is equivalent to</p>
<pre class="lang-scala prettyprint-override"><code>(x1: S1, x2: S2, /* … */, xn: Sn) => (x1, x2, /* … */, xn) match {
  case p1 => e1
  case p2 => e2
  // …
  case pn => en
}
</code>```

provided that the result type is SAM-convertible to FunctionN[S1, S2, /* … */, Sn, R], or as a special case PartialFunction1[S1, R] (which is where the name Partial Function Literal comes from.)

In Scala 3, there is a new feature which can make this code even more concise: For a very long time, the Scala Designers wanted to unify Tuples and Argument Lists. In other words, they wanted to make it so that methods in Scala only ever take one argument, and that argument is a tuple. Unfortunately, it turned out that a) this massively breaks backwards-compatibility and b) massively breaks platform interoperability.

Now, Scala 3 was an opportunity to ignore problem a), but you cannot ignore problem b) since one of the major design goals of Scala is to have seamless, tight, good, performant integration with the underlying host platform (e.g. .NET in the case of the now-abandoned Scala.NET, the ECMASCript / HTML5 / DOM / WebAPI platform in the case of Scala.js, the native Operating System in the case of Scala-native, or the Java platform (JRE, JDK, JVM, J2SE, J2EE, Java, Kotlin, Clojure, etc.) in the case of Scala-JVM).

However, the Scala designers managed to find a compromise, where arguments and tuples are not the same thing, but parameters can be easily converted to tuples and tuples can be easily converted to arguments.

This is called Parameter Untupling, and it basically means that a function of type FunctionN[S1, S2, /* … */, Sn, R] can be automatically converted to a function of type Function1[(S1, S2, /* … */, Sn), R] which is syntactic sugar for Function1[TupleN[S1, S2, /* … */, Sn], R].

Simply put,

(p1: S1, p2: S2, /* … */, pn: Sn) => e: R
```
<p>can automatically be converted to</p>
<pre class="lang-scala prettyprint-override"><code>(x: (S1, S2, /* … */, Sn)) => {
  val p1: S1 = x._1
  val p2: S2 = x._2
  // …
  val pn: Sn = x._n

  e
}
</code>```

With this, your code would look like:

val sVersion = CrossVersion.partialVersion(scalaVersion)
  .map { (major: Long, minor: Long) => s"_$major.$minor" } getOrElse ""
```

Note: unfortunately, there is no comprehensive specification of Scala 3 yet. There is a partial Language Reference, which however only describes differences to Scala 2. So, you typically have to bounce back and forth between the SLS and the Scala 3 docs.

Title: Scala - what is this map + case syntax?

Body:
I can't seem to find further information on this language feature where you can put a case inside a map like this:

   val sVersion = CrossVersion.partialVersion(scalaVersion)
      .map { case (major:Long, minor: Long) => s"_$major.$minor" } getOrElse ""

I've been starting to use this syntax, but what is it called and where can I find more information on it?

Body:
I've been starting to use this syntax, but what is it called […]

It is officially called a Pattern Matching Anonymous Function. The Scala community also sometimes refers to it as a Partial Function Literal.

[…] and where can I find more information on it?

The ultimate source of truth for everything in the Scala Programming Language is the Scala Language Specification (aka SLS). You will note that I have linked to version 2.13 of the spec – unfortunately, a single consolidated spec for Scala 3 has not been published yet.

See Scala Language Specification 8.5 Pattern Matching Anonymous Functions for all the gory details. Simply put, the expression

{
  case p1 => e1
  case p2 => e2
  // …
  case pn => en
}

is equivalent to

(x1: S1, x2: S2, /* … */, xn: Sn) => (x1, x2, /* … */, xn) match {
  case p1 => e1
  case p2 => e2
  // …
  case pn => en
}

provided that the result type is SAM-convertible to FunctionN[S1, S2, /* … */, Sn, R], or as a special case PartialFunction1[S1, R] (which is where the name Partial Function Literal comes from.)

In Scala 3, there is a new feature which can make this code even more concise: For a very long time, the Scala Designers wanted to unify Tuples and Argument Lists. In other words, they wanted to make it so that methods in Scala only ever take one argument, and that argument is a tuple. Unfortunately, it turned out that a) this massively breaks backwards-compatibility and b) massively breaks platform interoperability.

Now, Scala 3 was an opportunity to ignore problem a), but you cannot ignore problem b) since one of the major design goals of Scala is to have seamless, tight, good, performant integration with the underlying host platform (e.g. .NET in the case of the now-abandoned Scala.NET, the ECMASCript / HTML5 / DOM / WebAPI platform in the case of Scala.js, the native Operating System in the case of Scala-native, or the Java platform (JRE, JDK, JVM, J2SE, J2EE, Java, Kotlin, Clojure, etc.) in the case of Scala-JVM).

However, the Scala designers managed to find a compromise, where arguments and tuples are not the same thing, but parameters can be easily converted to tuples and tuples can be easily converted to arguments.

This is called Parameter Untupling, and it basically means that a function of type FunctionN[S1, S2, /* … */, Sn, R] can be automatically converted to a function of type Function1[(S1, S2, /* … */, Sn), R] which is syntactic sugar for Function1[TupleN[S1, S2, /* … */, Sn], R].

Simply put,

(p1: S1, p2: S2, /* … */, pn: Sn) => e: R

can automatically be converted to

(x: (S1, S2, /* … */, Sn)) => {
  val p1: S1 = x._1
  val p2: S2 = x._2
  // …
  val pn: Sn = x._n

  e
}

With this, your code would look like:

val sVersion = CrossVersion.partialVersion(scalaVersion)
  .map { (major: Long, minor: Long) => s"_$major.$minor" } getOrElse ""

Note: unfortunately, there is no comprehensive specification of Scala 3 yet. There is a partial Language Reference, which however only describes differences to Scala 2. So, you typically have to bounce back and forth between the SLS and the Scala 3 docs.


答:
You're not using the result of filter(), so it should be forEach().

You need to display the appropriate array depending on enter.

const person = [
  { name: 'Jessica', age: 25 },
  { name: 'Ilary', age: 27 },
  { name: 'Frank', age: 70 },
  { name: 'Dan', age: 65 },
  { name: 'Pop', age: 22 },
  { name: 'Maur', age: 68 },
];

let nameOver50 = [];
let nameUnder50 = [];

function check(enter) {
  person.forEach(({ name, age }) => {
    if (age > 50 && enter === 'over') {
      nameOver50.push({ name });
    } else if (age < 50 && enter === 'under') {
      nameUnder50.push(name);
    }
  });
  if (enter === 'over') {
    console.log(nameOver50);
  } else {
    console.log(nameUnder50);
  }
}

check('over');```