问:
Delete product Final total didn't reduced using php ajax
I am creating a ecommerce site for my final year project. I am ran into the problem with delete the product . if I delete product  product has been deleted from database success. but final total didn’t reduced what I tried so far I attached below along with screen shot image below.

Table

```<code> <div class="container">
                <table class="table table-striped" id="mytable">
                    <thead>
                    <tr>
                        <th>ProductID</th>
                        <th>Productname</th>
                        <th>Price</th>
                        <th>Qty</th>
                        <th>Amount</th>
                        <th>Delete</th>
                    </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
            </div>

        </div>

        <div style='text-align: right; margin:10px'>
            <label><h3>Total amount: </h3></label>
            <span style="font-size: 40px; color: #ff0911" id='total-amount'></span>
        </div>
</code>```

Display the Products

```<code><script>
getProducts();
function getProducts() {
    $.ajax({
        type: 'GET',
        url: 'all_cart.php',
        dataType: 'JSON',
        success: function(data) {
            data.forEach(function(element) {
                var id = element.id;
                var product_name = element.product_name;
                var price = element.price;
                $('#mytable tbody').after
                (
                    '<tr> ' +
                    '<td>' + id + '</td>' +
                    '<td>' + product_name + '</td>' +
                    '<td>' + price + '</td>' +
                    "<input type='hidden' class='price' name='price' value='" + price + "'>" +
                    '<td>' + "<input type = 'text' class='qty' name='qty' value='1'/>" + '</td>' +
                    '<td>' + "<input type = 'text' class='amount' id='amount' disabled/>" + '</td>' +

                    '<td>' +  " <Button type='button' class='btn btn-primary' onclick='deleteProduct(" + id + ")' >Delete</Button> " + '</td>' +
                    '</tr>');
            });
        },
        error: function(xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}
</code>```

delete product function

```<code>function deleteProduct(id) {
    $(this).find('deleteProduct').click(function(event) {
        deleteProduct($(event.currentTarget).parent('tr'));
    });
    var total = 0;
    $('.amount').each(function(e){
        total -= Number($(this).val());
    });
    $('#total-amount').text(total);
                $.ajax({
                    type: 'POST',
                    url: 'remove.php',
                    dataType: 'JSON',
                    data: {id: id},
                    success: function (data) {
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);

                    }
                });
}
</script>
</code>```

remove.php

```<code><?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    include "db.php";
    $conn = new mysqli($servername, $username, $password, $dbname);
    $stmt = $conn->prepare("delete from cart where id=?");
    $stmt->bind_param("s", $id);
    $id = $_POST["id"];
    if ($stmt->execute())
        {
            echo 1;
        }
    else
        {
                echo 0;
        }
        $stmt->close();
        }
?>
</code>```

答:
I think your issue is js-related more then php related. Since the remove.php files looks fine you may have a problem with AJAX.

```<code>function deleteProduct(id) {
$(this).find('deleteProduct').click(function(event) {
    deleteProduct($(event.currentTarget).parent('tr'));
});
</code>```

This looks weird already since you're using jquery "find" on a non-class. Maybe u forgot a dot? Should be $(this).find(".deleteProduct").... and if u do so remember to actually add the class.

Beside this when you delete your product via ajax you are never refreshing the table, so the product-row will still be present. When you calculate your total you are fetching your current table elements:

```<code> var total = 0;
$('.amount').each(function(e){
    total -= Number($(this).val());
});
</code>```

this will lead to incorrect values if you don't delete the row u're pressing delete onto.

```<code>$('#total-amount').text(total);
            $.ajax({
                type: 'POST',
                url: 'remove.php',
                dataType: 'JSON',
                data: {id: id},
                success: function (data) {
                },
                error: function (xhr, status, error) {
                    alert(xhr.responseText);

                }
            });
</code>```

You should add to the success callback function the part where you are calculating totals, but before that, you should delete the table row with something like $("....").remove();

Edit with correct code:
First of all bring the jquery delete button listener out of your delete function and make it like this:

```<code><script>
     $('.mydeletebtn').click(function(event) {
    deleteProduct($(this).data("rowid"));
    });
    function deleteProduct(id) {
     .....
    }
</code>```

Then modify the HTML output for the delete row changing it like this:

```<code>'<td>' +  " <Button type='button' class='mydeletebtn btn btn-primary' data-rowid="'+id+'" >Delete</Button> " + '</td>' +
</code>```

since you don't really need the onclick when u're using jquery. I modified it so that your rowid is passed as javascript data-attribute.

After all of this you need to actually handle the row delete + total update like this:

```<code>    var $parentRow = $(this).closest("tr");
                $.ajax({
                    type: 'POST',
                    url: 'remove.php',
                    dataType: 'JSON',
                    data: {id: id},
                    success: function (data) {
                        $parentRow.delete();
                        updateTotals();
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);

                    }
                });
</code>```

Your final JS should be something like this:

```<code><script>
function updateTotals(){
var total = 0;
    $('.amount').each(function(e){
        total -= Number($(this).val());
    });
$('#total-amount').text(total);
}
$('.mydeletebtn').click(function(event) {
        deleteProduct($(this).data("rowid"),$(this));
        });
function deleteProduct(rowid,$row) {
         var $parentRow = $(this).closest("tr");
                    $.ajax({
                        type: 'POST',
                        url: 'remove.php',
                        dataType: 'JSON',
                        data: {id: rowid},
                        success: function (data) {
                            $parentRow.delete();
                            updateTotals();
                        },
                        error: function (xhr, status, error) {
                            alert(xhr.responseText);

                        }
                    });
        }

</script
</code>```

Body:
I am creating a ecommerce site for my final year project. I am ran into the problem with delete the product . if I delete product  product has been deleted from database success. but final total didn’t reduced what I tried so far I attached below along with screen shot image below.

Table

                        ProductID
                        Productname
                        Price
                        Qty
                        Amount
                        Delete

Total amount:

Display the Products

remove.php

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    include "db.php";
    $conn = new mysqli($servername, $username, $password, $dbname);
    $stmt = $conn->prepare("delete from cart where id=?");
    $stmt->bind_param("s", $id);
    $id = $_POST["id"];
    if ($stmt->execute())
        {
            echo 1;
        }
    else
        {
                echo 0;
        }
        $stmt->close();
        }
?>

Body:
I think your issue is js-related more then php related. Since the remove.php files looks fine you may have a problem with AJAX.

function deleteProduct(id) {
$(this).find('deleteProduct').click(function(event) {
    deleteProduct($(event.currentTarget).parent('tr'));
});

This looks weird already since you're using jquery "find" on a non-class. Maybe u forgot a dot? Should be $(this).find(".deleteProduct").... and if u do so remember to actually add the class.

Beside this when you delete your product via ajax you are never refreshing the table, so the product-row will still be present. When you calculate your total you are fetching your current table elements:

 var total = 0;
$('.amount').each(function(e){
    total -= Number($(this).val());
});

this will lead to incorrect values if you don't delete the row u're pressing delete onto.

$('#total-amount').text(total);
            $.ajax({
                type: 'POST',
                url: 'remove.php',
                dataType: 'JSON',
                data: {id: id},
                success: function (data) {
                },
                error: function (xhr, status, error) {
                    alert(xhr.responseText);

                }
            });

You should add to the success callback function the part where you are calculating totals, but before that, you should delete the table row with something like $("....").remove();

Edit with correct code:
First of all bring the jquery delete button listener out of your delete function and make it like this:

<script>
     $('.mydeletebtn').click(function(event) {
    deleteProduct($(this).data("rowid"));
    });
    function deleteProduct(id) {
     .....
    }

Then modify the HTML output for the delete row changing it like this:

'<td>' +  " <Button type='button' class='mydeletebtn btn btn-primary' data-rowid="'+id+'" >Delete</Button> " + '</td>' +

since you don't really need the onclick when u're using jquery. I modified it so that your rowid is passed as javascript data-attribute.

After all of this you need to actually handle the row delete + total update like this:

    var $parentRow = $(this).closest("tr");
                $.ajax({
                    type: 'POST',
                    url: 'remove.php',
                    dataType: 'JSON',
                    data: {id: id},
                    success: function (data) {
                        $parentRow.delete();
                        updateTotals();
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);

                    }
                });

Your final JS should be something like this:

<script>
function updateTotals(){
var total = 0;
    $('.amount').each(function(e){
        total -= Number($(this).val());
    });
$('#total-amount').text(total);
}
$('.mydeletebtn').click(function(event) {
        deleteProduct($(this).data("rowid"),$(this));
        });
function deleteProduct(rowid,$row) {
         var $parentRow = $(this).closest("tr");
                    $.ajax({
                        type: 'POST',
                        url: 'remove.php',
                        dataType: 'JSON',
                        data: {id: rowid},
                        success: function (data) {
                            $parentRow.delete();
                            updateTotals();
                        },
                        error: function (xhr, status, error) {
                            alert(xhr.responseText);

                        }
                    });
        }

</script


来源: stackexchange

问:
Which part of MVC we consider while working with ReactJS
I am new to ReactJS, i know we can consider MVC while working with ReactJS. My Question is
ReactJS Focuses on which of the following part when considering MVC

Model

View

Controller

答:
React is a library and not a framework. This mean that it provides only the "V" of MVC.
And although it manages views, the paradigm at its base is composition and the architecture is Flux, where data flow isn't bidirectional (like MVC) but instead flows unidirectionally from top to bottom.

Ref: https://medium.com/of-all-things-tech-progress/understanding-mvc-architecture-with-react-6cd38e91fefd

ContentLicense: CC BY-SA 4.0


问:
Reasons for MovieClip to ignore Timeline code AS3
I have a custom class that is extended from MovieClip.  The class is basically creating a button that uses frame labels in the MovieClip to move between button states as mouse events are dispatched.  Each state (each approx 20 frames long) is terminated with a timeline stop().

This class has been used in numerous other projects, but after a certain point in my current application any buttons created as an extension of my button class stop executing the code on the timeline, and just play on a loop.  This includes any traces put into the timeline, but all code in the class still executes correctly, even the gotoAndPlay calls when the button state changes.

The strangest part is that no error is thrown by any of the misbehaving button instances on the stage.

What I need are suggestions of what could prevent any object that extends a certain class from executing timeline code without throwing an error.

Thanks!

UPDATE: This still has me stumped.  Our projects usually come in three parts: a lightweight preloader, a language and age gate, then the main application.  Each is loaded into the previous, each time using the current application domain.  After the main application has been loaded, any custom display object that extends MovieClip (directly or indirectly) will ignore any actionscript directly on its timeline.  The playhead can still be controlled though the class however.

UPDATE 2:  This is the code in the test button class that I have made.  Notice how there is nothing in it.

```<code>package com.test
{
    import flash.display.MovieClip;

    public class TestLabelButton extends MovieClip
    {
        public function TestLabelButton():void
        {

        }
    }
}
</code>```

