问:
Segfault when assigning to struct within 2d array through function call
I have the following typedef:

```<code>typedef struct cell_t {
    int x; // x coord of this cell
    int y; // y coord of this cell
    int neighbour_count; // Size of the following array
    struct cell_t **neighbours; // array of pointers to neighbours
} cell_t;
</code>```

and some code to initialize this type (neighbour_count and neighbours are to be set later)

```<code>cell_t *create_cell(int x, int y){
    cell_t *cell = malloc(sizeof(cell_t));
    cell->x = x;
    cell->y = y;

    return cell;
}
</code>```

I have myfun to initialize the neighbours and neighbour_count variables for a matrix of cell_t, which it reads from some external source.

```<code>int myfun(cell_t ***cells, int width, int height){
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            // Read data from source, including the long `list_size`

            cells[x][y]->neighbour_count = (int) list_size; // This segfaults
        }
    }
}
</code>```

So in my main, I have the following:

```<code>int width = 3, height = 3;

cell_t *cells[width][height];

for (int x = 0; x < width; x++){
    for(int y = 0; y < height; y++){
        cells[x][y] = create_cell(x,y);
    }
}

myfun(cells, width, height);
</code>```

When setting the neighbour count, it segfaults (as marked in the third block of code).

What I think I'm doing is that in my main I initialize an empty matrix of pointers to cell objects, and then loop through width and height, creating cells, and storing the pointers to them in the matrix. Then in myfun, I'm simply accessing a the variable neighbour_count of these cells and setting it. But apparently I'm mistaken, as it segfaults (not always on the first loop though, but generally quite quickly).

I'm thinking perhaps I did something wrong such that the matrix cells does not actually contain pointers to cell_t structs. But I can't see what I'm doing wrong.

I am getting a warning that "passing argument 1 of ‘myfun’ from incompatible pointer type", and that it should instead be of type cell_t * (*)[(sizetype)(height)]; perhaps that helps? I would expect there not to be a problem, as struct_t *** should be good for a 2d array of pointers, no?

答:
The type of the first function parameter

```<code>int myfun(cell_t ***cells, int width, int height){
</code>```

and the type of the supplied argument

```<code>myfun(cells, width, height);
</code>```

do not correspond each other. The function argument declared like

```<code>cell_t *cells[width][height];
</code>```

is implicitly converted to pointer to its first element. That is it has the type cell_t * ( * )[height].

Thus the corresponding function should be declared like

```<code>int myfun( int width, int height, cell_t * cells[][height] ){
</code>```

or like

```<code>int myfun( int width, int height, cell_t * ( *cells )[height] ){
</code>```

that declares the same function.

Body:
I have the following typedef:

typedef struct cell_t {
    int x; // x coord of this cell
    int y; // y coord of this cell
    int neighbour_count; // Size of the following array
    struct cell_t **neighbours; // array of pointers to neighbours
} cell_t;

and some code to initialize this type (neighbour_count and neighbours are to be set later)

cell_t *create_cell(int x, int y){
    cell_t *cell = malloc(sizeof(cell_t));
    cell->x = x;
    cell->y = y;

    return cell;
}

I have myfun to initialize the neighbours and neighbour_count variables for a matrix of cell_t, which it reads from some external source.

int myfun(cell_t ***cells, int width, int height){
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            // Read data from source, including the long `list_size`

            cells[x][y]->neighbour_count = (int) list_size; // This segfaults
        }
    }
}

So in my main, I have the following:

int width = 3, height = 3;

cell_t *cells[width][height];

for (int x = 0; x < width; x++){
    for(int y = 0; y < height; y++){
        cells[x][y] = create_cell(x,y);
    }
}

myfun(cells, width, height);

When setting the neighbour count, it segfaults (as marked in the third block of code).

What I think I'm doing is that in my main I initialize an empty matrix of pointers to cell objects, and then loop through width and height, creating cells, and storing the pointers to them in the matrix. Then in myfun, I'm simply accessing a the variable neighbour_count of these cells and setting it. But apparently I'm mistaken, as it segfaults (not always on the first loop though, but generally quite quickly).

I'm thinking perhaps I did something wrong such that the matrix cells does not actually contain pointers to cell_t structs. But I can't see what I'm doing wrong.

I am getting a warning that "passing argument 1 of ‘myfun’ from incompatible pointer type", and that it should instead be of type cell_t * (*)[(sizetype)(height)]; perhaps that helps? I would expect there not to be a problem, as struct_t *** should be good for a 2d array of pointers, no?

Body:
The type of the first function parameter

