问:
Can someone please find the reason why there is insertion of empty rows in the database except the id field which i have set to auto-increment?
I am trying to insert data into a database using PHP and Angular js. But whenever I insert, only blank rows get inserted into the database except the id field which has been set to auto-increment.

I have tried to solve this, even I searched about this problem but I could not find much helpful resource.
These are my codes: connection.php and insert.html
Kindly help me find the problem please.

connection.php

```<code><?php
    $hostname="localhost";
    $dbname="sampledb";
    $username="root";
    $password="";

    $conn=mysqli_connect($hostname, $username, $password, $dbname);
    $info=json_decode(file_get_contents("php://input"));
    $empname=mysqli_real_escape_string($conn, $info['empname']);
    $email=mysqli_real_escape_string($conn, $info['email']);
    $salary=mysqli_real_escape_string($conn, $info['salary']);
    $query="insert into empdetails(empname, email, salary) values
    ('$empname','$email','$salary')";

    if(mysqli_query($conn, $query))
    {
        echo"Result inserted successfully";
    }
    else
    {
        echo"Oops! Failed to insert.";
    }
?>
</code>```

insert.html

```<code><html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/
    angular.min.js" ></script>
    <script>
        var app=angular.module("Myapp",[]);
        app.controller("Mycontroller",function($scope,$http)
        {
            $scope.insert=function()
            {
                $http.post('connection.php',
                {
                    'empname'=$scope.empname;
                    'email'=$scope.email;
                    'salary'=$scope.salary;
                })
                .success(function(data)
                {
                    alert(data);
                    $scope.empname=null;
                    $scope.email=null;
                    $scope.salary=null;
                });
            }
        });
    </script>
    </head>
    <body>
        <center>
        <h1>Insert Records Into Database</h1>
        <hr/>
        <div ng-app="Myapp"ng-controller="Mycontroller">
            Name: <input type="text"ng-model="empname"/><br/>
            Email: <input type="text"ng-model="email"/><br/>
            Salary: <input type="text"ng-model="salary"/><br/>
        <hr/>
        <input type="submit" value="Insert Records"ng-click="Insert()"/>
        </div>
    </center>
    </body>
</html>
</code>```

答:
TL;DR
Put a true as the second parameter of json_decode

```<code>$info=json_decode(file_get_contents("php://input"), true);
</code>```

Alot of things are wrong here, i'll break my comment into answers. The biggest being this:

```<code>$info=json_decode(file_get_contents("php://input"));
$empname=mysqli_real_escape_string($conn, $info['empname']);
$email=mysqli_real_escape_string($conn, $info['email']);
$salary=mysqli_real_escape_string($conn, $info['salary']);
</code>```

Json decode returns an object not an array unless you pass it true like so:

```<code>$info=json_decode(file_get_contents("php://input"), true);
</code>```

Next lets talk about coding habbits.

First mysqli_real_escape_string is a big no no, use prepared statements as escaping strings can be exploited still.

Next with your query you need to use a space here:

```<code>$query="insert into empdetails SPACEGOESHERE (empname, email, salary) values
    ('$empname','$email','$salary')";
</code>```

Finally i'd suggest using mysqli as object oriented instead of procedural, it will look alot better and its better practice.

Body:
I am trying to insert data into a database using PHP and Angular js. But whenever I insert, only blank rows get inserted into the database except the id field which has been set to auto-increment.

I have tried to solve this, even I searched about this problem but I could not find much helpful resource.
These are my codes: connection.php and insert.html
Kindly help me find the problem please.

connection.php

<?php
    $hostname="localhost";
    $dbname="sampledb";
    $username="root";
    $password="";

    $conn=mysqli_connect($hostname, $username, $password, $dbname);
    $info=json_decode(file_get_contents("php://input"));
    $empname=mysqli_real_escape_string($conn, $info['empname']);
    $email=mysqli_real_escape_string($conn, $info['email']);
    $salary=mysqli_real_escape_string($conn, $info['salary']);
    $query="insert into empdetails(empname, email, salary) values
    ('$empname','$email','$salary')";

    if(mysqli_query($conn, $query))
    {
        echo"Result inserted successfully";
    }
    else
    {
        echo"Oops! Failed to insert.";
    }
?>

insert.html

Insert Records Into Database

            Name: <input type="text"ng-model="empname"/>

            Email: <input type="text"ng-model="email"/>

            Salary: <input type="text"ng-model="salary"/>

        <input type="submit" value="Insert Records"ng-click="Insert()"/>

Body:
TL;DR
Put a true as the second parameter of json_decode

$info=json_decode(file_get_contents("php://input"), true);

Alot of things are wrong here, i'll break my comment into answers. The biggest being this:

$info=json_decode(file_get_contents("php://input"));
$empname=mysqli_real_escape_string($conn, $info['empname']);
$email=mysqli_real_escape_string($conn, $info['email']);
$salary=mysqli_real_escape_string($conn, $info['salary']);

Json decode returns an object not an array unless you pass it true like so:

$info=json_decode(file_get_contents("php://input"), true);

Next lets talk about coding habbits.

First mysqli_real_escape_string is a big no no, use prepared statements as escaping strings can be exploited still.

Next with your query you need to use a space here:

$query="insert into empdetails SPACEGOESHERE (empname, email, salary) values
    ('$empname','$email','$salary')";

Finally i'd suggest using mysqli as object oriented instead of procedural, it will look alot better and its better practice.


来源: stackexchange

问:
Cannot replace colons with .replace() method
I'm trying to replace every instance of a colon in a .txt file with double dashes - "--"

```<code>textof = []

with open("myfile.txt") as myfile:
    textof = myfile.readlines()

for line in textof:
    if ":" in line:
        for char in line:
            if char == ":":
                line = line.replace(":", "--")

print(textof[0])
</code>```

the string print() returns is the same as it was in the original .txt - with colons, and no double dashes. not sure what i'm doing wrong.

答:
You're being misled. The replacement is happening, it's just not getting saved. When you do

```<code>line = line.replace(":", "--")
</code>```

you're not changing the line from textof - instead, you're making an entirely new variable and changing the name line to point to that. To change the original, you'll need to do something like this:

```<code>for idx in range(len(textof)):
    textof[idx] = textof[idx].replace(":", "--")
</code>```

which changes the list textof directly. Or you could be flashy and do it in a list comprehension, which is the idiomatic way of doing it - this doesn't modify the original list, it just creates a new one however you want it:

```<code>replacedLines = [line.replace(":", "--") for line in textof]
</code>```

Note that you also want to write this to a file, and you'll  have to do that explicitly:

```<code>with open("myfile.txt", "w") as myfile:
    myfile.writelines(replacedlines)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to replace every instance of a colon in a .txt file with double dashes - "--"

textof = []

with open("myfile.txt") as myfile:
    textof = myfile.readlines()

for line in textof:
    if ":" in line:
        for char in line:
            if char == ":":
                line = line.replace(":", "--")

print(textof[0])

the string print() returns is the same as it was in the original .txt - with colons, and no double dashes. not sure what i'm doing wrong.

Body:
You're being misled. The replacement is happening, it's just not getting saved. When you do

line = line.replace(":", "--")

you're not changing the line from textof - instead, you're making an entirely new variable and changing the name line to point to that. To change the original, you'll need to do something like this:

for idx in range(len(textof)):
    textof[idx] = textof[idx].replace(":", "--")

which changes the list textof directly. Or you could be flashy and do it in a list comprehension, which is the idiomatic way of doing it - this doesn't modify the original list, it just creates a new one however you want it:

replacedLines = [line.replace(":", "--") for line in textof]

Note that you also want to write this to a file, and you'll  have to do that explicitly:

with open("myfile.txt", "w") as myfile:
    myfile.writelines(replacedlines)


问:
Laravel only retrieve Model Records if they belong to authenticated user
I'm using Laravel 5.4 and have a Model called Order.
To test things I've created two users and two Orders, each user having one Order.

I've just seen that I'm able to retrieve the order of someone who is not my current user. I'm retrieving a list of user's own orders using Auth::user()->orders. But in order to show the details of a specific order I do this:

```<code>/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $order = CustomerOrder::findOrFail($id)->with('products')->get();
    return view('order.show')
        ->with('order', $order);
}
</code>```

What am I missing out here? Is there a middleware or something to tell the application to only allow access to orders associated with the authenticated user?

Edit: So I've tried to do it using a Policy OrderPolicy (CRUD).

The view() fucntion of the Policy:

```<code>/**
 * Determine whether the user can view the customerOrder.
 *
 * @param  \App\User  $user
 * @param  \App\CustomerOrder  $customerOrder
 * @return mixed
 */