Update 3:  So I've narrowed it down, but it's strange.  It seems that I can load my language gate into the preloader just fine, with the language gate being an swf with a custom document class that extends MovieClip. After that though, if I load any more SWFs that contain a custom doc class extending MovieClip it's like all subsequently instantiated MovieClips of extentions thereof loose all the code on their timelines.

答:
My recommendation is to design your movieclip button thing in such a way that any animations needed for the states are happening in their own clips, with their own looping timelines. In other words, each "state" of your button has one frame on the timeline of your button clip thing--no ordinary playing or looping on your main timeline. All playback head control is in your external class, and consists only of *gotoAndStop*s to control the main timeline, and possibly stop() and play() commands to start and stop timelines of the animation clips on each button state frame.

Bottom line, don't attempt to control the playback head of any clip from more than one place, because to do so is to invite weird, often hard-to-reproduce control conflict bugs.

Also, an error in your frame script will stop the Flash Player from executing frame scripts on that clip. Are you getting compile-time errors or warnings?

ContentLicense: CC BY-SA 3.0

Body:
I have a custom class that is extended from MovieClip.  The class is basically creating a button that uses frame labels in the MovieClip to move between button states as mouse events are dispatched.  Each state (each approx 20 frames long) is terminated with a timeline stop().

This class has been used in numerous other projects, but after a certain point in my current application any buttons created as an extension of my button class stop executing the code on the timeline, and just play on a loop.  This includes any traces put into the timeline, but all code in the class still executes correctly, even the gotoAndPlay calls when the button state changes.

The strangest part is that no error is thrown by any of the misbehaving button instances on the stage.

What I need are suggestions of what could prevent any object that extends a certain class from executing timeline code without throwing an error.

Thanks!

UPDATE: This still has me stumped.  Our projects usually come in three parts: a lightweight preloader, a language and age gate, then the main application.  Each is loaded into the previous, each time using the current application domain.  After the main application has been loaded, any custom display object that extends MovieClip (directly or indirectly) will ignore any actionscript directly on its timeline.  The playhead can still be controlled though the class however.

UPDATE 2:  This is the code in the test button class that I have made.  Notice how there is nothing in it.

package com.test
{
    import flash.display.MovieClip;

    public class TestLabelButton extends MovieClip
    {
        public function TestLabelButton():void
        {

        }
    }
}

Update 3:  So I've narrowed it down, but it's strange.  It seems that I can load my language gate into the preloader just fine, with the language gate being an swf with a custom document class that extends MovieClip. After that though, if I load any more SWFs that contain a custom doc class extending MovieClip it's like all subsequently instantiated MovieClips of extentions thereof loose all the code on their timelines.


问:
How to replace one value calculated by COUNT with another value in SELECT result?
Suppose there are two tables

```<code>shop        seller
------      -------
id          id
seller_id   seller_name
goods       sallary
</code>```

seller_id may be repeated, parts from seller.id may not be there at all. So, I need to get the result of the request consisting of saller_name and counting the number of stores on each seller. I did it like this

```<code>SELECT seller_name, COUNT(seller_id) AS shops FROM seller
LEFT JOIN shop ON seller.id = shop.seller_id GROUP BY seller_name.
</code>```

And it works. But the problem is that I need to replace all 0 in shops with the text 'none'.
I tried to do it through

```<code>REPLACE(COUNT(seller_id),0,"none")
</code>```

and with

```<code>CASE
WHEN COUNT(seller_id)=0 THEN "none"
ELSE COUNT(seller_id)
END
</code>```

But instead of the expected numbers and none, I get a random set of numbers and letters. How to do it?

答:
```<code>Point 1: REPLACE(COUNT(seller_id),0,"none") --It will replace all zero's with 'none'.
</code>```

Like your count is 10 it will return 1none  in output.

```<code>Point 2: CASE  WHEN COUNT(seller_id)=0 THEN "none" ELSE COUNT(seller_id) END--It will gives you conversion failed error.
</code>```

So you need you cast the count in varchar as given below.

```<code>   SELECT se.seller_name,
       (CASE WHEN COUNT(s.seller_id) = 0
            THEN 'none'
            ELSE CAST(COUNT(s.seller_id) AS VARCHAR(10))
        END) AS shops
FROM seller se LEFT JOIN
     shop s
     ON se.id = sh.seller_id
GROUP BY se.seller_name;
</code>```

Body:
Suppose there are two tables

shop        seller
------      -------
id          id
seller_id   seller_name
goods       sallary

seller_id may be repeated, parts from seller.id may not be there at all. So, I need to get the result of the request consisting of saller_name and counting the number of stores on each seller. I did it like this

SELECT seller_name, COUNT(seller_id) AS shops FROM seller
LEFT JOIN shop ON seller.id = shop.seller_id GROUP BY seller_name.

And it works. But the problem is that I need to replace all 0 in shops with the text 'none'.
I tried to do it through

REPLACE(COUNT(seller_id),0,"none")

and with

CASE
WHEN COUNT(seller_id)=0 THEN "none"
ELSE COUNT(seller_id)
END

But instead of the expected numbers and none, I get a random set of numbers and letters. How to do it?

Body:
Point 1: REPLACE(COUNT(seller_id),0,"none") --It will replace all zero's with 'none'.

Like your count is 10 it will return 1none  in output.

Point 2: CASE  WHEN COUNT(seller_id)=0 THEN "none" ELSE COUNT(seller_id) END--It will gives you conversion failed error.

So you need you cast the count in varchar as given below.

   SELECT se.seller_name,
       (CASE WHEN COUNT(s.seller_id) = 0
            THEN 'none'
            ELSE CAST(COUNT(s.seller_id) AS VARCHAR(10))
        END) AS shops
FROM seller se LEFT JOIN
     shop s
     ON se.id = sh.seller_id
GROUP BY se.seller_name;


问:
Does Botium box requires docker container to be killed on every system start
I've read the command for docker kill. Now exactly how to stop
all containers or kill the container?

Should I navigate to the Docker folder in program files in cmd, or should I navigate to botium folder which I created for botium box in cmd? Currently I have Docker desktop version.

I'm getting the below error:

I restarted the Docker desktop app

Cmd : navigated to botium folder which I created for botium box

entered : docker-compose -f docker-compose-all.yml up

Error was thrown

C:\Users\Ram\Documents\Botium>docker-compose -f
  docker-compose-all.yml up Starting botium_redis_1 ... botium_mysql_1
  is up-to-date Starting botium_prisma_1 ... error

ERROR: for botium_prisma_1  Cannot start service prisma: driver failed
  programming external connectivity on endpoint botStarting
  botium_redis_1  ... error lready allocated

ERROR: for botium_redis_1  Cannot start service redis: driver failed
  programming external connectivity on endpoint botium_redis_1
  (023c3f7d0101a509a677a2f5434b00f25a8e4d3e238166eae6e0c1678b81035b):
  Bind for 0.0.0.0:6379 failed: port is already allocated

ERROR: for prisma  Cannot start service prisma: driver failed
  programming external connectivity on endpoint botium_prisma_1
  (1ad423ca349cd5d987a082407c64c8300e2822a0e4c3bf6a63c4369705f1413a):
  Bind for 0.0.0.0:4466 failed: port is already allocated

ERROR: for redis  Cannot start service redis: driver failed
  programming external connectivity on endpoint botium_redis_1
  (023c3f7d0101a509a677a2f5434b00f25a8e4d3e238166eae6e0c1678b81035b):
  Bind for 0.0.0.0:6379 failed: port is already allocated ERROR:
  Encountered errors while bringing up the project.

However when I retried the http://127.0.0.1:4000/quickstart a couple of times
the botium box opened. But initially this was not opening.

答:
You don't have to navigate.

If you run using docker-compose, you can go to the directory where your docker-compose.yml file is located and run docker-compose down.

Without docker-compose, you have to run docker ps to list all currently running containers and find the name of the container to kill. You can use the CONTAINER ID or the NAMES. Then run docker kill <container name>.

Example:

```<code>$ docker ps
CONTAINER ID        IMAGE                              COMMAND                  CREATED             STATUS              PORTS                              NAMES
myId                myimage:2.5                       "/opt/command/ba…"        24 hours ago        Up About an hour    0.0.0.0:9000->9000/tcp             very_cool_name_1
$ docker kill very_cool_name_1
very_cool_name_1
$ docker ps
CONTAINER ID        IMAGE                              COMMAND                  CREATED             STATUS              PORTS                              NAMES
$
</code>```

Body:
You don't have to navigate.

If you run using docker-compose, you can go to the directory where your docker-compose.yml file is located and run docker-compose down.

Without docker-compose, you have to run docker ps to list all currently running containers and find the name of the container to kill. You can use the CONTAINER ID or the NAMES. Then run docker kill <container name>.

Example:

$ docker ps
CONTAINER ID        IMAGE                              COMMAND                  CREATED             STATUS              PORTS                              NAMES
myId                myimage:2.5                       "/opt/command/ba…"        24 hours ago        Up About an hour    0.0.0.0:9000->9000/tcp             very_cool_name_1
$ docker kill very_cool_name_1
very_cool_name_1
$ docker ps
CONTAINER ID        IMAGE                              COMMAND                  CREATED             STATUS              PORTS                              NAMES
$


答:
Just type below commands when you open your Powershell or Bash.

To stop all running containers:

```<code>docker stop $(docker ps -q)
</code>```

To remove all containers:

```<code>docker rm $(docker ps -qa)
</code>```

Please note that rm will just remove your container not the Docker image. If your want to delete an image then you can use: docker rmi -f container_id

Title: Does Botium box requires docker container to be killed on every system start

Body:
I've read the command for docker kill. Now exactly how to stop
all containers or kill the container?

Should I navigate to the Docker folder in program files in cmd, or should I navigate to botium folder which I created for botium box in cmd? Currently I have Docker desktop version.

I'm getting the below error:

I restarted the Docker desktop app

Cmd : navigated to botium folder which I created for botium box

entered : docker-compose -f docker-compose-all.yml up

Error was thrown

C:\Users\Ram\Documents\Botium>docker-compose -f
  docker-compose-all.yml up Starting botium_redis_1 ... botium_mysql_1
  is up-to-date Starting botium_prisma_1 ... error

ERROR: for botium_prisma_1  Cannot start service prisma: driver failed
  programming external connectivity on endpoint botStarting
  botium_redis_1  ... error lready allocated

ERROR: for botium_redis_1  Cannot start service redis: driver failed
  programming external connectivity on endpoint botium_redis_1
  (023c3f7d0101a509a677a2f5434b00f25a8e4d3e238166eae6e0c1678b81035b):
  Bind for 0.0.0.0:6379 failed: port is already allocated

ERROR: for prisma  Cannot start service prisma: driver failed
  programming external connectivity on endpoint botium_prisma_1
  (1ad423ca349cd5d987a082407c64c8300e2822a0e4c3bf6a63c4369705f1413a):
  Bind for 0.0.0.0:4466 failed: port is already allocated

