问:
Grails, Weblogic and redirection on root "/" seems not working
I configured my grails application with an root path like this (in UrlMapping):

```<code>"/"{
    controller="mycontroller"
    action="myaction"
 }
</code>```

in mycontroller.myaction, depending of the role, I redirect to the right action :

```<code>def link
if (SpringSecurityUtils.ifAnyGranted("ROLE_ADMIN") link = g.createLink(action:      "action1", controller:"controller")
else if (SpringSecurityUtils.ifAnyGranted("ROLE_ADMIN") link = g.createLink(action: "action2", controller:"controller")
else ...ANONYMOUS... {
  link = g.creatLink(action:"public", controller:"mycontroller")
}
redirect (url:link)
</code>```

With embedded grails server, it's working fine but with weblogic it redirect on the index.gsp.

Why ?

Do you have an idea ?

Thanks

答:
I found the solution here

I created a taglib.

I rename the mapping on "/" to "/redirect" in
UrlMapping

I call the taglib in GSP.

Body:
I configured my grails application with an root path like this (in UrlMapping):

"/"{
    controller="mycontroller"
    action="myaction"
 }

in mycontroller.myaction, depending of the role, I redirect to the right action :

def link
if (SpringSecurityUtils.ifAnyGranted("ROLE_ADMIN") link = g.createLink(action:      "action1", controller:"controller")
else if (SpringSecurityUtils.ifAnyGranted("ROLE_ADMIN") link = g.createLink(action: "action2", controller:"controller")
else ...ANONYMOUS... {
  link = g.creatLink(action:"public", controller:"mycontroller")
}
redirect (url:link)

With embedded grails server, it's working fine but with weblogic it redirect on the index.gsp.

Why ?

Do you have an idea ?

Thanks


来源: stackexchange

问:
Getting errors while compiling a C program to find the duplicate values from an m×n matrix using malloc() and free()
SO i was solving this problem and i am getting this error

What is my mistake here?Why is it saying invalid argument type?Is there any declaration mistake I made?
I am a newbie still I am trying hard to learn these. A detailed explanation will be useful

```<code>#include <stdio.h>
#include <stdlib.h>

int main(void) {
  int m,n;
  printf("Input the number of Rows: ");
  scanf("%i", &m);
  printf("Input the number of Columns: ");
  scanf("%i", &n);

int *arr=(int*)malloc(m * sizeof(int));
    for(int i=0;i<m;i++)
    {
        arr[i] = (int*)malloc(n*sizeof(int));
    }

    printf("Populate Matrix Row by Row\n--------------------------\n");

    for(int i=0; i<m; i++){
        printf("Row [%i]\n--------\n",i);
        for(int j=0; j<n; j++){
            printf("At Col [%i]= ",j);
            scanf("%i", &*(*(arr+i) + j));
            printf("\n");
        }
    }
printf("[MATRIX]\n------------------\n");
  for(int i=0; i<m; i++){
    for(int j=0; j<n; j++){
      printf("%i ",*(*(arr+i) + j));
    }
    printf("\n");
  }
  printf("------------------\n");

printf("The duplicate value(s) are:\n");
  int temp_index=0;
  for(int i=0; i<m; i++){
    for(int j=0; j<n; j++){
      temp_index=j;
      for(int x=i; x<m; x++){
        for(int y=temp_index; y<n; y++){
           if(j!=y){
             if(*(*(arr+i) + j) == *(*(arr+x) + y)){
             printf("%i in position (%i, %i)\n",*(*(arr+i) + j),x,y);
           }
          }
        }
        temp_index=0;
      }
    }
  }

  free(arr);

  return 0;
}
</code>```

答:
```<code>int *arr=(int*)malloc(m * sizeof(int));
</code>```

*(*(arr+i) + j): *(arr+i) is int, you are trying to dereference the int value *(arr+i) + j . I assume you would wish

```<code>int **arr = malloc(m * sizeof(int*));
</code>```

It would be more clear and shorter if you had used arr[i][j] instead of *(*(arr+i) + j).

ContentLicense: CC BY-SA 4.0

Body:
SO i was solving this problem and i am getting this error

What is my mistake here?Why is it saying invalid argument type?Is there any declaration mistake I made?
I am a newbie still I am trying hard to learn these. A detailed explanation will be useful

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  int m,n;
  printf("Input the number of Rows: ");
  scanf("%i", &m);
  printf("Input the number of Columns: ");
  scanf("%i", &n);

int *arr=(int*)malloc(m * sizeof(int));
    for(int i=0;i<m;i++)
    {
        arr[i] = (int*)malloc(n*sizeof(int));
    }

    printf("Populate Matrix Row by Row\n--------------------------\n");

    for(int i=0; i<m; i++){
        printf("Row [%i]\n--------\n",i);
        for(int j=0; j<n; j++){
            printf("At Col [%i]= ",j);
            scanf("%i", &*(*(arr+i) + j));
            printf("\n");
        }
    }
printf("[MATRIX]\n------------------\n");
  for(int i=0; i<m; i++){
    for(int j=0; j<n; j++){
      printf("%i ",*(*(arr+i) + j));
    }
    printf("\n");
  }
  printf("------------------\n");

printf("The duplicate value(s) are:\n");
  int temp_index=0;
  for(int i=0; i<m; i++){
    for(int j=0; j<n; j++){
      temp_index=j;
      for(int x=i; x<m; x++){
        for(int y=temp_index; y<n; y++){
           if(j!=y){
             if(*(*(arr+i) + j) == *(*(arr+x) + y)){
             printf("%i in position (%i, %i)\n",*(*(arr+i) + j),x,y);
           }
          }
        }
        temp_index=0;
      }
    }
  }

  free(arr);

  return 0;
}

Body:
int *arr=(int*)malloc(m * sizeof(int));

*(*(arr+i) + j): *(arr+i) is int, you are trying to dereference the int value *(arr+i) + j . I assume you would wish

int **arr = malloc(m * sizeof(int*));

It would be more clear and shorter if you had used arr[i][j] instead of *(*(arr+i) + j).


问:
Verilog timing and clocking - input and output issues
I have written this code in verilog and I have a problem with my code!
What I want to do is to give as input the numbers 0 - 127 , so they can be written in mem and then to read them and see the output. I have set the clock to change every 5 from 0 to 1, which is happening, according to the results. But the numbers are being witten more than once in the memory.
How can I fix this, in order the numbers will be written only once ? Could it be a timing-clocking problem ?

At the beginning the output data is 0, because I need to write the data first and then read them.

Also, I would like to know what I need to change so that when the last position of the memory is filled with the number 127, my program will understand that no other position of the memory is left empty!!
I am running the code in EDA Playground.

```<code>module process_data(
  input wire [63:0] DATA_IN ,  //input data
  input QUE_Mode,              //fifo or filo
  //input wire [6:0] AdrR ,    //pointers for read, write
  //input wire [6:0] AdrW,
  input R_W ,
  input Cen,
  input clk,
  input reset,
  output reg [63:0]Reg_Data_Out,  //output data
  output reg Que_Full,            //state of the queue
  output reg Que_Last,
  output reg Que_Empty);

  integer i;
  reg [63:0] Memory [0:127];      //array
  reg [6:0] AdrW;
  reg [6:0] AdrR;

  initial begin        //initialization
   Que_Full= 1'b0;     //when  Que_Full = 1'b0, the queue is not full
   Que_Last = 1'b0;    //when  Que_Last = 1'b0, this is not the last item of the list that can be added to
   Que_Empty = 1'b0;   //when Que_Empty = 1'b0, the queue is empty.
   AdrR=7'b0000_000;
   AdrW=7'b0000_000;

   i=0;
    repeat (128)        //initialization of memory
    begin
        Memory[i]=64'd1;    //64 bits/ position , 127 positions
        i=i+1;
    end
   end

  always @* begin
    $display("AdrR=%d",AdrR);
    $display("AdrW=%d",AdrW);

  end

  always @(negedge(clk))
  begin
    if(Cen == 1'b1) begin                        // cen = chip enabled , when 1=> chip is enabled => circuit works
    case (R_W)
      1'b1:
         begin
           if(Que_Empty == 1'b1 )begin           //check if queue not empty
                                                 // Return the value from the FIFO  foun at the read address
              Reg_Data_Out <= Memory[AdrR];      // (read)  out put memory context
              AdrR<=AdrR+7'b0000_001;            //assign  AdrR [6:0] <= AdrR [6:0] +7'b0000_001;
           end
         end

      1'b0:
        begin
          if( Que_Full == 1'b0  )begin               //check if queue not full
            if(AdrW >= 7'b0000_000) begin
              Memory[AdrW] <= DATA_IN ;              // write input to memory , On any write -> update the memory
              AdrW <= AdrW+7'b0000_001;              //non blocking statements to avoid race conditions
              Que_Empty = 1'b1;                      //when Que_Empty = 1'b1, the queue is NOT empty

              if(AdrW==7'b1111_111)begin
                                                     //AdrW <= 7'b0000_000;
                 Que_Full= 1'b1;                     //when  Que_Full = 1'b1, the queue IS full
                 Que_Last = 1'b1;                    //when  Que_Last = 1'b0, this IS the last item of the list that can be added to
              end
            end
          end
        end

      default:
        Reg_Data_Out = 64'bxxxxxxxx;
    endcase

    end
  end
endmodule

module clock(output reg clk);
  initial
  clk=1'b0;
  always
  #5 clk=~clk;
endmodule

module TOP();
  parameter ENDTIME=40000;

  reg [63:0] inputdata1;  // is an 63-bit "register", or variable
  wire [6:0] AddressR,AddressW;

  reg cen, R_W, reset;  //clk=1'b0  ,
  reg QUE_Mode;

  wire [63:0] Data_Out;

  integer count;
  integer i;

  wire Que_Full, Que_Last, Que_Empty;

  wire clk;

  //call module for data I/O
  process_data process_data(
    inputdata1,
    QUE_Mode,
    //AddressR,
    //AddressW,
    R_W ,
    cen,
    clk,
    reset,
    Data_Out,
    Que_Full,
    Que_Last,
    Que_Empty);  //reset, Que_Full, Que_Last, Que_Empty do not do anything yet

  clock MyClock(clk);
  initial
  begin
    $dumpfile("ALU.vcd");
    $dumpvars(0);

    $display("\t\t\t\t\t\t\t\t\tSIMULATION RESULT ");
    $display("\t\ttime\tclk\t\t\tinputdata1\t\tData_Out\tQUE_Mode\t\tAddressR\t\tAddressW\t\tQue_Full\t\Que_Last\t\Que_Empty");
    $monitor($time, "\t%d\t%d\t%d\t%d",clk,inputdata1,Data_Out,QUE_Mode,AddressR,AddressW,Que_Full,Que_Last,Que_Empty);

    cen=1'b1;   //chip enabled
    count = 0;
    R_W = 1'b0;   //write
    QUE_Mode = 1'b0; // QUE_Mode = 1'b0 => FIFO MODE
    i=0;

    //input
    for (i = 0; i < 128; i = i + 1) begin   //input
                R_W=1'b0;   //write
                inputdata1 = i;
                #20;
           end

    #10
    for (i = 0; i < 128; i = i + 1) begin //output
                #20;
                R_W=1'b1;   //read  => output
                #20;
           end
    $display("-------------- THE SIMULATION FINISHED ------------");
    $finish;
   end

endmodule

</code>```

RESULTS:

```<code>                            SIMULATION RESULT
        time    clk         inputdata1      Data_Out    QUE_Mode        AddressR        AddressW         Que_Full   Que_Last    Que_Empty
AdrR=  0
AdrW=  0
AdrR=  0
AdrW=  1
                   0    0                      0                       x    0  z  z001
                   5    1                      0                       x    0  z  z001
AdrR=  0
AdrW=  2
                  10    0                      0                       x    0  z  z001
                  15    1                      0                       x    0  z  z001
AdrR=  0
AdrW=  3
                  20    0                      1                       x    0  z  z001
                  25    1                      1                       x    0  z  z001
AdrR=  0
AdrW=  4
                  30    0                      1                       x    0  z  z001
                  35    1                      1                       x    0  z  z001
AdrR=  0
AdrW=  5
                  40    0                      2                       x    0  z  z001
                  45    1                      2                       x    0  z  z001
AdrR=  0
AdrW=  6
                  50    0                      2                       x    0  z  z001
                  55    1                      2                       x    0  z  z001
AdrR=  0
AdrW=  7
                  60    0                      3                       x    0  z  z001
                  65    1                      3                       x    0  z  z001
AdrR=  0
AdrW=  8
                  70    0                      3                       x    0  z  z001
                  75    1                      3                       x    0  z  z001
AdrR=  0
AdrW=  9
                  80    0                      4                       x    0  z  z001
                  85    1                      4                       x    0  z  z001
AdrR=  0
AdrW= 10
                  90    0                      4                       x    0  z  z001
                  95    1                      4                       x    0  z  z001
AdrR=  0
AdrW= 11
                 100    0                      5                       x    0  z  z001
                 105    1                      5                       x    0  z  z001
AdrR=  0
AdrW= 12
                 110    0                      5                       x    0  z  z001
                 115    1                      5                       x    0  z  z001
AdrR=  0
AdrW= 13
                 120    0                      6                       x    0  z  z001
                 125    1                      6                       x    0  z  z001
AdrR=  0
AdrW= 14
                 130    0                      6                       x    0  z  z001
                 135    1                      6                       x    0  z  z001
......................

AdrR=121
AdrW=  0
                7630    0                    127                      60    0  z  z111
                7635    1                    127                      60    0  z  z111
AdrR=122
AdrW=  0
                7640    0                    127                      60    0  z  z111
                7645    1                    127                      60    0  z  z111
AdrR=123
AdrW=  0
                7650    0                    127                      61    0  z  z111
                7655    1                    127                      61    0  z  z111
AdrR=124
AdrW=  0
                7660    0                    127                      61    0  z  z111
                7665    1                    127                      61    0  z  z111
AdrR=125
AdrW=  0
                7670    0                    127                      62    0  z  z111
                7675    1                    127                      62    0  z  z111
AdrR=126
AdrW=  0
                7680    0                    127                      62    0  z  z111
                7685    1                    127                      62    0  z  z111
-------------- THE SIMULATION FINISHED ------------
AdrR=127
                7690    0                    127                      63    0  z  z111
Done

</code>```

答:
You need to change your input data twice as quickly.  Change #20 to #10:

```<code>    //input
    for (i = 0; i < 128; i = i + 1) begin   //input
                R_W=1'b0;   //write
                inputdata1 = i;
//                #20;
                #10;
           end
</code>```

This will write 0 to address 0, 1 to address 1, ... 127 to address 127.

The 1st write is to address 0 at time=0.  However, there is a race condition between the initial and always blocks which could result in different behavior on different simulators.

The log file shows output on every edge of clk, both posedge and negedge, because you have clk in the $monitor statement. But, the data is only changing once per clock period (as desired).

Body:
I have written this code in verilog and I have a problem with my code!
What I want to do is to give as input the numbers 0 - 127 , so they can be written in mem and then to read them and see the output. I have set the clock to change every 5 from 0 to 1, which is happening, according to the results. But the numbers are being witten more than once in the memory.
How can I fix this, in order the numbers will be written only once ? Could it be a timing-clocking problem ?

At the beginning the output data is 0, because I need to write the data first and then read them.

Also, I would like to know what I need to change so that when the last position of the memory is filled with the number 127, my program will understand that no other position of the memory is left empty!!
I am running the code in EDA Playground.

module process_data(
  input wire [63:0] DATA_IN ,  //input data
  input QUE_Mode,              //fifo or filo
  //input wire [6:0] AdrR ,    //pointers for read, write
  //input wire [6:0] AdrW,
  input R_W ,
  input Cen,
  input clk,
  input reset,
  output reg [63:0]Reg_Data_Out,  //output data
  output reg Que_Full,            //state of the queue
  output reg Que_Last,
  output reg Que_Empty);

  integer i;
  reg [63:0] Memory [0:127];      //array
  reg [6:0] AdrW;
  reg [6:0] AdrR;

  initial begin        //initialization
   Que_Full= 1'b0;     //when  Que_Full = 1'b0, the queue is not full
   Que_Last = 1'b0;    //when  Que_Last = 1'b0, this is not the last item of the list that can be added to
   Que_Empty = 1'b0;   //when Que_Empty = 1'b0, the queue is empty.
   AdrR=7'b0000_000;
   AdrW=7'b0000_000;

   i=0;
    repeat (128)        //initialization of memory
    begin
        Memory[i]=64'd1;    //64 bits/ position , 127 positions
        i=i+1;
    end
   end

  always @* begin
    $display("AdrR=%d",AdrR);
    $display("AdrW=%d",AdrW);

  end

  always @(negedge(clk))
  begin
    if(Cen == 1'b1) begin                        // cen = chip enabled , when 1=> chip is enabled => circuit works
    case (R_W)
      1'b1:
         begin
           if(Que_Empty == 1'b1 )begin           //check if queue not empty
                                                 // Return the value from the FIFO  foun at the read address
              Reg_Data_Out <= Memory[AdrR];      // (read)  out put memory context
              AdrR<=AdrR+7'b0000_001;            //assign  AdrR [6:0] <= AdrR [6:0] +7'b0000_001;
           end
         end

      1'b0:
        begin
          if( Que_Full == 1'b0  )begin               //check if queue not full
            if(AdrW >= 7'b0000_000) begin
              Memory[AdrW] <= DATA_IN ;              // write input to memory , On any write -> update the memory
              AdrW <= AdrW+7'b0000_001;              //non blocking statements to avoid race conditions
              Que_Empty = 1'b1;                      //when Que_Empty = 1'b1, the queue is NOT empty

              if(AdrW==7'b1111_111)begin
                                                     //AdrW <= 7'b0000_000;
                 Que_Full= 1'b1;                     //when  Que_Full = 1'b1, the queue IS full
                 Que_Last = 1'b1;                    //when  Que_Last = 1'b0, this IS the last item of the list that can be added to
              end
            end
          end
        end

      default:
        Reg_Data_Out = 64'bxxxxxxxx;
    endcase

    end
  end
endmodule

module clock(output reg clk);
  initial
  clk=1'b0;
  always
  #5 clk=~clk;
endmodule

module TOP();
  parameter ENDTIME=40000;

  reg [63:0] inputdata1;  // is an 63-bit "register", or variable
  wire [6:0] AddressR,AddressW;

  reg cen, R_W, reset;  //clk=1'b0  ,
  reg QUE_Mode;

  wire [63:0] Data_Out;

  integer count;
  integer i;

  wire Que_Full, Que_Last, Que_Empty;

  wire clk;

  //call module for data I/O
  process_data process_data(
    inputdata1,
    QUE_Mode,
    //AddressR,
    //AddressW,
    R_W ,
    cen,
    clk,
    reset,
    Data_Out,
    Que_Full,
    Que_Last,
    Que_Empty);  //reset, Que_Full, Que_Last, Que_Empty do not do anything yet

  clock MyClock(clk);
  initial
  begin
    $dumpfile("ALU.vcd");
    $dumpvars(0);

    $display("\t\t\t\t\t\t\t\t\tSIMULATION RESULT ");
    $display("\t\ttime\tclk\t\t\tinputdata1\t\tData_Out\tQUE_Mode\t\tAddressR\t\tAddressW\t\tQue_Full\t\Que_Last\t\Que_Empty");
    $monitor($time, "\t%d\t%d\t%d\t%d",clk,inputdata1,Data_Out,QUE_Mode,AddressR,AddressW,Que_Full,Que_Last,Que_Empty);

    cen=1'b1;   //chip enabled
    count = 0;
    R_W = 1'b0;   //write
    QUE_Mode = 1'b0; // QUE_Mode = 1'b0 => FIFO MODE
    i=0;

    //input
    for (i = 0; i < 128; i = i + 1) begin   //input
                R_W=1'b0;   //write
                inputdata1 = i;
                #20;
           end

    #10
    for (i = 0; i < 128; i = i + 1) begin //output
                #20;
                R_W=1'b1;   //read  => output
                #20;
           end
    $display("-------------- THE SIMULATION FINISHED ------------");
    $finish;
   end

endmodule

RESULTS:

                            SIMULATION RESULT
        time    clk         inputdata1      Data_Out    QUE_Mode        AddressR        AddressW         Que_Full   Que_Last    Que_Empty
AdrR=  0
AdrW=  0
AdrR=  0
AdrW=  1
                   0    0                      0                       x    0  z  z001
                   5    1                      0                       x    0  z  z001
AdrR=  0
AdrW=  2
                  10    0                      0                       x    0  z  z001
                  15    1                      0                       x    0  z  z001
AdrR=  0
AdrW=  3
                  20    0                      1                       x    0  z  z001
                  25    1                      1                       x    0  z  z001
AdrR=  0
AdrW=  4
                  30    0                      1                       x    0  z  z001
                  35    1                      1                       x    0  z  z001
AdrR=  0
AdrW=  5
                  40    0                      2                       x    0  z  z001
                  45    1                      2                       x    0  z  z001
AdrR=  0
AdrW=  6
                  50    0                      2                       x    0  z  z001
                  55    1                      2                       x    0  z  z001
AdrR=  0
AdrW=  7
                  60    0                      3                       x    0  z  z001
                  65    1                      3                       x    0  z  z001
AdrR=  0
AdrW=  8
                  70    0                      3                       x    0  z  z001
                  75    1                      3                       x    0  z  z001
AdrR=  0
AdrW=  9
                  80    0                      4                       x    0  z  z001
                  85    1                      4                       x    0  z  z001
AdrR=  0
AdrW= 10
                  90    0                      4                       x    0  z  z001
                  95    1                      4                       x    0  z  z001
AdrR=  0
AdrW= 11
                 100    0                      5                       x    0  z  z001
                 105    1                      5                       x    0  z  z001
AdrR=  0
AdrW= 12
                 110    0                      5                       x    0  z  z001
                 115    1                      5                       x    0  z  z001
AdrR=  0
AdrW= 13
                 120    0                      6                       x    0  z  z001
                 125    1                      6                       x    0  z  z001
AdrR=  0
AdrW= 14
                 130    0                      6                       x    0  z  z001
                 135    1                      6                       x    0  z  z001
......................

AdrR=121
AdrW=  0
                7630    0                    127                      60    0  z  z111
                7635    1                    127                      60    0  z  z111
AdrR=122
AdrW=  0
                7640    0                    127                      60    0  z  z111
                7645    1                    127                      60    0  z  z111
AdrR=123
AdrW=  0
                7650    0                    127                      61    0  z  z111
                7655    1                    127                      61    0  z  z111
AdrR=124
AdrW=  0
                7660    0                    127                      61    0  z  z111
                7665    1                    127                      61    0  z  z111
AdrR=125
AdrW=  0
                7670    0                    127                      62    0  z  z111
                7675    1                    127                      62    0  z  z111
AdrR=126
AdrW=  0
                7680    0                    127                      62    0  z  z111
                7685    1                    127                      62    0  z  z111
-------------- THE SIMULATION FINISHED ------------
AdrR=127
                7690    0                    127                      63    0  z  z111
Done

Body:
You need to change your input data twice as quickly.  Change #20 to #10:

    //input
    for (i = 0; i < 128; i = i + 1) begin   //input
                R_W=1'b0;   //write
                inputdata1 = i;
//                #20;
                #10;
           end

This will write 0 to address 0, 1 to address 1, ... 127 to address 127.

The 1st write is to address 0 at time=0.  However, there is a race condition between the initial and always blocks which could result in different behavior on different simulators.

The log file shows output on every edge of clk, both posedge and negedge, because you have clk in the $monitor statement. But, the data is only changing once per clock period (as desired).


问:
MFC: how to differentiate "Save" vs "Save As"?
In my previous question (MFC: how to change default file name for CFileDialog?), I overload DoSave function to supply a file name suggestion. Within this function is there way to differentiate "Save" vs "Save As"? Because I should only pop out dialog window if it is "Save As".

```<code>BOOL CMyDoc::DoSave(LPCTSTR lpszPathName, BOOL bReplace)
{
    if (IsSaveAS() || m_saved_file_name.IsEmpty())
    {
        CString file_name = some_suggested_file_name;

        CFileDialog file_dialog(false, ..., file_name, ...);

        if (file_dialog.DoModal() == IDOK)
        {
            m_saved_file_name = file_dialog.GetPathName();
        }
    }

    OnSaveDocument(m_saved_file_name);

    return TRUE;
}
</code>```

答:
The dialog should be popped when lpszPathName == NULL || *lpszPathName == '\0'.

This covers the case where DoSave is called from OnFileSaveAs:

```<code>void CDocument::OnFileSaveAs()
{
    if(!DoSave(NULL))
        TRACE(traceAppMsg, 0, "Warning: File save-as failed.\n");
}
</code>```

And also the case where the associated file is read-only and cannot be written to.

```<code>BOOL CDocument::DoFileSave()
{
    DWORD dwAttrib = GetFileAttributes(m_strPathName);
    if (dwAttrib & FILE_ATTRIBUTE_READONLY)
    {
        // we do not have read-write access or the file does not (now) exist
        if (!DoSave(NULL))
        {
            TRACE(traceAppMsg, 0, "Warning: File save with new name failed.\n");
            return FALSE;
        }
    }
    else
    {
        if (!DoSave(m_strPathName))
        {
            TRACE(traceAppMsg, 0, "Warning: File save failed.\n");
            return FALSE;
        }
    }
    return TRUE;
}
</code>```

It also matches the logic of the builtin DoSave.

```<code>BOOL CDocument::DoSave(LPCTSTR lpszPathName, BOOL bReplace)
    // Save the document data to a file
    // lpszPathName = path name where to save document file
    // if lpszPathName is NULL then the user will be prompted (SaveAs)
    // note: lpszPathName can be different than 'm_strPathName'
    // if 'bReplace' is TRUE will change file name if successful (SaveAs)
    // if 'bReplace' is FALSE will not change path name (SaveCopyAs)
{
    CString newName = lpszPathName;

    if (newName.IsEmpty())
    {
        // ...
        if (!AfxGetApp()->DoPromptFileName(newName,
    // ...
</code>```

Body:
In my previous question (MFC: how to change default file name for CFileDialog?), I overload DoSave function to supply a file name suggestion. Within this function is there way to differentiate "Save" vs "Save As"? Because I should only pop out dialog window if it is "Save As".

BOOL CMyDoc::DoSave(LPCTSTR lpszPathName, BOOL bReplace)
{
    if (IsSaveAS() || m_saved_file_name.IsEmpty())
    {
        CString file_name = some_suggested_file_name;

        CFileDialog file_dialog(false, ..., file_name, ...);

        if (file_dialog.DoModal() == IDOK)
        {
            m_saved_file_name = file_dialog.GetPathName();
        }
    }

    OnSaveDocument(m_saved_file_name);

    return TRUE;
}

Body:
The dialog should be popped when lpszPathName == NULL || *lpszPathName == '\0'.

This covers the case where DoSave is called from OnFileSaveAs:

void CDocument::OnFileSaveAs()
{
    if(!DoSave(NULL))
        TRACE(traceAppMsg, 0, "Warning: File save-as failed.\n");
}

And also the case where the associated file is read-only and cannot be written to.

BOOL CDocument::DoFileSave()
{
    DWORD dwAttrib = GetFileAttributes(m_strPathName);
    if (dwAttrib & FILE_ATTRIBUTE_READONLY)
    {
        // we do not have read-write access or the file does not (now) exist
        if (!DoSave(NULL))
        {
            TRACE(traceAppMsg, 0, "Warning: File save with new name failed.\n");
            return FALSE;
        }
    }
    else
    {
        if (!DoSave(m_strPathName))
        {
            TRACE(traceAppMsg, 0, "Warning: File save failed.\n");
            return FALSE;
        }
    }
    return TRUE;
}

It also matches the logic of the builtin DoSave.

BOOL CDocument::DoSave(LPCTSTR lpszPathName, BOOL bReplace)
    // Save the document data to a file
    // lpszPathName = path name where to save document file
    // if lpszPathName is NULL then the user will be prompted (SaveAs)
    // note: lpszPathName can be different than 'm_strPathName'
    // if 'bReplace' is TRUE will change file name if successful (SaveAs)
    // if 'bReplace' is FALSE will not change path name (SaveCopyAs)
{
    CString newName = lpszPathName;

    if (newName.IsEmpty())
    {
        // ...
        if (!AfxGetApp()->DoPromptFileName(newName,
    // ...


问:
regular expression in java to print after n characters
I am writing java code to print something between two expressions.

My file from where I am reading is:

```<code> CAL|AB12345|hi, how are you }
</code>```

my java code:

```<code>final Pattern pattern = Patter.compile("CAL|AB[0-9]{5}|(.+?)}", Pattern.DOTALL);
final Matcher matcher = pattern.matcher(filename);
while (matcher.find()) {
 String a = matcher.group(0);
  System.out.println(a);}
</code>```

I want the output to be:

```<code>hi, how are you
</code>```

ALso, how can i calculate the number of characters for example if i want to print after 9 characters after CAL, it will also work.

答:
you can modify your code like this :

```<code>public static void main(String []args){

    final Pattern pattern = Pattern.compile("(CAL\\|AB[0-9]{5}\\|)([a-zA-Z0-9,><@#\\s]+)(})");
    final Matcher matcher = pattern.matcher("CAL|AB12345|hi, how are you }");

    String a;
    while (matcher.find()) {
         a = matcher.group(2);

        System.out.println(a);}
}
}
</code>```

OUTPUT

```<code> hi, how are you
</code>```

Hint : for  9 characters part ,you can start substring from that index count

Hope it helps !

Body:
I am writing java code to print something between two expressions.

My file from where I am reading is:

 CAL|AB12345|hi, how are you }

my java code:

final Pattern pattern = Patter.compile("CAL|AB[0-9]{5}|(.+?)}", Pattern.DOTALL);
final Matcher matcher = pattern.matcher(filename);
while (matcher.find()) {
 String a = matcher.group(0);
  System.out.println(a);}

I want the output to be:

hi, how are you

ALso, how can i calculate the number of characters for example if i want to print after 9 characters after CAL, it will also work.

Body:
you can modify your code like this :

public static void main(String []args){

    final Pattern pattern = Pattern.compile("(CAL\\|AB[0-9]{5}\\|)([a-zA-Z0-9,><@#\\s]+)(})");
    final Matcher matcher = pattern.matcher("CAL|AB12345|hi, how are you }");

    String a;
    while (matcher.find()) {
         a = matcher.group(2);

        System.out.println(a);}
}
}

OUTPUT

 hi, how are you

Hint : for  9 characters part ,you can start substring from that index count

Hope it helps !


问:
Using dictionary of GraphServiceClient is thread safe?
I have to maintain number of graphClients in my application .<br>
is it better way to store in dictionary? is it thread safe ?   what could be the best option ? </p>

```<code>IDictionary<string, IGraphServiceClient> dict = new Dictionary<string, IGraphServiceClient>();

    private IGraphServiceClient GetGraphServiceClient()
    {
        IDictionary<string, IGraphServiceClient> dict = new Dictionary<string, IGraphServiceClient>();
        var tenantIds = new List<string> { "Tenant1", "Tenant4", "Tenant1", "Tenant1" };
        foreach (var tenant in tenantIds)
        {
            var graphServiceClient = GetGraphServiceClient(tenant);
            var users = await graphServiceClient.Users.GetAsync();
        }
    }
</code>```

```<code>
    private IGraphServiceClient GetGraphServiceClient(string i)
            {
                if (!dict.ContainsKey(i))
                {
                    dict.Add(i, new GraphServiceClient(new MyAuthenticationProvider(i)));
                }
                return dict[i];
            }
</code>```

答:
Dictionaries are not thread-safe. Moreover, even if a dictionary was thread-safe, the composite statements like

```<code>private IGraphServiceClient GetGraphServiceClient(string i)
{
    if (!dict.ContainsKey(i))
    {
        dict.Add(i, new GraphServiceClient(new MyAuthenticationProvider(i)));
    }
    return dict[i];
}
</code>```

are never thread-safe. You need to guard this with a mutex.

Body:
I have to maintain number of graphClients in my application .

is it better way to store in dictionary? is it thread safe ?   what could be the best option ?

IDictionary<string, IGraphServiceClient> dict = new Dictionary<string, IGraphServiceClient>();

    private IGraphServiceClient GetGraphServiceClient()
    {
        IDictionary<string, IGraphServiceClient> dict = new Dictionary<string, IGraphServiceClient>();
        var tenantIds = new List<string> { "Tenant1", "Tenant4", "Tenant1", "Tenant1" };
        foreach (var tenant in tenantIds)
        {
            var graphServiceClient = GetGraphServiceClient(tenant);
            var users = await graphServiceClient.Users.GetAsync();
        }
    }

    private IGraphServiceClient GetGraphServiceClient(string i)
            {
                if (!dict.ContainsKey(i))
                {
                    dict.Add(i, new GraphServiceClient(new MyAuthenticationProvider(i)));
                }
                return dict[i];
            }

Body:
Dictionaries are not thread-safe. Moreover, even if a dictionary was thread-safe, the composite statements like

private IGraphServiceClient GetGraphServiceClient(string i)
{
    if (!dict.ContainsKey(i))
    {
        dict.Add(i, new GraphServiceClient(new MyAuthenticationProvider(i)));
    }
    return dict[i];
}

are never thread-safe. You need to guard this with a mutex.


答:
Can you floor the min_mark column in the grades dataset and JOIN on that:

```<code>val students2 = student.withColumn("min_mark" , 10 * floor($"marks" / 10))
val df3 = students2.join(grades, col("grades2.min_mark") === col("students.min_mark"))
</code>```

You have edge cases (grade = 100) that you have to deal with. Either do a LEFT join and impute or add a row to your dataframe (with a union). Up to you !

Title: spark fast range lookup on 2 columns

Body:
I have 2 datasets, StudentMarks and Grades.
The Grades table has maximum and minimum marks for each grade.
Grades Dataset

+-----+--------+--------+
|Grade|Min_Mark|Max_Mark|
+-----+--------+--------+
|    1|       0|       9|
|    2|      10|      19|
|    3|      20|      29|
|    4|      30|      39|
|    5|      40|      49|
|    6|      50|      59|
|    7|      60|      69|
|    8|      70|      79|
|    9|      80|      89|
|   10|      90|     100|
+-----+--------+--------+

StudentMarks Dataset

+---+--------+-----+
| ID|    Name|Marks|
+---+--------+-----+
|  1|   Julia|   88|
|  2|Samantha|   68|
|  3|   Maria|   99|
|  4| Scarlet|   78|
|  5|  Ashley|   63|
|  6|    Jane|   81|
+---+--------+-----+

I need to find grade for each student. Expected Result-

+---+--------+-----+-----+
| ID|    Name|Marks|Grade|
+---+--------+-----+-----+
|  1|   Julia|   88| 9   |
|  2|Samantha|   68| 7   |
|  3|   Maria|   99| 10  |
|  4| Scarlet|   78| 8   |
|  5|  Ashley|   63| 7   |
|  6|    Jane|   81| 9   |
+---+--------+-----+-----+

Is there an efficient way of looking up for number in a range?

Body:
Can you floor the min_mark column in the grades dataset and JOIN on that:

val students2 = student.withColumn("min_mark" , 10 * floor($"marks" / 10))
val df3 = students2.join(grades, col("grades2.min_mark") === col("students.min_mark"))

You have edge cases (grade = 100) that you have to deal with. Either do a LEFT join and impute or add a row to your dataframe (with a union). Up to you !


问:
gitlab ci/cd trigger two or more downstream pipelines
I have three projects A, B and C.     Projects B & C are dependent on A but are otherwise separate.  What is the syntax for the gitlab yml for project A to trigger BOTH project B & C, independently?

The following syntax is valid but only the second pipeline is executed.  And I've been unable to find any examples in the docs for listing more than one downstream project.

```<code># Build trigger downstream pipelines
staging:
  stage: deploy
  trigger:
      project: WA/ProjectB
      project: WA/ProjectC
</code>```

答:
answer was simple enough;  just split out the two pipelines </p>

```<code># Build trigger downstream pipelines
staging-B:
  variables:
  stage: deploy
  trigger:
      project: WA/B

# Build trigger downstream pipelines
staging-C:
  variables:
  stage: deploy
  trigger:
      project: WA/C
</code>```

Body:
I have three projects A, B and C.     Projects B & C are dependent on A but are otherwise separate.  What is the syntax for the gitlab yml for project A to trigger BOTH project B & C, independently?

The following syntax is valid but only the second pipeline is executed.  And I've been unable to find any examples in the docs for listing more than one downstream project.

# Build trigger downstream pipelines
staging:
  stage: deploy
  trigger:
      project: WA/ProjectB
      project: WA/ProjectC

Body:
answer was simple enough;  just split out the two pipelines

# Build trigger downstream pipelines
staging-B:
  variables:
  stage: deploy
  trigger:
      project: WA/B

# Build trigger downstream pipelines
staging-C:
  variables:
  stage: deploy
  trigger:
      project: WA/C


问:
cached_property and classmethod doesnt work together, Django
I am trying to use cached_property and classmethod decorators together in a viewset but it doesnt work regardless of their mutual position. Is it any chance to make it work together or cached_property doesnt work with classmethod?
Tnanks.

```<code>    @cached_property
    @classmethod
    def get_child_extra_actions(cls):
        """
        Returns only extra actions defined in this exact viewset exclude actions defined in superclasses.
        """
        all_extra_actions = cls.get_extra_actions()
        parent_extra_actions = cls.__base__.get_extra_actions()
        child_extra_actions = set(all_extra_actions).difference(parent_extra_actions)
        return (act.__name__ for act in child_extra_actions)
</code>```

答:
For cached property with classmethod usage i wrote that code a few days ago:

```<code>from django.utils.decorators import classproperty

class cached_classproperty(classproperty):
    def get_result_field_name(self):
        return self.fget.__name__ + "_property_result" if self.fget else None

    def __get__(self, instance, cls=None):
        result_field_name = self.get_result_field_name()

        if hasattr(cls, result_field_name):
            return getattr(cls, result_field_name)

        if not cls or not result_field_name:
            return self.fget(cls)

        setattr(cls, result_field_name, self.fget(cls))
        return getattr(cls, result_field_name)
</code>```

It will be caching result in class-level.

Usage is similar as classproperty:

```<code>@cached_classproperty
def some_func(cls, *args, **kwargs):
    ...
</code>```

If you do not have django in dependencies, then you may want prevent classproperty parent usage (sources). In that case you may use that decorator:

```<code>class cached_classproperty(classproperty):
    def __init__(self, method=None):
        self.fget = method

    def get_result_field_name(self):
        return self.fget.__name__ + "_property_result" if self.fget else None

    def __get__(self, instance, cls=None):
        result_field_name = self.get_result_field_name()

        if hasattr(cls, result_field_name):
            return getattr(cls, result_field_name)

        if not cls or not result_field_name:
            return self.fget(cls)

        setattr(cls, result_field_name, self.fget(cls))
        return getattr(cls, result_field_name)

    def getter(self, method):
        self.fget = method
        return self
</code>```

Body:
I am trying to use cached_property and classmethod decorators together in a viewset but it doesnt work regardless of their mutual position. Is it any chance to make it work together or cached_property doesnt work with classmethod?
Tnanks.

    @cached_property
    @classmethod
    def get_child_extra_actions(cls):
        """
        Returns only extra actions defined in this exact viewset exclude actions defined in superclasses.
        """
        all_extra_actions = cls.get_extra_actions()
        parent_extra_actions = cls.__base__.get_extra_actions()
        child_extra_actions = set(all_extra_actions).difference(parent_extra_actions)
        return (act.__name__ for act in child_extra_actions)

Body:
For cached property with classmethod usage i wrote that code a few days ago:

from django.utils.decorators import classproperty

class cached_classproperty(classproperty):
    def get_result_field_name(self):
        return self.fget.__name__ + "_property_result" if self.fget else None

    def __get__(self, instance, cls=None):
        result_field_name = self.get_result_field_name()

        if hasattr(cls, result_field_name):
            return getattr(cls, result_field_name)

        if not cls or not result_field_name:
            return self.fget(cls)

        setattr(cls, result_field_name, self.fget(cls))
        return getattr(cls, result_field_name)

It will be caching result in class-level.

Usage is similar as classproperty:

@cached_classproperty
def some_func(cls, *args, **kwargs):
    ...

If you do not have django in dependencies, then you may want prevent classproperty parent usage (sources). In that case you may use that decorator:

class cached_classproperty(classproperty):
    def __init__(self, method=None):
        self.fget = method

    def get_result_field_name(self):
        return self.fget.__name__ + "_property_result" if self.fget else None

    def __get__(self, instance, cls=None):
        result_field_name = self.get_result_field_name()

        if hasattr(cls, result_field_name):
            return getattr(cls, result_field_name)

        if not cls or not result_field_name:
            return self.fget(cls)

        setattr(cls, result_field_name, self.fget(cls))
        return getattr(cls, result_field_name)

    def getter(self, method):
        self.fget = method
        return self


问:
Getting error on while importing webdriver in pycharm"No matching distribution found for webdriver"
Getting error while importing webdriver in pycharm

"No matching distribution found for webdriver"

Using Pip version 20.0.2, Selenium version – 3.141.0, OS –windows &  Python 3.7

Problem mentioned here in image.

Tried cmd pip install webdriver and tried pip3 install webdriver still getting error.

I can run my script through IDLE but not through pycharm .

答:
This means that you are probably working in an automatic virtual environment. To install libraries there, you need to open a terminal from the Pycharm environment. Open it in the bottom corner, and then just pip install.
Then, you will be able to access the library in your configuration.

Edit: for some reason I didn't read you can start it from IDLE, you can probably ignore the rest.

If you want to use the Selenium webdriver, you need to import it from the Selenium library: it's not a standalone package. Since you have already installed it, you should:

from selenium import webdriver
```

<p>And then, to check if it works, you may for example:</p>

<pre class="lang-py prettyprint-override"><code>browser = webdriver.Chrome()
browser.get('stackoverflow.com')
</code>```

You may need to install the Webdriver for your browser, though.
Check your browser version and then download the according Webdriver - remembering to go for the same version of your browser.

For Chrome, the download page is here.
The constructor assumes that the Webdriver is accessible in your PATH environment variable: if you don't want to set it, you can pass the path of the Webdriver to the constructor in this way:

browser = webdriver.Chrome(executable='path/to/webdriver')
```

Body:
This means that you are probably working in an automatic virtual environment. To install libraries there, you need to open a terminal from the Pycharm environment. Open it in the bottom corner, and then just pip install.
Then, you will be able to access the library in your configuration.

Edit: for some reason I didn't read you can start it from IDLE, you can probably ignore the rest.

If you want to use the Selenium webdriver, you need to import it from the Selenium library: it's not a standalone package. Since you have already installed it, you should:

from selenium import webdriver

And then, to check if it works, you may for example:

browser = webdriver.Chrome()
browser.get('stackoverflow.com')

You may need to install the Webdriver for your browser, though.
Check your browser version and then download the according Webdriver - remembering to go for the same version of your browser.

For Chrome, the download page is here.
The constructor assumes that the Webdriver is accessible in your PATH environment variable: if you don't want to set it, you can pass the path of the Webdriver to the constructor in this way:

browser = webdriver.Chrome(executable='path/to/webdriver')


问:
Draw partially transparent UIView while using the backgroundColor
I'm creating a custom UIControl that renders it's view via drawRect:. I want to use the existing backgroundColor property to permit customization via Interface Builder. However, if the backgroundColor is set, by the time drawRect: is called, the entire rectangle has already been filled in. I have opaque = NO and clearsContextBeforeDrawing = YES. If I set the backgroundColor to clearColor then I can render only the parts that I want.

How do I prevent the UIView from filling in the entire rectangle with the backgroundColor automatically?

I should mention that the custom control is placed in Interface Builder so the initWithCoder: method is being used to instantiate the object.

This should certainly possible as if you inherit from UIButton - which uses the backgroundColor - the rectangle has not been filled in.

答:
You need to overide:

```<code>- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx;
</code>```

This is where the background color is applied.  If you want the view to handle the background color, call the super's drawLayer method.

ContentLicense: CC BY-SA 3.0

Body:
You need to overide:

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx;

This is where the background color is applied.  If you want the view to handle the background color, call the super's drawLayer method.


问:
Icon for ipywidgets Button not working in Google colab
I'm trying to create a button with an icon using ipywidgets in Google colab without success.

import ipywidgets as widgets
from IPython.display import display

my_button = widgets.Button(icon="home")
display(my_button)
```

However, no icon is displayed...

答:
The following workaround was shared with me from an open issue on github for google colab:

# Create the button
my_button = widgets.Button(icon="home")

# Display the HTML for the button
display(HTML('''<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> '''))
# Display the actual button
display(my_button)
```

Two items are overlaid – the font-awesome icon and the actual button – though rendering of the actual button isn't achieved.

Body:
I'm trying to create a button with an icon using ipywidgets in Google colab without success.

import ipywidgets as widgets
from IPython.display import display

my_button = widgets.Button(icon="home")
display(my_button)

However, no icon is displayed...

Body:
The following workaround was shared with me from an open issue on github for google colab:

# Create the button
my_button = widgets.Button(icon="home")

# Display the HTML for the button
display(HTML('''<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> '''))
# Display the actual button
display(my_button)

Two items are overlaid – the font-awesome icon and the actual button – though rendering of the actual button isn't achieved.


问:
Powershell won't install almost any module using install-module
My Powershell v5.1 won't install almost any module automatically using install-module whereas manually installation does work.

First, when I run install-module, it would download the module then throw an error, say the pscx module:

```<code>PackageManagement\Install-Package : Package 'Pscx' failed to be installed because: Specified cast is not valid.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.0.4\PSModule.psm1:9307 char:21
+ ...          $null = PackageManagement\Install-Package @PSBoundParameters
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidResult: (Pscx:String) [Install-Package], Exception
    + FullyQualifiedErrorId : Package '{0}' failed to be installed because: {1},Microsoft.PowerShell.PackageManag
   ement.Cmdlets.InstallPackage
</code>```

What I can do now is to manually download the module and use import-module myself. The error occurs almost every time when I'm trying to install any module through this cmdlet. How can I address this problem?

For troubleshooting, Get-PSRepository gives me this:

```<code>PS C:\> Get-PSRepository

Name                      InstallationPolicy   SourceLocation
----                      ------------------   --------------
PSGallery                 Trusted              https://www.powershellgallery.com/api/v2
GalleryRolling            Trusted              https://www.poshtestgallery.com/api/v2/
</code>```

EDIT:

Got the same error when trying to use Save-Module:

```<code>PS C:\> Find-Module -Name 'pscx' | Save-Module -Path "G:\Temp\System Documents\WindowsPowerShell\Modules"
WARNING: Package 'Pscx' failed to be installed because: Specified cast is not valid.
WARNING: Package 'Pscx' failed to install.
PackageManagement\Save-Package : Unable to save the module 'Pscx'.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.0.4\PSModule.psm1:11331 char:25
+ ...             $null = PackageManagement\Save-Package @PSBoundParameters
+                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (Microsoft.Power...ets.SavePackage:SavePackage) [Save-Packag
   e], Exception
    + FullyQualifiedErrorId : ProviderFailToDownloadFile,Microsoft.PowerShell.PackageManagement.Cmdlets.Save
   Package
</code>```

It downloaded the package then displays the WARNING.

When using the Find-Module alone, the result is:

```<code>PS C:\> Find-Module -Name 'pscx'

Version              Name                                Repository           Description
-------              ----                                ----------           -----------
3.3.2                Pscx                                PSGallery            PowerShell Community Extensi...
</code>```

EDIT 2:

Oh I forgot to say that there are no files created in the specific download folder after the download process bar disappeared. Does that mean the download has failed?

EDIT 3: @Sage Pourpre

Debugging log

I Always run PS as administrator.

-Scope CurrentUser throws the same error.

Both PS C:\> Uninstall-Module -Name "PowerShellGet" and PS C:\> Uninstall-Script -Name "PowerShellGet" -RequiredVersion 2.0.3 produce the same result.

PackageManagement\Uninstall-Package : No match was found for the specified search criteria and script names
'PowerShellGet'.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.0.4\PSModule.psm1:12343 char:21

...        $null = PackageManagement\Uninstall-Package @PSBoundParameters

```<code>+ CategoryInfo          : ObjectNotFound: (Microsoft.Power...ninstallPackage:UninstallPackage) [Uninstal
l-Package], Exception
+ FullyQualifiedErrorId : NoMatchFound,Microsoft.PowerShell.PackageManagement.Cmdlets.UninstallPackage
</code>```

Then I tried to list available modules:

```<code>PS C:\> Get-Module -ListAvailable

    Directory: G:\Temp\System Documents\WindowsPowerShell\Modules

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Binary     2.7.1.7    ISESteroids                         {Get-PSSharperData, Add-SteroidsContextMenuComma...
Script     1.2        Use-RawPipeline                     {Invoke-NativeCommand, Receive-RawPipeline, Get-...

    Directory: C:\Program Files\WindowsPowerShell\Modules

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     1.0.1      Microsoft.PowerShell.Operation.V... {Get-OperationValidation, Invoke-OperationValida...
Script     1.2.4      PackageManagement                   {Find-Package, Get-Package, Get-PackageProvider,...
Script     4.5.0      Pester                              {Describe, Context, It, Should...}
Script     2.0.4      PowerShellGet                       {Find-Command, Find-DSCResource, Find-Module, Fi...
Script     2.0.3      PowerShellGet                       {Find-Command, Find-DSCResource, Find-Module, Fi...
Script     1.2        PSReadline                          {Get-PSReadlineKeyHandler, Set-PSReadlineKeyHand...

    Directory: C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.0.0.0    AppBackgroundTask                   {Disable-AppBackgroundTaskDiagnosticLog, Enable-...
Manifest   2.0.0.0    AppLocker                           {Get-AppLockerFileInformation, Get-AppLockerPoli...
Manifest   1.0.0.0    AppvClient                          {Add-AppvClientConnectionGroup, Add-AppvClientPa...
Manifest   2.0.0.0    Appx                                {Add-AppxPackage, Get-AppxPackage, Get-AppxPacka...
Script     1.0.0.0    AssignedAccess                      {Clear-AssignedAccess, Get-AssignedAccess, Set-A...
Manifest   1.0.0.0    BitLocker                           {Unlock-BitLocker, Suspend-BitLocker, Resume-Bit...
etc...
</code>```

And Get-InstalledModule

```<code>PS C:\> Get-InstalledModule -Name "PowerShellGet" -RequiredVersion 2.0.3
PackageManagement\Get-Package : No match was found for the specified search criteria and module names
'PowerShellGet'.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.0.4\PSModule.psm1:9050 char:9
+         PackageManagement\Get-Package @PSBoundParameters | Microsoft. ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Microsoft.Power...lets.GetPackage:GetPackage) [Get-Package],
   Exception
    + FullyQualifiedErrorId : NoMatchFound,Microsoft.PowerShell.PackageManagement.Cmdlets.GetPackage
</code>```

答:
Finally solved by:

```<code>[Net.ServicePointManager]::SecurityProtocol = "tls12"
</code>```

The solution is from the following blog posted by vanBrenk:

Trying to install a PowerShell module behind a proxy? Chances are you're getting this error: "Unable to resolve package source 'https://www.powershellgallery.com/api/v2/'". Turns out it isn't allowed through your proxy server [...] Now every command you run is sent and allowed through the proxy.

Body:
My Powershell v5.1 won't install almost any module automatically using install-module whereas manually installation does work.

First, when I run install-module, it would download the module then throw an error, say the pscx module:

PackageManagement\Install-Package : Package 'Pscx' failed to be installed because: Specified cast is not valid.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.0.4\PSModule.psm1:9307 char:21
+ ...          $null = PackageManagement\Install-Package @PSBoundParameters
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidResult: (Pscx:String) [Install-Package], Exception
    + FullyQualifiedErrorId : Package '{0}' failed to be installed because: {1},Microsoft.PowerShell.PackageManag
   ement.Cmdlets.InstallPackage

What I can do now is to manually download the module and use import-module myself. The error occurs almost every time when I'm trying to install any module through this cmdlet. How can I address this problem?

For troubleshooting, Get-PSRepository gives me this:

PS C:\> Get-PSRepository

Name                      InstallationPolicy   SourceLocation
----                      ------------------   --------------
PSGallery                 Trusted              https://www.powershellgallery.com/api/v2
GalleryRolling            Trusted              https://www.poshtestgallery.com/api/v2/

EDIT:

Got the same error when trying to use Save-Module:

PS C:\> Find-Module -Name 'pscx' | Save-Module -Path "G:\Temp\System Documents\WindowsPowerShell\Modules"
WARNING: Package 'Pscx' failed to be installed because: Specified cast is not valid.
WARNING: Package 'Pscx' failed to install.
PackageManagement\Save-Package : Unable to save the module 'Pscx'.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.0.4\PSModule.psm1:11331 char:25
+ ...             $null = PackageManagement\Save-Package @PSBoundParameters
+                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (Microsoft.Power...ets.SavePackage:SavePackage) [Save-Packag
   e], Exception
    + FullyQualifiedErrorId : ProviderFailToDownloadFile,Microsoft.PowerShell.PackageManagement.Cmdlets.Save
   Package

It downloaded the package then displays the WARNING.

When using the Find-Module alone, the result is:

PS C:\> Find-Module -Name 'pscx'

Version              Name                                Repository           Description
-------              ----                                ----------           -----------
3.3.2                Pscx                                PSGallery            PowerShell Community Extensi...

EDIT 2:

Oh I forgot to say that there are no files created in the specific download folder after the download process bar disappeared. Does that mean the download has failed?

EDIT 3: @Sage Pourpre

Debugging log

I Always run PS as administrator.

-Scope CurrentUser throws the same error.

Both PS C:\> Uninstall-Module -Name "PowerShellGet" and PS C:\> Uninstall-Script -Name "PowerShellGet" -RequiredVersion 2.0.3 produce the same result.

PackageManagement\Uninstall-Package : No match was found for the specified search criteria and script names
'PowerShellGet'.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.0.4\PSModule.psm1:12343 char:21

...        $null = PackageManagement\Uninstall-Package @PSBoundParameters

+ CategoryInfo          : ObjectNotFound: (Microsoft.Power...ninstallPackage:UninstallPackage) [Uninstal
l-Package], Exception
+ FullyQualifiedErrorId : NoMatchFound,Microsoft.PowerShell.PackageManagement.Cmdlets.UninstallPackage

Then I tried to list available modules:

PS C:\> Get-Module -ListAvailable

    Directory: G:\Temp\System Documents\WindowsPowerShell\Modules

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Binary     2.7.1.7    ISESteroids                         {Get-PSSharperData, Add-SteroidsContextMenuComma...
Script     1.2        Use-RawPipeline                     {Invoke-NativeCommand, Receive-RawPipeline, Get-...

    Directory: C:\Program Files\WindowsPowerShell\Modules

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     1.0.1      Microsoft.PowerShell.Operation.V... {Get-OperationValidation, Invoke-OperationValida...
Script     1.2.4      PackageManagement                   {Find-Package, Get-Package, Get-PackageProvider,...
Script     4.5.0      Pester                              {Describe, Context, It, Should...}
Script     2.0.4      PowerShellGet                       {Find-Command, Find-DSCResource, Find-Module, Fi...
Script     2.0.3      PowerShellGet                       {Find-Command, Find-DSCResource, Find-Module, Fi...
Script     1.2        PSReadline                          {Get-PSReadlineKeyHandler, Set-PSReadlineKeyHand...

    Directory: C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.0.0.0    AppBackgroundTask                   {Disable-AppBackgroundTaskDiagnosticLog, Enable-...
Manifest   2.0.0.0    AppLocker                           {Get-AppLockerFileInformation, Get-AppLockerPoli...
Manifest   1.0.0.0    AppvClient                          {Add-AppvClientConnectionGroup, Add-AppvClientPa...
Manifest   2.0.0.0    Appx                                {Add-AppxPackage, Get-AppxPackage, Get-AppxPacka...
Script     1.0.0.0    AssignedAccess                      {Clear-AssignedAccess, Get-AssignedAccess, Set-A...
Manifest   1.0.0.0    BitLocker                           {Unlock-BitLocker, Suspend-BitLocker, Resume-Bit...
etc...

And Get-InstalledModule

PS C:\> Get-InstalledModule -Name "PowerShellGet" -RequiredVersion 2.0.3
PackageManagement\Get-Package : No match was found for the specified search criteria and module names
'PowerShellGet'.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.0.4\PSModule.psm1:9050 char:9
+         PackageManagement\Get-Package @PSBoundParameters | Microsoft. ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Microsoft.Power...lets.GetPackage:GetPackage) [Get-Package],
   Exception
    + FullyQualifiedErrorId : NoMatchFound,Microsoft.PowerShell.PackageManagement.Cmdlets.GetPackage

Body:
Finally solved by:

[Net.ServicePointManager]::SecurityProtocol = "tls12"

The solution is from the following blog posted by vanBrenk:

Trying to install a PowerShell module behind a proxy? Chances are you're getting this error: "Unable to resolve package source 'https://www.powershellgallery.com/api/v2/'". Turns out it isn't allowed through your proxy server [...] Now every command you run is sent and allowed through the proxy.


问:
how to get return value of a non-blocking function with an await on it
Lets say i have the following function:

```<code>async function commentMediaId(ig, media_id, commentContent, commentIfAlreadyCommented = false, extraInfo = new Object(), callback) {

    try {
        let alreadyExists = ig.db.get('comments').find({media_id: media_id}).value();
        alreadyExists == undefined ? false : true;
        if(alreadyExists && !commentIfAlreadyCommented) {
            console.log('Already commented'.yellow);
            return "already_commented";
        }

        if(commentIfAlreadyCommented || !alreadyExists){
            await ig.media.comment({
                module_name: 'profile',
                mediaId: media_id,
                text: commentContent,
            });

            return callback('success');
        }
    } catch (e) {
        return callback('not success');
    }

}
</code>```

then I am calling the following function (i do not want to use await here because it will block):

```<code>commentMediaId(object, 'someid', 'some string');
</code>```

how can i seet a callback on commentMediaId such that when it returns i get the value of success or not success ?

I basically wanted to do as follows

```<code>commentMediaId(object, 'someid', 'some string', function(result) {
   if (result == 'success')

});
</code>```

but I am getting a bunch of syntax error.. any ideas on how to implement it ?

答:
When you use an async function, you are working with the Promise interface, which exposes a .then() method. You can pass a callback into this method, and the callback will automatically be invoked for you when a value is returned from the commentMediaId function:

```<code>commentMediaId(object, 'someid', 'some string')
  .then(function (result) {
    console.log(result);
  })
;
</code>```

Finally, you need not take in a callback parameter in the commentMediaId function. You can omit the callback and simply return the values directly. That is the whole idea of the async/await "syntactic sugar", it makes it feel more like a regular function without the need for callbacks.

E.g. the following:

```<code>return callback('success');
</code>```

...should be changed to the following:

```<code>return 'success';
</code>```

Body:
Lets say i have the following function:

async function commentMediaId(ig, media_id, commentContent, commentIfAlreadyCommented = false, extraInfo = new Object(), callback) {

    try {
        let alreadyExists = ig.db.get('comments').find({media_id: media_id}).value();
        alreadyExists == undefined ? false : true;
        if(alreadyExists && !commentIfAlreadyCommented) {
            console.log('Already commented'.yellow);
            return "already_commented";
        }

        if(commentIfAlreadyCommented || !alreadyExists){
            await ig.media.comment({
                module_name: 'profile',
                mediaId: media_id,
                text: commentContent,
            });

            return callback('success');
        }
    } catch (e) {
        return callback('not success');
    }

}

then I am calling the following function (i do not want to use await here because it will block):

commentMediaId(object, 'someid', 'some string');

how can i seet a callback on commentMediaId such that when it returns i get the value of success or not success ?

I basically wanted to do as follows

commentMediaId(object, 'someid', 'some string', function(result) {
   if (result == 'success')

});

but I am getting a bunch of syntax error.. any ideas on how to implement it ?

Body:
When you use an async function, you are working with the Promise interface, which exposes a .then() method. You can pass a callback into this method, and the callback will automatically be invoked for you when a value is returned from the commentMediaId function:

commentMediaId(object, 'someid', 'some string')
  .then(function (result) {
    console.log(result);
  })
;

Finally, you need not take in a callback parameter in the commentMediaId function. You can omit the callback and simply return the values directly. That is the whole idea of the async/await "syntactic sugar", it makes it feel more like a regular function without the need for callbacks.

E.g. the following:

return callback('success');

...should be changed to the following:

return 'success';


问:
Terraform interpreting locals expression when it shouldn't be
I have a Kafka client container running on AWS ECS, which should receive a regular expression for which topics to subscribe to from the containers environment variables. In my terraform I define the environment variable like so:

```<code>..
      {
        "name": "KAFKA_TOPIC_REGEX",
        "value": "${local.kafka_topic_regex[local.environment]}"
      }
..
</code>```

With a corresponding value in the locals.tf file like so:

```<code>..
  kafka_topic_regex = {
    development = "^(ab\..*\..*)$|^(foo\.bar)$"
  }
..
</code>```

However I'm having difficulty getting this to work as expected. When I terraform plan, the following error is shown:

```<code>The symbol "." is not a valid escape sequence selector.
</code>```

Unfortunately I need the backward slash there for the regex to use the literal dot as a character in the topic name. I can't escape the backward slash as I actually require it be there for the regex.

I have equally tried the regex like so:

```<code>^(ab[.].*[.].*)$|^(foo[.]bar)$
</code>```

Again, Terraform does some strange interpretation of this and in the plan the value appears as:

```<code>^ab.(.*)
</code>```

This will mean that the literal dot I require isn't in the regex as it is required to be escaped in the regex.

It appears Terraform is interpreting my string and causing a failed plan / apply, when it shouldn't be interpreting it.

Any help would be appreciated, thank you

答:
Unfortunately this is a typical sort of situation that results when source code in one language is written as a string in another language: you need to deal with multiple levels of escaping. Although it may seem generous to talk about regular expressions as "another language", from Terraform's perspective that's exactly what they are, albeit a very terse language with a very specific featureset.

The requirement here is to write an expression that Terraform can evaluate to produce a string containing a regular expression that the regular expression engine can then interpret. The resulting regular expression string must contain literal backslashes, as you noted, because backslashes are part of the regular expression language.

We can produce a string containing a literal backslash in the Terraform language by escaping the backslash with an additional backslash:

```<code>"\\"
</code>```

The above would, from Terraform's standpoint, produce a string containing just a single backslash.

We can extend that idea to your regular expression problem by escaping all of the backslashes in your regular expression:

```<code>  kafka_topic_regex = {
    development = "^(ab\\..*\\..*)$|^(foo\\.bar)$"
  }
</code>```

When Terraform evaluates that quoted string it will respond to the escaped backslashes by producing a single literal backslash, and so the resulting string will be ^(ab\..*\..*)$|^(foo\.bar)$ as the regular expression engine is expecting. You can then pass that result on to the regular expression engine for processing, at which point it should see the \. sequences and (as you intended) treat it as a literal . rather than as the "any single character" wildcard.

One "trap" to watch out for is that Terraform uses a variant of its own quoted string syntax when rendering string values in the UI for situations like describing a planned change. In doing so, it will re-introduce the backslash escaping necessary to unambiguously render the result on-screen, showing it as ^(ab\\..*\\..*)$|^(foo\\.bar)$. Generally when reading values Terraform shows on-screen in its output we should understand them as representations of constant values in Terraform's own language, not as the literal values that will be used. This is similar to how Terraform will show numbers on-screen as sequences of decimal digits, like 1234, rather than showing the raw binary value that really represents that value in memory inside Terraform.

Body:
I have a Kafka client container running on AWS ECS, which should receive a regular expression for which topics to subscribe to from the containers environment variables. In my terraform I define the environment variable like so:

..
      {
        "name": "KAFKA_TOPIC_REGEX",
        "value": "${local.kafka_topic_regex[local.environment]}"
      }
..

With a corresponding value in the locals.tf file like so:

..
  kafka_topic_regex = {
    development = "^(ab\..*\..*)$|^(foo\.bar)$"
  }
..

However I'm having difficulty getting this to work as expected. When I terraform plan, the following error is shown:

The symbol "." is not a valid escape sequence selector.

Unfortunately I need the backward slash there for the regex to use the literal dot as a character in the topic name. I can't escape the backward slash as I actually require it be there for the regex.

I have equally tried the regex like so:

^(ab[.].*[.].*)$|^(foo[.]bar)$

Again, Terraform does some strange interpretation of this and in the plan the value appears as:

^ab.(.*)

This will mean that the literal dot I require isn't in the regex as it is required to be escaped in the regex.

It appears Terraform is interpreting my string and causing a failed plan / apply, when it shouldn't be interpreting it.

Any help would be appreciated, thank you

Body:
Unfortunately this is a typical sort of situation that results when source code in one language is written as a string in another language: you need to deal with multiple levels of escaping. Although it may seem generous to talk about regular expressions as "another language", from Terraform's perspective that's exactly what they are, albeit a very terse language with a very specific featureset.

The requirement here is to write an expression that Terraform can evaluate to produce a string containing a regular expression that the regular expression engine can then interpret. The resulting regular expression string must contain literal backslashes, as you noted, because backslashes are part of the regular expression language.

We can produce a string containing a literal backslash in the Terraform language by escaping the backslash with an additional backslash:

"\\"

The above would, from Terraform's standpoint, produce a string containing just a single backslash.

We can extend that idea to your regular expression problem by escaping all of the backslashes in your regular expression:

  kafka_topic_regex = {
    development = "^(ab\\..*\\..*)$|^(foo\\.bar)$"
  }

When Terraform evaluates that quoted string it will respond to the escaped backslashes by producing a single literal backslash, and so the resulting string will be ^(ab\..*\..*)$|^(foo\.bar)$ as the regular expression engine is expecting. You can then pass that result on to the regular expression engine for processing, at which point it should see the \. sequences and (as you intended) treat it as a literal . rather than as the "any single character" wildcard.

One "trap" to watch out for is that Terraform uses a variant of its own quoted string syntax when rendering string values in the UI for situations like describing a planned change. In doing so, it will re-introduce the backslash escaping necessary to unambiguously render the result on-screen, showing it as ^(ab\\..*\\..*)$|^(foo\\.bar)$. Generally when reading values Terraform shows on-screen in its output we should understand them as representations of constant values in Terraform's own language, not as the literal values that will be used. This is similar to how Terraform will show numbers on-screen as sequences of decimal digits, like 1234, rather than showing the raw binary value that really represents that value in memory inside Terraform.


问:
Separating two built equations
I have built a form which will build two equations, one with an original equation and one with dynamic variables.  Although both equations are built properly, equation #2 will not build on the next line down.

I have tried using the selection.paragraphs.add between the two equations, but no luck.

Any thoughts?  Thank you for your help.

```<code>Set objRange1 = Selection.Range
objRange1.Text = "BSA" & "(m" & "^2" & ")" & " = " & ChrW(8730) & "(" & "(" & "Height" & "_(cm)" _
     & " * " & "Weight" & "_(kg)" & ")" & "/3600" & ")"
Set objRange1 = Selection.OMaths.Add(objRange1)
Set objEq1 = objRange1.OMaths(1)
objEq1.BuildUp

Set objRange = Selection.Range
objRange.Text = "BSA" & "(m" & "^2" & ")" & " = " & ChrW(8730) & "(" & "(" & intHeight _
& "_cm" & " * " & dblweight & "_kg" & ")" & "/3600" & ")"
Set objRange = Selection.OMaths.Add(objRange)
Set objeq = objRange.OMaths(1)
objeq.BuildUp
</code>```

答:
As a general rule it is better to use Ranges than the Selection in Word. For example:</p>

```<code>Sub Insert2Eqs1()
Dim dblWeight As Double
Dim intHeight As Long
Dim objEq As Word.OMath
Dim objRange As Word.Range
Set objRange = Selection.Range
' You might need to adjust this depending on exactly where you want the
' equations to appear in relation to the selection
objRange.InsertParagraph
objRange.InsertParagraphBefore
' You now have a range containing two paragraph marks
objRange.Collapse wdCollapseStart
objRange.Text = "BSA" & "(m" & "^2" & ")" & " = " & ChrW(8730) & "(" & "(" & "Height" & "_(cm)" _
     & " * " & "Weight" & "_(kg)" & ")" & "/3600" & ")"
Set objEq = objRange.OMaths.Add(objRange).OMaths(1)
objEq.BuildUp
Set objRange = objEq.Range
objRange.Collapse wdCollapseEnd
' If you use + 1, you get two equations, one below the other
objRange.Start = objRange.Start + 1
' if you use + 2, you get two equations separated by a paragraph on its own
objRange.Start = objRange.Start + 2
intHeight = 0#
dblWeight = 2.45
objRange.Text = "BSA" & "(m" & "^2" & ")" & " = " & ChrW(8730) & "(" & "(" & intHeight _
& "_cm" & " * " & dblWeight & "_kg" & ")" & "/3600" & ")"
Set objEq = objRange.OMaths.Add(objRange).OMaths(1)
objEq.BuildUp
Set objEq = Nothing
Set objRange = Nothing
End Sub
</code>```

Title: Separating two built equations

Body:
I have built a form which will build two equations, one with an original equation and one with dynamic variables.  Although both equations are built properly, equation #2 will not build on the next line down.

I have tried using the selection.paragraphs.add between the two equations, but no luck.

Any thoughts?  Thank you for your help.

Set objRange1 = Selection.Range
objRange1.Text = "BSA" & "(m" & "^2" & ")" & " = " & ChrW(8730) & "(" & "(" & "Height" & "_(cm)" _
     & " * " & "Weight" & "_(kg)" & ")" & "/3600" & ")"
Set objRange1 = Selection.OMaths.Add(objRange1)
Set objEq1 = objRange1.OMaths(1)
objEq1.BuildUp

Set objRange = Selection.Range
objRange.Text = "BSA" & "(m" & "^2" & ")" & " = " & ChrW(8730) & "(" & "(" & intHeight _
& "_cm" & " * " & dblweight & "_kg" & ")" & "/3600" & ")"
Set objRange = Selection.OMaths.Add(objRange)
Set objeq = objRange.OMaths(1)
objeq.BuildUp

Body:
As a general rule it is better to use Ranges than the Selection in Word. For example:

Sub Insert2Eqs1()
Dim dblWeight As Double
Dim intHeight As Long
Dim objEq As Word.OMath
Dim objRange As Word.Range
Set objRange = Selection.Range
' You might need to adjust this depending on exactly where you want the
' equations to appear in relation to the selection
objRange.InsertParagraph
objRange.InsertParagraphBefore
' You now have a range containing two paragraph marks
objRange.Collapse wdCollapseStart
objRange.Text = "BSA" & "(m" & "^2" & ")" & " = " & ChrW(8730) & "(" & "(" & "Height" & "_(cm)" _
     & " * " & "Weight" & "_(kg)" & ")" & "/3600" & ")"
Set objEq = objRange.OMaths.Add(objRange).OMaths(1)
objEq.BuildUp
Set objRange = objEq.Range
objRange.Collapse wdCollapseEnd
' If you use + 1, you get two equations, one below the other
objRange.Start = objRange.Start + 1
' if you use + 2, you get two equations separated by a paragraph on its own
objRange.Start = objRange.Start + 2
intHeight = 0#
dblWeight = 2.45
objRange.Text = "BSA" & "(m" & "^2" & ")" & " = " & ChrW(8730) & "(" & "(" & intHeight _
& "_cm" & " * " & dblWeight & "_kg" & ")" & "/3600" & ")"
Set objEq = objRange.OMaths.Add(objRange).OMaths(1)
objEq.BuildUp
Set objEq = Nothing
Set objRange = Nothing
End Sub


答: it looks like you have some typos - asyn should be async and you also have an extra parenthesis in the last argument to the function commentMediaId(...otherArgs, callback(){} instead of commentMediaId(...otherArgs, callback){}

Title: how to get return value of a non-blocking function with an await on it


问:
How to output the largest number in keySet if there are several such numbers?
How to output the largest word if there are several such numbers? (should output the one, which occurs earlier). My code didn't work properly.</p>

```<code>import java.io.*;
import java.util.*;
public class solved {
    public static void main(String[] args) {
        LinkedHashMap<Integer, String> hashMap = new LinkedHashMap<>();
        Scanner scan = new Scanner(System.in);
        String[] str = scan.nextLine().split(" ");
        for (int i=1; i < str.length; i++) {
             int n = str[i].length();
             String s = str[i];
             hashMap.put(n, s);
         }
         int maxKey = Collections.max(hashMap.keySet());
         System.out.println(hashMap.get(maxKey));
    }
}
</code>```

答:
Do you want to store all words? In your exaple "dog" will replace "cat", so you lose the first word. If you want to store all words, you cannot have an Integer as key in a HashMap, because it can only ever have a single key for each value.

If you want to retain all words for some later use, you can invert your map to Map<String, Integer> - and use words as keys and lengths as values. Or, you could skip using Collections altogether:

```<code>public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String[] str = scan.nextLine().split(" ");

    int longestWordLength = -1;
    for (String s : str) {
        if (s.length() > longestWordLength)
            longestWordLength = s.length();
    }

    for (String s : str) {
        if (s.length() == longestWordLength)
            System.out.printf("Longest word: %s is %s", s, s.length());
    }
}
</code>```

Or, with Java 8 streams for fun and learning:

```<code>public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String[] str = scan.nextLine().split(" ");

    int longest = Arrays.stream(str)
            .mapToInt(String::length).max().orElse(-1);
    Predicate<String> isLongest = s -> s.length() == longest;
    String firstLongest = Arrays.stream(str)
            .filter(isLongest).findFirst().orElse("no words");

    System.err.println(firstLongest + " " + longest);
}
</code>```

Body:
How to output the largest word if there are several such numbers? (should output the one, which occurs earlier). My code didn't work properly.

import java.io.*;
import java.util.*;
public class solved {
    public static void main(String[] args) {
        LinkedHashMap<Integer, String> hashMap = new LinkedHashMap<>();
        Scanner scan = new Scanner(System.in);
        String[] str = scan.nextLine().split(" ");
        for (int i=1; i < str.length; i++) {
             int n = str[i].length();
             String s = str[i];
             hashMap.put(n, s);
         }
         int maxKey = Collections.max(hashMap.keySet());
         System.out.println(hashMap.get(maxKey));
    }
}

Body:
Do you want to store all words? In your exaple "dog" will replace "cat", so you lose the first word. If you want to store all words, you cannot have an Integer as key in a HashMap, because it can only ever have a single key for each value.

If you want to retain all words for some later use, you can invert your map to Map<String, Integer> - and use words as keys and lengths as values. Or, you could skip using Collections altogether:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String[] str = scan.nextLine().split(" ");

    int longestWordLength = -1;
    for (String s : str) {
        if (s.length() > longestWordLength)
            longestWordLength = s.length();
    }

    for (String s : str) {
        if (s.length() == longestWordLength)
            System.out.printf("Longest word: %s is %s", s, s.length());
    }
}

Or, with Java 8 streams for fun and learning:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String[] str = scan.nextLine().split(" ");

    int longest = Arrays.stream(str)
            .mapToInt(String::length).max().orElse(-1);
    Predicate<String> isLongest = s -> s.length() == longest;
    String firstLongest = Arrays.stream(str)
            .filter(isLongest).findFirst().orElse("no words");

    System.err.println(firstLongest + " " + longest);
}


问:
How to convert string object to Json in Nestjs
I want to convert this to json. I tried JSON.parse() but got this error

```<code>"{"status":"00","message":"OK","access_token":"2347682423567","customer":{"name":"John Doe","address":"Mr. John Doe 34 Tokai, leaflet. 7999.","util":"Demo Utility","minimumAmount":"13897"},"response_hash":"c43c9d74480f340f55156f6r5c56487v8w"}"
</code>```

There is the error

```<code>SyntaxError: Unexpected token  in JSON at position 0

</code>```

That means I have to remove the first double quote. I don't know how to do remove it.

How can achieve this and get a valid json?

The code here below

```<code> const url = `https://irecharge.com.ng/pwr_api_sandbox/v2/get_meter_info.php?vendor_code=${vendorcode}&reference_id=${reference_id}&meter=${meterNum}&disco=${discoName}&response_format=json&hash=${hash}`;

            const meterInfo = await this.httpService.get(url).toPromise();

            const data = meterInfo.data;

            const data = meterInfo.data;
            var ParsedData = JSON.parse(data.substring(1, data.length - 1))

            console.log(ParsedData);
            return ParsedData
    ```
I am supposed to pass response format, which should be json as you can see in the code

```

答:
If that is truly the JSON you get back from the API, you need to raise an issue with them about the invalid JSON format they are sending.

In the meantime, if you need to parse it, you can do JSON.parse(data.substring(1, data.length - 1)) and you should have no problems (just tested locally).

I suspect the issue is rather that you are wrapping the response in " yourself, because as I said in the comments, that's an invalid JSON that cannot be serialized or consumed properly by anything.

Body:
I want to convert this to json. I tried JSON.parse() but got this error

"{"status":"00","message":"OK","access_token":"2347682423567","customer":{"name":"John Doe","address":"Mr. John Doe 34 Tokai, leaflet. 7999.","util":"Demo Utility","minimumAmount":"13897"},"response_hash":"c43c9d74480f340f55156f6r5c56487v8w"}"

There is the error

SyntaxError: Unexpected token  in JSON at position 0

That means I have to remove the first double quote. I don't know how to do remove it.

How can achieve this and get a valid json?

The code here below

 const url = `https://irecharge.com.ng/pwr_api_sandbox/v2/get_meter_info.php?vendor_code=${vendorcode}&reference_id=${reference_id}&meter=${meterNum}&disco=${discoName}&response_format=json&hash=${hash}`;

            const meterInfo = await this.httpService.get(url).toPromise();

            const data = meterInfo.data;

            const data = meterInfo.data;
            var ParsedData = JSON.parse(data.substring(1, data.length - 1))

            console.log(ParsedData);
            return ParsedData
    ```
I am supposed to pass response format, which should be json as you can see in the code


问:
Remove duplicate keys and combine unique values in JavaScript array
I have an array containing a customer ID, value of transaction, and transaction ID for each transaction performed by the customer.

I have 20,000 transactions performed by 9,000 customers.
I want one customer ID, an array of all the prices per that customer ID, and an array of all the transaction Ids per customer ID.

Currently looks like this:

```<code>var transactionArray =
{
  customerId: '1',
  price: [ 100 ],
  transactionID: ['00a13']
},
{
  customerId: '2',
  price: [ 200 ],
  transactionID: ['00a14']
},
{
  customerId: '1',
  price: [ 700 ],
  transactionID: ['00a15']
},
{
  customerId: '2',
  price: [ 1700 ],
  transactionID: ['00a16']
},

... 19996 more items
</code>```

and I'd like it to look like this:

```<code>var customerArray =

{
  customerId: '1',
  price: [ 100, 700 ],
  transactionID: ['00a13', '00a15']
},
{
  customerId: '2',
  price: [ 200, 1700 ],
  transactionID: ['00a14', '00a16']
},

...8998 more items
</code>```

答:
Just using reduce and push the elements onto the array

var transactionArray = [{
    customerId: '1',
    price: [100],
    transactionID: ['00a13']
  },
  {
    customerId: '2',
    price: [200],
    transactionID: ['00a14']
  },
  {
    customerId: '1',
    price: [700],
    transactionID: ['00a15']
  },
  {
    customerId: '2',
    price: [1700],
    transactionID: ['00a16']
  },
]

var results = Object.values(transactionArray.reduce((custs, { customerId, price, transactionID }) => {
  var customer = custs[customerId]
  if (!customer) {
    custs[customerId] = {
      customerId: customerId,
      price: [...price],
      transactionID: [...transactionID]
    }
  } else {
    customer.price = [...customer.price, ...price]
    customer.transactionID =  [...customer.transactionID, ...transactionID]
  }

  return custs
}, {}))

console.log(results)```

Body:
I have an array containing a customer ID, value of transaction, and transaction ID for each transaction performed by the customer.

I have 20,000 transactions performed by 9,000 customers.
I want one customer ID, an array of all the prices per that customer ID, and an array of all the transaction Ids per customer ID.

Currently looks like this:

var transactionArray =
{
  customerId: '1',
  price: [ 100 ],
  transactionID: ['00a13']
},
{
  customerId: '2',
  price: [ 200 ],
  transactionID: ['00a14']
},
{
  customerId: '1',
  price: [ 700 ],
  transactionID: ['00a15']
},
{
  customerId: '2',
  price: [ 1700 ],
  transactionID: ['00a16']
},

... 19996 more items

and I'd like it to look like this:

var customerArray =

{
  customerId: '1',
  price: [ 100, 700 ],
  transactionID: ['00a13', '00a15']
},
{
  customerId: '2',
  price: [ 200, 1700 ],
  transactionID: ['00a14', '00a16']
},

...8998 more items