public function view(User $user, CustomerOrder $customerOrder)
{
    return $user->id === $customerOrder->user_id;
}
</code>```

And I've registered it in the AuthServiceProvider.php:

```<code>protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    Adress::class => AdressPolicy::class, //Doesn't work either
    Order::class => OrderPolicy::class
];
</code>```

I can still check the Order for another user.

答:
Remember,

first you create policy.

second you register it.

third you use something like $this->authorize('view', $order); in your normal controller.

You are missing the third step, you can find the doc here:
[https://laravel.com/docs/5.8/authorization#authorizing-actions-using-policies][1]

ContentLicense: CC BY-SA 3.0

Body:
I'm using Laravel 5.4 and have a Model called Order.
To test things I've created two users and two Orders, each user having one Order.

I've just seen that I'm able to retrieve the order of someone who is not my current user. I'm retrieving a list of user's own orders using Auth::user()->orders. But in order to show the details of a specific order I do this:

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $order = CustomerOrder::findOrFail($id)->with('products')->get();
    return view('order.show')
        ->with('order', $order);
}

What am I missing out here? Is there a middleware or something to tell the application to only allow access to orders associated with the authenticated user?

Edit: So I've tried to do it using a Policy OrderPolicy (CRUD).

The view() fucntion of the Policy:

/**
 * Determine whether the user can view the customerOrder.
 *
 * @param  \App\User  $user
 * @param  \App\CustomerOrder  $customerOrder
 * @return mixed
 */
public function view(User $user, CustomerOrder $customerOrder)
{
    return $user->id === $customerOrder->user_id;
}

And I've registered it in the AuthServiceProvider.php:

protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    Adress::class => AdressPolicy::class, //Doesn't work either
    Order::class => OrderPolicy::class
];

I can still check the Order for another user.


问:
Terminate k8s pods faster
I have a simple Node.js server running on some Kubernetes pods. When I delete a deployment with:

```<code>kubectl delete deployment <deployment-name>
</code>```

sometimes pods have a status of terminating for 5-8 seconds. Seems excessive - is there a way to kill them faster somehow?

答:
If you really want to kill them instead of gracefully shutdown, then:

```<code>kubectl delete deployment <deployment-name> --grace-period=0
</code>```

Also, if you have any preStop handlers configured, you could investigate if they are causing any unnecessary delay.

Title: Terminate k8s pods faster

Body:
I have a simple Node.js server running on some Kubernetes pods. When I delete a deployment with:

kubectl delete deployment <deployment-name>

sometimes pods have a status of terminating for 5-8 seconds. Seems excessive - is there a way to kill them faster somehow?

Body:
If you really want to kill them instead of gracefully shutdown, then:

kubectl delete deployment <deployment-name> --grace-period=0

Also, if you have any preStop handlers configured, you could investigate if they are causing any unnecessary delay.


问:
How to enlarge image without overlapping other elements?
My images in desktop view https://adsler.co.uk/find-an-event/ are flat. Want to increase their height so they look great in desktop too. However, 2 points.

One, can't seem to find the correct css selector.
Two, can't seem to do it without it overlapping other elements.

I just want it to make it taller (proportionally of course)

Html:

```<code><form class "event_filters" id class="event_filters" >....</form>
<div class="event-listing-view-header"></div>
<ul class="event_listings event-listings-table-bordered-change
event-listings-change" id ="event-listing-view">
<div class="line-layout" style="display: none;">
</h4><div class="boxes-view-listing-registered-code"></div></div>
<div class="events-organizer-name">....</div></div>
<div class="col-md-2">....</div>
<div class="col-md-3">....</div>
<div class="col-md-2">....</div>
<div class="col-md-3">....</div>
</div>
</code>```

Tried css:

```<code>@media (min-width: 768px) {.box-layout.event-img img {height: 200px; width: 400px;}}
</code>```

Nothing....

答:
It is hard to tell exactly what you are looking for, but I would try something like this:

Using the css selector .box-layout .event-img img and object-fit:coverto prevent distorting the images.

@media (min-width: 768px) {
  .box-layout .event-img img {
    height: 200px;
    width: 400px;
    object-fit: cover;
  }
}
```