int myfun(cell_t ***cells, int width, int height){

and the type of the supplied argument

myfun(cells, width, height);

do not correspond each other. The function argument declared like

cell_t *cells[width][height];

is implicitly converted to pointer to its first element. That is it has the type cell_t * ( * )[height].

Thus the corresponding function should be declared like

int myfun( int width, int height, cell_t * cells[][height] ){

or like

int myfun( int width, int height, cell_t * ( *cells )[height] ){

that declares the same function.


来源: stackexchange

问:
How Swing components implements MVC architecture?
Suppose I have a JTextfield . How does only this JTextfield implement an MVC architecture?</p>

答:
All Java Swing components use MVC though its not always clear from the api. For each component there is a Controller, Model and View. JTextField, JButton, etc.. are all the Controllers. They also all support a getModel() which contains the state of the component. A lot of swing API pollute the controller api with convience methods so this is not always obvious. The text displayed in a JTextField is actually saved in the model. textField.getText() and textField.setText() are actually there for your convienence, what they really are doing is textField.getModel().getText() and textField.getModel().setText().

For the view there is a UI getComponentUI(). This is updated by propertyChanges fired from the Model. The ComponentUI is what lets different L&Fs be developed easily.

ContentLicense: CC BY-SA 3.0


问:
iisexpress crash triggered by the client web browser. The error is "the program iisexpress exe has exited with code 0xc0000005 access violation"
When developing a Web appication, a button on the web client started crashing the application.

The VS Debug seesion and the Client browser close together. VS 2019 debug output shows the following error (no other information is available on client or server):

The program '[23396] iisexpress.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.
This bypasses all try/catch which makes it difficult to debug.

答:
I got this error because of an infinite recursive call.

To pinpoint such a bug add breakpoints and log lines (or step into)!!!

In my case, by mistake, a get property returned itself under some conditions.

This crash of Visual Studio Debug session naturally closes the Web Browser (opened by VS) which adds to the confusion. It's as if the client side crashed.
Only if you keep another browser session connected to localhost://nnnnn you see that it is the server that crashes.

ContentLicense: CC BY-SA 4.0


答:
One thing is not correct in your code that i recognize is the definition of pointer.

```<code>cell_t *cells[width][height];
</code>```

This defifnition is not for pointer that points to an array 2D. Like @Lundin commented above, it is not compatible with cell_t ***cells. If you want to define a pointer that points to an array 2D, you can use the code below:

```<code>cell_t cells[width][height];
cell_t *ptr = &cells;
</code>```

The pointer ptr is compatible with ***cells in your code

Title: Segfault when assigning to struct within 2d array through function call

Body:
One thing is not correct in your code that i recognize is the definition of pointer.

cell_t *cells[width][height];

This defifnition is not for pointer that points to an array 2D. Like @Lundin commented above, it is not compatible with cell_t ***cells. If you want to define a pointer that points to an array 2D, you can use the code below:

cell_t cells[width][height];
cell_t *ptr = &cells;

The pointer ptr is compatible with ***cells in your code


问:
Fix url in laravel
so I have done a AJAX call in Laravel project and in a method I want to return a output.

This is the output

```<code>$output = ' <div class="col-xs-12 col-width">
                                <div class="single-product mb-30">
                                    <div class="single-product-item clearfix">
                                        <div class="single-product-img clearfix">
                                            <a href=\"{{route(\'product_details\',' . $product->slug . ')}}\">
                                                <img class="primary-image" src="'.env('PRODUCT_URL'). $product->image . '" style="width: 200px;height: 240px" alt="">
                                            </a>
                                        </div>

                                        <div class="single-product-info clearfix">
                                            <h3><a href="{{route(\'product_details\','.$product->slug.')}}">' . $product->name . '</a></h3>
                                            <div class="pro-price">
                                          ' . $new . '
                                         </div>
                                        </div>
                                    </div>
                                    <div class="new-sale">
                                    ' . $offer . '
                                    </div>
                                </div>
                            </div>';
</code>```

When i click the product I see the route:

/"%7B%7Burl('product_details',test)%7D%7D/"

What should I do to fix the quotes ?

答:
Replace

```<code><a href="{{route(\'product_details\','.$product->slug.')}}">
</code>```

by

```<code><a href="' . route('product_details', $product->slug) . '">
</code>```

Final result:

```<code>$output = ' <div class="col-xs-12 col-width">
   <div class="single-product mb-30">
      <div class="single-product-item clearfix">
          <div class="single-product-img clearfix">
             <a href="' . route('product_details', $product->slug) . '">
                <img class="primary-image" src="'.env('PRODUCT_URL'). $product->image . '" style="width: 200px;height: 240px" alt="">
             </a>
       </div>

 <div class="single-product-info clearfix">
     <h3><a href="' . route('product_details', $product->slug) . '">' . $product->name . '</a></h3>
     <div class="pro-price">
         ' . $new . '
     </div>
   </div>
  </div>
 <div class="new-sale">
 ' . $offer . '
  </div>
</div>
</div>';
</code>```

Then it will be fixed.

Title: Fix url in laravel

Body:
so I have done a AJAX call in Laravel project and in a method I want to return a output.

This is the output

$output = '

                                            slug . ')}}\">
                                                image . '" style="width: 200px;height: 240px" alt="">

slug.')}}">' . $product->name . '

                                          ' . $new . '

                                    ' . $offer . '

';

When i click the product I see the route:

/"%7B%7Burl('product_details',test)%7D%7D/"

What should I do to fix the quotes ?

Body:
Replace

<a href="{{route(\'product_details\','.$product->slug.')}}">

by

<a href="' . route('product_details', $product->slug) . '">

Final result:

$output = ' <div class="col-xs-12 col-width">
   <div class="single-product mb-30">
      <div class="single-product-item clearfix">
          <div class="single-product-img clearfix">
             <a href="' . route('product_details', $product->slug) . '">
                <img class="primary-image" src="'.env('PRODUCT_URL'). $product->image . '" style="width: 200px;height: 240px" alt="">
             </a>
       </div>

 <div class="single-product-info clearfix">
     <h3><a href="' . route('product_details', $product->slug) . '">' . $product->name . '</a></h3>
     <div class="pro-price">
         ' . $new . '
     </div>
   </div>
  </div>
 <div class="new-sale">
 ' . $offer . '
  </div>
</div>
</div>';

Then it will be fixed.


问:
printing to pdf
The existing system has many reports . Using a free pdf printer like dopdf or cutepdf the user can open the report , choose the pdf printer , type in the filename and save the report as a pdf file.This seems a bit tedious

It would be nice to have the report directly saved as a pdf file just on click of a button.
Unfortunately the reporting tool component doesnt have pdf export functionality.
. Is there a way to programatically do this function using a third party component.

The printing should be silent , so that the user is not asked for a filename.Report 1 when clicked will make a file called c:\1.pdf for example.
something like this
ActivatePdfPrinter(c:\1.pdf);
printreport;
ClosePdfPrinter;

or any other method .

I use delphi but if you suggest any other tools that work in other programming languages then I can search in the right direction.

答:
Win2PDF 10 does all of that and more.

Check out the registry functions:

https://www.win2pdf.com/doc/registryoverview.html

Feature Comparison Chart:

https://www.win2pdf.com/features.html#Win2PDF-Product-Comparison

I've been using Win2PDF Pro for at least 20 years at home and on my workstation at work; and have always found it reliable and speedy. I just downloaded the latest version service pack and will be updating my installation at next reboot. Enjoy.

ContentLicense: CC BY-SA 2.5

Title: printing to pdf


问:
JSONB - update array value by index
How to update JSON(B) array value by index? And also to retrieve the index of each value in JSONB array?

There is ServiceStack ORMLite model:

```<code>  public class Page
  {
    [AutoIncrement]
    public long Id { get; set; }

    [PgSqlJsonB]
    public List<Widget> Widgets { get; set; }
  }
</code>```

For example, how to update the second item in Widgets list?

Here is an example of how to do select array indexes and update array value by index in raw Postgres SQL:
How to update objects inside JSONB

The idea is to select array indexes with AutoQuery and update particular JSONB array value knowing it's index in database array.

答:
In OrmLite complex Types like List<Widget> are blobbed, so if you change the value in C# and save it, it will serialize the entire Widgets property to JSON and update the entire field.

If you want to use PostgreSQL native functions to manipulate the column contents in a server side query you'd need to use the Custom SQL APIs, e.g:

```<code>db.Execute("UPDATE page SET widgets = jsonb_set(widgets, ...) WHERE id = @id",
    new { id });
</code>```

Title: JSONB - update array value by index

Body:
How to update JSON(B) array value by index? And also to retrieve the index of each value in JSONB array?

There is ServiceStack ORMLite model:

  public class Page
  {
    [AutoIncrement]
    public long Id { get; set; }

    [PgSqlJsonB]
    public List<Widget> Widgets { get; set; }
  }

For example, how to update the second item in Widgets list?

Here is an example of how to do select array indexes and update array value by index in raw Postgres SQL:
How to update objects inside JSONB

The idea is to select array indexes with AutoQuery and update particular JSONB array value knowing it's index in database array.

Body:
In OrmLite complex Types like List<Widget> are blobbed, so if you change the value in C# and save it, it will serialize the entire Widgets property to JSON and update the entire field.

If you want to use PostgreSQL native functions to manipulate the column contents in a server side query you'd need to use the Custom SQL APIs, e.g:

db.Execute("UPDATE page SET widgets = jsonb_set(widgets, ...) WHERE id = @id",
    new { id });


问:
How to continue execution of Python script after evaluating a Click cli function?
Say I have a basic click CLI command defined in a file cli.py:

import click

@click.command()
@click.option('--test-option')
def get_inputs(test_option):
    return test_option
```

<p>Then another module script <code>test_cli.py</code>, from which I'd like to use the CLI defined in the above:</p>

<pre class="lang-py prettyprint-override"><code>from cli import get_inputs

print('before calling get_inputs')
print(get_inputs())
print('after calling get_inputs')
</code>```

Then on the command line:

```<code>$ python test_cli.py --test-option test123
before calling get_inputs
</code>```

So it appears that after a Click command is ran, the entire Python process finishes, and even if there are statements and expressions to be evaluated after that Click command in the script that  initiated the call, they will not be executed. How would I achieve this?

答:
Actually the Click documentation provides a good explanation for why this occurs, and how to change this behavior.

By default all commands inherit from BaseCommand, which defines a main method that by default exits upon successful completion with sys.exit(), which emits the SystemExit exception.

To change this behavior, one may disable what they term standalone_mode as documented here.

So for the example provided in my question, changing the line containing get_inputs() call in test_cli.py from print(get_inputs()) into print(get_inputs.main(standalone_mode=False)), then invoking the script from the command line gives the desired behavior, like so:

```<code>$ python test_cli.py --test-option test123
before calling get_inputs
test123
after calling get_inputs
</code>```

Body:
Say I have a basic click CLI command defined in a file cli.py:

import click

@click.command()
@click.option('--test-option')
def get_inputs(test_option):
    return test_option

Then another module script test_cli.py, from which I'd like to use the CLI defined in the above:

from cli import get_inputs

print('before calling get_inputs')
print(get_inputs())
print('after calling get_inputs')

Then on the command line:

$ python test_cli.py --test-option test123
before calling get_inputs

So it appears that after a Click command is ran, the entire Python process finishes, and even if there are statements and expressions to be evaluated after that Click command in the script that  initiated the call, they will not be executed. How would I achieve this?

Body:
Actually the Click documentation provides a good explanation for why this occurs, and how to change this behavior.

By default all commands inherit from BaseCommand, which defines a main method that by default exits upon successful completion with sys.exit(), which emits the SystemExit exception.

To change this behavior, one may disable what they term standalone_mode as documented here.

So for the example provided in my question, changing the line containing get_inputs() call in test_cli.py from print(get_inputs()) into print(get_inputs.main(standalone_mode=False)), then invoking the script from the command line gives the desired behavior, like so:

$ python test_cli.py --test-option test123
before calling get_inputs
test123
after calling get_inputs


问:
Why is my Javascript only working at the first row of the table?
Hey Guys im having a problem with my javascript code. It only works on the first row of the table and not the rest.

      Name
      Section
      3rd Quarter Grades
      4th Quarter Grades
       Semester Average

    <?php
$sql = $conn2->query("SELECT  Name, Section, Initial1, Initial2, Final, id FROM " .$subid. " ORDER BY Name");
if ($sql->num_rows > 0) {
while ($row = $sql->fetch_assoc())  {
echo "<form method='POST' action='savesem1.php'>";
echo "
";
echo "" .str_replace('!', ' ', str_replace('_', ' ', $row["Name"])). "	";
echo "" .$row["Section"]. "	";
echo "<input  name='I1sem2G11' id='I1sem2G11' onChange='CD();' value='" .$row["Initial1"]. "'/>	";
echo "<input  name='I2sem2G11' id='I2sem2G11' onChange='CD();' value='" .$row["Initial2"]. "'/>	";
echo "<input  name='Finalsem2G11' id='Finalsem2G11'  value='" .$row["Final"]. "'  />	";
echo "<input type='submit' name='submitcardsem2G11' id='submitcardsem2G11' class='btnupdate' value='Save Changes'>	";
echo "<input type='hidden' name='idsem2G11' id='idsem2G11' value='" .$row["id"]. "'/>	";
echo "<input type='hidden' name='y' id='y' value='" .$subid. "'/>	";
echo "
";
echo "</form>";
}
} else { echo ""; }
?>

```

<p>This is the javascript its purpose is to get the average of the two inputs and put it in another input</p>

<pre class="lang-js prettyprint-override"><code>function CD() {
  var C = $("#I1sem2G11").val();
  var D = $("#I2sem2G11").val();
  var CD = (+C + +D) / 2;
  document.getElementById("Finalsem2G11").value = CD;
}
</code>```

答:
Your problem is duplicate IDs

I am not super happy with the <form> wrapping
s either but it works

$("#tb").on("input", "input", function() {
  const $row = $(this).closest("tr");
  const C = $row.find("[name=I1sem2G11]").val();
  const D = $row.find("[name=I2sem2G11]").val();
  const CD = (+C + +D) / 2;
  console.log(C,D,CD)
  $row.find("[name=Finalsem2G11]").val(CD);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Q2">
  <table>
    <tr class="headtop">
      <th>Name</th>
      <th>Section</th>
      <th>3rd Quarter Grades</th>
      <th>4th Quarter Grades</th>
      <th> Semester Average</th>
      <th></th>
    </tr>
    <tbody id="tb">
      <form method='POST' action='savesem1.php'>
        <tr>
          <td>Name1</td>
          <td>Section1</td>
          <td><input name='I1sem2G11' value='10' /></td>
          <td><input name='I2sem2G11' value='21' /></td>
          <td><input name='Finalsem2G11' id='Finalsem2G11' value='0' /></td>
          <td><input type='submit' name='submitcardsem2G11' class='btnupdate' value='Save Changes'></td>
          <td><input type='hidden' name='idsem2G11' value='id1' /></td>
          <td><input type='hidden' name='y' id='y' value='subid1' /></td>
        </tr>
      </form>
      <form method='POST' action='savesem1.php'>
        <tr>
          <td>Name2</td>
          <td>Section2</td>
          <td><input name='I1sem2G11' value='11' /></td>
          <td><input name='I2sem2G11' value='22' /></td>
          <td><input name='Finalsem2G11' value='0' /></td>
          <td><input type='submit' name='submitcardsem2G11' class='btnupdate' value='Save Changes'></td>
          <td><input type='hidden' name='idsem2G11' value='id2' /></td>
          <td><input type='hidden' name='y' id='y' value='subid2' /></td>
        </tr>
      </form>
    </tbody>
  </table>
</div></code>```

Body:
Hey Guys im having a problem with my javascript code. It only works on the first row of the table and not the rest.

      Name
      Section
      3rd Quarter Grades
      4th Quarter Grades
       Semester Average

    <?php
$sql = $conn2->query("SELECT  Name, Section, Initial1, Initial2, Final, id FROM " .$subid. " ORDER BY Name");
if ($sql->num_rows > 0) {
while ($row = $sql->fetch_assoc())  {
echo "<form method='POST' action='savesem1.php'>";
echo "
";
echo "" .str_replace('!', ' ', str_replace('_', ' ', $row["Name"])). "	";
echo "" .$row["Section"]. "	";
echo "<input  name='I1sem2G11' id='I1sem2G11' onChange='CD();' value='" .$row["Initial1"]. "'/>	";
echo "<input  name='I2sem2G11' id='I2sem2G11' onChange='CD();' value='" .$row["Initial2"]. "'/>	";
echo "<input  name='Finalsem2G11' id='Finalsem2G11'  value='" .$row["Final"]. "'  />	";
echo "<input type='submit' name='submitcardsem2G11' id='submitcardsem2G11' class='btnupdate' value='Save Changes'>	";
echo "<input type='hidden' name='idsem2G11' id='idsem2G11' value='" .$row["id"]. "'/>	";
echo "<input type='hidden' name='y' id='y' value='" .$subid. "'/>	";
echo "
";
echo "</form>";
}
} else { echo ""; }
?>

This is the javascript its purpose is to get the average of the two inputs and put it in another input

function CD() {
  var C = $("#I1sem2G11").val();
  var D = $("#I2sem2G11").val();
  var CD = (+C + +D) / 2;
  document.getElementById("Finalsem2G11").value = CD;
}

Body:
Your problem is duplicate IDs

I am not super happy with the <form> wrapping <tr>s either but it works

$("#tb").on("input", "input", function() {
  const $row = $(this).closest("tr");
  const C = $row.find("[name=I1sem2G11]").val();
  const D = $row.find("[name=I2sem2G11]").val();
  const CD = (+C + +D) / 2;
  console.log(C,D,CD)
  $row.find("[name=Finalsem2G11]").val(CD);
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Q2">
  <table>
    <tr class="headtop">
      <th>Name</th>
      <th>Section</th>
      <th>3rd Quarter Grades</th>
      <th>4th Quarter Grades</th>
      <th> Semester Average</th>
      <th></th>
    </tr>
    <tbody id="tb">
      <form method='POST' action='savesem1.php'>
        <tr>
          <td>Name1</td>
          <td>Section1</td>
          <td><input name='I1sem2G11' value='10' /></td>
          <td><input name='I2sem2G11' value='21' /></td>
          <td><input name='Finalsem2G11' id='Finalsem2G11' value='0' /></td>
          <td><input type='submit' name='submitcardsem2G11' class='btnupdate' value='Save Changes'></td>
          <td><input type='hidden' name='idsem2G11' value='id1' /></td>
          <td><input type='hidden' name='y' id='y' value='subid1' /></td>
        </tr>
      </form>
      <form method='POST' action='savesem1.php'>
        <tr>
          <td>Name2</td>
          <td>Section2</td>
          <td><input name='I1sem2G11' value='11' /></td>
          <td><input name='I2sem2G11' value='22' /></td>
          <td><input name='Finalsem2G11' value='0' /></td>
          <td><input type='submit' name='submitcardsem2G11' class='btnupdate' value='Save Changes'></td>
          <td><input type='hidden' name='idsem2G11' value='id2' /></td>
          <td><input type='hidden' name='y' id='y' value='subid2' /></td>
        </tr>
      </form>
    </tbody>
  </table>
</div>


问:
Encountered an unexpected error from Waterline in (pretty much) identical create's
Running the following code to create a new Database (PostgreSQL 11.3) row:</p>

```<code>const supplier = await Supplier.create(
      Object.assign({}, entityData, {
        last_activity_date: sails.services.datehelper.GetTimeNow(),
        account: supplierParams.supplier,
        monitored: !!activeRegistry,
        verified: true
      })
    );
</code>```

```<code>error: Error (E_UNKNOWN) :: Encountered an unexpected error
    at new WLError (invoice-portal/node_modules/waterline/lib/waterline/error/WLError.js:25:15)
    at invoice-portal/node_modules/waterline/lib/waterline/model/lib/defaultMethods/save.js:188:17
    at invoice-portal/node_modules/waterline/node_modules/async/lib/async.js:52:16
    at invoice-portal/node_modules/waterline/node_modules/async/lib/async.js:550:17
    at invoice-portal/node_modules/waterline/node_modules/async/lib/async.js:544:17
    at _arrayEach (invoice-portal/node_modules/waterline/node_modules/async/lib/async.js:85:13)
    at Immediate.taskComplete (invoice-portal/node_modules/waterline/node_modules/async/lib/async.js:543:13)
    at runCallback (timers.js:789:20)
    at tryOnImmediate (timers.js:751:5)
    at processImmediate [as _immediateCallback] (timers.js:722:5)
</code>```

答:
I added some additional logging (finally in the correct place) in invoice-portal/node_modules/waterline/lib/waterline/model/lib/defaultMethods/save.js to catch all of the saved data and it was not the creation of the Supplier that failed but the insert of invoice row item (which happens after supplier is created/updated).

Some timing/correlation glitch makes Sails throw the error after the Supplier is created (probably at the end of the transaction) why I was looking at the wrong place... Fixing the validation error for the Invoice Item data solved the issue!

Body:
Running the following code to create a new Database (PostgreSQL 11.3) row:

const supplier = await Supplier.create(
      Object.assign({}, entityData, {
        last_activity_date: sails.services.datehelper.GetTimeNow(),
        account: supplierParams.supplier,
        monitored: !!activeRegistry,
        verified: true
      })
    );

error: Error (E_UNKNOWN) :: Encountered an unexpected error
    at new WLError (invoice-portal/node_modules/waterline/lib/waterline/error/WLError.js:25:15)
    at invoice-portal/node_modules/waterline/lib/waterline/model/lib/defaultMethods/save.js:188:17
    at invoice-portal/node_modules/waterline/node_modules/async/lib/async.js:52:16
    at invoice-portal/node_modules/waterline/node_modules/async/lib/async.js:550:17
    at invoice-portal/node_modules/waterline/node_modules/async/lib/async.js:544:17
    at _arrayEach (invoice-portal/node_modules/waterline/node_modules/async/lib/async.js:85:13)
    at Immediate.taskComplete (invoice-portal/node_modules/waterline/node_modules/async/lib/async.js:543:13)
    at runCallback (timers.js:789:20)
    at tryOnImmediate (timers.js:751:5)
    at processImmediate [as _immediateCallback] (timers.js:722:5)


问:
How to add S3 BucketPolicy with AWS CDK?
I wanna translate this CloudFormation piece into CDK:

```<code>Type: AWS::S3::BucketPolicy
Properties:
  Bucket:
    Ref: S3BucketImageUploadBuffer
  PolicyDocument:
    Version: "2012-10-17"
    Statement:
      Action:
        - s3:PutObject
        - s3:PutObjectAcl
      Effect: Allow
      Resource:
        - ...
</code>```

Looking at the documentation here, I don't see a way to provide the policy document itself.

答:
This is an example from a working CDK-Stack:</p>
```<code>   artifactBucket.addToResourcePolicy(
      new PolicyStatement({
        resources: [
          this.pipeline.artifactBucket.arnForObjects("*"),
          this.pipeline.artifactBucket.bucketArn],
        ],
        actions: ["s3:List*", "s3:Get*"],
        principals: [new ArnPrincipal(this.deploymentRole.roleArn)]
      })
    );
</code>```

Body:
I wanna translate this CloudFormation piece into CDK:

Type: AWS::S3::BucketPolicy
Properties:
  Bucket:
    Ref: S3BucketImageUploadBuffer
  PolicyDocument:
    Version: "2012-10-17"
    Statement:
      Action:
        - s3:PutObject
        - s3:PutObjectAcl
      Effect: Allow
      Resource:
        - ...

Looking at the documentation here, I don't see a way to provide the policy document itself.

Body:
This is an example from a working CDK-Stack:

   artifactBucket.addToResourcePolicy(
      new PolicyStatement({
        resources: [
          this.pipeline.artifactBucket.arnForObjects("*"),
          this.pipeline.artifactBucket.bucketArn],
        ],
        actions: ["s3:List*", "s3:Get*"],
        principals: [new ArnPrincipal(this.deploymentRole.roleArn)]
      })
    );


问:
Retry requests from an API that returns errors
I am requesting data from an API that returns back end errors occasionally. I have a list of identifiers that I hand to the apifunction by index to retrieve its respective data. The returned dataframe is stored.

```<code>x=0
while x <= 13000:
    file_checked = Path("path\\%05d.pkl" % (x))

    if file_checked.is_file():
        print(str(x) + list_of_identifiers[x])
        x += 1

    else:
        identifier = list_of_identifiers[x]
        data = apifunction

        data.to_pickle("path\\\\%05d.pkl" % (x))
        print(str(x) + list_of_identifiers[x])
        x += 1
</code>```

The print command just gives me visual feedback on the progression. Checking if the file exists makes it easier for me to restart the loop as I don't have to set the x manually when my loop breaks.

And this is my big problem. The loop breaks. Occasionally the server returns back end errors of various different types (maybe around three different error codes).

Can someone help me to make this code (or alternative ways) robust to the mentioned errors? It should simply retry the same "x" and afterwards proceed. I should mention that from my experience the errors seem to occur arbitrarily which makes it highly unlikely that one could get stuck in an endless loop of retries.
Although I have found several posts on this topic, I was not able to transfer it to my problem.

答:
Can someone comment on my current solution:</p>

```<code>x=0
while x <= 13073:
    file_checked = Path("path\\%05d.pkl" % (x))

    if file_checked.is_file():
        x += 1

    else:
        while x <= 13073:
            try:
                identifier  = list_of_identifiers[x]
                data = apifunction
                data.to_pickle("path\\%05d.pkl" % (x))
                x += 1
            except:
                print("Error")
                continue
</code>```

Body:
I am requesting data from an API that returns back end errors occasionally. I have a list of identifiers that I hand to the apifunction by index to retrieve its respective data. The returned dataframe is stored.

x=0
while x <= 13000:
    file_checked = Path("path\\%05d.pkl" % (x))

    if file_checked.is_file():
        print(str(x) + list_of_identifiers[x])
        x += 1

    else:
        identifier = list_of_identifiers[x]
        data = apifunction

        data.to_pickle("path\\\\%05d.pkl" % (x))
        print(str(x) + list_of_identifiers[x])
        x += 1

The print command just gives me visual feedback on the progression. Checking if the file exists makes it easier for me to restart the loop as I don't have to set the x manually when my loop breaks.

And this is my big problem. The loop breaks. Occasionally the server returns back end errors of various different types (maybe around three different error codes).

Can someone help me to make this code (or alternative ways) robust to the mentioned errors? It should simply retry the same "x" and afterwards proceed. I should mention that from my experience the errors seem to occur arbitrarily which makes it highly unlikely that one could get stuck in an endless loop of retries.
Although I have found several posts on this topic, I was not able to transfer it to my problem.

Body:
Can someone comment on my current solution:

x=0
while x <= 13073:
    file_checked = Path("path\\%05d.pkl" % (x))

    if file_checked.is_file():
        x += 1

    else:
        while x <= 13073:
            try:
                identifier  = list_of_identifiers[x]
                data = apifunction
                data.to_pickle("path\\%05d.pkl" % (x))
                x += 1
            except:
                print("Error")
                continue


问:
Google Maps info Bubble With Font Awesome Icons and bootstrap?
I am attempting to customize links int a Google Maps info-bubble with Bootstrap and font awesome Icons.

I was able to use a list-group from bootstrap for my links in the info bubble successfully, but when I tried to add a font awesome Icon to the link it just does not show up.

```<code><a href="https://www.youtube.com/watch?v=u8iaZF-iFNk" target="_blank" class="list-group-item list-group-item-action"> <i class="fab fa-youtube"></i> Hiking 42 Miles along Michigan's Lake Superior (Adventure Archive)</a>
</code>```

I followed the code on this link here: https://fontawesome.com/v4.7.0/examples/

But when I test on my site the font awesome icon doesn't show up like in the example I followed.

Not sure what I am doing wrong....

答: Check either you font awesome link <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/fontawesome.min.css"> is working or not as i can see one ERROR in you console window

Body:
I am attempting to customize links int a Google Maps info-bubble with Bootstrap and font awesome Icons.

I was able to use a list-group from bootstrap for my links in the info bubble successfully, but when I tried to add a font awesome Icon to the link it just does not show up.

  Hiking 42 Miles along Michigan's Lake Superior (Adventure Archive)

I followed the code on this link here: https://fontawesome.com/v4.7.0/examples/

But when I test on my site the font awesome icon doesn't show up like in the example I followed.

Not sure what I am doing wrong....


问:
Bigger value without greater than or less than operators
this is just for fun.

Can you give me a way to determine the greater value of two numbers? You can use other operators except greater than or less than operator.

Use any tool you like (programming language, pencil paper, etc.).
And another thing you cannot do the following:

int main()
{
    int num1, num2;
    cin >> num1 >> num2;

    if( (num1-num2) + abs(num1-num2) )
        cout << num1 << " is bigger" << endl;
    else
        cout << num2 << " is bigger" << endl;
    return 0;
}
```

答:
Warning: Untested code.

```<code>num2 ~= num2;
++num2;

num1 += num2;

rotate_left(num1, 1);

if (num1 == 0)
    std::cout << "num1 == num2";
else if (num1 & 1)
    std::cout << "num1 < num2";
else
    std::cout << "num1 > num2";
</code>```

I haven't thought about it a lot, but there are probably combinations that will fail due to overflow.

Body:
Warning: Untested code.

num2 ~= num2;
++num2;

num1 += num2;

rotate_left(num1, 1);

if (num1 == 0)
    std::cout << "num1 == num2";
else if (num1 & 1)
    std::cout << "num1 < num2";
else
    std::cout << "num1 > num2";

I haven't thought about it a lot, but there are probably combinations that will fail due to overflow.


问:
Scala filter multiple condition
How do I perform a DataFrame select for Distance greater than or equal to 50 AND a Treatment_Type of 1 or 2? My code below seems not to like the multiple condition &&/and in the filter statement.

```<code>df.select("Distance", "Treatment_Type").filter("Distance >= 50").filter("Treatment_Type == 1" && "Treatment_Type == 2").show
</code>```

Thanks in advance.

答:
You want OR condition but you gave the condition for the Treatment_Type 1 AND 2. So, you should give the correct OR condition. Here is an example dataframe

```<code>+---+--------+--------------+
| id|Distance|Treatment_Type|
+---+--------+--------------+
|  1|      40|             1|
|  2|      40|             2|
|  3|      40|             3|
|  4|      50|             1|
|  5|      50|             2|
|  6|      50|             3|
|  7|      60|             1|
|  8|      60|             2|
+---+--------+--------------+
</code>```

Under the below conditions, it give the same results as follows:

```<code>df.select("Distance", "Treatment_Type").filter(col("Distance") >= 50 && (col("Treatment_Type") === 1 || col("Treatment_Type") === 2))
df.select("Distance", "Treatment_Type").filter(col("Distance") >= 50 && col("Treatment_Type").isin(1,2))
df.select("Distance", "Treatment_Type").where("Distance >= 50 and Treatment_Type in (1, 2)").show()

+--------+--------------+
|Distance|Treatment_Type|
+--------+--------------+
|      50|             1|
|      50|             2|
|      60|             1|
|      60|             2|
+--------+--------------+
</code>```

Title: Scala filter multiple condition

Body:
How do I perform a DataFrame select for Distance greater than or equal to 50 AND a Treatment_Type of 1 or 2? My code below seems not to like the multiple condition &&/and in the filter statement.

df.select("Distance", "Treatment_Type").filter("Distance >= 50").filter("Treatment_Type == 1" && "Treatment_Type == 2").show

Thanks in advance.

Body:
You want OR condition but you gave the condition for the Treatment_Type 1 AND 2. So, you should give the correct OR condition. Here is an example dataframe

+---+--------+--------------+
| id|Distance|Treatment_Type|
+---+--------+--------------+
|  1|      40|             1|
|  2|      40|             2|
|  3|      40|             3|
|  4|      50|             1|
|  5|      50|             2|
|  6|      50|             3|
|  7|      60|             1|
|  8|      60|             2|
+---+--------+--------------+

Under the below conditions, it give the same results as follows:

df.select("Distance", "Treatment_Type").filter(col("Distance") >= 50 && (col("Treatment_Type") === 1 || col("Treatment_Type") === 2))
df.select("Distance", "Treatment_Type").filter(col("Distance") >= 50 && col("Treatment_Type").isin(1,2))
df.select("Distance", "Treatment_Type").where("Distance >= 50 and Treatment_Type in (1, 2)").show()

+--------+--------------+
|Distance|Treatment_Type|
+--------+--------------+
|      50|             1|
|      50|             2|
|      60|             1|
|      60|             2|
+--------+--------------+


问:
How to ignore/skip duplicate (index) on update
I´ve the following table with two columns. The two columns are the combined index key of the table:

```<code>ID1    ID2
A    X
A    Y
A    Z
B    Z
</code>```

Now I need to do the following:

```<code>UPDATE table SET ID2=X WHERE ID2=Z
</code>```

As the table has a combined key (ID1 + ID2) this leads to a "duplicate key value violates unique constraint" exception cause there is already an "A-X" combination and the update for row "A-Z" violates that key.

So my question is:
Is there in Postgres an option to skip on duplicate key? Or do you have any other hint for me?

Final state of the table should be:

```<code>ID1    ID2
A    X
A    Y
B    X
</code>```

答:
One solution I can think of, is to define the primary key as deferrable and then do the update and delete in a single statement:

```<code>create table t1 (
  id1 text,
  id2 text,
  primary key (id1, id2) deferrable
);
</code>```

Then you can do the following:

```<code>with changed as (
  UPDATE t1
    SET ID2='X'
  WHERE ID2='Z'
  returning id1, id2
)
delete from t1
where (id1, id2) in (select id1, id2 from changed)
</code>```

The DELETE does not see the new row that has been created by the update, but it sees the "old" one, so only the conflicting one(s) are deleted.

Online example

Body:
I´ve the following table with two columns. The two columns are the combined index key of the table:

ID1    ID2
A    X
A    Y
A    Z
B    Z

Now I need to do the following:

UPDATE table SET ID2=X WHERE ID2=Z

As the table has a combined key (ID1 + ID2) this leads to a "duplicate key value violates unique constraint" exception cause there is already an "A-X" combination and the update for row "A-Z" violates that key.

So my question is:
Is there in Postgres an option to skip on duplicate key? Or do you have any other hint for me?

Final state of the table should be:

ID1    ID2
A    X
A    Y
B    X

Body:
One solution I can think of, is to define the primary key as deferrable and then do the update and delete in a single statement:

create table t1 (
  id1 text,
  id2 text,
  primary key (id1, id2) deferrable
);

Then you can do the following:

with changed as (
  UPDATE t1
    SET ID2='X'
  WHERE ID2='Z'
  returning id1, id2
)
delete from t1
where (id1, id2) in (select id1, id2 from changed)

The DELETE does not see the new row that has been created by the update, but it sees the "old" one, so only the conflicting one(s) are deleted.

Online example


问:
Communicate with Python subprocess
I have the following Rust code that sends a string to a subprocess via stdin and read whatever comes from it's stdout:

use std::io::{BufRead, BufReader, Write};
use std::process::{Command, Stdio};
fn main() {
   let mut child = Command::new("cat")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("Did not run");
    let v = vec!["11111", "2222222", "3333", "end", "soooooooooooooooo"];
    let k = child.stdin.as_mut().unwrap();
    let mut g = BufReader::new(child.stdout.as_mut().unwrap());
    for x in v.into_iter() {
        k.write_all(x.as_bytes()).unwrap();
        k.write_all("\n".as_bytes()).unwrap();
        let mut s: String = String::new();
        g.read_line(&mut s).unwrap();
        println!("{}", s)
    }
}

```

<p>The example runs without issues but when I try to do the same using a python script it fails.</p>

<p>To call the script I'm creating <code>child</code> like this:</p>

```    let mut child = Command::new("c:\\Windows\\py.exe")
        .args(&["-u", "echo.py"])
```

<p>And in the script I'm just echoing whatever comes from <code>stdin</code> to <code>stdout</code></p>

```import sys
import time
if __name__=="__main__":
    fo=sys.stdout
    fo.write('python starts at: %.0f\n'%(time.time()*1000))
    line = sys.stdin.readline()
    while True:
        fo.write(line+"\n")
        line = sys.stdin.readline()
    fo.write('python ends at: %.0f\n'%(time.time()*1000))
```

<p>The output I'm getting is:</p>

```python starts at: 1582166542281

11111

2222222

Traceback (most recent call last):
  File "c:\Users\asia\Documents\projects\python\echo.py", line 8, in <module>
    fo.write(line+"\n")
OSError: [Errno 22] Invalid argument

```

My take is the pipe breaks somewhere around printing the second string but I can't figure out why. What am I missing here?

Thanks in advance

答:
Rust process writes 5 lines on the stdin of python process, precisely the strings coming from:

```<code>let v = vec!["11111", "2222222", "3333", "end", "soooooooooooooooo"];
</code>```

But on the python side you are trying to write back to rust 7 lines: an header, the 5 lines coming
from stdin and a footer.

The read_line inside for x in v.into_iter()
reads only 5 lines and the rust process terminates, triggering a BrokenPipe on python side that has to write two more lines.

I think it is also needed some control to exit the while True loop on python side.

Something along these lines, just to get the idea:

```<code>use std::io::{BufRead, BufReader, Write};
use std::process::{Command, Stdio};
fn main() {
   let mut child = Command::new("python").args(&["-u", "echo.py"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("Did not run");
    let v = vec!["11111", "2222222", "3333", "end", "soooooooooooooooo"];
    let k = child.stdin.as_mut().unwrap();
    let mut g = BufReader::new(child.stdout.as_mut().unwrap());

    // read the header "python starts at ..."
    let mut s: String = String::new();
    g.read_line(&mut s).unwrap();
    println!("{}", s);

    for x in v.into_iter() {
        k.write_all(x.as_bytes()).unwrap();
        k.write_all("\n".as_bytes()).unwrap();
        let mut s: String = String::new();

        // read len(v) lines, in this case 5 lines
        g.read_line(&mut s).unwrap();
        println!("{}", s)
    }

    // Something is neeeded to signal termination of input
    // assume for this example a zero length string
    k.write_all("\n".as_bytes()).unwrap();

    // read the empty string and the footer "python ends at ..."
    let mut s: String = String::new();
    g.read_line(&mut s).unwrap();
    g.read_line(&mut s).unwrap();
    println!("{}", s);
}
</code>```

python:

```<code>import sys
import time

if __name__ == "__main__":
    fo = sys.stdout
    fo.write('python starts at: %.0f\n' % (time.time()*1000))
    line = sys.stdin.readline()
    while True:
        fo.write(line)
        line = sys.stdin.readline()
        if (line == "\n"):
            break

    fo.write('python ends at: %.0f\n' % (time.time()*1000))
</code>```

Title: Communicate with Python subprocess

Body:
I have the following Rust code that sends a string to a subprocess via stdin and read whatever comes from it's stdout:

use std::io::{BufRead, BufReader, Write};
use std::process::{Command, Stdio};
fn main() {
   let mut child = Command::new("cat")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("Did not run");
    let v = vec!["11111", "2222222", "3333", "end", "soooooooooooooooo"];
    let k = child.stdin.as_mut().unwrap();
    let mut g = BufReader::new(child.stdout.as_mut().unwrap());
    for x in v.into_iter() {
        k.write_all(x.as_bytes()).unwrap();
        k.write_all("\n".as_bytes()).unwrap();
        let mut s: String = String::new();
        g.read_line(&mut s).unwrap();
        println!("{}", s)
    }
}

The example runs without issues but when I try to do the same using a python script it fails.

To call the script I'm creating child like this:

    let mut child = Command::new("c:\\Windows\\py.exe")
        .args(&["-u", "echo.py"])

And in the script I'm just echoing whatever comes from stdin to stdout

import sys
import time
if __name__=="__main__":
    fo=sys.stdout
    fo.write('python starts at: %.0f\n'%(time.time()*1000))
    line = sys.stdin.readline()
    while True:
        fo.write(line+"\n")
        line = sys.stdin.readline()
    fo.write('python ends at: %.0f\n'%(time.time()*1000))

The output I'm getting is:

python starts at: 1582166542281

11111

2222222

Traceback (most recent call last):
  File "c:\Users\asia\Documents\projects\python\echo.py", line 8, in <module>
    fo.write(line+"\n")
OSError: [Errno 22] Invalid argument

My take is the pipe breaks somewhere around printing the second string but I can't figure out why. What am I missing here?

Thanks in advance

Body:
Rust process writes 5 lines on the stdin of python process, precisely the strings coming from:

let v = vec!["11111", "2222222", "3333", "end", "soooooooooooooooo"];

But on the python side you are trying to write back to rust 7 lines: an header, the 5 lines coming
from stdin and a footer.

The read_line inside for x in v.into_iter()
reads only 5 lines and the rust process terminates, triggering a BrokenPipe on python side that has to write two more lines.

I think it is also needed some control to exit the while True loop on python side.

Something along these lines, just to get the idea:

use std::io::{BufRead, BufReader, Write};
use std::process::{Command, Stdio};
fn main() {
   let mut child = Command::new("python").args(&["-u", "echo.py"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("Did not run");
    let v = vec!["11111", "2222222", "3333", "end", "soooooooooooooooo"];
    let k = child.stdin.as_mut().unwrap();
    let mut g = BufReader::new(child.stdout.as_mut().unwrap());

    // read the header "python starts at ..."
    let mut s: String = String::new();
    g.read_line(&mut s).unwrap();
    println!("{}", s);

    for x in v.into_iter() {
        k.write_all(x.as_bytes()).unwrap();
        k.write_all("\n".as_bytes()).unwrap();
        let mut s: String = String::new();

        // read len(v) lines, in this case 5 lines
        g.read_line(&mut s).unwrap();
        println!("{}", s)
    }

    // Something is neeeded to signal termination of input
    // assume for this example a zero length string
    k.write_all("\n".as_bytes()).unwrap();

    // read the empty string and the footer "python ends at ..."
    let mut s: String = String::new();
    g.read_line(&mut s).unwrap();
    g.read_line(&mut s).unwrap();
    println!("{}", s);
}

python:

import sys
import time

if __name__ == "__main__":
    fo = sys.stdout
    fo.write('python starts at: %.0f\n' % (time.time()*1000))
    line = sys.stdin.readline()
    while True:
        fo.write(line)
        line = sys.stdin.readline()
        if (line == "\n"):
            break

    fo.write('python ends at: %.0f\n' % (time.time()*1000))


问:
How to use a variable inside a regular expression
I'd like to use a variable inside a regex, how can I do this in Python?</p>
```<code>TEXTO = sys.argv[1]

if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE):
    # Successful match
else:
    # Match attempt failed
</code>```

答:
more example

I have configus.yml
with flows files

```<code>"pattern":
  - _(\d{14})_
"datetime_string":
  - "%m%d%Y%H%M%f"
</code>```

in python code I use

```<code>data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)
</code>```

Body:
I'd like to use a variable inside a regex, how can I do this in Python?

TEXTO = sys.argv[1]

if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE):
    # Successful match
else:
    # Match attempt failed

Body:
more example

I have configus.yml
with flows files

"pattern":
  - _(\d{14})_
"datetime_string":
  - "%m%d%Y%H%M%f"

in python code I use

data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)


问:
Background image size for Android
I have an image that I want to place on the background on my activity.  For the G1 I would use a background of 320x480 but with the nexus 1 the resolution is almost double that.  Should I just place the large image and make the smaller phones size down?  I am trying to keep the size of my package down as much as possible.</p>

答:
A repeatable background image can be the best way to handle device resolution compatibility for simple patterns:

How to make android app's background image repeat

Title: Background image size for Android


问:
How to insert a matrix into another matrix
I'm trying to create a function to insert a matrix in an another(square matrix), for example:</p>

```<code>A = [(1,2,3),(4,5,6),(7,8,9)]
B = [(2,4),(6,8)]

C = funcmatrix(A,B)

result: [1 2 3 0 0
         4 5 6 0 0
         7 8 9 0 0
         0 0 0 2 4
         0 0 0 6 8]
</code>```

Body:
I'm trying to create a function to insert a matrix in an another(square matrix), for example:

A = [(1,2,3),(4,5,6),(7,8,9)]
B = [(2,4),(6,8)]

C = funcmatrix(A,B)

result: [1 2 3 0 0
         4 5 6 0 0
         7 8 9 0 0
         0 0 0 2 4
         0 0 0 6 8]

Body:
import numpy as np

A = np.array([(1,2,3),(4,5,6),(7,8,9)])
B = np.array([(2,4),(6,8)])

combined = np.block([[A, np.zeros((len(A), len(B)))],
                     [np.zeros((len(B), len(A))), B]])

Out:

array([[1., 2., 3., 0., 0.],
       [4., 5., 6., 0., 0.],
       [7., 8., 9., 0., 0.],
       [0., 0., 0., 2., 4.],
       [0., 0., 0., 6., 8.]])

Please refer to docs.


问:
What is better design approach for RabbitMQ?
I have been playing around with RabbitMQ for last couple of weeks and developed the following design pattern

producer <--> Exchange <---> queues <---> consumer.

I have used couple of RabbitMQ clients like EasyNetQ and MassTransit. Both clients work with my above design however one thing common between them is that if an Exchange doesn't exist it creates one and similarly if a queue doesn't exist then it creates one accordingly.

However, I am thinking creating exchange, queues and binding from either producer or consumers a good design approach?

Is it more meaningful to create the exchange and queues within the RabbitMQ Management manually? Then prevent Producer and Consumer from creating the above in the code?

But I am more concerned what if the exchanges and queues are deleted then it also breaks the producer and consumers?

What do you suggest guys?

答:
I believe the question has two parts. I will try taking each one separately:

Topology

On your diagram, your producer puts messages to the queue of a consumer. It simply doesn't work with RabbitMQ:

The core idea in the messaging model in RabbitMQ is that the producer never sends any messages directly to a queue.
  (from the docs)

Therefore, as you noticed, messaging middleware libraries you mentioned always create a queue and an exchange matching that queue, then bind them together. By doing that, they enable you to "publish" a message to the particular exchange that is bound to the queue of your consumer, so you get the send functionality.

So, under the hood, it is still publish-subscribe.

Using a library or do things yourself

Setting up queues and exchanges is tedious work. There're surely some cases where you want to take control on low level and take care of all those things from code.

However, using messaging middleware, would it be EasyNetQ, MassTransit or NServiceBus is extremely valuable. All of those libraries have comprehensive topology management capabilities that enable developers to concentrate on delivering value instead of dealing with exchanges and queues.

In many cases using type-based routing, as each of those libraries does, makes perfect sense.

Here I give you a quick list of things you'd need to do in your code, or manually if you choose not to use a messaging middleware library:

Configuring the topology

Configure routing

Handling exceptions using retries and redelivery

Controlling scoped dependencies for message consumers

Logging and tracing

Scheduling

Long-running processes and distributed transactions

The list if by far not comprehensive, but it gives you the idea. If you're ready to take care of all those concerns yourself - go for it.


问:
Order of elimination in Josephus problem
Josephus Problem (or Josephus permutation) is a theoretical problem related to a certain counting-out game.

People are standing in a circle waiting to be executed. Counting
  begins at the first point in the circle and proceeds around the circle
  in a clockwise direction. After a specified number of people are
  skipped, the next person is executed. The procedure is repeated with
  the remaining people, starting with the next person, going in the same
  direction and skipping the same number of people, until only one
  person remains, and is freed. For example if n=10 then the order of
  elimination is 2, 4, 6, 8, 10, 3, 7, 1, 9 and 5

```<code>The problem is, without simulation of the above game, try to find out the order of
elimination through means of mathematical formula or a mathematical pattern.
</code>```

Initially we are given n i.e the number of people in the circle at the start. Give the order of elimination keeping in mind the above conditions and constraints.

In simple words, print the pattern of deaths without using any data structures like arrays and linked lists.

答:
```<code>function josIterative(n, k) {
let queue = [];
for (let i = 1; i <= n; i++) queue.push(i);

let deathOrder = [];

while (queue.length !== 1) {
    for (let skip = 1; skip < k; skip++) queue.push(queue.shift());
    deathOrder.push(queue.shift());
}

console.log("Death order is " + deathOrder.join(" "));
return queue[0]; //survivor
}

console.log(josIterative(7, 3) + " is survivor");
</code>```

This program is written in javascript es6.
Queue takes care to preserve the new position
Alternate way is to solve using recurrence relation

Body:
Josephus Problem (or Josephus permutation) is a theoretical problem related to a certain counting-out game.

People are standing in a circle waiting to be executed. Counting
  begins at the first point in the circle and proceeds around the circle
  in a clockwise direction. After a specified number of people are
  skipped, the next person is executed. The procedure is repeated with
  the remaining people, starting with the next person, going in the same
  direction and skipping the same number of people, until only one
  person remains, and is freed. For example if n=10 then the order of
  elimination is 2, 4, 6, 8, 10, 3, 7, 1, 9 and 5

The problem is, without simulation of the above game, try to find out the order of
elimination through means of mathematical formula or a mathematical pattern.

Initially we are given n i.e the number of people in the circle at the start. Give the order of elimination keeping in mind the above conditions and constraints.

In simple words, print the pattern of deaths without using any data structures like arrays and linked lists.

Body:
function josIterative(n, k) {
let queue = [];
for (let i = 1; i <= n; i++) queue.push(i);

let deathOrder = [];

while (queue.length !== 1) {
    for (let skip = 1; skip < k; skip++) queue.push(queue.shift());
    deathOrder.push(queue.shift());
}

console.log("Death order is " + deathOrder.join(" "));
return queue[0]; //survivor
}

console.log(josIterative(7, 3) + " is survivor");

This program is written in javascript es6.
Queue takes care to preserve the new position
Alternate way is to solve using recurrence relation


问:
How to get a file from a server in a cluster in Vsphere using pyVmomi to remote(host) pc
I am able to execute a command inside the server but I want to get that output in my local pc. I don't want want to use ssh keys. I want to use just the host's username and password as well as vm's(server's) username and password. I couldn't find a direct method to get the shell output of server in my pc, but this method seems half done like generate and save the output in server and then get the file from server. I am finding it difficult to get file(sample.txt) from server to local host(pc).

[EDIT: I am able to do this using via via method(Store the output to server and then get it back into local pc, is there a direct method ?) ]

```<code>from pyVim import connect
from config import *
from pyVmomi import vim, vmodl
import ssl

service_instance = connect.SmartConnect(host="yyyyyyy", port=some_number,user="xxx" , pwd=pwd,sslContext=ssl._create_unverified_context())
content = service_instance.RetrieveContent()

vm = searcher.FindByIp(ip="zzzzzz", vmSearch=True)

creds = vim.vm.guest.NamePasswordAuthentication(username='root', password=vmpwd)

pm = service_instance.content.guestOperationsManager.processManager

#checks python version and stores in sample.txt in server
ps = vim.vm.guest.ProcessManager.ProgramSpec(programPath='/usr/bin/python', arguments='--version  &> sample.txt')
res = pm.StartProgramInGuest(vm, creds, ps)
print(res) #Prints pid
</code>```

答:
This does the job but I would appreciate if someone knows how to directly get the output of shell command from server to my local pc. This code makes a file with the output of cmd inside the server and it gets copied into my local pc</p>

```<code>from pyVim import connect
from config import *
from pyVmomi import vim, vmodl
import ssl
import os
import requests

service_instance = connect.SmartConnect(host="xxxx", port=aaa,user="yyy" , pwd=pwd,sslContext=ssl._create_unverified_context())

content = service_instance.RetrieveContent()

# # Find a VM
vm = searcher.FindByIp(ip="aaaa", vmSearch=True)

creds = vim.vm.guest.NamePasswordAuthentication(username='root', password=vmpwd)

pm = service_instance.content.guestOperationsManager.processManager

#executes and saves sample.txt into server
ps = vim.vm.guest.ProcessManager.ProgramSpec(programPath='/usr/bin/python', arguments='--version  &> sample.txt')
res = pm.StartProgramInGuest(vm, creds, ps)

dest="/Users/username/Desktop/vcenter/sample.txt" #My local pc

src="/root/sample.txt" #Server's directory
fti = content.guestOperationsManager.fileManager.InitiateFileTransferFromGuest(vm, creds, src)

resp=requests.get(fti.url, verify=False)

#Writes into file
with open(dest, 'wb') as f:
        f.write(resp.content)
</code>```

Body:
I am able to execute a command inside the server but I want to get that output in my local pc. I don't want want to use ssh keys. I want to use just the host's username and password as well as vm's(server's) username and password. I couldn't find a direct method to get the shell output of server in my pc, but this method seems half done like generate and save the output in server and then get the file from server. I am finding it difficult to get file(sample.txt) from server to local host(pc).

[EDIT: I am able to do this using via via method(Store the output to server and then get it back into local pc, is there a direct method ?) ]

from pyVim import connect
from config import *
from pyVmomi import vim, vmodl
import ssl

service_instance = connect.SmartConnect(host="yyyyyyy", port=some_number,user="xxx" , pwd=pwd,sslContext=ssl._create_unverified_context())
content = service_instance.RetrieveContent()

vm = searcher.FindByIp(ip="zzzzzz", vmSearch=True)

creds = vim.vm.guest.NamePasswordAuthentication(username='root', password=vmpwd)

pm = service_instance.content.guestOperationsManager.processManager

#checks python version and stores in sample.txt in server
ps = vim.vm.guest.ProcessManager.ProgramSpec(programPath='/usr/bin/python', arguments='--version  &> sample.txt')
res = pm.StartProgramInGuest(vm, creds, ps)
print(res) #Prints pid

Body:
This does the job but I would appreciate if someone knows how to directly get the output of shell command from server to my local pc. This code makes a file with the output of cmd inside the server and it gets copied into my local pc

from pyVim import connect
from config import *
from pyVmomi import vim, vmodl
import ssl
import os
import requests

service_instance = connect.SmartConnect(host="xxxx", port=aaa,user="yyy" , pwd=pwd,sslContext=ssl._create_unverified_context())

content = service_instance.RetrieveContent()

# # Find a VM
vm = searcher.FindByIp(ip="aaaa", vmSearch=True)

creds = vim.vm.guest.NamePasswordAuthentication(username='root', password=vmpwd)

pm = service_instance.content.guestOperationsManager.processManager

#executes and saves sample.txt into server
ps = vim.vm.guest.ProcessManager.ProgramSpec(programPath='/usr/bin/python', arguments='--version  &> sample.txt')
res = pm.StartProgramInGuest(vm, creds, ps)

dest="/Users/username/Desktop/vcenter/sample.txt" #My local pc

src="/root/sample.txt" #Server's directory
fti = content.guestOperationsManager.fileManager.InitiateFileTransferFromGuest(vm, creds, src)

resp=requests.get(fti.url, verify=False)

#Writes into file
with open(dest, 'wb') as f:
        f.write(resp.content)


问:
Exported Project Template from VS2008 but it is corrupted?
I am working on creating a custom project template with Visual Studio 2008 Team System edition.  I have also created a custom wizard for the custom template.

So I have to update the vstemplate file to tell the template to use my custom wizard.  But the archive is corrupted!

7zip thinks folders within the archive are using non-standard zip compression.  The latest winzip thinks the CRC header on the folders doesn't match the main CRC header.

What am I doing wrong?

If I don't change the template zip file created by VS2008, it works just fine.  But I need to be able to update the zip file.  If I do, 7zip/winzip fixes the zip file structure and then VS2008 doesn't like the template anymore.  Files that are in folders within the zip file are inaccessible.

I do notice that the standard templates seem to keep a flat file structure.  That is no nested folders or anything.  But the vstemplate file has targetfilename attributes that recreate the original folder structure.

For example instead of...

```<code><Folder Name="My Project" TargetFolderName="My Project">
    <ProjectItem ReplaceParameters="true" TargetFileName="AssemblyInfo.vb">AssemblyInfo.vb</ProjectItem>
</Folder>
</code>```

the standard vstemplate defines the following...

```<code><ProjectItem ReplaceParameters="true" TargetFileName="My Project\AssemblyInfo.vb">AssemblyInfo.vb</ProjectItem>
</code>```

I've just had a little think about the above.  Are they actually the same thing?

Is the problem with the creation of the original zip file?

Is the folder structure within the zip file tripping everything up?

Should it have added all the files to the zip archive in as flat folder structure?  If so is there a fix for VS2008 so that I do not have to manually fix the template archives?

答:
Same problem here. I solved it by using <ProjectItem>MyFolder\MyFile.cs</ProjectItem> instead of <Folder>...<Folder>.

PS: TargetFileName doesn't work for me in VS2008 + Windows7.

OwnerDisplayName: BlackMael

Body:
I am working on creating a custom project template with Visual Studio 2008 Team System edition.  I have also created a custom wizard for the custom template.

So I have to update the vstemplate file to tell the template to use my custom wizard.  But the archive is corrupted!

7zip thinks folders within the archive are using non-standard zip compression.  The latest winzip thinks the CRC header on the folders doesn't match the main CRC header.

What am I doing wrong?

If I don't change the template zip file created by VS2008, it works just fine.  But I need to be able to update the zip file.  If I do, 7zip/winzip fixes the zip file structure and then VS2008 doesn't like the template anymore.  Files that are in folders within the zip file are inaccessible.

I do notice that the standard templates seem to keep a flat file structure.  That is no nested folders or anything.  But the vstemplate file has targetfilename attributes that recreate the original folder structure.

For example instead of...

<Folder Name="My Project" TargetFolderName="My Project">
    <ProjectItem ReplaceParameters="true" TargetFileName="AssemblyInfo.vb">AssemblyInfo.vb</ProjectItem>
</Folder>

the standard vstemplate defines the following...

<ProjectItem ReplaceParameters="true" TargetFileName="My Project\AssemblyInfo.vb">AssemblyInfo.vb</ProjectItem>

I've just had a little think about the above.  Are they actually the same thing?

Is the problem with the creation of the original zip file?

Is the folder structure within the zip file tripping everything up?

Should it have added all the files to the zip archive in as flat folder structure?  If so is there a fix for VS2008 so that I do not have to manually fix the template archives?

LastEditorDisplayName: BlackMael


问:
How to encode in base 64 and hex?
I read following two lines in the book : The Web Application Hacker’s Hand-
book.

For example, the Base64-encoded form of The Web Application Hacker’s Hand-
book is:
VGhlIFdlYiBBcHBsaWNhdGlvbiBIYWNrZXIncyBIYW5kYm9vaw==

For example, hex-encoding the username “daf” within a cookie would result in:
646166

Can anybody explain me how this conversion is done?

答:
You can read more about Base64 in the Wikipedia article.

Doing the actual conversion to Base64 will depend on what programming language you are using. For instance, in the System.Text namespace of the .NET Framework you will find a method called Convert.ToBase64String that will do it for you.

For the hex encoding, all you need to do is get the corresponding hexadecimal value of each character. Take a look at this ASCII Table, in the Hx column you will see that d is 64, a is 61 and f is 66.

Again, the actual conversion will depend on the language you're using.

Title: How to encode in base 64 and hex?


问:
json cleanup and remove bad columns and unnecessary lists
I have the following json:

```<code>{
    "pfe-statistics" : [
    {
        "pfe-traffic-statistics" : [
        {
            "pfe-input-packets" : [
            {
                "data" : "3895887"
            }
            ],
            "input-pps" : [
            {
                "data" : "0"
            }
            ],
            "pfe-output-packets" : [
            {
                "data" : "1114541"
            }
            ],
            "output-pps" : [
            {
                "data" : "0"
            }
            ]
        }
        ],
        "pfe-local-traffic-statistics" : [
        {
            "pfe-input-packets" : [
            {
                "data" : "3893502"
            }
            ],
            "pfe-output-packets" : [
            {
                "data" : "1114541"
            }
            ],
            "software-input-control-drops" : [
            {
                "data" : "0"
            }
            ],
            "software-input-high-drops" : [
            {
                "data" : "0"
            }
            ],
            "software-input-medium-drops" : [
            {
                "data" : "0"
            }
            ],
            "software-input-low-drops" : [
            {
                "data" : "0"
            }
            ],
            "software-output-low-drops" : [
            {
                "data" : "0"
            }
            ],
            "hardware-input-drops" : [
            {
                "data" : "0"
            }
            ]
        }
        ],
        "pfe-local-protocol-statistics" : [
        {
            "hdlc-keepalive-count" : [
            {
                "data" : "0"
            }
            ],
            "atm-oam-count" : [
            {
                "data" : "0"
            }
            ],
            "fr-lmi-count" : [
            {
                "data" : "0"
            }
            ],
            "ppp-lcp-ncp-count" : [
            {
                "data" : "0"
            }
            ],
            "ospf-hello-count" : [
            {
                "data" : "0"
            }
            ],
            "ospf3-hello-count" : [
            {
                "data" : "0"
            }
            ],
            "rsvp-hello-count" : [
            {
                "data" : "0"
            }
            ],
            "ldp-hello-count" : [
            {
                "data" : "0"
            }
            ],
            "bfd-count" : [
            {
                "data" : "0"
            }
            ],
            "isis-iih-count" : [
            {
                "data" : "0"
            }
            ],
            "lacp-count" : [
            {
                "data" : "0"
            }
            ],
            "arp-count" : [
            {
                "data" : "0"
            }
            ],
            "ether-oam-count" : [
            {
                "data" : "0"
            }
            ],
            "unknown-count" : [
            {
                "data" : "0"
            }
            ]
        }
        ],
        "pfe-hardware-discard-statistics" : [
        {
            "timeout-discard" : [
            {
                "data" : "0"
            }
            ],
            "truncated-key-discard" : [
            {
                "data" : "0"
            }
            ],
            "bits-to-test-discard" : [
            {
                "data" : "0"
            }
            ],
            "data-error-discard" : [
            {
                "data" : "0"
            }
            ],
            "stack-underflow-discard" : [
            {
                "data" : "0"
            }
            ],
            "stack-overflow-discard" : [
            {
                "data" : "0"
            }
            ],
            "bad-route-discard" : [
            {
                "data" : "0"
            }
            ],
            "nexthop-discard" : [
            {
                "data" : "0"
            }
            ],
            "invalid-iif-discard" : [
            {
                "data" : "0"
            }
            ],
            "info-cell-discard" : [
            {
                "data" : "0"
            }
            ],
            "fabric-discard" : [
            {
                "data" : "0"
            }
            ]
        }
        ],
        "pfe-chip-statistics" : [
        {
            "input-checksum" : [
            {
                "data" : "0"
            }
            ],
            "output-mtu" : [
            {
                "data" : "0"
            }
            ]
        }
        ]
    }
    ]
}
</code>```

I want to generate the following:

```<code>{
    "pfe-statistics" :
    {
        "pfe-traffic-statistics" :
        {
            "pfe-input-packets" : "56601136",
            "input-pps" : "30",
            "pfe-output-packets" : "71427636",
            "output-pps" : "28",
            "pfe-fabric-input" : "0",
            "pfe-fabric-input-pps" : "0",
            "pfe-fabric-output" : "0",
            "pfe-fabric-output-pps" : "0"
        },
        "pfe-local-traffic-statistics" :
        {
            "pfe-input-packets" : "56226309",
            "pfe-output-packets" : "142458974",
            "software-input-control-drops" : "0",
            "software-input-high-drops" : "0",
            "software-input-medium-drops" : "0",
            "software-input-low-drops" : "0",
            "software-output-low-drops" : "0",
            "hardware-input-drops" : "0"
        },
        "pfe-local-protocol-statistics" :
        {
            "hdlc-keepalive-count" : "0",
            "atm-oam-count" : "0",
            "fr-lmi-count" : "0",
            "ppp-lcp-ncp-count" : "0",
            "ospf-hello-count" : "0",
            "ospf3-hello-count" : "0",
            "rsvp-hello-count" : "0",
            "ldp-hello-count" : "0",
            "bfd-count" : "49316136",
            "isis-iih-count" : "0",
            "lacp-count" : "0",
            "arp-count" : "433208",
            "ether-oam-count" : "0",
            "unknown-count" : "0"
        },
        "pfe-hardware-discard-statistics" :
        {
            "timeout-discard" : "0",
            "truncated-key-discard" : "0",
            "bits-to-test-discard" : "0",
            "data-error-discard" : "0",
            "tcp-header-error-discard" : "0",
            "stack-underflow-discard" : "0",
            "stack-overflow-discard" : "0",
            "bad-route-discard" : "0",
            "nexthop-discard" : "0",
            "invalid-iif-discard" : "0",
            "info-cell-discard" : "0",
            "fabric-discard" : "0"
        },
        "pfe-chip-statistics" :
        {
            "input-checksum" : "0",
            "output-mtu" : "0"
        }
    }
}
</code>```

I wrote the following function but can't make get it to work 100 percent:

```<code>d = {}
l = []
def compact_json(df):
    for k, v in df.items():
        if isinstance(v, list):
            print("list")
            print(k)
            if "data" not in v[0].keys():
                val = v[0].keys()
                if val not in l:
                    l.append(k)
            compact_json(v[0])

            #d.update(k)
        if isinstance(v[0], dict):
            print("dict")
            if "data" in v[0].keys():
                print("if data yes")
                print(k, v[0]["data"])
                d1 = {k: v}
                #d[val] = v[0]["data"]
                d[k] = v[0]["data"]
            else:
                print("else no data")
                print(v[0])
                compact_json(v[0])

compact_json(df)
print("==============")
print(d)
</code>```

I can only print leaves but not the branches. Note that I want to make it universal for multiple json, so nested depths can be different in all the forms.

答:
You can use a nested dictionary comprehension:

```<code>result = {a:{j:{l:b['data'] for y in k for l, [b] in y.items()}
             for g in c for j, k in g.items()} for a, c in data.items()}
</code>```

```<code>import json
print(json.dumps(result, indent=4))
</code>```

Output:

```<code>{
  "pfe-statistics": {
     "pfe-traffic-statistics": {
        "pfe-input-packets": "3895887",
        "input-pps": "0",
        "pfe-output-packets": "1114541",
        "output-pps": "0"
    },
    "pfe-local-traffic-statistics": {
        "pfe-input-packets": "3893502",
        "pfe-output-packets": "1114541",
        "software-input-control-drops": "0",
        "software-input-high-drops": "0",
        "software-input-medium-drops": "0",
        "software-input-low-drops": "0",
        "software-output-low-drops": "0",
        "hardware-input-drops": "0"
    },
    "pfe-local-protocol-statistics": {
        "hdlc-keepalive-count": "0",
        "atm-oam-count": "0",
        "fr-lmi-count": "0",
        "ppp-lcp-ncp-count": "0",
        "ospf-hello-count": "0",
        "ospf3-hello-count": "0",
        "rsvp-hello-count": "0",
        "ldp-hello-count": "0",
        "bfd-count": "0",
        "isis-iih-count": "0",
        "lacp-count": "0",
        "arp-count": "0",
        "ether-oam-count": "0",
        "unknown-count": "0"
    },
    "pfe-hardware-discard-statistics": {
        "timeout-discard": "0",
        "truncated-key-discard": "0",
        "bits-to-test-discard": "0",
        "data-error-discard": "0",
        "stack-underflow-discard": "0",
        "stack-overflow-discard": "0",
        "bad-route-discard": "0",
        "nexthop-discard": "0",
        "invalid-iif-discard": "0",
        "info-cell-discard": "0",
        "fabric-discard": "0"
    },
    "pfe-chip-statistics": {
        "input-checksum": "0",
        "output-mtu": "0"
      }
   }
}
</code>```

Body:
I have the following json:

{
    "pfe-statistics" : [
    {
        "pfe-traffic-statistics" : [
        {
            "pfe-input-packets" : [
            {
                "data" : "3895887"
            }
            ],
            "input-pps" : [
            {
                "data" : "0"
            }
            ],
            "pfe-output-packets" : [
            {
                "data" : "1114541"
            }
            ],
            "output-pps" : [
            {
                "data" : "0"
            }
            ]
        }
        ],
        "pfe-local-traffic-statistics" : [
        {
            "pfe-input-packets" : [
            {
                "data" : "3893502"
            }
            ],
            "pfe-output-packets" : [
            {
                "data" : "1114541"
            }
            ],
            "software-input-control-drops" : [
            {
                "data" : "0"
            }
            ],
            "software-input-high-drops" : [
            {
                "data" : "0"
            }
            ],
            "software-input-medium-drops" : [
            {
                "data" : "0"
            }
            ],
            "software-input-low-drops" : [
            {
                "data" : "0"
            }
            ],
            "software-output-low-drops" : [
            {
                "data" : "0"
            }
            ],
            "hardware-input-drops" : [
            {
                "data" : "0"
            }
            ]
        }
        ],
        "pfe-local-protocol-statistics" : [
        {
            "hdlc-keepalive-count" : [
            {
                "data" : "0"
            }
            ],
            "atm-oam-count" : [
            {
                "data" : "0"
            }
            ],
            "fr-lmi-count" : [
            {
                "data" : "0"
            }
            ],
            "ppp-lcp-ncp-count" : [
            {
                "data" : "0"
            }
            ],
            "ospf-hello-count" : [
            {
                "data" : "0"
            }
            ],
            "ospf3-hello-count" : [
            {
                "data" : "0"
            }
            ],
            "rsvp-hello-count" : [
            {
                "data" : "0"
            }
            ],
            "ldp-hello-count" : [
            {
                "data" : "0"
            }
            ],
            "bfd-count" : [
            {
                "data" : "0"
            }
            ],
            "isis-iih-count" : [
            {
                "data" : "0"
            }
            ],
            "lacp-count" : [
            {
                "data" : "0"
            }
            ],
            "arp-count" : [
            {
                "data" : "0"
            }
            ],
            "ether-oam-count" : [
            {
                "data" : "0"
            }
            ],
            "unknown-count" : [
            {
                "data" : "0"
            }
            ]
        }
        ],
        "pfe-hardware-discard-statistics" : [
        {
            "timeout-discard" : [
            {
                "data" : "0"
            }
            ],
            "truncated-key-discard" : [
            {
                "data" : "0"
            }
            ],
            "bits-to-test-discard" : [
            {
                "data" : "0"
            }
            ],
            "data-error-discard" : [
            {
                "data" : "0"
            }
            ],
            "stack-underflow-discard" : [
            {
                "data" : "0"
            }
            ],
            "stack-overflow-discard" : [
            {
                "data" : "0"
            }
            ],
            "bad-route-discard" : [
            {
                "data" : "0"
            }
            ],
            "nexthop-discard" : [
            {
                "data" : "0"
            }
            ],
            "invalid-iif-discard" : [
            {
                "data" : "0"
            }
            ],
            "info-cell-discard" : [
            {
                "data" : "0"
            }
            ],
            "fabric-discard" : [
            {
                "data" : "0"
            }
            ]
        }
        ],
        "pfe-chip-statistics" : [
        {
            "input-checksum" : [
            {
                "data" : "0"
            }
            ],
            "output-mtu" : [
            {
                "data" : "0"
            }
            ]
        }
        ]
    }
    ]
}

I want to generate the following:

{
    "pfe-statistics" :
    {
        "pfe-traffic-statistics" :
        {
            "pfe-input-packets" : "56601136",
            "input-pps" : "30",
            "pfe-output-packets" : "71427636",
            "output-pps" : "28",
            "pfe-fabric-input" : "0",
            "pfe-fabric-input-pps" : "0",
            "pfe-fabric-output" : "0",
            "pfe-fabric-output-pps" : "0"
        },
        "pfe-local-traffic-statistics" :
        {
            "pfe-input-packets" : "56226309",
            "pfe-output-packets" : "142458974",
            "software-input-control-drops" : "0",
            "software-input-high-drops" : "0",
            "software-input-medium-drops" : "0",
            "software-input-low-drops" : "0",
            "software-output-low-drops" : "0",
            "hardware-input-drops" : "0"
        },
        "pfe-local-protocol-statistics" :
        {
            "hdlc-keepalive-count" : "0",
            "atm-oam-count" : "0",
            "fr-lmi-count" : "0",
            "ppp-lcp-ncp-count" : "0",
            "ospf-hello-count" : "0",
            "ospf3-hello-count" : "0",
            "rsvp-hello-count" : "0",
            "ldp-hello-count" : "0",
            "bfd-count" : "49316136",
            "isis-iih-count" : "0",
            "lacp-count" : "0",
            "arp-count" : "433208",
            "ether-oam-count" : "0",
            "unknown-count" : "0"
        },
        "pfe-hardware-discard-statistics" :
        {
            "timeout-discard" : "0",
            "truncated-key-discard" : "0",
            "bits-to-test-discard" : "0",
            "data-error-discard" : "0",
            "tcp-header-error-discard" : "0",
            "stack-underflow-discard" : "0",
            "stack-overflow-discard" : "0",
            "bad-route-discard" : "0",
            "nexthop-discard" : "0",
            "invalid-iif-discard" : "0",
            "info-cell-discard" : "0",
            "fabric-discard" : "0"
        },
        "pfe-chip-statistics" :
        {
            "input-checksum" : "0",
            "output-mtu" : "0"
        }
    }
}

I wrote the following function but can't make get it to work 100 percent:

d = {}
l = []
def compact_json(df):
    for k, v in df.items():
        if isinstance(v, list):
            print("list")
            print(k)
            if "data" not in v[0].keys():
                val = v[0].keys()
                if val not in l:
                    l.append(k)
            compact_json(v[0])

            #d.update(k)
        if isinstance(v[0], dict):
            print("dict")
            if "data" in v[0].keys():
                print("if data yes")
                print(k, v[0]["data"])
                d1 = {k: v}
                #d[val] = v[0]["data"]
                d[k] = v[0]["data"]
            else:
                print("else no data")
                print(v[0])
                compact_json(v[0])

compact_json(df)
print("==============")
print(d)

I can only print leaves but not the branches. Note that I want to make it universal for multiple json, so nested depths can be different in all the forms.

Body:
You can use a nested dictionary comprehension:

result = {a:{j:{l:b['data'] for y in k for l, [b] in y.items()}
             for g in c for j, k in g.items()} for a, c in data.items()}

import json
print(json.dumps(result, indent=4))

Output:

{
  "pfe-statistics": {
     "pfe-traffic-statistics": {
        "pfe-input-packets": "3895887",
        "input-pps": "0",
        "pfe-output-packets": "1114541",
        "output-pps": "0"
    },
    "pfe-local-traffic-statistics": {
        "pfe-input-packets": "3893502",
        "pfe-output-packets": "1114541",
        "software-input-control-drops": "0",
        "software-input-high-drops": "0",
        "software-input-medium-drops": "0",
        "software-input-low-drops": "0",
        "software-output-low-drops": "0",
        "hardware-input-drops": "0"
    },
    "pfe-local-protocol-statistics": {
        "hdlc-keepalive-count": "0",
        "atm-oam-count": "0",
        "fr-lmi-count": "0",
        "ppp-lcp-ncp-count": "0",
        "ospf-hello-count": "0",
        "ospf3-hello-count": "0",
        "rsvp-hello-count": "0",
        "ldp-hello-count": "0",
        "bfd-count": "0",
        "isis-iih-count": "0",
        "lacp-count": "0",
        "arp-count": "0",
        "ether-oam-count": "0",
        "unknown-count": "0"
    },
    "pfe-hardware-discard-statistics": {
        "timeout-discard": "0",
        "truncated-key-discard": "0",
        "bits-to-test-discard": "0",
        "data-error-discard": "0",
        "stack-underflow-discard": "0",
        "stack-overflow-discard": "0",
        "bad-route-discard": "0",
        "nexthop-discard": "0",
        "invalid-iif-discard": "0",
        "info-cell-discard": "0",
        "fabric-discard": "0"
    },
    "pfe-chip-statistics": {
        "input-checksum": "0",
        "output-mtu": "0"
      }
   }
}


问:
HTTP request based on timestamp using Jmeter
I am trying to send HTTP requests using jmeter for which I am using a HTTP sampler. The http requests have a parameter TaskID and these parameters read from a CSV file. I just wanted to make changes on how the HTTP request will be send.

The CSV file looks like this

```<code>Time TaskID
9000 42353456
9000 53463464
9000 65475787
9300 42354366
9300 23423535
9600 43545756
9600 53463467
9600 23435346
</code>```

Now I want to send request based on the Time. For example in Time 9000 there are 3 TaskID. So I want to send 3 HTTP requests with those TaskIDs at a time. Similarly for the other Times as well. Any idea on how to do it?

Update:

答:
I created a minimal working example for one possible solution.

Basically I read the csv in a JSR223 Sampler and group it with following groovy code in "read csv" sampler:

```<code>import org.apache.jmeter.services.FileServer

current_dir = FileServer.getFileServer().getBaseDir().replace("\\","/")
csv_lines = new File(current_dir + "/test.csv").readLines()

times = []

csv_lines.each { line ->
    line = line.split(",")
    time = line[0]
    task_id = line[1]
    if (vars.getObject(time)){
        tasks = vars.getObject(time)
        tasks.add(task_id)
        vars.putObject(time, tasks)
    }
    else{
        times.add(time)
        vars.putObject(time, [task_id])
    }
}

times.eachWithIndex { time, i ->
    vars.put("time_" + (i+1), time)
    }
</code>```

Notes:

(i+1) is used because the ForEach Controller will not consider the 0th element

I used "," as csv separator and omitted the header line

the "initialize task_ids" sampler holds following code:

.

```<code>time = vars.get("time")
tasks = vars.getObject(time)

tasks.eachWithIndex {task, i ->
    vars.put(time + "_" + (i+1), task)
}
</code>```

I hope, this helps!

Body:
I am trying to send HTTP requests using jmeter for which I am using a HTTP sampler. The http requests have a parameter TaskID and these parameters read from a CSV file. I just wanted to make changes on how the HTTP request will be send.

The CSV file looks like this

Time TaskID
9000 42353456
9000 53463464
9000 65475787
9300 42354366
9300 23423535
9600 43545756
9600 53463467
9600 23435346

Now I want to send request based on the Time. For example in Time 9000 there are 3 TaskID. So I want to send 3 HTTP requests with those TaskIDs at a time. Similarly for the other Times as well. Any idea on how to do it?

Update:

Body:
I created a minimal working example for one possible solution.

Basically I read the csv in a JSR223 Sampler and group it with following groovy code in "read csv" sampler:

import org.apache.jmeter.services.FileServer

current_dir = FileServer.getFileServer().getBaseDir().replace("\\","/")
csv_lines = new File(current_dir + "/test.csv").readLines()

times = []

csv_lines.each { line ->
    line = line.split(",")
    time = line[0]
    task_id = line[1]
    if (vars.getObject(time)){
        tasks = vars.getObject(time)
        tasks.add(task_id)
        vars.putObject(time, tasks)
    }
    else{
        times.add(time)
        vars.putObject(time, [task_id])
    }
}

times.eachWithIndex { time, i ->
    vars.put("time_" + (i+1), time)
    }

Notes:

(i+1) is used because the ForEach Controller will not consider the 0th element

I used "," as csv separator and omitted the header line

the "initialize task_ids" sampler holds following code:

.

time = vars.get("time")
tasks = vars.getObject(time)

tasks.eachWithIndex {task, i ->
    vars.put(time + "_" + (i+1), task)
}

I hope, this helps!


问:
webpack: Critical dependency message
I'm getting this error when I load my components:

./~/@angular/core/@angular/core.es5.js
  5889:15-36 Critical dependency: the request of a dependency is an expression

Anyone could help out to figure out what does it mean?

答:
I got the same kind of message with typescript.js.

[...]/node_modules/typescript/lib/typescript.js 5123:41-60
Critical dependency: the request of a dependency is an expression

I understand that it have something to do with typescript.js file and the dynamic require written at line 5123 :

return { module: require(modulePath), modulePath: modulePath, error: undefined };
```

<p>I tried many times but I really don't know how to use the ContextReplacementPlugin to avoid this warning. </p>

<p>The warning appear when I use transpile from the typescript module</p>

<pre class="lang-js prettyprint-override"><code>import { transpile } from 'typescript';
</code>```

Does anyone have the same problem?

Title: webpack: Critical dependency message

Body:
I got the same kind of message with typescript.js.

[...]/node_modules/typescript/lib/typescript.js 5123:41-60
Critical dependency: the request of a dependency is an expression

I understand that it have something to do with typescript.js file and the dynamic require written at line 5123 :

return { module: require(modulePath), modulePath: modulePath, error: undefined };

I tried many times but I really don't know how to use the ContextReplacementPlugin to avoid this warning.

The warning appear when I use transpile from the typescript module

import { transpile } from 'typescript';

Does anyone have the same problem?


问:
Wget download pdf
I am trying to download a pdf file using wget.

When I do:

wget <url> it downloads a corrupted file however if I run wget -i test.txt with the pdf URL inside this test txt file it works and the file is not corrupted.

Does anyone know why?

From the logs I can see the following.

In the first case, it is downloading a note found page.

Length: 11322 (11K) [text/html] Saving to: ‘media.nl?id=39194.1’

In the second it is a proper pdf.

Length: 58272 (57K) [application/pdf] Saving to:
  ‘media.nl?id=39194&c=4667446&h=34c63dbaaa7adc7c8a33&_xt=.pdf’

Thanks,

答:
I got the same issue but I changed the command to this and then it worked fine when i tested it:

Wget —-no-check-certificate https://www.roofingsuppliesuk.co.uk/core/media/'media.nl?id=39194&c=4667446&h=34c63dbaaa7adc7c8a33&_xt=.pdf'

i just added single quotes beginning at 'media.nl.......pdf'

Make sure the file with same name doesnt exist. You dont need to add --no-check-certificate if you dont get self-signed certificate error

Title: Wget download pdf


问:
Oracle Select max where a certain key is matched
i'm working with oracle, plSql, i need to query a table and select the max id where a key is matched, now i have this query

```<code>select t.* from (
select  distinct (TO_CHAR(I.DATE, 'YYMMDD') || I.AUTH_CODE || I.AMOUNT || I.CARD_NUMBER)  as kies, I.SID as ids
from transactions I) t group by kies, ids order by ids desc;
</code>```

It's displaying this data

If i remove the ID from the query, it displays the distinct keys (in the query i use the alias KIES because keys was in blue, so i thought it might be a reserved word)

How can i display the max id (last one inserted) for every different key without displaying all the data like in the first image??

greetings.

答:
Do you just want aggregation?</p>

```<code>select thekey, max(sid)
from (select t.*,
             (TO_CHAR(t.DATE, 'YYMMDD') || t.AUTH_CODE || t.AMOUNT || t.CARD_NUMBER) as thekey,
             t.SID
      from transactions t
     ) t
group by thekey
order by max(ids) desc;
</code>```

Body:
i'm working with oracle, plSql, i need to query a table and select the max id where a key is matched, now i have this query

select t.* from (
select  distinct (TO_CHAR(I.DATE, 'YYMMDD') || I.AUTH_CODE || I.AMOUNT || I.CARD_NUMBER)  as kies, I.SID as ids
from transactions I) t group by kies, ids order by ids desc;

It's displaying this data

If i remove the ID from the query, it displays the distinct keys (in the query i use the alias KIES because keys was in blue, so i thought it might be a reserved word)

How can i display the max id (last one inserted) for every different key without displaying all the data like in the first image??

greetings.

Body:
Do you just want aggregation?

select thekey, max(sid)
from (select t.*,
             (TO_CHAR(t.DATE, 'YYMMDD') || t.AUTH_CODE || t.AMOUNT || t.CARD_NUMBER) as thekey,
             t.SID
      from transactions t
     ) t
group by thekey
order by max(ids) desc;