ERROR: for redis  Cannot start service redis: driver failed
  programming external connectivity on endpoint botium_redis_1
  (023c3f7d0101a509a677a2f5434b00f25a8e4d3e238166eae6e0c1678b81035b):
  Bind for 0.0.0.0:6379 failed: port is already allocated ERROR:
  Encountered errors while bringing up the project.

However when I retried the http://127.0.0.1:4000/quickstart a couple of times
the botium box opened. But initially this was not opening.

Body:
Just type below commands when you open your Powershell or Bash.

To stop all running containers:

docker stop $(docker ps -q)

To remove all containers:

docker rm $(docker ps -qa)

Please note that rm will just remove your container not the Docker image. If your want to delete an image then you can use: docker rmi -f container_id


问:
Background Image need to give innner div space
I would like to give a space of repeating background.

Tried Code :

#bg_img {
  background-image: url("https://image.freepik.com/free-vector/diagonal-lines-vector-background-design_1017-12303.jpg");
  background-repeat: repeat;
  background-position: left center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bg_img">
  <div id="tbles">
    <table width="100%" cellspacing="0" cellpadding="0" border="1">
      <tbody>
        <tr>
          <td width="4%" align="center"><strong>No</strong></td>
          <td style="min-width:25%" align="center"><strong>Name</strong></td>
          <td style="min-width:11%" align="center"><strong>Unit</strong></td>
          <td style="width:11%" align="center"><strong>Unit Price</strong></td>
        </tr>
        <tr>
          <td class="materialRow" align="center">1.</td>
          <td class="materialRow" align="left"><strong>Banana 1</strong><br>
            <font style="font-size:11px;">FIRE BARRIER CAULK</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">780.00</td>
        </tr>
        <tr>
          <td class="materialRow" align="center">2.</td>
          <td class="materialRow" align="left"><strong>Banana 2</strong><br>
            <font style="font-size:11px;">INTUMESCENT STRIP</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">73,600.00</td>
        </tr>
        <tr>
          <td class="materialRow" align="center">3.</td>
          <td class="materialRow" align="left"><strong>Banana 3</strong><br>
            <font style="font-size:11px;">STAINLESS STEEL HOOP</font>
          </td>
          <td class="materialRow" align="center">25.00</td>
          <td class="materialRow" align="center">Test</td>

        </tr>
        <tr>
          <td class="materialRow" align="center">4.</td>
          <td class="materialRow" align="left"><strong>Banana 4</strong><br>
            <font style="font-size:11px;">COATED FIRESTOP BOARD</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">125.00</td>
        </tr>
        <tr>
          <td class="materialRow" align="center">5.</td>
          <td class="materialRow" align="left"><strong>Banana 5</strong><br>
            <font style="font-size:11px;">MORTAR</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">185.00</td>
        </tr>
      </tbody>
    </table>
  </div>
</div></code>```

Is it possible to display Background Images on specific Area only with using backgroud space, margin or padding?

Actual Result :

Expected Result :

答:
No need to add extra empty element, you can consider multiple background where you can add white layers above the background to control the space. Simply adjust the background-size of each layer to reduce/increase the space:

#bg_img {
  background:
    linear-gradient(#fff,#fff) left  /2% 100% no-repeat,
    linear-gradient(#fff,#fff) right /2% 100% no-repeat,
    linear-gradient(#fff,#fff) top   /100% 25px no-repeat,
    linear-gradient(#fff,#fff) bottom/100% 10px no-repeat,
    url("https://image.freepik.com/free-vector/diagonal-lines-vector-background-design_1017-12303.jpg");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bg_img">
  <div id="tbles">
    <table width="100%" cellspacing="0" cellpadding="0" border="1">
      <tbody>
        <tr>
          <td width="4%" align="center"><strong>No</strong></td>
          <td style="min-width:25%" align="center"><strong>Name</strong></td>
          <td style="min-width:11%" align="center"><strong>Unit</strong></td>
          <td style="width:11%" align="center"><strong>Unit Price</strong></td>
        </tr>
        <tr>
          <td class="materialRow" align="center">1.</td>
          <td class="materialRow" align="left"><strong>Banana 1</strong><br>
            <font style="font-size:11px;">FIRE BARRIER CAULK</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">780.00</td>
        </tr>
        <tr>
          <td class="materialRow" align="center">2.</td>
          <td class="materialRow" align="left"><strong>Banana 2</strong><br>
            <font style="font-size:11px;">INTUMESCENT STRIP</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">73,600.00</td>
        </tr>
        <tr>
          <td class="materialRow" align="center">3.</td>
          <td class="materialRow" align="left"><strong>Banana 3</strong><br>
            <font style="font-size:11px;">STAINLESS STEEL HOOP</font>
          </td>
          <td class="materialRow" align="center">25.00</td>
          <td class="materialRow" align="center">Test</td>

        </tr>
        <tr>
          <td class="materialRow" align="center">4.</td>
          <td class="materialRow" align="left"><strong>Banana 4</strong><br>
            <font style="font-size:11px;">COATED FIRESTOP BOARD</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">125.00</td>
        </tr>
        <tr>
          <td class="materialRow" align="center">5.</td>
          <td class="materialRow" align="left"><strong>Banana 5</strong><br>
            <font style="font-size:11px;">MORTAR</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">185.00</td>
        </tr>
      </tbody>
    </table>
  </div>
</div></code>```

Body:
I would like to give a space of repeating background.

Tried Code :

#bg_img {
  background-image: url("https://image.freepik.com/free-vector/diagonal-lines-vector-background-design_1017-12303.jpg");
  background-repeat: repeat;
  background-position: left center;
}

          No
          Name
          Unit
          Unit Price

          1.
          Banana 1

            FIRE BARRIER CAULK

          Test
          780.00

          2.
          Banana 2

            INTUMESCENT STRIP

          Test
          73,600.00

          3.
          Banana 3

            STAINLESS STEEL HOOP

          25.00
          Test

          4.
          Banana 4

            COATED FIRESTOP BOARD

          Test
          125.00

          5.
          Banana 5

            MORTAR

          Test
          185.00

Is it possible to display Background Images on specific Area only with using backgroud space, margin or padding?

Actual Result :

Expected Result :

Body:
No need to add extra empty element, you can consider multiple background where you can add white layers above the background to control the space. Simply adjust the background-size of each layer to reduce/increase the space:

#bg_img {
  background:
    linear-gradient(#fff,#fff) left  /2% 100% no-repeat,
    linear-gradient(#fff,#fff) right /2% 100% no-repeat,
    linear-gradient(#fff,#fff) top   /100% 25px no-repeat,
    linear-gradient(#fff,#fff) bottom/100% 10px no-repeat,
    url("https://image.freepik.com/free-vector/diagonal-lines-vector-background-design_1017-12303.jpg");
}

<div id="bg_img">
  <div id="tbles">
    <table width="100%" cellspacing="0" cellpadding="0" border="1">
      <tbody>
        <tr>
          <td width="4%" align="center"><strong>No</strong></td>
          <td style="min-width:25%" align="center"><strong>Name</strong></td>
          <td style="min-width:11%" align="center"><strong>Unit</strong></td>
          <td style="width:11%" align="center"><strong>Unit Price</strong></td>
        </tr>
        <tr>
          <td class="materialRow" align="center">1.</td>
          <td class="materialRow" align="left"><strong>Banana 1</strong><br>
            <font style="font-size:11px;">FIRE BARRIER CAULK</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">780.00</td>
        </tr>
        <tr>
          <td class="materialRow" align="center">2.</td>
          <td class="materialRow" align="left"><strong>Banana 2</strong><br>
            <font style="font-size:11px;">INTUMESCENT STRIP</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">73,600.00</td>
        </tr>
        <tr>
          <td class="materialRow" align="center">3.</td>
          <td class="materialRow" align="left"><strong>Banana 3</strong><br>
            <font style="font-size:11px;">STAINLESS STEEL HOOP</font>
          </td>
          <td class="materialRow" align="center">25.00</td>
          <td class="materialRow" align="center">Test</td>

        </tr>
        <tr>
          <td class="materialRow" align="center">4.</td>
          <td class="materialRow" align="left"><strong>Banana 4</strong><br>
            <font style="font-size:11px;">COATED FIRESTOP BOARD</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">125.00</td>
        </tr>
        <tr>
          <td class="materialRow" align="center">5.</td>
          <td class="materialRow" align="left"><strong>Banana 5</strong><br>
            <font style="font-size:11px;">MORTAR</font>
          </td>
          <td class="materialRow" align="center">Test</td>
          <td class="materialRow" align="center">185.00</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>


问:
Declare is not valid at this position, expecting
Have Declares which are giving unbefore seen errors, that have attempted to find the solution of. As well as weird as have previous procedures which use same syntax but do not throw any errors

This is for a procedure which uses cursors to retrieve information from a table, then insert it into another table, which is done so that the information within may be used to be able calculate a total, which is passed along along with some required values

```<code>BEGIN
     DECLARE fin INT DEFAULT FALSE;
     DECLARE pol VARCHAR(30) default '';
     DECLARE total_accrued decimal(20,2) DEFAULT '0.00';
     DECLARE total_paid decimal(20,2) DEFAULT '0';
     DECLARE TOTAL DECIMAL(20,2) DEFAULT '0.00';
     DECLARE user_pol varchar(45) default '';

     DECLARE c3 CURSOr FOR SELECT total_accrued FROM fn_policy_mast;
     DECLARE c4 CURSOR FOr SELECT total_amount_paid FROM fn_policy_mast;
     DECLARE c2 CURSOR FOR SELECt policy_number FROM fn_policy_mast;
     DECLARE c1 CURSOr FOR SELECT balance FROM fn_policy_mast;

    -- DECLARE d_policy CURSOR FOR SELECT DISTINCT cod_policy FROM fn_policy_mast;
     DECLARE CONTINUE HANDLER FOR NOT FOUND SET fin = TRUE;

     OPEN c1;
     OPEN c2;
     OPEN c3;
     OPEN c4;
    -- OPEN d_policy;

     read_loop: LOOP

     FETCH c3 INTO total_accrued;
     FETCH c4 INTO total_paid;
     FETCH c2 INTO pol;
     set total = 0;
    -- FETCH d_policy INTO user_pol;

     -- IF user_pol = pol then
      set total_accrued = (SELECT SUM(monthly_premium) FROM col_trans_log WHERE policy_number LIKE pol);
      set total_paid = (SELECT SUM(transaction_amount) FROM col_Trans_log WHERE policy_number LIKE pol);

      set total =  total_paid - total_accrued;
     -- END IF;

    -- set TOTAL = (total_accrued-total_paid);
     UPDATE fn_policy_mast set balance = TOTAL WHERE policy_number like pol;

     IF fin=TRUE THEN
        LEAVE read_loop;
     END IF;

     -- INSERT STATEMENTS HERE
    --  set total = 0;
     END LOOP;
     select * FROM fn_policy_mast;
     close c1;
     close c2;
     CLOSE c3;
     CLOSE c4;

END//
DELIMITER ;````

Expected result to run, accepting the declares, actual experience is thaere is some form of syntax wrong, as it does not properly recognise the declare statements

This is the error message : Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5

```

答:
```<code>DECLARE total_paid decimal(20,2) DEFAULT '0'
</code>```

Is this the line?
Have you tried changing the default to '0.00' ?

Body:
Have Declares which are giving unbefore seen errors, that have attempted to find the solution of. As well as weird as have previous procedures which use same syntax but do not throw any errors

This is for a procedure which uses cursors to retrieve information from a table, then insert it into another table, which is done so that the information within may be used to be able calculate a total, which is passed along along with some required values

BEGIN
     DECLARE fin INT DEFAULT FALSE;
     DECLARE pol VARCHAR(30) default '';
     DECLARE total_accrued decimal(20,2) DEFAULT '0.00';
     DECLARE total_paid decimal(20,2) DEFAULT '0';
     DECLARE TOTAL DECIMAL(20,2) DEFAULT '0.00';
     DECLARE user_pol varchar(45) default '';

     DECLARE c3 CURSOr FOR SELECT total_accrued FROM fn_policy_mast;
     DECLARE c4 CURSOR FOr SELECT total_amount_paid FROM fn_policy_mast;
     DECLARE c2 CURSOR FOR SELECt policy_number FROM fn_policy_mast;
     DECLARE c1 CURSOr FOR SELECT balance FROM fn_policy_mast;

    -- DECLARE d_policy CURSOR FOR SELECT DISTINCT cod_policy FROM fn_policy_mast;
     DECLARE CONTINUE HANDLER FOR NOT FOUND SET fin = TRUE;

     OPEN c1;
     OPEN c2;
     OPEN c3;
     OPEN c4;
    -- OPEN d_policy;

     read_loop: LOOP

     FETCH c3 INTO total_accrued;
     FETCH c4 INTO total_paid;
     FETCH c2 INTO pol;
     set total = 0;
    -- FETCH d_policy INTO user_pol;

     -- IF user_pol = pol then
      set total_accrued = (SELECT SUM(monthly_premium) FROM col_trans_log WHERE policy_number LIKE pol);
      set total_paid = (SELECT SUM(transaction_amount) FROM col_Trans_log WHERE policy_number LIKE pol);

      set total =  total_paid - total_accrued;
     -- END IF;

    -- set TOTAL = (total_accrued-total_paid);
     UPDATE fn_policy_mast set balance = TOTAL WHERE policy_number like pol;

     IF fin=TRUE THEN
        LEAVE read_loop;
     END IF;

     -- INSERT STATEMENTS HERE
    --  set total = 0;
     END LOOP;
     select * FROM fn_policy_mast;
     close c1;
     close c2;
     CLOSE c3;
     CLOSE c4;

END//
DELIMITER ;````

Expected result to run, accepting the declares, actual experience is thaere is some form of syntax wrong, as it does not properly recognise the declare statements

This is the error message : Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5

Body:
DECLARE total_paid decimal(20,2) DEFAULT '0'

Is this the line?
Have you tried changing the default to '0.00' ?


问:
VT-x is not available (VERR_VMX_NO_VMX) when vagrant up
I am hitting error above. I am running windows 7 and virtual box version 5.2.22

vtx is enabled as the picture shown below. I have checked from the bios and it's has enabled.

i have click the option when i run virtual box too

Somehow i still hitting the error when i run vagrant up

refer to the VMware below, the VTX is enable running on the same windows but this is not the case for virtual box.

Base on the link below, it shows that that is the limitation of virtual box. Not sure anyone has workaround or solve this issue
CentOS guest in Debian guest on Windows 7 host: "VT-x is not available (VERR_VMX_NO_VMX)"

答: You might have Hyper-V enabled. It is usually needed for the Docker. Try disabling it via Control Panel -> Programs and Features -> Turn Windows features on or off -> Hyper - V. Windows restart is required.


问:
Google sheet =getId() script failing for some copied sheets
I'm using this script to return the ID of an open spreadsheet:

```<code>    function getId() {
        SpreadsheetApp.getActiveSpreadsheet().getId()
    }
</code>```

In the cell, I've added:

```<code>    =getId()
</code>```

The problem is, when I copy the spreadsheet, the new spreadsheet returns the ID for the original spreadsheet - not the ID for the active  sheet.

If I enter =getId() in a new cell in the active sheet, it returns the correct ID. So the script is apparently working, it's not just not 'refreshing' the data for a copied sheet.

(Bizarrely, this has worked before! I don't know what's changed but it's stopped returning a new ID value.)

Can anyone suggest how to make sure the ID for the active sheet is shown?

答:
Your code for function getId() didn't work for me when calling from a cell using =getId(), it's not returning anything at all.

Try this instead:

```<code>function getId() {
  var id = SpreadsheetApp.getActiveSpreadsheet().getId();
  return id;
}
</code>```

This should return the Spreadsheet ID using the formula, I've tested making a copy of the sheet and it updates as expected.

Body:
I'm using this script to return the ID of an open spreadsheet:

    function getId() {
        SpreadsheetApp.getActiveSpreadsheet().getId()
    }

In the cell, I've added:

    =getId()

The problem is, when I copy the spreadsheet, the new spreadsheet returns the ID for the original spreadsheet - not the ID for the active  sheet.

If I enter =getId() in a new cell in the active sheet, it returns the correct ID. So the script is apparently working, it's not just not 'refreshing' the data for a copied sheet.

(Bizarrely, this has worked before! I don't know what's changed but it's stopped returning a new ID value.)

Can anyone suggest how to make sure the ID for the active sheet is shown?

Body:
Your code for function getId() didn't work for me when calling from a cell using =getId(), it's not returning anything at all.

Try this instead:

function getId() {
  var id = SpreadsheetApp.getActiveSpreadsheet().getId();
  return id;
}

This should return the Spreadsheet ID using the formula, I've tested making a copy of the sheet and it updates as expected.


问:
Word frequency count Java 8
How to count the frequency of words of List in Java 8?

```<code>List <String> wordsList = Lists.newArrayList("hello", "bye", "ciao", "bye", "ciao");
</code>```

The result must be:

```<code>{ciao=2, hello=1, bye=2}
</code>```

答:
```<code>public class Main {

    public static void main(String[] args) {

        String testString ="qqwweerrttyyaaaaaasdfasafsdfadsfadsewfywqtedywqtdfewyfdweytfdywfdyrewfdyewrefdyewdyfwhxvsahxvfwytfx";
        long java8Case2 = testString.codePoints().filter(ch -> ch =='a').count();
        System.out.println(java8Case2);

        ArrayList<Character> list = new ArrayList<Character>();
        for (char c : testString.toCharArray()) {
          list.add(c);
        }
        Map<Object, Integer> counts = list.parallelStream().
            collect(Collectors.toConcurrentMap(
                w -> w, w -> 1, Integer::sum));
        System.out.println(counts);
    }

}
</code>```

Title: Word frequency count Java 8

Body:
How to count the frequency of words of List in Java 8?

List <String> wordsList = Lists.newArrayList("hello", "bye", "ciao", "bye", "ciao");

The result must be:

{ciao=2, hello=1, bye=2}


问:
Camera connection and disconnection catch
Hey guys,
I'm using OpenCV with the C++ API, and in order for my project to be more reliable I need a certain camera connection\disconnection handling.
I have searched for how-to's, but I could only find answers that require an ugly hack in order to do so.

Can you suggest a cleaner way to do it?

Thnx

答:
Detecting camera connection/disconnection might require some tricks.

I suggest that you start another thread to check the success of cvCreateCameraCapture() in a loop, while your application is running.

Something like the following:

```<code>while (run_detection_thread) // global variable controlled by the main thread
{
  CvCapture* capture = cvCreateCameraCapture(-1); //-1 or whatever number works for you
  if (camera) //camera is connected
  {
    sleep(1);
  }
  else
  {
    // camera was disconnected
  }
}
</code>```

Body:
Detecting camera connection/disconnection might require some tricks.

I suggest that you start another thread to check the success of cvCreateCameraCapture() in a loop, while your application is running.

Something like the following:

while (run_detection_thread) // global variable controlled by the main thread
{
  CvCapture* capture = cvCreateCameraCapture(-1); //-1 or whatever number works for you
  if (camera) //camera is connected
  {
    sleep(1);
  }
  else
  {
    // camera was disconnected
  }
}


问:
Cookie not set when localhost web app accesses remote API
I have a React web app served on http://localhost:3000.

This web app accesses a remote API i.e. https://app.example.com/api.

When performing a login on the API, the server returns a session Cookie like this one:

```<code>Set-Cookie: JSESSIONID=ZmQ2Yzg4OWYtYzdiNi00Mzc1LTkzMzUtYzhiZjZmM2MzZjMy; Domain=app.example.com; Path=/api/; Secure; HttpOnly; SameSite=Lax
</code>```

However, on Chrome, the Set-Cookie doesn't appear in the list of response headers. Also, if I re send the same request, Chrome doesn't include the Cookie in the request headers.

So, my understanding is that it ignores the Cookie. Why?

Regarding CORS, I don't see any issue with it, and the request is sent correctly by Chrome. Here are the returned CORS headers in the preflight:

```<code>Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: PATCH,GET,POST,PUT,DELETE
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Expose-Headers: ETag, X-XSRF-TOKEN
</code>```

I tried adding a local DNS entry app.me pointig to 127.0.0.1 but still doesn't work.

I also tried with Edge, and I can see the Set-Cookie header appearing, however, the cookie doesn't appear to be set too.

EDIT:

This it the Axios code:

const axios = require('axios');

const backendUrl = 'https://app.example.com/api';
const constructUrl = url => `${backendUrl}${url}`;

const axiosConfig = {
  withCredentials: true,
};

export default {
  get: url => axios.get(constructUrl(url), axiosConfig),
  post: (url, data) => axios.post(constructUrl(url), data, axiosConfig),
  put: (url, data) => axios.put(constructUrl(url), data, axiosConfig),
  delete: (url, data) => axios.delete(constructUrl(url), data, axiosConfig),
};

//And in a different file...

HttpService.post('/login', creds)
        .then((response) => {
          const userInfo = response.data;
          const token = response.headers['x-xsrf-token'];
          sessionStorage.setItem('user-info', JSON.stringify(userInfo));
          sessionStorage.setItem('user-xsrf-token', JSON.stringify(token));

          window.location.replace('/');
        })
        .catch((err) => {
          if (err.response.status === 401) {
            setLoginError('Bad cred');
          } else {
            setLoginError('Fail to auth');
          }
        });
```

答:
First, for some reason, I can't make Chrome show cookies associated to other domains than the one mentioned inside the address bar. So, inside the address bar, I have http://localhost:3000 and I'm not able to see cookies associated with app.example.com.
Also, the dev tools don't show the Set-Cookie (response) and Cookie (request) for the same reason. But that doesn't mean the cookie is not received and set.

However, in my case, the cookie wasn't set because of the presence of SameSite=Lax.

After removing this cookie attribute, the cookie is set and included in the next requests.

Body:
I have a React web app served on http://localhost:3000.

This web app accesses a remote API i.e. https://app.example.com/api.

When performing a login on the API, the server returns a session Cookie like this one:

Set-Cookie: JSESSIONID=ZmQ2Yzg4OWYtYzdiNi00Mzc1LTkzMzUtYzhiZjZmM2MzZjMy; Domain=app.example.com; Path=/api/; Secure; HttpOnly; SameSite=Lax

However, on Chrome, the Set-Cookie doesn't appear in the list of response headers. Also, if I re send the same request, Chrome doesn't include the Cookie in the request headers.

So, my understanding is that it ignores the Cookie. Why?

Regarding CORS, I don't see any issue with it, and the request is sent correctly by Chrome. Here are the returned CORS headers in the preflight:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: PATCH,GET,POST,PUT,DELETE
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Expose-Headers: ETag, X-XSRF-TOKEN

I tried adding a local DNS entry app.me pointig to 127.0.0.1 but still doesn't work.

I also tried with Edge, and I can see the Set-Cookie header appearing, however, the cookie doesn't appear to be set too.

EDIT:

This it the Axios code:

const axios = require('axios');

const backendUrl = 'https://app.example.com/api';
const constructUrl = url => `${backendUrl}${url}`;

const axiosConfig = {
  withCredentials: true,
};

export default {
  get: url => axios.get(constructUrl(url), axiosConfig),
  post: (url, data) => axios.post(constructUrl(url), data, axiosConfig),
  put: (url, data) => axios.put(constructUrl(url), data, axiosConfig),
  delete: (url, data) => axios.delete(constructUrl(url), data, axiosConfig),
};

//And in a different file...

HttpService.post('/login', creds)
        .then((response) => {
          const userInfo = response.data;
          const token = response.headers['x-xsrf-token'];
          sessionStorage.setItem('user-info', JSON.stringify(userInfo));
          sessionStorage.setItem('user-xsrf-token', JSON.stringify(token));

          window.location.replace('/');
        })
        .catch((err) => {
          if (err.response.status === 401) {
            setLoginError('Bad cred');
          } else {
            setLoginError('Fail to auth');
          }
        });


问:
How to ignore files from 'git status' if only white spaces and line breaks changed
I often push code with some tab instead of spaces or vice versa, or insert a line break to improve code readability. How do I tell git not to look for those changes?</p>

答:
When it comes to find non-white changes in your workspace, git diff really is your friend (as apposed to "git status"). git diff has a couple of options to tailor this, some of which are

```<code>--ignore-space-at-eol
--ignore-space-change / -b
--ignore-all-space / -w
</code>```

If you are interested in a git status-like list of changed files, you can issue

```<code>git diff --name-only
</code>```

Unfortunately, combining that with e.g. -w to see only files that contain non-white changes does not work (at least not in my current version of git, 2.15)

So what I came up with to achieve the latter, is to use the normal git diff -w command and then extract the file names:

```<code>git diff -w |grep "^--- a"
</code>```

This is taking advantage of the way git diff introduces the output of differences of a specific file, and is a tad simpler than other one-line scripts people suggested on this page.

One caveat: AFAIK inserting a line break in the middle of text (e.g. to improve code readability, as the OP describes) will never be ignored, as it is effectively replacing one line of text with two new lines.

Body:
When it comes to find non-white changes in your workspace, git diff really is your friend (as apposed to "git status"). git diff has a couple of options to tailor this, some of which are

--ignore-space-at-eol
--ignore-space-change / -b
--ignore-all-space / -w

If you are interested in a git status-like list of changed files, you can issue

git diff --name-only

Unfortunately, combining that with e.g. -w to see only files that contain non-white changes does not work (at least not in my current version of git, 2.15)

So what I came up with to achieve the latter, is to use the normal git diff -w command and then extract the file names:

git diff -w |grep "^--- a"

This is taking advantage of the way git diff introduces the output of differences of a specific file, and is a tad simpler than other one-line scripts people suggested on this page.

One caveat: AFAIK inserting a line break in the middle of text (e.g. to improve code readability, as the OP describes) will never be ignored, as it is effectively replacing one line of text with two new lines.


问:
hisafer installation - how do I solve hard-coded installation path?
I am installing the hisafer package (for biophysical modeling) following instructions from author(s) lead by Kevin Wolz:

```<code>install.packages("devtools")
devtools::install_github("kevinwolz/hisafer")
</code>```

here I got the answer:

```<code>...
write_param_file                        html
write_weather                           html
** building package indices
** installing vignettes
** testing if installed package can be loaded from temporary location
** testing if installed package can be loaded from final location
** testing if installed package keeps a record of temporary installation path
ERROR: hard-coded installation path: please report to the package maintainer and use '--no-staged-install'
* removing 'C:/Users/houska/Documents/R/R-3.6.0/library/hisafer'
Error in i.p(...) :
  (converted from warning) installation of package ‘C:/Users/houska/AppData/Local/Temp/RtmpI5hUAl/file32dc572b4098/hisafer_1.4.14.tar.gz’ had non-zero exit status
</code>```

the following commands do not work, then:

```<code>library(hisafer)
vignette("hisafer-vignette")
</code>```

What should I do to solve this problem?

答:
This is related to the staged installation of packages introduced with R 3.6.0. You can disable it by passing the --no-staged-install option to R CMD INSTALL (as suggested by the error message):

```<code>devtools::install_github("kevinwolz/hisafer", INSTALL_opts="--no-staged-install")
</code>```

Body:
I am installing the hisafer package (for biophysical modeling) following instructions from author(s) lead by Kevin Wolz:

install.packages("devtools")
devtools::install_github("kevinwolz/hisafer")

here I got the answer:

...
write_param_file                        html
write_weather                           html
** building package indices
** installing vignettes
** testing if installed package can be loaded from temporary location
** testing if installed package can be loaded from final location
** testing if installed package keeps a record of temporary installation path
ERROR: hard-coded installation path: please report to the package maintainer and use '--no-staged-install'
* removing 'C:/Users/houska/Documents/R/R-3.6.0/library/hisafer'
Error in i.p(...) :
  (converted from warning) installation of package ‘C:/Users/houska/AppData/Local/Temp/RtmpI5hUAl/file32dc572b4098/hisafer_1.4.14.tar.gz’ had non-zero exit status

the following commands do not work, then:

library(hisafer)
vignette("hisafer-vignette")

What should I do to solve this problem?

Body:
This is related to the staged installation of packages introduced with R 3.6.0. You can disable it by passing the --no-staged-install option to R CMD INSTALL (as suggested by the error message):

devtools::install_github("kevinwolz/hisafer", INSTALL_opts="--no-staged-install")


问:
Updating first 7 characters of string with another 3 characters using SQL, throws "Error 19 - UNIQUE constraint failed: MGOFile.File."
I have a rather simple DB with a column called File, and I need to remove the first 7 characters of each row, and replace with a new string. I thought I had the code sorted, but I am getting error "SQLite3 Error 19 - UNIQUE constraint failed: MGOFile.File."

My table name is MGOFile, and the column is File. This is a simple select statement on the first few rows, the left column is the raw data, the right is what I need the resultant rows to look like...

I query my table using this:

```<code>    '''sql
    SELECT
      File,
      'T:\'|| substr(File, 8,2000) as File
    FROM
      MGOFile
    WHERE
      file like 'M:\_TV%';
    '''
</code>```

I then tried updating using this:

```<code>    UPDATE MGOFile
    SET File = 'T:\' || substr(File, 8, 2000)
    WHERE File like 'M:\_TV%';
</code>```

But here is where my error comes in, this fails with an error:

I am sure I am doing something simple wrong, but I have done plenty of Googling but all responses are over my head, this is the most advanced SQL I have tried to do!

Any ideas on how to can update these strings with some simple SQLite?

答:
The error seems quite clear to me.  You are changing the file name to a name that is already in the table.

You can identify the duplicates by running:

```<code>SELECT f.*
FROM MGOFile f
WHERE EXISTS (SELECT 1
              FROM MGOFile f2
              WHERE f2.File = 'T:\'|| substr(File, 8,2000)
             ) AND
      f.file LIKE 'M:\_TV%';
</code>```

I don't know what you want to do about the duplicate.

Body:
I have a rather simple DB with a column called File, and I need to remove the first 7 characters of each row, and replace with a new string. I thought I had the code sorted, but I am getting error "SQLite3 Error 19 - UNIQUE constraint failed: MGOFile.File."

My table name is MGOFile, and the column is File. This is a simple select statement on the first few rows, the left column is the raw data, the right is what I need the resultant rows to look like...

I query my table using this:

    '''sql
    SELECT
      File,
      'T:\'|| substr(File, 8,2000) as File
    FROM
      MGOFile
    WHERE
      file like 'M:\_TV%';
    '''

I then tried updating using this:

    UPDATE MGOFile
    SET File = 'T:\' || substr(File, 8, 2000)
    WHERE File like 'M:\_TV%';

But here is where my error comes in, this fails with an error:

I am sure I am doing something simple wrong, but I have done plenty of Googling but all responses are over my head, this is the most advanced SQL I have tried to do!

Any ideas on how to can update these strings with some simple SQLite?

Body:
The error seems quite clear to me.  You are changing the file name to a name that is already in the table.

You can identify the duplicates by running:

SELECT f.*
FROM MGOFile f
WHERE EXISTS (SELECT 1
              FROM MGOFile f2
              WHERE f2.File = 'T:\'|| substr(File, 8,2000)
             ) AND
      f.file LIKE 'M:\_TV%';

I don't know what you want to do about the duplicate.


问:
How do I handle auto-generated IDs in a RESTful API?
When designing a RESTful API that uses a datastore that makes use of auto-generated IDs (and there aren't any reliable unique values otherwise), how do I specify an add (PUT) operation?

For example:

```<code>GET /widgets/
</code>```

Would return a list of all widgets.

```<code>GET /widgets/123
</code>```

Would return information for a specific widget.

```<code>POST /widgets/123
</code>```

Would update a widget.

But what's the URL for adding a widget?

```<code>PUT /widgets/???
</code>```

i.e., I (as the client) don't know the ID until I have added it.

答:
REST conventions typically specify a POST for creation and a PUT for updating. This is because PUT along with GET and DELETE are idempotent methods. Meaning that they can be run any number of times and the state of the server should be the same. POST is a non-idempotent action though, which means that the server state is not guaranteed to be the same after running the action each time.

Typically you would POST to the /widgets url to add an item.

See this for more detail.

Body:
When designing a RESTful API that uses a datastore that makes use of auto-generated IDs (and there aren't any reliable unique values otherwise), how do I specify an add (PUT) operation?

For example:

GET /widgets/

Would return a list of all widgets.

GET /widgets/123

Would return information for a specific widget.

POST /widgets/123

Would update a widget.

But what's the URL for adding a widget?

PUT /widgets/???

i.e., I (as the client) don't know the ID until I have added it.


问:
Trouble deserializing JSON (got value array when single value expected)
I am reading data from a graph database and getting the response as a dynamic object. I go through the results and try to deserialize them as so:

```<code>var e = results.GetEnumerator();

while (e.MoveNext())
{
    var serialized = JsonConvert.SerializeObject(e.Current);
    // {"FlagCalculateclientside":[false],"Description":["Some detailed info"], "Name": ["MyDetailedEntity"]}
    var val = JsonConvert.DeserializeObject<MyObject>(serialized);
}

public class MyObject
{
    public bool FlagCalculateclientside { get; set; }
    public string Description { get; set; }
    public string Name { get; set; }
}
</code>```

But I get the following error:

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: [. Path 'FlagCalculateclientside', line 1, position 28.
     at Newtonsoft.Json.JsonTextReader.ReadAsBoolean()
     at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
  ...

I guess this is because the values are in arrays, but only a single value per key was expected.

Any idea how to fix this?

答:
Your model doesn't match your JSON, all of the properties are arrays, in other words they are surround with [...]. To fix, change the model to this:

```<code>public class MyObject
{
    public List<bool> FlagCalculateclientside { get; set; }
    public List<string> Description { get; set; }
    public List<string> Name { get; set; }
}
</code>```

An alternative would be to use a custom converter, for example:

```<code>public class ArrayConverter<T> : JsonConverter<T>
{
    public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);

        //This isn't the best code but shows you what you need to do.
        return token.ToObject<List<T>>().First();
    }

    public override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
</code>```

And change your model to this:

```<code>public class MyObject
{
    [JsonConverter(typeof(ArrayConverter<bool>))]
    public bool FlagCalculateclientside { get; set; }

    [JsonConverter(typeof(ArrayConverter<string>))]
    public string Description { get; set; }

    [JsonConverter(typeof(ArrayConverter<string>))]
    public string Name { get; set; }
}
</code>```

Body:
I am reading data from a graph database and getting the response as a dynamic object. I go through the results and try to deserialize them as so:

var e = results.GetEnumerator();

while (e.MoveNext())
{
    var serialized = JsonConvert.SerializeObject(e.Current);
    // {"FlagCalculateclientside":[false],"Description":["Some detailed info"], "Name": ["MyDetailedEntity"]}
    var val = JsonConvert.DeserializeObject<MyObject>(serialized);
}

public class MyObject
{
    public bool FlagCalculateclientside { get; set; }
    public string Description { get; set; }
    public string Name { get; set; }
}

But I get the following error:

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: [. Path 'FlagCalculateclientside', line 1, position 28.
     at Newtonsoft.Json.JsonTextReader.ReadAsBoolean()
     at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
  ...

I guess this is because the values are in arrays, but only a single value per key was expected.

Any idea how to fix this?

Body:
Your model doesn't match your JSON, all of the properties are arrays, in other words they are surround with [...]. To fix, change the model to this:

public class MyObject
{
    public List<bool> FlagCalculateclientside { get; set; }
    public List<string> Description { get; set; }
    public List<string> Name { get; set; }
}

An alternative would be to use a custom converter, for example:

public class ArrayConverter<T> : JsonConverter<T>
{
    public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);

        //This isn't the best code but shows you what you need to do.
        return token.ToObject<List<T>>().First();
    }

    public override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

And change your model to this:

public class MyObject
{
    [JsonConverter(typeof(ArrayConverter<bool>))]
    public bool FlagCalculateclientside { get; set; }

    [JsonConverter(typeof(ArrayConverter<string>))]
    public string Description { get; set; }

    [JsonConverter(typeof(ArrayConverter<string>))]
    public string Name { get; set; }
}


问:
Parsing XML with namespace in Python via 'ElementTree'
I have the following XML which I want to parse using Python's ElementTree:

<rdf:RDF xml:base="http://dbpedia.org/ontology/"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:owl="http://www.w3.org/2002/07/owl#"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
    xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
    xmlns="http://dbpedia.org/ontology/">

    <owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague">
        <rdfs:label xml:lang="en">basketball league</rdfs:label>
        <rdfs:comment xml:lang="en">
          a group of sports teams that compete against each other
          in Basketball
        </rdfs:comment>
    </owl:Class>

</rdf:RDF>
```

<p>I want to find all <code>owl:Class</code> tags and then extract the value of all <code>rdfs:label</code> instances inside them. I am using the following code:</p>

<pre class="lang-py prettyprint-override"><code>tree = ET.parse("filename")
root = tree.getroot()
root.findall('owl:Class')
</code>```

Because of the namespace, I am getting the following error.

SyntaxError: prefix 'owl' not found in prefix map
```

I tried reading the document at http://effbot.org/zone/element-namespaces.htm but I am still not able to get this working since the above XML has multiple nested namespaces.

Kindly let me know how to change the code to find all the owl:Class tags.

答:
My solution is based on @Martijn Pieters' comment:

register_namespace only influences serialisation, not search.

So the trick here is to use different dictionaries for serialization and for searching.

```<code>namespaces = {
    '': 'http://www.example.com/default-schema',
    'spec': 'http://www.example.com/specialized-schema',
}
</code>```

Now, register all namespaces for parsing and writing:

```<code>for name, value in namespaces.iteritems():
    ET.register_namespace(name, value)
</code>```

For searching (find(), findall(), iterfind()) we need a non-empty prefix. Pass these functions a modified dictionary (here I modify the original dictionary, but this must be made only after the namespaces are registered).

```<code>self.namespaces['default'] = self.namespaces['']
</code>```

Now, the functions from the find() family can be used with the default prefix:

```<code>print root.find('default:myelem', namespaces)
</code>```

but

```<code>tree.write(destination)
</code>```

does not use any prefixes for elements in the default namespace.

Body:
I have the following XML which I want to parse using Python's ElementTree:

<rdf:RDF xml:base="http://dbpedia.org/ontology/"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:owl="http://www.w3.org/2002/07/owl#"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
    xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
    xmlns="http://dbpedia.org/ontology/">

    <owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague">
        <rdfs:label xml:lang="en">basketball league</rdfs:label>
        <rdfs:comment xml:lang="en">
          a group of sports teams that compete against each other
          in Basketball
        </rdfs:comment>
    </owl:Class>

</rdf:RDF>

I want to find all owl:Class tags and then extract the value of all rdfs:label instances inside them. I am using the following code:

tree = ET.parse("filename")
root = tree.getroot()
root.findall('owl:Class')

Because of the namespace, I am getting the following error.

SyntaxError: prefix 'owl' not found in prefix map

I tried reading the document at http://effbot.org/zone/element-namespaces.htm but I am still not able to get this working since the above XML has multiple nested namespaces.

Kindly let me know how to change the code to find all the owl:Class tags.

Body:
My solution is based on @Martijn Pieters' comment:

register_namespace only influences serialisation, not search.

So the trick here is to use different dictionaries for serialization and for searching.

namespaces = {
    '': 'http://www.example.com/default-schema',
    'spec': 'http://www.example.com/specialized-schema',
}

Now, register all namespaces for parsing and writing:

for name, value in namespaces.iteritems():
    ET.register_namespace(name, value)

For searching (find(), findall(), iterfind()) we need a non-empty prefix. Pass these functions a modified dictionary (here I modify the original dictionary, but this must be made only after the namespaces are registered).

self.namespaces['default'] = self.namespaces['']

Now, the functions from the find() family can be used with the default prefix:

print root.find('default:myelem', namespaces)

but

tree.write(destination)

does not use any prefixes for elements in the default namespace.


问:
JTree vertical scrollbars not working
I have a JTree embedded in a JScrollPane. When the JTree grows bigger than the display can show, the remainder of the tree is located at the bottom outside of the visible range. I expected the JScrollPane to start displaying vertical scrollbars if this happens so that you can scroll the remainder into view. The vertical scrollbars do not appear at all if the JTree is expanded and doesn't fit. Here is how it looks like:

I have both, the horizontal and vertical scrollbarPolicy set to as needed. I also tried embedding the JScrollPane containing the JTree into a JPanel but it didn't help. I'm using the UI designer in IntelliJ IDEA to build the GUI by the way.

Any help on making the vertical scrollbars behave as expected? Forcing them to be shown at all times also doesn't work: They cannot be dragged down regardless.

答:
not use preferredSize.
in UI designer choos JTree element, find property preferredSize and in context menu select Restore default value

Title: JTree vertical scrollbars not working


问:
Initialize array in Kotlin based on list size
I need to add LineChart(using MpAndroidChart) dynamically in LinearLayout.

I have declared an arrayList,named list.

```<code> val list = arrayListOf<ABC>()
       ....

 for (i in list) {
   chart[] = LineChart(activity)
 }
</code>```

What is the value I should put inside [] ? Let say the list's saiz is 2, I need to have 2 chart in LinearLayout.

How should I initialize LineChart?

Example

chart[i] = LineChart(activity) ???

LineChart

```<code>public class LineChart extends BarLineChartBase<LineData> implements LineDataProvider {

    public LineChart(Context context) {
        super(context);
    }

    public LineChart(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public LineChart(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void init() {
        super.init();

        mRenderer = new LineChartRenderer(this, mAnimator, mViewPortHandler);
    }

    @Override
    public LineData getLineData() {
        return mData;
    }

    @Override
    protected void onDetachedFromWindow() {
        // releases the bitmap in the renderer to avoid oom error
        if (mRenderer != null && mRenderer instanceof LineChartRenderer) {
            ((LineChartRenderer) mRenderer).releaseBitmap();
        }
        super.onDetachedFromWindow();
    }
}
</code>```

答:
Your question is a little unclear, but I'm following correctly, you can do it in one line like this:

```<code>val chart = Array(list.size){ LineChart(list[it]) }
</code>```

Or:

```<code>val chart = list.map{ LineChart(it) }.toTypedArray()
</code>```

(The latter creates a temporary list, which may be slightly less efficient; but it iterates through the list instead of indexing, which could be faster if the list isn't random-access.)

Body:
I need to add LineChart(using MpAndroidChart) dynamically in LinearLayout.

I have declared an arrayList,named list.

 val list = arrayListOf<ABC>()
       ....

 for (i in list) {
   chart[] = LineChart(activity)
 }

What is the value I should put inside [] ? Let say the list's saiz is 2, I need to have 2 chart in LinearLayout.

How should I initialize LineChart?

Example

chart[i] = LineChart(activity) ???

LineChart

public class LineChart extends BarLineChartBase<LineData> implements LineDataProvider {

    public LineChart(Context context) {
        super(context);
    }

    public LineChart(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public LineChart(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void init() {
        super.init();

        mRenderer = new LineChartRenderer(this, mAnimator, mViewPortHandler);
    }

    @Override
    public LineData getLineData() {
        return mData;
    }

    @Override
    protected void onDetachedFromWindow() {
        // releases the bitmap in the renderer to avoid oom error
        if (mRenderer != null && mRenderer instanceof LineChartRenderer) {
            ((LineChartRenderer) mRenderer).releaseBitmap();
        }
        super.onDetachedFromWindow();
    }
}

Body:
Your question is a little unclear, but I'm following correctly, you can do it in one line like this:

val chart = Array(list.size){ LineChart(list[it]) }

Or:

val chart = list.map{ LineChart(it) }.toTypedArray()

(The latter creates a temporary list, which may be slightly less efficient; but it iterates through the list instead of indexing, which could be faster if the list isn't random-access.)


问:
Download zips on google cloud via terminal
There are a large amount of zip files stored on google cloud that I would like to download, I would like a script to do this, so I do not have to do it one at a time.

I have tried to download one file using

```<code>curl -o https://storage.cloud.google.com/foo.zip
</code>```

but I get an error message saying there is no URL specified.

Maybe curl is the wrong function for this?

I would like to download multiple zips hosted on google cloud that are listed in a .txt file at the same time, or one after the other.

答:
There are 2 solutions to download your files using the command line.

Use gsutil

You can just use gsutil cp command :

```<code>gsutil cp gs://[BUCKET_NAME]/foo.zip .
</code>```

You can also take a look at gsutil rsync command.

Use cURL

If using gsutil is not possible, you can still use cURL but you might need to authenticate if the object inside your bucket is not public (I assume that you do not want your objects to be public here).

From the docs about downloading objects (REST APIS tab) :

```<code>curl -X GET \
    -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    -o "[SAVE_TO_LOCATION]" \
    "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/[OBJECT_NAME]?alt=media"
</code>```

As you can see, you will need a oauth2 authorization access token to do so (see docs on how to authenticate to Cloud Storage).

However, even if this is possible, I strongly suggest you to use the first option (gsutil), as stated in the docs :

To easily download all objects in a bucket or subdirectory, use the gsutil cp command.

Body:
There are a large amount of zip files stored on google cloud that I would like to download, I would like a script to do this, so I do not have to do it one at a time.

I have tried to download one file using

curl -o https://storage.cloud.google.com/foo.zip

but I get an error message saying there is no URL specified.

Maybe curl is the wrong function for this?

I would like to download multiple zips hosted on google cloud that are listed in a .txt file at the same time, or one after the other.

Body:
There are 2 solutions to download your files using the command line.

Use gsutil

You can just use gsutil cp command :

gsutil cp gs://[BUCKET_NAME]/foo.zip .

You can also take a look at gsutil rsync command.

Use cURL

If using gsutil is not possible, you can still use cURL but you might need to authenticate if the object inside your bucket is not public (I assume that you do not want your objects to be public here).

From the docs about downloading objects (REST APIS tab) :

curl -X GET \
    -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    -o "[SAVE_TO_LOCATION]" \
    "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/[OBJECT_NAME]?alt=media"

As you can see, you will need a oauth2 authorization access token to do so (see docs on how to authenticate to Cloud Storage).

However, even if this is possible, I strongly suggest you to use the first option (gsutil), as stated in the docs :

To easily download all objects in a bucket or subdirectory, use the gsutil cp command.


问:
Creating UILabel programmatically with constraints?
What I want to do is create a new UILabel programmatically every time a certain action occurs in my code. I know the x, y, and height that I want to give the label, but I don't want to give it a set width. I want to constrain the sides so that the UILabel width is equal to the width of the screen, and so that the label width will change if the orientation is flipped.

I have considered using:

```<code>CGRect(x:, y:, width:, height:)
</code>```

However, I would have to give it a set width if I use this, so I don't think it will work.

I also tried using:

```<code>CGPoint(x:, y:)
</code>```

Then setting leading, trailing and height anchors, however, this doesn't seem to work either as even though it does compile, I get an error when I try creating a new UILabel.

I'm kind of new to programming in Swift so I'm not sure if there is an obvious fix to this.

答:
You can use following code to create UILabel programmatically.

```<code>private let label: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.numberOfLines = 0
    label.text = "Hello World"
    return label
}()
</code>```

Then inside your viewDidLoad()

```<code>addSubview(label)
NSLayoutConstraint.activate([
    topAnchor.constraint(equalTo: label.topAnchor),
    bottomAnchor.constraint(equalTo: label.bottomAnchor),
    leadingAnchor.constraint(equalTo: label.leadingAnchor),
    trailingAnchor.constraint(equalTo: label.trailingAnchor)
])
</code>```

Body:
What I want to do is create a new UILabel programmatically every time a certain action occurs in my code. I know the x, y, and height that I want to give the label, but I don't want to give it a set width. I want to constrain the sides so that the UILabel width is equal to the width of the screen, and so that the label width will change if the orientation is flipped.

I have considered using:

CGRect(x:, y:, width:, height:)

However, I would have to give it a set width if I use this, so I don't think it will work.

I also tried using:

CGPoint(x:, y:)

Then setting leading, trailing and height anchors, however, this doesn't seem to work either as even though it does compile, I get an error when I try creating a new UILabel.

I'm kind of new to programming in Swift so I'm not sure if there is an obvious fix to this.

Body:
You can use following code to create UILabel programmatically.

private let label: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.numberOfLines = 0
    label.text = "Hello World"
    return label
}()

Then inside your viewDidLoad()

addSubview(label)
NSLayoutConstraint.activate([
    topAnchor.constraint(equalTo: label.topAnchor),
    bottomAnchor.constraint(equalTo: label.bottomAnchor),
    leadingAnchor.constraint(equalTo: label.leadingAnchor),
    trailingAnchor.constraint(equalTo: label.trailingAnchor)
])


问:
How to replace a substring in a line that contains another substring
I have this lines.

I want for each line that contains "Id" of any case to replace "string" with int.

Not sure how to do grouping for this.

This is my list

I've tried something like this ^(.*(string).*(Id).*)$ and replace with \1 or \2

```<code>public string ID {get; set}
public string IdSite {get; set}
public string IdParent {get; set}
public string IdPageType {get; set}
public string PageType {get; set}
public string IdTemplate {get; set}
public string TemplateName {get; set}
public string IdTemplateParent {get; set}
</code>```

答:
You may use

```<code>(?i)^(\s*\w+\s+)string(\s+Id)
</code>```

Or, if the ID may be inside a word

```<code>(?i)^(\s*\w+\s+)string(\s+\w*Id)
                          ^^^
</code>```

Replace with $1int$2. See the regex demo. See the regex graph:

Details

(?i) - case insensitive inline option

^ - start of a line (or string, if not used in a text editor, use (?im) at the start instead of (?i))

(\s*\w+\s+) - Group 1 ($1): 0+ whitespaces, 1+ word chars, 1+ whitespaces

string - a string word

(\s+Id) - Group 2 ($2): 1+ whitespaces and ID string  (if you use \w* in this group pattern, it will match 0+ word chars).

Body:
I have this lines.

I want for each line that contains "Id" of any case to replace "string" with int.

Not sure how to do grouping for this.

This is my list

I've tried something like this ^(.*(string).*(Id).*)$ and replace with \1 or \2

public string ID {get; set}
public string IdSite {get; set}
public string IdParent {get; set}
public string IdPageType {get; set}
public string PageType {get; set}
public string IdTemplate {get; set}
public string TemplateName {get; set}
public string IdTemplateParent {get; set}

Body:
You may use

(?i)^(\s*\w+\s+)string(\s+Id)

Or, if the ID may be inside a word

(?i)^(\s*\w+\s+)string(\s+\w*Id)
                          ^^^

Replace with $1int$2. See the regex demo. See the regex graph:

Details

(?i) - case insensitive inline option

^ - start of a line (or string, if not used in a text editor, use (?im) at the start instead of (?i))

(\s*\w+\s+) - Group 1 ($1): 0+ whitespaces, 1+ word chars, 1+ whitespaces

string - a string word

(\s+Id) - Group 2 ($2): 1+ whitespaces and ID string  (if you use \w* in this group pattern, it will match 0+ word chars).


问:
Android - Make an envelope shape background in xml/vector
I'm trying to do a shape as this one in xml:

It is a simple rectangle, with a solid color and a little transparent triangle in the top-center, from the inner side.

Can this be achieved using vectors?

Body:
Try this

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="200dp"
    android:height="150dp"
    android:viewportWidth="400"
    android:viewportHeight="230">
    <path
        android:fillColor="#24b44c"
        android:fillType="evenOdd"
        android:strokeWidth="1"
        android:pathData="M50.964 49.856 C 50.870 54.145,50.871 86.953,50.965 122.761 L 51.136 187.868 198.416 187.868 L 345.696 187.868 345.730 154.882 C 345.749 136.739,345.800 118.931,345.844 115.309 C 345.888 111.687,345.857 93.720,345.775 75.382 L 345.626 42.041 282.161 42.107 L 218.696 42.172 215.844 45.176 C 211.458 49.794,198.283 62.854,198.009 62.854 C 197.876 62.854,193.061 58.174,187.311 52.455 L 176.856 42.057 113.995 42.057 L 51.134 42.057 50.964 49.856" />
    <path
        android:fillColor="#74cc8c"
        android:fillType="evenOdd"
        android:strokeWidth="1"
        android:pathData="M50.923 48.296 C 50.923 49.630,50.961 50.176,51.008 49.509 C 51.055 48.842,51.055 47.750,51.008 47.083 C 50.961 46.415,50.923 46.961,50.923 48.296 M345.805 64.125 C 345.805 72.132,345.834 75.374,345.869 71.329 C 345.905 67.285,345.905 60.734,345.869 56.771 C 345.834 52.809,345.805 56.118,345.805 64.125 M345.750 79.723 C 345.750 80.168,345.797 80.350,345.855 80.127 C 345.914 79.905,345.914 79.541,345.855 79.318 C 345.797 79.096,345.750 79.278,345.750 79.723 M124.745 188.042 C 165.330 188.074,231.673 188.074,272.174 188.042 C 312.675 188.009,279.469 187.983,198.382 187.983 C 117.296 187.983,84.159 188.009,124.745 188.042" />
    <path
        android:fillColor="#9cdcac"
        android:fillType="evenOdd"
        android:strokeWidth="1"
        android:pathData="M50.912 44.598 C 50.912 45.425,50.954 45.763,51.005 45.350 C 51.056 44.936,51.056 44.261,51.005 43.847 C 50.954 43.434,50.912 43.772,50.912 44.598 M345.787 46.678 C 345.787 48.394,345.823 49.096,345.867 48.238 C 345.912 47.380,345.912 45.976,345.867 45.118 C 345.823 44.261,345.787 44.962,345.787 46.678" />
    <path
        android:fillColor="#b0e4c0"
        android:fillType="evenOdd"
        android:strokeWidth="1"
        android:pathData="M345.750 42.981 C 345.750 43.426,345.797 43.608,345.855 43.385 C 345.914 43.163,345.914 42.799,345.855 42.577 C 345.797 42.354,345.750 42.536,345.750 42.981 M202.531 58.521 L 201.618 59.503 202.600 58.590 C 203.513 57.740,203.688 57.539,203.513 57.539 C 203.475 57.539,203.033 57.981,202.531 58.521 M193.876 59.041 C 194.308 59.486,194.712 59.850,194.776 59.850 C 194.839 59.850,194.539 59.486,194.107 59.041 C 193.676 58.596,193.272 58.232,193.208 58.232 C 193.144 58.232,193.445 58.596,193.876 59.041" />
</vector>

OUTPUT


问:
How to generate dataframe using column values in some other dataframe
I am working on a dataset which is in the following dataframe.

```<code>#print(old_df)
   col1 col2 col3
0   1   10  1.5
1   1   11  2.5
2   1   12  5,6
3   2   10  7.8
4   2   24  2.1
5   3   10  3.2
6   4   10  22.1
7   4   11  1.3
8   4   89  0.5
9   4   91  3.3
</code>```

I am trying to generate another data frame which contains selected col1 values as index, selected col2 values as columns and assign respective col3 value.

Eg:

```<code>selected_col1 = [1,2]
selected_col2 = [10,11,24]
</code>```

New data frame should be looking like:

```<code>#print(selected_df)
     10     11     24
1    1.5    2.5    Nan
2    7.8    Nan    2.1
</code>```

I have tried following method

```<code>selected_col1 = [1,2]
selected_col2 = [10,11,24]
selected_df =pd.DataFrame(index=selected_col1,columns=selected_col2)
for col1_value in selected_col1:
    for col2_value in selected_col2:
        qry = 'col1 == {} & col2 == {}'.format(col1_value,col2_value)
        col3_value = old_df.query(qry).col3.values
        if(len(col3_value) > 0):
            selected_df.at[col1_value,col2_value] = col3_value[0]
</code>```

But because my dataframe has around 20 million rows, this brute force kind of method is taking long time. Is there a way better than this?

答:
First filter rows by membership by Series.isin in both columns chained by & for bitwise AND and then use DataFrame.pivot:

```<code>df = df[df['col1'].isin(selected_col1) & df['col2'].isin(selected_col2)]

df = df.pivot('col1','col2','col3')
print (df)
col2   10   11   24
col1
1     1.5  2.5  NaN
2     7.8  NaN  2.1
</code>```

If possible some duplicated pairs in col1 with col2 after filtering use DataFrame.pivot_table:

```<code>df = df.pivot_table(index='col1',columns='col2',values='col3', aggfunc='mean')
</code>```

EDIT:

If use | for bitwise OR get different output:

```<code>df = df[df['col1'].isin(selected_col1) | df['col2'].isin(selected_col2)]

df = df.pivot('col1','col2','col3')
print (df)
col2    10   11   12   24
col1
1      1.5  2.5  5,6  NaN
2      7.8  NaN  NaN  2.1
3      3.2  NaN  NaN  NaN
4     22.1  1.3  NaN  NaN
</code>```

Body:
I am working on a dataset which is in the following dataframe.

#print(old_df)
   col1 col2 col3
0   1   10  1.5
1   1   11  2.5
2   1   12  5,6
3   2   10  7.8
4   2   24  2.1
5   3   10  3.2
6   4   10  22.1
7   4   11  1.3
8   4   89  0.5
9   4   91  3.3

I am trying to generate another data frame which contains selected col1 values as index, selected col2 values as columns and assign respective col3 value.

Eg:

selected_col1 = [1,2]
selected_col2 = [10,11,24]

New data frame should be looking like:

#print(selected_df)
     10     11     24
1    1.5    2.5    Nan
2    7.8    Nan    2.1

I have tried following method

selected_col1 = [1,2]
selected_col2 = [10,11,24]
selected_df =pd.DataFrame(index=selected_col1,columns=selected_col2)
for col1_value in selected_col1:
    for col2_value in selected_col2:
        qry = 'col1 == {} & col2 == {}'.format(col1_value,col2_value)
        col3_value = old_df.query(qry).col3.values
        if(len(col3_value) > 0):
            selected_df.at[col1_value,col2_value] = col3_value[0]

But because my dataframe has around 20 million rows, this brute force kind of method is taking long time. Is there a way better than this?

Body:
First filter rows by membership by Series.isin in both columns chained by & for bitwise AND and then use DataFrame.pivot:

df = df[df['col1'].isin(selected_col1) & df['col2'].isin(selected_col2)]

df = df.pivot('col1','col2','col3')
print (df)
col2   10   11   24
col1
1     1.5  2.5  NaN
2     7.8  NaN  2.1

If possible some duplicated pairs in col1 with col2 after filtering use DataFrame.pivot_table:

df = df.pivot_table(index='col1',columns='col2',values='col3', aggfunc='mean')

EDIT:

If use | for bitwise OR get different output:

df = df[df['col1'].isin(selected_col1) | df['col2'].isin(selected_col2)]

df = df.pivot('col1','col2','col3')
print (df)
col2    10   11   12   24
col1
1      1.5  2.5  5,6  NaN
2      7.8  NaN  NaN  2.1
3      3.2  NaN  NaN  NaN
4     22.1  1.3  NaN  NaN


问:
How can I implement pagination in symfony2?
I am working on a project using Symfony2 framework. I am using XAMPP with PHP version 5.5.19. I have table and what I want to do is to put pagination for easy navigation and so on... I am new to symfony that I don't know how to implement it?

Can somebody help me?

答:
// controller file</p>

```<code>public function paginationAction($page)
{
    $commObj = new CommonController();
    $commObj->setContainer($this->container);
    /** session manager creation */
    $session = $this->getRequest()->getSession();
    /* Session Check */
    if(!$session->has('Id'))
    {
      return $this->redirectToRoute('login_login_homepage');
    }

    if(isset($page) && (!empty($page))){
      $page_no = $page;
    }
    else{
      $page_no = 1;
    }

    $total_records_per_page = 25;
    $offset = ($page_no-1) * $total_records_per_page;
    $previous_page = $page_no - 1;
    $next_page = $page_no + 1;
    $adjacents = "2";

    $total_records = sizeof($lists);

    $total_no_of_pages = ceil($total_records / $total_records_per_page);
    $second_last = $total_no_of_pages - 1;

    $em = $this->getDoctrine()->getManager();

    $repository = $em->getRepository('AppAppBundle:MasterCustomer');
    $select_query       = $repository->createQueryBuilder('QB')
                                     ->select('QB.id,QB.uniqueId,QB.customerName,QB.emailId,QB.mobileNo,QB.customerAddress,QB.customerCity,QB.customerState,QB.customerCountry,QB.status')
                                     ->setFirstResult($offset)
                                     ->setMaxResults($total_records_per_page)
                                     ->where('QB.status!=:sts')
                                     ->setParameter('sts', 2)
                                     ->orderBy('QB.id', 'DESC')
                                     ->getQuery();
    $list        = $select_query->getArrayResult();

    return $this->render('MasterMasterBundle:Customer:index.html.twig',array('lists' => $list, 'total_no_of_pages' => $total_no_of_pages, 'page_no' => $page_no, 'second_last' => $second_last, 'adjacents' => $adjacents, 'total_records' => $total_records, 'next_page' => $next_page, 'previous_page' => $previous_page, 'total_records_per_page' => $total_records_per_page));
}
</code>```

Body:
// controller file

public function paginationAction($page)
{
    $commObj = new CommonController();
    $commObj->setContainer($this->container);
    /** session manager creation */
    $session = $this->getRequest()->getSession();
    /* Session Check */
    if(!$session->has('Id'))
    {
      return $this->redirectToRoute('login_login_homepage');
    }

    if(isset($page) && (!empty($page))){
      $page_no = $page;
    }
    else{
      $page_no = 1;
    }

    $total_records_per_page = 25;
    $offset = ($page_no-1) * $total_records_per_page;
    $previous_page = $page_no - 1;
    $next_page = $page_no + 1;
    $adjacents = "2";

    $total_records = sizeof($lists);

    $total_no_of_pages = ceil($total_records / $total_records_per_page);
    $second_last = $total_no_of_pages - 1;

    $em = $this->getDoctrine()->getManager();

    $repository = $em->getRepository('AppAppBundle:MasterCustomer');
    $select_query       = $repository->createQueryBuilder('QB')
                                     ->select('QB.id,QB.uniqueId,QB.customerName,QB.emailId,QB.mobileNo,QB.customerAddress,QB.customerCity,QB.customerState,QB.customerCountry,QB.status')
                                     ->setFirstResult($offset)
                                     ->setMaxResults($total_records_per_page)
                                     ->where('QB.status!=:sts')
                                     ->setParameter('sts', 2)
                                     ->orderBy('QB.id', 'DESC')
                                     ->getQuery();
    $list        = $select_query->getArrayResult();

    return $this->render('MasterMasterBundle:Customer:index.html.twig',array('lists' => $list, 'total_no_of_pages' => $total_no_of_pages, 'page_no' => $page_no, 'second_last' => $second_last, 'adjacents' => $adjacents, 'total_records' => $total_records, 'next_page' => $next_page, 'previous_page' => $previous_page, 'total_records_per_page' => $total_records_per_page));
}


问:
rxjs and typescript return an function with no parameters
I am trying to use rxjs with amqplib to convert the received messages from rabbit to a stream of messages:

```<code>const connection = await amqplib.connect(constr);
const channel = await connection.createChannel();
const callBack: any = bindCallback(channel.consume);
const observalble = callBack("queue");
</code>```

the problem is callBack returned from bindCallback is a method with no parameters..
what am is doing wrong here?

I depended on the example:

```<code>// From a callback (last argument is a callback)
// fs.exists = (path, cb(exists))
var exists = Rx.Observable.bindCallback(fs.exists);
exists('file.txt').subscribe(exists => console.log('Does file exist?', exists));
</code>```

form the rxjs documentation...

please help

im using rxjs 6.5.2
typescript 3.4.5
amqplib 0.5.2

答:
This should do the trick.</p>

```<code>const connection = await amqplib.connect(constr);
const channel = bindCallback(connection.createChannel);
channel().subscribe(args => {
    const err = args[0]
    const ch = args[1]
    if(err) throw err

    const ch_observable = bindCallback(ch.consume)
    ch_observable("queue").subscribe(msg => {
        console.log(msg)
    })

})
</code>```

Body:
I am trying to use rxjs with amqplib to convert the received messages from rabbit to a stream of messages:

const connection = await amqplib.connect(constr);
const channel = await connection.createChannel();
const callBack: any = bindCallback(channel.consume);
const observalble = callBack("queue");

the problem is callBack returned from bindCallback is a method with no parameters..
what am is doing wrong here?

I depended on the example:

// From a callback (last argument is a callback)
// fs.exists = (path, cb(exists))
var exists = Rx.Observable.bindCallback(fs.exists);
exists('file.txt').subscribe(exists => console.log('Does file exist?', exists));

form the rxjs documentation...

please help

im using rxjs 6.5.2
typescript 3.4.5
amqplib 0.5.2

Body:
This should do the trick.

const connection = await amqplib.connect(constr);
const channel = bindCallback(connection.createChannel);
channel().subscribe(args => {
    const err = args[0]
    const ch = args[1]
    if(err) throw err

    const ch_observable = bindCallback(ch.consume)
    ch_observable("queue").subscribe(msg => {
        console.log(msg)
    })

})