<p>Edit: To fix the overlapping text and image you need to remove the heights for <code>.box-layout .event-img</code> selector (or override them if you don't have access to change)</p>

```.box-layout .event-img {
    display: table-cell;
    /* height: 100px; */
    /* max-height: 100px; */
    text-align: center;
    vertical-align: middle;
    width: 100%;
    float: left;
}
```

<p><img src="https://i.stack.imgur.com/8gzz2.png" alt="enter image description here"></p>

<p>In order to override the CSS you can add:</p>

```.box-layout .event-img {
  height: initial;
  max-height: initial;
}
```

This needs to be added in a stylesheet (or on page) after frontend.min.css is included on the page.

Body:
My images in desktop view https://adsler.co.uk/find-an-event/ are flat. Want to increase their height so they look great in desktop too. However, 2 points.

One, can't seem to find the correct css selector.
Two, can't seem to do it without it overlapping other elements.

I just want it to make it taller (proportionally of course)

Html:

<form class "event_filters" id class="event_filters" >....</form>

....

....

....

....

....

Tried css:

@media (min-width: 768px) {.box-layout.event-img img {height: 200px; width: 400px;}}

Nothing....

Body:
It is hard to tell exactly what you are looking for, but I would try something like this:

Using the css selector .box-layout .event-img img and object-fit:coverto prevent distorting the images.

@media (min-width: 768px) {
  .box-layout .event-img img {
    height: 200px;
    width: 400px;
    object-fit: cover;
  }
}

Edit: To fix the overlapping text and image you need to remove the heights for .box-layout .event-img selector (or override them if you don't have access to change)

.box-layout .event-img {
    display: table-cell;
    /* height: 100px; */
    /* max-height: 100px; */
    text-align: center;
    vertical-align: middle;
    width: 100%;
    float: left;
}

In order to override the CSS you can add:

.box-layout .event-img {
  height: initial;
  max-height: initial;
}

This needs to be added in a stylesheet (or on page) after frontend.min.css is included on the page.


问:
Filter keys of map1 based on filtering criteria in map 2 and filtering info for each item in map 3 using java8 streams
I have 3 maps and they are setup as follows:-

```<code>  //Map1
  Map<CatalogCd, Set<ItemUID>> availableItems
  //Map2
  Map<CatalogCd, FilteringPreferences> filteringPrefs
  //Map3
  Map<ItemUID, ItemInformation> itemDetailInformation
</code>```

What I am trying to do is ,

go through the availableItems, and then see if the ItemInformation for a given ItemUID, matches with the preferences ( by basically doing some kind of predicate check).

As you can see the first two maps have the same keys, the filteringPrefs for the same key apply to the entire set of that catalogcd key, any object that does not qualify as per the predicates setup in Preferences , should be removed from the resulting set of itemuids.

I am interested in doing the java 8 stream, map, filter way of making this look better rather than traditional for loop over one map and then manually removing or adding items to a new result map.

This is the traditional for-loop non-java-8 style of code I got.

```<code>public Map<CatalogCd, Set<ItemUID>> filterResponse(Map<CatalogCd, Set<ItemUID>> availableItems,  Map<CatalogCd, FilteringPreferences> filteringPrefs, Map<ItemUID, ItemInformation> itemDetailInformation)
{
    Map<CatalogCd, Set<ItemUID>> resultingFilteredItemsMap = new HashMap<>();
    for(Map.Entry<CatalogCd,FilteringPreferences> catalogCdEntry : filteringPrefs.entrySet()){
    CatalogCd catalogCdInRequest = catalogCdEntry.getKey();
    EnumSet<PrefA> prefA = catalogCdEntry.getValue().getSupportedPrefAs();

    //get set of items for this catalogcd, loop over each itemuid, check from itemDetailInformation map
    //to see if that itemuid's enumset has intersection with the enumset in request's preference.
    Set<ItemUID> itemsForThisCatalogCd = availableItems.get(catalogCdInRequest);
    for(ItemUID item:itemsForThisCatalogCd){
        EnumSet<PrefA> enumSetFromItemInfo = itemDetailInformation.get(item).getPrefAs();
        enumSetFromItemInfo.retainAll(prefA);
        if(!enumSetFromItemInfo.isEmpty()){
            if(resultingFilteredItemsMap.get(catalogCdInRequest)!=null){
                Set<ItemUID> items = resultingFilteredItemsMap.get(catalogCdInRequest);
                items.add(item);
                resultingFilteredItemsMap.put(catalogCdInRequest, items);
            }else{
                resultingFilteredItemsMap.put(catalogCdInRequest, Sets.newHashSet(item));
              }
           }
        }
    }
   return resultingFilteredItemsMap;
}
</code>```

What I have tried so far is this:-

```<code>availableItems
    .entrySet()
    .stream()
    .filter(x- >predicateFilterFactory.createPredicateFilter(filteringPref.get(x.getKey())))
    .collect(Collectors.toMap(x->x.getKey(),x->x.getValue));
</code>```

but this says Predicate cannot be converted to boolean Also, I dont know how to rope-in the actual content map into this.
Any help would be great.
Thanks

答:
This method should solve your issue:

```<code>public static Map<CatalogCd, Set<ItemUID>> filterResponse(Map<CatalogCd, Set<ItemUID>> availableItems,
            Map<CatalogCd, FilteringPreferences> filteringPrefs, Map<ItemUID, ItemInformation> itemDetailInformation) {
    return filteringPrefs.entrySet().stream()
            .flatMap(e -> availableItems.getOrDefault(e.getKey(), Collections.emptySet())
                    .stream().map(item -> new AbstractMap.SimpleEntry<>(e, item)))
            .filter(e -> itemDetailInformation.get(e.getValue()).getPrefAs().stream()
                    .anyMatch(e.getKey().getValue().getSupportedPrefAs()::contains))
            .collect(Collectors.groupingBy(e -> e.getKey().getKey(), Collectors.mapping(Map.Entry::getValue, Collectors.toSet())));
}
</code>```

But I do not think that this will make your code more readable. Hope this helps.

You can just add the filter() statement you already have directly after the flatMap() or before the collect().

EDIT: Here is a little explanation:

the flatMap() joins the availableItems based on the keys of filteringPrefs. This is the first part in your first loop:

```<code>CatalogCd catalogCdInRequest = catalogCdEntry.getKey();
EnumSet<PrefA> prefA = catalogCdEntry.getValue().getSupportedPrefAs();
Set<ItemUID> itemsForThisCatalogCd = availableItems.get(catalogCdInRequest);
for (ItemUID item: itemsForThisCatalogCd) {
    // ...
}
</code>```

The filter() part looks for items which have any pref available in supported itemDetailInformation. This is the retainAll() and not empty part of your code.

```<code>EnumSet<PrefA> enumSetFromItemInfo = itemDetailInformation.get(item).getPrefAs();
enumSetFromItemInfo.retainAll(prefA);
if (!enumSetFromItemInfo.isEmpty()) {
    // ...
}
</code>```

The collect() step joins all items back to a Map<CatalogCd, Set<ItemUID>>, using the original key of filteringPrefs and the value of availableItems. This is the last part of your code:

```<code>if (resultingFilteredItemsMap.get(catalogCdInRequest) != null) {
    items = resultingFilteredItemsMap.get(catalogCdInRequest);
    items.add(item);
} else {
    items = new HashSet<>(Arrays.asList(item));
}
</code>```

Body:
I have 3 maps and they are setup as follows:-

  //Map1
  Map<CatalogCd, Set<ItemUID>> availableItems
  //Map2
  Map<CatalogCd, FilteringPreferences> filteringPrefs
  //Map3
  Map<ItemUID, ItemInformation> itemDetailInformation

What I am trying to do is ,

go through the availableItems, and then see if the ItemInformation for a given ItemUID, matches with the preferences ( by basically doing some kind of predicate check).

As you can see the first two maps have the same keys, the filteringPrefs for the same key apply to the entire set of that catalogcd key, any object that does not qualify as per the predicates setup in Preferences , should be removed from the resulting set of itemuids.

I am interested in doing the java 8 stream, map, filter way of making this look better rather than traditional for loop over one map and then manually removing or adding items to a new result map.

This is the traditional for-loop non-java-8 style of code I got.

public Map<CatalogCd, Set<ItemUID>> filterResponse(Map<CatalogCd, Set<ItemUID>> availableItems,  Map<CatalogCd, FilteringPreferences> filteringPrefs, Map<ItemUID, ItemInformation> itemDetailInformation)
{
    Map<CatalogCd, Set<ItemUID>> resultingFilteredItemsMap = new HashMap<>();
    for(Map.Entry<CatalogCd,FilteringPreferences> catalogCdEntry : filteringPrefs.entrySet()){
    CatalogCd catalogCdInRequest = catalogCdEntry.getKey();
    EnumSet<PrefA> prefA = catalogCdEntry.getValue().getSupportedPrefAs();

    //get set of items for this catalogcd, loop over each itemuid, check from itemDetailInformation map
    //to see if that itemuid's enumset has intersection with the enumset in request's preference.
    Set<ItemUID> itemsForThisCatalogCd = availableItems.get(catalogCdInRequest);
    for(ItemUID item:itemsForThisCatalogCd){
        EnumSet<PrefA> enumSetFromItemInfo = itemDetailInformation.get(item).getPrefAs();
        enumSetFromItemInfo.retainAll(prefA);
        if(!enumSetFromItemInfo.isEmpty()){
            if(resultingFilteredItemsMap.get(catalogCdInRequest)!=null){
                Set<ItemUID> items = resultingFilteredItemsMap.get(catalogCdInRequest);
                items.add(item);
                resultingFilteredItemsMap.put(catalogCdInRequest, items);
            }else{
                resultingFilteredItemsMap.put(catalogCdInRequest, Sets.newHashSet(item));
              }
           }
        }
    }
   return resultingFilteredItemsMap;
}

What I have tried so far is this:-

availableItems
    .entrySet()
    .stream()
    .filter(x- >predicateFilterFactory.createPredicateFilter(filteringPref.get(x.getKey())))
    .collect(Collectors.toMap(x->x.getKey(),x->x.getValue));

but this says Predicate cannot be converted to boolean Also, I dont know how to rope-in the actual content map into this.
Any help would be great.
Thanks

Body:
This method should solve your issue:

public static Map<CatalogCd, Set<ItemUID>> filterResponse(Map<CatalogCd, Set<ItemUID>> availableItems,
            Map<CatalogCd, FilteringPreferences> filteringPrefs, Map<ItemUID, ItemInformation> itemDetailInformation) {
    return filteringPrefs.entrySet().stream()
            .flatMap(e -> availableItems.getOrDefault(e.getKey(), Collections.emptySet())
                    .stream().map(item -> new AbstractMap.SimpleEntry<>(e, item)))
            .filter(e -> itemDetailInformation.get(e.getValue()).getPrefAs().stream()
                    .anyMatch(e.getKey().getValue().getSupportedPrefAs()::contains))
            .collect(Collectors.groupingBy(e -> e.getKey().getKey(), Collectors.mapping(Map.Entry::getValue, Collectors.toSet())));
}

But I do not think that this will make your code more readable. Hope this helps.

You can just add the filter() statement you already have directly after the flatMap() or before the collect().

EDIT: Here is a little explanation:

the flatMap() joins the availableItems based on the keys of filteringPrefs. This is the first part in your first loop:

CatalogCd catalogCdInRequest = catalogCdEntry.getKey();
EnumSet<PrefA> prefA = catalogCdEntry.getValue().getSupportedPrefAs();
Set<ItemUID> itemsForThisCatalogCd = availableItems.get(catalogCdInRequest);
for (ItemUID item: itemsForThisCatalogCd) {
    // ...
}

The filter() part looks for items which have any pref available in supported itemDetailInformation. This is the retainAll() and not empty part of your code.

EnumSet<PrefA> enumSetFromItemInfo = itemDetailInformation.get(item).getPrefAs();
enumSetFromItemInfo.retainAll(prefA);
if (!enumSetFromItemInfo.isEmpty()) {
    // ...
}

The collect() step joins all items back to a Map<CatalogCd, Set<ItemUID>>, using the original key of filteringPrefs and the value of availableItems. This is the last part of your code:

if (resultingFilteredItemsMap.get(catalogCdInRequest) != null) {
    items = resultingFilteredItemsMap.get(catalogCdInRequest);
    items.add(item);
} else {
    items = new HashSet<>(Arrays.asList(item));
}


问:
Calculate height of div based off width & maintain proportion
I am looking for a pure CSS solution to what I have here done using jQuery to help.

Basically I have 3 divs that spread evenly in width in a container. They maintain a 3/4 ration with the height being calculated off of the width. Furthermore, each div has a background image that stays proportional and some text that is centered horizontally and vertically.

$(document).ready(function() {
  function setw() {
    var footdivwidth = $('footer div').width();
    var footdivheight = footdivwidth * .75;
    $('footer div').css({
      'height': footdivheight + 'px'
    });
    $('footer div span').html('w: ' + footdivwidth + '
h: ' + footdivheight);
  }
  setw();
  $(window).resize(function() {
    setw();
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>FOOTER {
  max-width: 1000px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.171);
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

FOOTER DIV {
  background-image: url('https://learnwebdesign.online/img/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

FOOTER DIV SPAN {
  display: inline-block;
  text-align: center;
  background-color: rgba(165, 165, 165, 0.282);
  padding: 7px 15px;
  border-radius: 3px;
  color: #FFFFFF;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 21px;
}</code>```

left photo

center photo

right photo and more text

```
</div>
</div>
</p>

<p>Here is a pen showing what I have.
https://codepen.io/nom3d/pen/arGpBV</p>

<p>Here is a gif showing the effect when resized. Note the background image staying proportional and text staying centered.
<img src="https://i.stack.imgur.com/OyB78.gif" alt="3 box resize with proportions kept"></p>

<p>Also wondering if it's not possible with just CSS, how to do this with <strong>plain javascript</strong>, would I need to add id's to my divs?</p>

<p>Update: here is a plain javaScript function to handle this task</p>

```function setHeight(el,val){
    var box = document.querySelectorAll(el);
    var i;
    for(i = 0;i < box.length;i++){
        var width = box[i].offsetWidth;
        var height = width * val;
        box[i].style.height = height + 'px';
    }
}
// set your element to target and the ratio value
setHeight('footer div',.75);
window.onresize = function(event) {
    setHeight('footer div',.75);
};
```

答:
Probably a bit late, but will add my solution as well.

I thought I should keep it a general solution, so I decided to not use your Footer classes. But I'm sure you'll get the trick.

In my opinion the easiest way is to use the padding calculation to get a fixed ratio and some divs.

Flex container

Flex items (with the padding on it): This container is used to maintain the resolution. The amount of padding for it depends on the width of the item.
For example: Item width = 100% --> Padding = (100/4)*3 --> 75% padding

Content container inside Flex-Item where you can put your stuff

Background-Div inside the content container

put everything you need as sibling to the background-div

Here's a fiddle to play around, some comments are in the code: https://jsfiddle.net/Hoargarth/Lry5gbsq/
Feel free to ask if you need anything

Just a quick note on all of those containers:
You could do it with just the flex-item and one other container. But in my opinion, with the extra container it get's more flexible if you need any hover-events, animations or som other exotic stuff.
For the simple solution see this fiddle: https://jsfiddle.net/Hoargarth/m57b9jcw/

.container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

/* padding bottom gives the height of the container, 33.33% padding would be a quadratic box. 100% would be the same height as the container's width. Therefore simple trignomometry, (100/4) * 3 = 75%; or for screen width > 500px: (33.33 / 4) * 3 for a 4/3 resolution. You'll find the media query at the end of the css. It's just to demonstrate that it's working with media queries as well. */
.item {
  position: relative;
  width: 100%;
  padding-bottom: 75%;
}

/* Overflow hidden so nothing can overlap to the other items */
.content-wrapper {
  position: absolute;
  overflow: hidden;
  width: 100%;
  height: 100%;
}

.image-holder {
  position: relative;
  height: 100%;
  background-image: url("https://previews.123rf.com/images/happydancing/happydancing1706/happydancing170600014/80282512-flat-lay-photo-of-workspace-desk-with-laptop-smartphone-blank-notebook-and-green-plant-with-copy-spa.jpg");
  background-size: cover;
  background-position: 50%;
  background-repeat: no-repeat;
}

/* Absolute positioned by 50% top, left; To completely center it, you have to translate the holder back by it's own half width and height transform: translate(-50%, -50%) */
.text-holder {
  position: absolute;
  top: 50%;
  left: 50%;
  padding: 10px;
  width: 70%;
  background-color: rgba(255, 255, 255, 0.5);
  transform: translate(-50%, -50%);
  text-align: center;
}

/* Simple media Query to test it. Be aware: If the item's width is changing, the padding has to change as well */
@media (min-width: 500px) {
  .item {
    width: 33.33%;
    padding-bottom: 24.75%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <div class="item">
    <div class="content-wrapper">
      <div class="image-holder"></div>
      <div class="text-holder">
        <p>
          Some Centered Text
        </p>
      </div>
    </div>
  </div>

  <div class="item">
    <div class="content-wrapper">
      <div class="image-holder"></div>
      <div class="text-holder">
        <p>
          Some Centered Text but larger and longer so we see a difference
        </p>
      </div>
    </div>
  </div>

  <div class="item">
    <div class="content-wrapper">
      <div class="image-holder"></div>
      <div class="text-holder">
        <p>
          Groot
        </p>
      </div>
    </div>
  </div>

</div></code>```

Body:
I am looking for a pure CSS solution to what I have here done using jQuery to help.

Basically I have 3 divs that spread evenly in width in a container. They maintain a 3/4 ration with the height being calculated off of the width. Furthermore, each div has a background image that stays proportional and some text that is centered horizontally and vertically.

$(document).ready(function() {
  function setw() {
    var footdivwidth = $('footer div').width();
    var footdivheight = footdivwidth * .75;
    $('footer div').css({
      'height': footdivheight + 'px'
    });
    $('footer div span').html('w: ' + footdivwidth + '
h: ' + footdivheight);
  }
  setw();
  $(window).resize(function() {
    setw();
  })
});

FOOTER {
  max-width: 1000px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.171);
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

FOOTER DIV {
  background-image: url('https://learnwebdesign.online/img/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

FOOTER DIV SPAN {
  display: inline-block;
  text-align: center;
  background-color: rgba(165, 165, 165, 0.282);
  padding: 7px 15px;
  border-radius: 3px;
  color: #FFFFFF;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 21px;
}

left photo

center photo

right photo and more text

Here is a pen showing what I have.
https://codepen.io/nom3d/pen/arGpBV

Here is a gif showing the effect when resized. Note the background image staying proportional and text staying centered.

Also wondering if it's not possible with just CSS, how to do this with plain javascript, would I need to add id's to my divs?

Update: here is a plain javaScript function to handle this task

function setHeight(el,val){
    var box = document.querySelectorAll(el);
    var i;
    for(i = 0;i < box.length;i++){
        var width = box[i].offsetWidth;
        var height = width * val;
        box[i].style.height = height + 'px';
    }
}
// set your element to target and the ratio value
setHeight('footer div',.75);
window.onresize = function(event) {
    setHeight('footer div',.75);
};

Body:
Probably a bit late, but will add my solution as well.

I thought I should keep it a general solution, so I decided to not use your Footer classes. But I'm sure you'll get the trick.

In my opinion the easiest way is to use the padding calculation to get a fixed ratio and some divs.

Flex container

Flex items (with the padding on it): This container is used to maintain the resolution. The amount of padding for it depends on the width of the item.
For example: Item width = 100% --> Padding = (100/4)*3 --> 75% padding

Content container inside Flex-Item where you can put your stuff

Background-Div inside the content container

put everything you need as sibling to the background-div

Here's a fiddle to play around, some comments are in the code: https://jsfiddle.net/Hoargarth/Lry5gbsq/
Feel free to ask if you need anything

Just a quick note on all of those containers:
You could do it with just the flex-item and one other container. But in my opinion, with the extra container it get's more flexible if you need any hover-events, animations or som other exotic stuff.
For the simple solution see this fiddle: https://jsfiddle.net/Hoargarth/m57b9jcw/

.container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

/* padding bottom gives the height of the container, 33.33% padding would be a quadratic box. 100% would be the same height as the container's width. Therefore simple trignomometry, (100/4) * 3 = 75%; or for screen width > 500px: (33.33 / 4) * 3 for a 4/3 resolution. You'll find the media query at the end of the css. It's just to demonstrate that it's working with media queries as well. */
.item {
  position: relative;
  width: 100%;
  padding-bottom: 75%;
}

/* Overflow hidden so nothing can overlap to the other items */
.content-wrapper {
  position: absolute;
  overflow: hidden;
  width: 100%;
  height: 100%;
}

.image-holder {
  position: relative;
  height: 100%;
  background-image: url("https://previews.123rf.com/images/happydancing/happydancing1706/happydancing170600014/80282512-flat-lay-photo-of-workspace-desk-with-laptop-smartphone-blank-notebook-and-green-plant-with-copy-spa.jpg");
  background-size: cover;
  background-position: 50%;
  background-repeat: no-repeat;
}

/* Absolute positioned by 50% top, left; To completely center it, you have to translate the holder back by it's own half width and height transform: translate(-50%, -50%) */
.text-holder {
  position: absolute;
  top: 50%;
  left: 50%;
  padding: 10px;
  width: 70%;
  background-color: rgba(255, 255, 255, 0.5);
  transform: translate(-50%, -50%);
  text-align: center;
}

/* Simple media Query to test it. Be aware: If the item's width is changing, the padding has to change as well */
@media (min-width: 500px) {
  .item {
    width: 33.33%;
    padding-bottom: 24.75%;
  }
}

<div class="container">

  <div class="item">
    <div class="content-wrapper">
      <div class="image-holder"></div>
      <div class="text-holder">
        <p>
          Some Centered Text
        </p>
      </div>
    </div>
  </div>

  <div class="item">
    <div class="content-wrapper">
      <div class="image-holder"></div>
      <div class="text-holder">
        <p>
          Some Centered Text but larger and longer so we see a difference
        </p>
      </div>
    </div>
  </div>

  <div class="item">
    <div class="content-wrapper">
      <div class="image-holder"></div>
      <div class="text-holder">
        <p>
          Groot
        </p>
      </div>
    </div>
  </div>

</div>


问:
Spring Boot controller not responding to POST request
I am working with a receipt printer that has a cloud function. It commuicates with a server specification which i am implementing. It polls a URL with POST requests every x seconds and when the POST response contains a certain piece of information, the printer sends a GET request to the same to URL get the information to print.

I'm implementing the print server as a Spring Boot server and i'm getting some strange problems with the POST method that i need some help with.

My problem is that the POST requests from the printer to the server never make it to the controller. However, i am able to send a POST request from Postman to the exact same URL and it gets handled by the controller.

The URL is simply: https://www.[my-domain].com:[port-number]/cloudprint

Also, i have tried copying the controller method to another Spring (not Boot) application, running on a Tomcat instance behind Apache and there, the POST requests from the printer are handled by the controller method. I can see them in the Apache log and the Tomcat log. The polling frequency is currently at 10 seconds.

Here's what the controller looks like:

```<code>package com.[my-domain].[application-name].controller;

[a bunch of imports]

@RestController
@CrossOrigin
public class PrintController {
    Logger logger = LoggerFactory.getLogger(PrintController.class);

    @RequestMapping(value="/cloudprint", method=RequestMethod.POST,
            headers={"Accept=application/json"})
    @ResponseStatus(HttpStatus.CREATED)
    public @ResponseBody String printPost() {
        logger.debug("in printPost");
        return "OK";
    }

    @RequestMapping(value="/cloudprint", method=RequestMethod.GET,
            headers={"Accept=application/json"})
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody String printGet(HttpServletRequest request) {
        logger.debug("in printGet");
        return "OK";
    }

    @RequestMapping(value="/cloudprint", method=RequestMethod.DELETE,
            headers={"Accept=application/json"})
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody String printDelete() {
        logger.debug("in printDelete");
        return "OK";
    }
}
</code>```

What could be causing this? What can i test to solve this issue?

---ADDED INFORMATION BELOW 2019-06-03 @13:21 cet---
Since i have a regular Spring (non-boot) application that accepts the POST requests from the printer, i am able to log the information in the incoming request. So i did that.

This is one of the POST requests from the printer, which is NOT accepted by the Spring boot oontroller:

```<code>auth type: null
content type: application/json
-- HEADERS --
Header: host : dev.[our-domain-name].com
Header: accept : */*
Header: user-agent : Cente HTTPc
Header: content-type : application/json
Header: content-length : 303
Header: connection : keep-alive
QueryString: null
-- PARAMETERS --
END
</code>```

This is one of the POST requests from Postman to the exact same URL, which IS accepted by the Spring boot oontroller:

```<code>auth type: null
cotent type: application/json
-- HEADERS --
Header: content-type : application/json
Header: cache-control : no-cache
Header: Postman-Token : caf99fa1-4730-4193-aab3-c4874273661d
Header: user-agent : PostmanRuntime/7.6.0
Header: accept : */*
Header: host : dev.[our-domain-name].com
Header: accept-encoding : gzip, deflate
Header: content-length : 0
Header: connection : keep-alive
QueryString: null
-- PARAMETERS --
END
</code>```

Analysis:
1. The user-agent headers differ.
2. The content-length headers differ.
3. The Postman request has three headers that the request from the cloud printer does not have. They are: cache-control, Postman-token and accept-encoding

---ADDED INFORMATION BELOW 2019-06-03 @17:56 cet---
OK, i figured out how to log the message body. It is a well-formatted json structure that is indeed 303 characters:

```<code>{"status": "29 a 0 0 0 0 0 0 0 0 0 0",
 "printerMAC": "00:11:62:1b:xx:xx",
 "statusCode": "200%20OK",
 "printingInProgress": false,
 "clientAction": null,
 "display": [
   {"name": "MainDisplay" ,
    "status": {"connected": false}}],
 "barcodeReader": [
   {"name": "MainBCR" ,
    "status": {"connected": false,"claimed": false}}]}
</code>```

I created the corresponding classes and changed the POST method in the Boot application to this:

```<code>@RequestMapping(value="/cloudprint", method=RequestMethod.POST,
        headers={"Accept=application/json"})
@ResponseStatus(HttpStatus.CREATED)
public @ResponseBody String printPost(@RequestBody PrinterPostRequest printerPostRequest,
        HttpServletRequest request) {
    HttpRequestLogger.log(request);
    return "OK";
}
</code>```

Still, it is not picking up the POST request from the printer. It picks up the Postman request and successfully marshals the request body json into the classes.

---ADDED INFORMATION BELOW 2019-06-05 @10:16 cet---
I had an idea. Using Spring RestTemplate, i sent a POST request to the Boot application with the same headers and same payload as the request the printer sends. I'm getting an org.springframework.web.client.ResourceAccessException with this message:

```<code>I/O error on POST request for "https://boot.[my-domain].com:8443/cloudprint":sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

答:
If you use Spring Boot 2, then it could happen because of the csrf-protection. It affects only the non-GET requests, and it's turned on by default on Spring Boot 2, but it's off in earlier versions.

So it quite well reflects your issue-description - although I don't fully understand how could it work via Postman... however there is a chance that it handles it automatically somehow...

Anyway it could worth a try:

```<code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
  }
}
</code>```

Body:
I am working with a receipt printer that has a cloud function. It commuicates with a server specification which i am implementing. It polls a URL with POST requests every x seconds and when the POST response contains a certain piece of information, the printer sends a GET request to the same to URL get the information to print.

I'm implementing the print server as a Spring Boot server and i'm getting some strange problems with the POST method that i need some help with.

My problem is that the POST requests from the printer to the server never make it to the controller. However, i am able to send a POST request from Postman to the exact same URL and it gets handled by the controller.

The URL is simply: https://www.[my-domain].com:[port-number]/cloudprint

Also, i have tried copying the controller method to another Spring (not Boot) application, running on a Tomcat instance behind Apache and there, the POST requests from the printer are handled by the controller method. I can see them in the Apache log and the Tomcat log. The polling frequency is currently at 10 seconds.

Here's what the controller looks like:

package com.[my-domain].[application-name].controller;

[a bunch of imports]

@RestController
@CrossOrigin
public class PrintController {
    Logger logger = LoggerFactory.getLogger(PrintController.class);

    @RequestMapping(value="/cloudprint", method=RequestMethod.POST,
            headers={"Accept=application/json"})
    @ResponseStatus(HttpStatus.CREATED)
    public @ResponseBody String printPost() {
        logger.debug("in printPost");
        return "OK";
    }

    @RequestMapping(value="/cloudprint", method=RequestMethod.GET,
            headers={"Accept=application/json"})
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody String printGet(HttpServletRequest request) {
        logger.debug("in printGet");
        return "OK";
    }

    @RequestMapping(value="/cloudprint", method=RequestMethod.DELETE,
            headers={"Accept=application/json"})
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody String printDelete() {
        logger.debug("in printDelete");
        return "OK";
    }
}

What could be causing this? What can i test to solve this issue?

---ADDED INFORMATION BELOW 2019-06-03 @13:21 cet---
Since i have a regular Spring (non-boot) application that accepts the POST requests from the printer, i am able to log the information in the incoming request. So i did that.

This is one of the POST requests from the printer, which is NOT accepted by the Spring boot oontroller:

auth type: null
content type: application/json
-- HEADERS --
Header: host : dev.[our-domain-name].com
Header: accept : */*
Header: user-agent : Cente HTTPc
Header: content-type : application/json
Header: content-length : 303
Header: connection : keep-alive
QueryString: null
-- PARAMETERS --
END

This is one of the POST requests from Postman to the exact same URL, which IS accepted by the Spring boot oontroller:

auth type: null
cotent type: application/json
-- HEADERS --
Header: content-type : application/json
Header: cache-control : no-cache
Header: Postman-Token : caf99fa1-4730-4193-aab3-c4874273661d
Header: user-agent : PostmanRuntime/7.6.0
Header: accept : */*
Header: host : dev.[our-domain-name].com
Header: accept-encoding : gzip, deflate
Header: content-length : 0
Header: connection : keep-alive
QueryString: null
-- PARAMETERS --
END

Analysis:
1. The user-agent headers differ.
2. The content-length headers differ.
3. The Postman request has three headers that the request from the cloud printer does not have. They are: cache-control, Postman-token and accept-encoding

---ADDED INFORMATION BELOW 2019-06-03 @17:56 cet---
OK, i figured out how to log the message body. It is a well-formatted json structure that is indeed 303 characters:

{"status": "29 a 0 0 0 0 0 0 0 0 0 0",
 "printerMAC": "00:11:62:1b:xx:xx",
 "statusCode": "200%20OK",
 "printingInProgress": false,
 "clientAction": null,
 "display": [
   {"name": "MainDisplay" ,
    "status": {"connected": false}}],
 "barcodeReader": [
   {"name": "MainBCR" ,
    "status": {"connected": false,"claimed": false}}]}

I created the corresponding classes and changed the POST method in the Boot application to this:

@RequestMapping(value="/cloudprint", method=RequestMethod.POST,
        headers={"Accept=application/json"})
@ResponseStatus(HttpStatus.CREATED)
public @ResponseBody String printPost(@RequestBody PrinterPostRequest printerPostRequest,
        HttpServletRequest request) {
    HttpRequestLogger.log(request);
    return "OK";
}

Still, it is not picking up the POST request from the printer. It picks up the Postman request and successfully marshals the request body json into the classes.

---ADDED INFORMATION BELOW 2019-06-05 @10:16 cet---
I had an idea. Using Spring RestTemplate, i sent a POST request to the Boot application with the same headers and same payload as the request the printer sends. I'm getting an org.springframework.web.client.ResourceAccessException with this message:

I/O error on POST request for "https://boot.[my-domain].com:8443/cloudprint":sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Body:
If you use Spring Boot 2, then it could happen because of the csrf-protection. It affects only the non-GET requests, and it's turned on by default on Spring Boot 2, but it's off in earlier versions.

So it quite well reflects your issue-description - although I don't fully understand how could it work via Postman... however there is a chance that it handles it automatically somehow...

Anyway it could worth a try:

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
  }
}


问:
Do I need to explicitly fold header lines in TidHttp ver 10.5498?
Please can someone (Remy Lebeau?) clarify the point on header line folding in TidHTTP?
My server expects headers to be folded if the line exceeds 998 characters, which one of mine certainly will.

Among many other posts discussing this I saw this one which is a more or less definitive post from a while back where Remy says

by default the TIdHeaderList.FoldLines property is set to True

```<code>and
</code>```

the default value of the TIdHeaderList.FoldLength property is 78

which seem to indicate that I don't need to do anything special to get my headers folded when using TIdHTTP.

However, looking at the source code of TidHTTP I find comments from Remy such as these
(in TIdCustomHTTP.Post)

Currently when issuing a POST, IdHTTP will automatically set the
  protocol to version 1.0 independently of the value it had initially.

and
(in TIdHTTPProtocol.BuildAndSendRequest)

TODO: disable header folding for HTTP 1.0 requests

Which appear to indicate that my request is going to be using HTTP 1.0 requests anyway, regardless if I ask for 1.1 or not and that the header lines will not be folded regardless.

My question therefore is simply; when using TidHttp ver 10.5498 do I need the lines

```<code> IdHTTP1.Request.CustomHeaders.FoldLines := true;
 IdHTTP1.Request.CustomHeaders.FoldLength := 998;  //could be less, but not more
</code>```

or can I simply accept the defaults and be confident that my headers will be correctly folded?

答:
The default FoldLength is 78 chars unless the QuoteType is QuoteHTTP, then the default is MaxInt instead (effectively disabling folding for HTTP headers even if FoldLines is True).  So, if you want your HTTP headers folded at 998 chars, you do need to set the FoldLength manually.

Note that while RFC 1945 (for HTTP 1.0) and RFC 2616 (for HTTP 1.1) do allow headers to be folded:

Header fields can be extended over multiple lines by preceding each extra line with at least one SP or HT, though this is not recommended.

<nbsp;>

Header fields can be extended over multiple lines by preceding each extra line with at least one SP or HT.

RFC 7230 (which updates HTTP 1.1) deprecates that practice:

Historically, HTTP header field values could be extended over multiple lines by preceding each extra line with at least one space or horizontal tab (obs-fold).  This specification deprecates such line folding except within the message/http media type (Section 8.3.1).  A sender MUST NOT generate a message that includes line folding (i.e., that has any field-value that contains a match to the obs-fold rule) unless the message is intended for packaging within the message/http media type.

As for TIdHTTP forcing HTTP 1.0 for POST requests, you can prevent that by enabling the hoKeepOrigProtocol flag in the TIdHTTP.HTTPOptions property.

Body:
Please can someone (Remy Lebeau?) clarify the point on header line folding in TidHTTP?
My server expects headers to be folded if the line exceeds 998 characters, which one of mine certainly will.

Among many other posts discussing this I saw this one which is a more or less definitive post from a while back where Remy says

by default the TIdHeaderList.FoldLines property is set to True

and

the default value of the TIdHeaderList.FoldLength property is 78

which seem to indicate that I don't need to do anything special to get my headers folded when using TIdHTTP.

However, looking at the source code of TidHTTP I find comments from Remy such as these
(in TIdCustomHTTP.Post)

Currently when issuing a POST, IdHTTP will automatically set the
  protocol to version 1.0 independently of the value it had initially.

and
(in TIdHTTPProtocol.BuildAndSendRequest)

TODO: disable header folding for HTTP 1.0 requests

Which appear to indicate that my request is going to be using HTTP 1.0 requests anyway, regardless if I ask for 1.1 or not and that the header lines will not be folded regardless.

My question therefore is simply; when using TidHttp ver 10.5498 do I need the lines

 IdHTTP1.Request.CustomHeaders.FoldLines := true;
 IdHTTP1.Request.CustomHeaders.FoldLength := 998;  //could be less, but not more

or can I simply accept the defaults and be confident that my headers will be correctly folded?


问:
How to handle state on Flat List Items in React-Native
I am setting a counter on the items of the FlatList component of React-Native. How can I update the list item every time the user press the "+" or "-" button?

I am currently being able to update the value on the state, however the list doesnt display the new state. I have tried adding extraData component to the FlatList, but it doesnt seem to update anyways.

This is the data structure

```<code>      data: [
        {
          id: 1,
          name: "Bread",
          price: "400",
          imageS: "../resources/pan-corteza-blanda.jpg",
          quantity: 2
        },
... more data
</code>```

This is the function that handles the increment

```<code>  handleIncrement = i => {
    this.setState(state => {
      const formatData = state.data.map((item, j) => {
        console.log("Id", i + " /// " + item.id);
        if (item.id === i) {
          item.quantity = item.quantity + 1;
          return item;
        } else {
          return item;
        }
      });
      console.log("FormatData" + formatData); //Displays the correct  quantity of the item updated

      return {
        formatData
      };
    });
  };
</code>```

And this is the list component

```<code>  <FlatList
          data={this.state.data}
          style={styles.list}
          extraData={this.state.data}
          renderItem={this.renderItem}
        />
</code>```

I expect to update the text component of the list item with the right quantity value every time a user presses the "+" or "-" button.

答:
this.state.data is never changed on your handleIncrement, and this is what you are passing into FlatList. Thats why FlatList doesn't update.

After handleIncrement runs, the only thing that changes in your state is:

```<code>{
  formatData: [...stuff here]
}
</code>```

Maybe you want to pass down this.state.formatData instead or rename it in handleIncrement to data.

Also, your state structure would probably be better as a map, where the keys are itemIds. This way you don need to map through the whole list every time you want to increment the quantity.

e.g.

```<code>  {

    1: {
      id: 1,
      name: "Bread",
      price: "400",
      imageS: "../resources/pan-corteza-blanda.jpg",
      quantity: 2
    },
    // more data...
  }
</code>```

Now, your handleIncrement looks like this:

```<code>handleIncrement = itemId => this.setState(prevState => ({
  ...prevState,
  [itemId]: ++prevState[itemId].quantity
}))
</code>```

Body:
I am setting a counter on the items of the FlatList component of React-Native. How can I update the list item every time the user press the "+" or "-" button?

I am currently being able to update the value on the state, however the list doesnt display the new state. I have tried adding extraData component to the FlatList, but it doesnt seem to update anyways.

This is the data structure

      data: [
        {
          id: 1,
          name: "Bread",
          price: "400",
          imageS: "../resources/pan-corteza-blanda.jpg",
          quantity: 2
        },
... more data

This is the function that handles the increment

  handleIncrement = i => {
    this.setState(state => {
      const formatData = state.data.map((item, j) => {
        console.log("Id", i + " /// " + item.id);
        if (item.id === i) {
          item.quantity = item.quantity + 1;
          return item;
        } else {
          return item;
        }
      });
      console.log("FormatData" + formatData); //Displays the correct  quantity of the item updated

      return {
        formatData
      };
    });
  };

And this is the list component

  <FlatList
          data={this.state.data}
          style={styles.list}
          extraData={this.state.data}
          renderItem={this.renderItem}
        />

I expect to update the text component of the list item with the right quantity value every time a user presses the "+" or "-" button.

Body:
this.state.data is never changed on your handleIncrement, and this is what you are passing into FlatList. Thats why FlatList doesn't update.

After handleIncrement runs, the only thing that changes in your state is:

{
  formatData: [...stuff here]
}

Maybe you want to pass down this.state.formatData instead or rename it in handleIncrement to data.

Also, your state structure would probably be better as a map, where the keys are itemIds. This way you don need to map through the whole list every time you want to increment the quantity.

e.g.

  {

    1: {
      id: 1,
      name: "Bread",
      price: "400",
      imageS: "../resources/pan-corteza-blanda.jpg",
      quantity: 2
    },
    // more data...
  }

Now, your handleIncrement looks like this:

handleIncrement = itemId => this.setState(prevState => ({
  ...prevState,
  [itemId]: ++prevState[itemId].quantity
}))


问:
Greedy algorithm correctness
I'm trying to solve the following problem:

CEO is checking on it's employees at a constant times every day (for
  an example the number of minutes after a shift started> {5, 35,
  120..}). Calculate when should employees work, so that every time the CEO checks on them they are working. Their work takes 3 minutes to
  complete and it increases by another 3 minutes every time they start
  working again (First time it takes 3 minutes, second time it takes 6
  minutes, third time it takes 9 minutes..).

This is my algorithm in pseudocode:

```<code>int time = 2
for: every CEOcheckTime in 0 to CEOcheckTime.length
    add (CEOcheckTimes-time) to results
    time = time + 2
</code>```

Ignoring the edge case, where the CEO checks on employees sooner that they can finish the work, is my algorithm correct? Thanks!

答:
Ignoring the 'edge case' this seems fine except your time is being incremented by 2 rather than 3 as per the spec.

```<code> int time = 3
 for: every CEOcheckTime in CEOcheckTimes
     add (CEOcheckTimes-time) to results
     time = time + 3
</code>```

a similar just in time approach could be used here that would account for your edge case too.

```<code>for: every CEOcheckTime in CEOcheckTimes
    if exists(time):
        if last(results) + time < CEOcheckTime:
            add (CEOcheckTimes) to results
            time = time + 3
    else:
         add (CEOcheckTimes) to results
         time = 3
</code>```

edit: i have assumed that if work starts / ends at the same time as a check that this counts as working.

Title: Greedy algorithm correctness

Body:
I'm trying to solve the following problem:

CEO is checking on it's employees at a constant times every day (for
  an example the number of minutes after a shift started> {5, 35,
  120..}). Calculate when should employees work, so that every time the CEO checks on them they are working. Their work takes 3 minutes to
  complete and it increases by another 3 minutes every time they start
  working again (First time it takes 3 minutes, second time it takes 6
  minutes, third time it takes 9 minutes..).

This is my algorithm in pseudocode:

int time = 2
for: every CEOcheckTime in 0 to CEOcheckTime.length
    add (CEOcheckTimes-time) to results
    time = time + 2

Ignoring the edge case, where the CEO checks on employees sooner that they can finish the work, is my algorithm correct? Thanks!

Body:
Ignoring the 'edge case' this seems fine except your time is being incremented by 2 rather than 3 as per the spec.

 int time = 3
 for: every CEOcheckTime in CEOcheckTimes
     add (CEOcheckTimes-time) to results
     time = time + 3

a similar just in time approach could be used here that would account for your edge case too.

for: every CEOcheckTime in CEOcheckTimes
    if exists(time):
        if last(results) + time < CEOcheckTime:
            add (CEOcheckTimes) to results
            time = time + 3
    else:
         add (CEOcheckTimes) to results
         time = 3

edit: i have assumed that if work starts / ends at the same time as a check that this counts as working.


问:
Why does my app has the READ_PHONE_STATE permission although it's not declared in manifest?
I noticed the READ_PHONE_STATE permission when I uploaded the apk to google play.
I have not added it and it is not written anywhere in my manifest or any other file of my project. (I looked through all libraries for this permission)

My app did not have this permission in my previous build with same libraries. Since last build I updated android studio to version 1, updated my android sdk and made a few changes (in code) to my app. I don't request the device ID in my app.

My app has minSDK 14 and no ads.
Here are my manifest permissions:

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</code>```

Here's the apk file

答:
One cause could be a (transitive) dependency, i.e. a library, that declares a minimum required Android SDK level below 4. In this case the "manifest merger tool" will add those permissions implicitly.

```<code>Lower-priority manifest declares                   Permissions added to the merged manifest

targetSdkVersion <= 3                              WRITE_EXTERNAL_STORAGE, READ_PHONE_STATE
targetSdkVersion <= 15 and using READ_CONTACTS     READ_CALL_LOG
targetSdkVersion <= 15 and using WRITE_CONTACTS    WRITE_CALL_LOG
</code>```

Source: https://developer.android.com/studio/build/manifest-merge#implicit_system_permissions

Look into the manifest-merger-*-report.txt log, found in build/outputs/logs if this was case.

Body:
I noticed the READ_PHONE_STATE permission when I uploaded the apk to google play.
I have not added it and it is not written anywhere in my manifest or any other file of my project. (I looked through all libraries for this permission)

My app did not have this permission in my previous build with same libraries. Since last build I updated android studio to version 1, updated my android sdk and made a few changes (in code) to my app. I don't request the device ID in my app.

My app has minSDK 14 and no ads.
Here are my manifest permissions:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Here's the apk file

Body:
One cause could be a (transitive) dependency, i.e. a library, that declares a minimum required Android SDK level below 4. In this case the "manifest merger tool" will add those permissions implicitly.

Lower-priority manifest declares                   Permissions added to the merged manifest

targetSdkVersion <= 3                              WRITE_EXTERNAL_STORAGE, READ_PHONE_STATE
targetSdkVersion <= 15 and using READ_CONTACTS     READ_CALL_LOG
targetSdkVersion <= 15 and using WRITE_CONTACTS    WRITE_CALL_LOG

Source: https://developer.android.com/studio/build/manifest-merge#implicit_system_permissions

Look into the manifest-merger-*-report.txt log, found in build/outputs/logs if this was case.


问:
How do I pass a parameter to my url for a POST function that takes a string parameter?
I'm using ASP.NET Core for a Web API and created a POST function and don't know how to pass a string "name" in the URL such that the function can return the correct string.

The url should be :

https://localhost/44320/api/

```<code>//This is in my Controller class
[HttpPost("test/{name}")]
public string PostTest(string name)
{
    return "Name: " + name;
}
</code>```

The return value is self explanatory but I just get a 405 error for when I do
https://localhost:44320/api/test/bob/

答:
Ensure your controller looks as follows:

```<code>[Route("api/[controller]")]
public class ListController : Controller
{
    [HttpPost("test/{name}")]
    public string Post([FromRoute] string name)
    {
        return "Name: " + name;
    }
}
</code>```

Put a breakpoint on the return statement, debug the application, and then send a POST request to it using: https://localhost:44320/api/list/test/bob

name should then contain the value bob.

Edit: Here's a working screenshot of the above, although the localhost port is obviously different.

Body:
I'm using ASP.NET Core for a Web API and created a POST function and don't know how to pass a string "name" in the URL such that the function can return the correct string.

The url should be :

https://localhost/44320/api/

//This is in my Controller class
[HttpPost("test/{name}")]
public string PostTest(string name)
{
    return "Name: " + name;
}

The return value is self explanatory but I just get a 405 error for when I do
https://localhost:44320/api/test/bob/

Body:
Ensure your controller looks as follows:

[Route("api/[controller]")]
public class ListController : Controller
{
    [HttpPost("test/{name}")]
    public string Post([FromRoute] string name)
    {
        return "Name: " + name;
    }
}

Put a breakpoint on the return statement, debug the application, and then send a POST request to it using: https://localhost:44320/api/list/test/bob

name should then contain the value bob.

Edit: Here's a working screenshot of the above, although the localhost port is obviously different.


问:
Get a subset of items using .WHERE and then REMOVEALL by condition using Lambda Expressions
I have a list of items, these items have a property called vog_code, it is an int, this list have a variety of items with 4 different types of vog_code, 1,10,14,16.

Now, I want to remove the items on that list that doesnt abide to a certain date, but for items with vog_codes equals 14 and 16 the condition will be different.

This is the expression I have now:

```<code>transaccionSinAgruparResp.ListaDeTransacciones.RemoveAll(x => x.vog_code == 14 || x.vog_code == 16 && x.fecha_recepcion >= fechaOriginal);
</code>```

Which is incorrect since it will eliminate all the items with vog_code 14 and 16 and doesnt abide the AND operator.

Is there any way to ask "for these elements that are vog_code 14 and 16 I then, will check if the dates are greater or equal".

I tried with a .Where and then .RemoveAll but that is not possible.

I dont want to use more an auxiliary list unless it is the only way to do it.

答: The && operator is a higher precedence than the || operator. If you want || to be executed before &&, then you need to wrap it in ().</p>

Body:
I have a list of items, these items have a property called vog_code, it is an int, this list have a variety of items with 4 different types of vog_code, 1,10,14,16.

Now, I want to remove the items on that list that doesnt abide to a certain date, but for items with vog_codes equals 14 and 16 the condition will be different.

This is the expression I have now:

transaccionSinAgruparResp.ListaDeTransacciones.RemoveAll(x => x.vog_code == 14 || x.vog_code == 16 && x.fecha_recepcion >= fechaOriginal);

Which is incorrect since it will eliminate all the items with vog_code 14 and 16 and doesnt abide the AND operator.

Is there any way to ask "for these elements that are vog_code 14 and 16 I then, will check if the dates are greater or equal".

I tried with a .Where and then .RemoveAll but that is not possible.

I dont want to use more an auxiliary list unless it is the only way to do it.


问:
ImageView not fading in CollapsingToolbarLayout
I am trying to get a fading effect on the ImageView when collapsing the AppbarLayout but the image still remains. I have read other solutions but its not working for me. I cant seem to find what is wrong with the code.

```<code><android.support.design.widget.CoordinatorLayout
android:id="@+id/coordinatorLayoutProfile"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.bolt.citywatch.ui.fragment.ProfileFragment">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="220dp"
        android:background="@color/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:id="@+id/profile_image"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="96dp"
            android:layout_height="96dp"
            android:layout_gravity="center"
            android:src="@drawable/ic_email_white"
            app:layout_collapseMode="parallax"/>

        <android.support.v7.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerViewData"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</code>```

答: For anyone stumbling upon this as I did and isn't satisfied with the accepted answer, as the image is supposed to fade out on its own without tinkering the code, make sure your Toolbar is the last child of your CollapsingToolbarLayout, and not your ImageView... found the answer on here. Fixed it for me.

Body:
I am trying to get a fading effect on the ImageView when collapsing the AppbarLayout but the image still remains. I have read other solutions but its not working for me. I cant seem to find what is wrong with the code.

<android.support.design.widget.CoordinatorLayout
android:id="@+id/coordinatorLayoutProfile"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.bolt.citywatch.ui.fragment.ProfileFragment">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="220dp"
        android:background="@color/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:id="@+id/profile_image"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="96dp"
            android:layout_height="96dp"
            android:layout_gravity="center"
            android:src="@drawable/ic_email_white"
            app:layout_collapseMode="parallax"/>

        <android.support.v7.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerViewData"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>


问:
Unhandled Exception: inheritFromWidgetOfExactType(_LocalizationsScope) or inheritFromElement() was called before _ScreenState.initState() completed
I am calling initial method to load data from API using initState. But it is resulting me an error. Here is error:

```<code>Unhandled Exception: inheritFromWidgetOfExactType(_LocalizationsScope) or inheritFromElement() was called before _ScreenState.initState() completed.
When an inherited widget changes, for example if the value of Theme.of() changes, its dependent widgets are rebuilt. If the dependent widget's reference to the inherited widget is in a constructor or an initState() method, then the rebuilt dependent widget will not reflect the changes in the inherited widget.
</code>```

My code is:

```<code>@override
  void initState() {
    super.initState();

    this._getCategories();
  }

  void _getCategories() async {
    AppRoutes.showLoader(context);
    Map<String, dynamic> data = await apiPostCall(
      apiName: API.addUser,
      context: context,
      parameterData: null,
      showAlert: false,
    );
    if(data.isNotEmpty){
      AppRoutes.dismissLoader(context);
      print(data);

    }else {
      AppRoutes.dismissLoader(context);
    }
   }
</code>```

答:
You need to call _getCategories after initState has completed.

@override
void initState() {
   super.initState();

   Future.delayed(Duration.zero, () {
      this._getCategories();
   });

   // Could do this in one line: Future.delayed(Duration.zero, this._getCategories);
}

```
<p>Also, you could do this on a different way, using addPostFrameCallback.
To make this task easier, you could create a mixin to be added to StatefulWidgets.</p>
<pre class="lang-dart prettyprint-override"><code>mixin PostFrameMixin<T extends StatefulWidget> on State<T> {
  void postFrame(void Function() callback) =>
      WidgetsBinding.instance?.addPostFrameCallback(
        (_) {
          // Execute callback if page is mounted
          if (mounted) callback();
        },
      );
}
</code>```

Then, you just need to plug this mixin to you page, like that:

class _MyPageState extends State<MyPage> with PostFrameMixin {
  @override
  void initState() {
    super.initState();

    postFrame(_getCategories);
  }
}

```

Body:
I am calling initial method to load data from API using initState. But it is resulting me an error. Here is error:

Unhandled Exception: inheritFromWidgetOfExactType(_LocalizationsScope) or inheritFromElement() was called before _ScreenState.initState() completed.
When an inherited widget changes, for example if the value of Theme.of() changes, its dependent widgets are rebuilt. If the dependent widget's reference to the inherited widget is in a constructor or an initState() method, then the rebuilt dependent widget will not reflect the changes in the inherited widget.

My code is:

@override
  void initState() {
    super.initState();

    this._getCategories();
  }

  void _getCategories() async {
    AppRoutes.showLoader(context);
    Map<String, dynamic> data = await apiPostCall(
      apiName: API.addUser,
      context: context,
      parameterData: null,
      showAlert: false,
    );
    if(data.isNotEmpty){
      AppRoutes.dismissLoader(context);
      print(data);

    }else {
      AppRoutes.dismissLoader(context);
    }
   }

Body:
You need to call _getCategories after initState has completed.

@override
void initState() {
   super.initState();

   Future.delayed(Duration.zero, () {
      this._getCategories();
   });

   // Could do this in one line: Future.delayed(Duration.zero, this._getCategories);
}

Also, you could do this on a different way, using addPostFrameCallback.
To make this task easier, you could create a mixin to be added to StatefulWidgets.

mixin PostFrameMixin<T extends StatefulWidget> on State<T> {
  void postFrame(void Function() callback) =>
      WidgetsBinding.instance?.addPostFrameCallback(
        (_) {
          // Execute callback if page is mounted
          if (mounted) callback();
        },
      );
}

Then, you just need to plug this mixin to you page, like that:

class _MyPageState extends State<MyPage> with PostFrameMixin {
  @override
  void initState() {
    super.initState();

    postFrame(_getCategories);
  }
}


问:
How do I extract a list of URLs off a page with selenium?
I am attempting to extract all urls that https://shop.freedommobile.ca/devices has when you click the 'see options' button under each phone and place them into a list of strings.

I am using python with Selenium and wait libraries.
Ive already tried using .text in my parameters. However, I keep running into an error that states:

typeError: 'str' object is not callable
line 17 is the issue.

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

class phoneCost:

    driver.get("https://shop.freedommobile.ca/devices")

    # extract the names of the phones
    wait = WebDriverWait(driver, 20) #10 second wait
    XPathLocation = """B//*[@id="skip-navigation"]/div/div/div[1]/div/div[2]/a'"""
    phonePlanLinksRaw = wait.until(EC.presence_of_all_elements_located(By.XPATH(XPathLocation)))
    phonePlanLinks = []

    for element in range(len(phonePlanLinksRaw)):
        link = element
        phonePlanLinks.append(str(link))

    numLink = 1
    for element in range(len(phonePlanLinks)):
        print("phone " + str(numLink) + " : " + phonePlanLinks[element])
        numLink += 1
</code>```

should return a list of urls in string format:

[https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786135&planSku=Freedom%20Big%20Gig%2015GB

,

https://shop.freedommobile.ca/devices/Apple/iPhone_XS?sku=190198790569&planSku=Freedom%20Big%20Gig%

,

https://shop.freedommobile.ca/devices/Apple/iPhone_XR?sku=190198776631&planSku=Freedom%20Big%20Gig%2015GB]

Any help is appreciated
Thank you

答:
Try using list comprehension to achieve the reults. Just take a look at this portion (By.XPATH(XPathLocation))) that you used which should be wait.until(EC.visibility_of_all_elements_located((By.XPATH, "some_xpath"))).

Rectified one is more like:

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

with webdriver.Chrome() as driver:
    wait = WebDriverWait(driver, 10)
    driver.get("https://shop.freedommobile.ca/devices")
    item_links = [item.get_attribute("href") for item in wait.until(EC.visibility_of_all_elements_located((By.XPATH, "//a[contains(@class,'__DeviceDetailsButton')]")))]
    print(item_links)
</code>```

Body:
I am attempting to extract all urls that https://shop.freedommobile.ca/devices has when you click the 'see options' button under each phone and place them into a list of strings.

I am using python with Selenium and wait libraries.
Ive already tried using .text in my parameters. However, I keep running into an error that states:

typeError: 'str' object is not callable
line 17 is the issue.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

class phoneCost:

    driver.get("https://shop.freedommobile.ca/devices")

    # extract the names of the phones
    wait = WebDriverWait(driver, 20) #10 second wait
    XPathLocation = """B//*[@id="skip-navigation"]/div/div/div[1]/div/div[2]/a'"""
    phonePlanLinksRaw = wait.until(EC.presence_of_all_elements_located(By.XPATH(XPathLocation)))
    phonePlanLinks = []

    for element in range(len(phonePlanLinksRaw)):
        link = element
        phonePlanLinks.append(str(link))

    numLink = 1
    for element in range(len(phonePlanLinks)):
        print("phone " + str(numLink) + " : " + phonePlanLinks[element])
        numLink += 1

should return a list of urls in string format:

[https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786135&planSku=Freedom%20Big%20Gig%2015GB

,

https://shop.freedommobile.ca/devices/Apple/iPhone_XS?sku=190198790569&planSku=Freedom%20Big%20Gig%

,

https://shop.freedommobile.ca/devices/Apple/iPhone_XR?sku=190198776631&planSku=Freedom%20Big%20Gig%2015GB]

Any help is appreciated
Thank you

Body:
Try using list comprehension to achieve the reults. Just take a look at this portion (By.XPATH(XPathLocation))) that you used which should be wait.until(EC.visibility_of_all_elements_located((By.XPATH, "some_xpath"))).

Rectified one is more like:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

with webdriver.Chrome() as driver:
    wait = WebDriverWait(driver, 10)
    driver.get("https://shop.freedommobile.ca/devices")
    item_links = [item.get_attribute("href") for item in wait.until(EC.visibility_of_all_elements_located((By.XPATH, "//a[contains(@class,'__DeviceDetailsButton')]")))]
    print(item_links)


问:
Parameter Value is being treated as a data type - PL/pgSQL
I am new to using PL/pgSQL. I've been a SQL Server Developer for the past 3 years. I'm trying to write a function using Dynamic SQL to pass in a table name and then pass a value and that table name back out. </p>

<p>I'm still trying to figure how how to write stored procs and functions in PostgreSQL, but I can't find any documentation how to do something like this. </p>

```<code>CREATE OR REPLACE FUNCTION exc_tables (tname VARCHAR)
RETURNS TABLE (module_id bigint, tablename varchar) AS $$
BEGIN
  RETURN QUERY EXECUTE format('SELECT DISTINCT module_id, '||CAST(tname AS varchar)||' as tablename FROM ' || tname || ' WHERE module_ID <> 6');

END;
$$
LANGUAGE plpgsql;

SQL Error [42804]: ERROR: structure of query does not match function result type
  Detail: Returned type dt_conn_type does not match expected type character varying in column 2.
  Where: PL/pgSQL function exc_tables(character varying) line 3 at RETURN QUERY
</code>```

答:
You needed to put the cast() into the query.

```<code>...
RETURN QUERY EXECUTE format('SELECT DISTINCT module_id, CAST('''||tname||''' AS varchar) as tablename FROM ' || tname || ' WHERE module_ID <> 6');
...
</code>```

But since it already is a varchar the cast is useless and you could just go with:

```<code>RETURN QUERY EXECUTE format('SELECT DISTINCT module_id, '''||tname||''' as tablename FROM ' || tname || ' WHERE module_ID <> 6');
</code>```

But you need to make sure to enclose it in single quotes in the query to make it a string literal as otherwise it means the whole record (which has the type of whatever tname is then, so not a varchar).

And BTW, using format() with only a placeholderless format string and no replacement arguments is also pretty useless.

Body:
I am new to using PL/pgSQL. I've been a SQL Server Developer for the past 3 years. I'm trying to write a function using Dynamic SQL to pass in a table name and then pass a value and that table name back out.

I'm still trying to figure how how to write stored procs and functions in PostgreSQL, but I can't find any documentation how to do something like this.

CREATE OR REPLACE FUNCTION exc_tables (tname VARCHAR)
RETURNS TABLE (module_id bigint, tablename varchar) AS $$
BEGIN
  RETURN QUERY EXECUTE format('SELECT DISTINCT module_id, '||CAST(tname AS varchar)||' as tablename FROM ' || tname || ' WHERE module_ID <> 6');

END;
$$
LANGUAGE plpgsql;

SQL Error [42804]: ERROR: structure of query does not match function result type
  Detail: Returned type dt_conn_type does not match expected type character varying in column 2.
  Where: PL/pgSQL function exc_tables(character varying) line 3 at RETURN QUERY

Body:
You needed to put the cast() into the query.

...
RETURN QUERY EXECUTE format('SELECT DISTINCT module_id, CAST('''||tname||''' AS varchar) as tablename FROM ' || tname || ' WHERE module_ID <> 6');
...

But since it already is a varchar the cast is useless and you could just go with:

RETURN QUERY EXECUTE format('SELECT DISTINCT module_id, '''||tname||''' as tablename FROM ' || tname || ' WHERE module_ID <> 6');

But you need to make sure to enclose it in single quotes in the query to make it a string literal as otherwise it means the whole record (which has the type of whatever tname is then, so not a varchar).

And BTW, using format() with only a placeholderless format string and no replacement arguments is also pretty useless.


问:
Cube's awkward shape when rendered on a small screen
I'm stacking a series of small divs to show a series of statistics. The problem is to display them correctly on a mobile phone. Can you suggest an alternative for me? It's worth noticing that this design came from an admin template.

This is what you'd see on a bigger screen:

And the following is the way the cubes are displayed while using a cellphone:

```<code><div class="col-2">
            <div class="bg-success p-10 text-white text-center">
                <i class="fas fa-warehouse m-b-5 font-16"></i>
                <h5 class="m-b-0 m-t-5">414</h5>
                <small class="font-light">Bodega stock</small>
            </div>
    </div>
</code>```

I've read about responsive typography but I'm not sure how should I proceed.

答:
From a designer point of view, I think what you should do is making the bottom columns be rows instead, so, in mobile, they would all be the same width as the blue box.

This should be pretty easy using Bootstrap 4, your col div would be:

```<code><div class="col-xs-6 col-sm-4> ... </div>
</code>```

Something like that.

Body:
I'm stacking a series of small divs to show a series of statistics. The problem is to display them correctly on a mobile phone. Can you suggest an alternative for me? It's worth noticing that this design came from an admin template.

This is what you'd see on a bigger screen:

And the following is the way the cubes are displayed while using a cellphone:

414

                Bodega stock

I've read about responsive typography but I'm not sure how should I proceed.

Body:
From a designer point of view, I think what you should do is making the bottom columns be rows instead, so, in mobile, they would all be the same width as the blue box.

This should be pretty easy using Bootstrap 4, your col div would be:

<div class="col-xs-6 col-sm-4> ... </div>

Something like that.


问:
How to get the cell object in tableView:(UITableView *)tableView heightForRowAtIndexPath function?
I wand to know the content of the cell when returning the heightForRowAtIndexPath. In this function how do I get the cell object?

```<code>- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

}
</code>```

If I try this

```<code> [tableView cellForRowAtIndexPath:indexPath]
</code>```

it fails and goes off in an infinite loop.

Any idea?

答:
```<code>uitableviewcell *ce=[self.view viewwithtag:indexPath.row];
</code>```

it returns the cell object.

Body:
I wand to know the content of the cell when returning the heightForRowAtIndexPath. In this function how do I get the cell object?

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

}

If I try this

 [tableView cellForRowAtIndexPath:indexPath]

it fails and goes off in an infinite loop.

Any idea?

Body:
uitableviewcell *ce=[self.view viewwithtag:indexPath.row];

it returns the cell object.


问:
Round time(7) column values no nearest 15 minutes
I have columns of type time(7)[nulls allowed], some of the values need to be to be adjusted to the nearest 15 minute mark and the seconds set to zero.

Example:

```<code>09:00:40.0000000 -> 09:00:00.0000000
12:50:00.0000000 -> 12:45:00.0000000
12:59:37.0000000 -> 13:00:00.0000000
</code>```

答:
I recommend timefromparts():

```<code>select timefromparts(datepart(hour, timecol),
                     (datepart(minute, timecol) / 15) * 15,
                     0, 0, 6)
</code>```

The above truncates the value.  Rounding the value is a little tricker.  I would recommend:

```<code>select timefromparts(datepart(hour, dateadd(second, 7 * 60 + 30, timecol)),
                     (datepart(minute, dateadd(second, 7 * 60 + 30, timecol)) / 15) * 15,
                     0, 0, 6)
</code>```

That is, add 7.5 minutes and truncate.

Body:
I have columns of type time(7)[nulls allowed], some of the values need to be to be adjusted to the nearest 15 minute mark and the seconds set to zero.

Example:

09:00:40.0000000 -> 09:00:00.0000000
12:50:00.0000000 -> 12:45:00.0000000
12:59:37.0000000 -> 13:00:00.0000000

Body:
I recommend timefromparts():

select timefromparts(datepart(hour, timecol),
                     (datepart(minute, timecol) / 15) * 15,
                     0, 0, 6)

The above truncates the value.  Rounding the value is a little tricker.  I would recommend:

select timefromparts(datepart(hour, dateadd(second, 7 * 60 + 30, timecol)),
                     (datepart(minute, dateadd(second, 7 * 60 + 30, timecol)) / 15) * 15,
                     0, 0, 6)

That is, add 7.5 minutes and truncate.


问:
Ansible: How to write a YAML Playbook as a JSON or Python data array?
I have some experience with JSON and Python, so I would like to visualize an Ansible YAML playbook as a regular Python or JSON inline data structure. Is it possible to write the entire contents of a YAML file as an inline data structure consisting of lists and dictionaries? If so, could I also use whitespace to make it easier to read?

Example:

```<code>---
- hosts: webservers
  remote_user: root
  gather_facts: true

  tasks:
  - name: ensure apache is at the latest version
    yum:
      name: httpd
      state: latest
  - name: write the apache config file
    template:
      src: /srv/httpd.j2
      dest: /etc/httpd.conf
</code>```

Which becomes:

```<code>---
[{hosts: webservers, remote_user: root, gather_facts: true, tasks: [{name: ensure apache is at the latest version, yum: {name: httpd, state: latest}}], [name: write the apache config file, template: {src: /srv/httpd.j2, dest: /etc/httpd.conf}]}]
</code>```

答:
In general you cannot represent YAML as JSON, because JSON is subset
of YAML. E.g. YAML tags and anchors cannot be expressed in JSON, and
the restrictions on keys in JSON object are extremely severe, whereas
YAML essentially can have any node as key in a mapping.

Python can represent YAML completely, if not then ruamel.yaml could
not round-trip YAML files. And so you can generate all YAML data
structures from scratch using regular Python constructs and then dump
them to YAML. For tagged constructs this is however not completely
trivial. You also have to consider that no library gives you complete
control over the syntactic representation, and indentation is normally
the same for all mappings and all sequences (or even the same for all
collections).

If your YAML doesn't contain tags, like your example, then the YAML can be loaded as the
regular Python constructs such as dicts, lists and primitives such as
strings, integers, float, datetime.datetime, boolean. You can just
load the YAML and print the data structure:

```<code>import sys
import ruamel.yaml

yaml_str = """---
- hosts: webservers
  remote_user: root
  gather_facts: true

  tasks:
  - name: ensure apache is at the latest version
    yum:
      name: httpd
      state: latest
  - name: write the apache config file
    template:
      src: /srv/httpd.j2
      dest: /etc/httpd.conf
"""

yaml = ruamel.yaml.YAML(typ='safe')
data = yaml.load(yaml_str)
print(data)
</code>```

which gives:

```<code>[{'hosts': 'webservers', 'remote_user': 'root', 'gather_facts': True, 'tasks': [{'name': 'ensure apache is at the latest version', 'yum': {'name': 'httpd', 'state': 'latest'}}, {'name': 'write the apache config file', 'template': {'src': '/srv/httpd.j2', 'dest': '/etc/httpd.conf'}}]}]
</code>```

Body:
I have some experience with JSON and Python, so I would like to visualize an Ansible YAML playbook as a regular Python or JSON inline data structure. Is it possible to write the entire contents of a YAML file as an inline data structure consisting of lists and dictionaries? If so, could I also use whitespace to make it easier to read?

Example:

---
- hosts: webservers
  remote_user: root
  gather_facts: true

  tasks:
  - name: ensure apache is at the latest version
    yum:
      name: httpd
      state: latest
  - name: write the apache config file
    template:
      src: /srv/httpd.j2
      dest: /etc/httpd.conf

Which becomes:

---
[{hosts: webservers, remote_user: root, gather_facts: true, tasks: [{name: ensure apache is at the latest version, yum: {name: httpd, state: latest}}], [name: write the apache config file, template: {src: /srv/httpd.j2, dest: /etc/httpd.conf}]}]

Body:
In general you cannot represent YAML as JSON, because JSON is subset
of YAML. E.g. YAML tags and anchors cannot be expressed in JSON, and
the restrictions on keys in JSON object are extremely severe, whereas
YAML essentially can have any node as key in a mapping.

Python can represent YAML completely, if not then ruamel.yaml could
not round-trip YAML files. And so you can generate all YAML data
structures from scratch using regular Python constructs and then dump
them to YAML. For tagged constructs this is however not completely
trivial. You also have to consider that no library gives you complete
control over the syntactic representation, and indentation is normally
the same for all mappings and all sequences (or even the same for all
collections).

If your YAML doesn't contain tags, like your example, then the YAML can be loaded as the
regular Python constructs such as dicts, lists and primitives such as
strings, integers, float, datetime.datetime, boolean. You can just
load the YAML and print the data structure:

import sys
import ruamel.yaml

yaml_str = """---
- hosts: webservers
  remote_user: root
  gather_facts: true

  tasks:
  - name: ensure apache is at the latest version
    yum:
      name: httpd
      state: latest
  - name: write the apache config file
    template:
      src: /srv/httpd.j2
      dest: /etc/httpd.conf
"""

yaml = ruamel.yaml.YAML(typ='safe')
data = yaml.load(yaml_str)
print(data)

which gives:

[{'hosts': 'webservers', 'remote_user': 'root', 'gather_facts': True, 'tasks': [{'name': 'ensure apache is at the latest version', 'yum': {'name': 'httpd', 'state': 'latest'}}, {'name': 'write the apache config file', 'template': {'src': '/srv/httpd.j2', 'dest': '/etc/httpd.conf'}}]}]